potree.js 3.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = global || self, factory(global.Potree = {}));
  5. }(this, (function (exports) { 'use strict';
  6. function mobileVersion(e, t) {
  7. //ios的版本
  8. var i = window.navigator.userAgent,
  9. n = i.match(e);
  10. return (
  11. (n = n ? n[1].split(t) : []),
  12. {
  13. major: parseInt(n[0]) || 0,
  14. minor: parseInt(n[1]) || 0,
  15. patch: parseInt(n[2]) || 0,
  16. }
  17. )
  18. }
  19. var browser = {
  20. isFullscreen: function() {
  21. return (
  22. document.fullscreenElement ||
  23. document.mozFullscreenElement ||
  24. document.mozFullScreenElement ||
  25. document.webkitFullscreenElement ||
  26. document.msFullscreenElement
  27. )
  28. },
  29. supportsFullscreen: function() {
  30. return (
  31. document.fullscreenEnabled ||
  32. document.mozFullscreenEnabled ||
  33. document.mozFullScreenEnabled ||
  34. document.webkitFullscreenEnabled ||
  35. document.msFullscreenEnabled
  36. )
  37. },
  38. isPointerLocked: function() {
  39. return (
  40. document.pointerLockElement ||
  41. document.mozPointerLockElement ||
  42. document.webkitPointerLockElement
  43. )
  44. },
  45. requestFullscreen: function(dom, t) {
  46. dom.requestFullscreen ?
  47. dom.requestFullscreen() :
  48. dom.mozRequestFullScreen ?
  49. dom.mozRequestFullScreen() :
  50. dom.webkitRequestFullscreen ?
  51. dom.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT) :
  52. dom.msRequestFullscreen && dom.msRequestFullscreen(),
  53. t &&
  54. $(document).on(
  55. "fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange",
  56. browser.requestPointerLock
  57. );
  58. },
  59. requestPointerLock: function() {
  60. var e;
  61. if (document.fullscreenElement) e = document.fullscreenElement();
  62. else if (document.mozFullscreenElement) e = document.mozFullscreenElement();
  63. else if (document.mozFullScreenElement) e = document.mozFullScreenElement();
  64. else {
  65. if (!document.webkitFullscreenElement) return
  66. e = document.webkitFullscreenElement();
  67. };
  68. (e.requestPointerLock =
  69. e.requestPointerLock || e.mozRequestPointerLock || e.webkitRequestPointerLock),
  70. e.requestPointerLock(),
  71. $(document).off(
  72. "fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange",
  73. this
  74. );
  75. },
  76. exitPointerLock: function() {
  77. ;
  78. (document.exitPointerLock =
  79. document.exitPointerLock ||
  80. document.mozExitPointerLock ||
  81. document.webkitExitPointerLock),
  82. document.exitPointerLock();
  83. },
  84. exitFullscreen: function() {
  85. document.exitFullscreen ?
  86. document.exitFullscreen() :
  87. document.msExitFullscreen ?
  88. document.msExitFullscreen() :
  89. document.mozCancelFullScreen ?
  90. document.mozCancelFullScreen() :
  91. document.webkitExitFullscreen && document.webkitExitFullscreen();
  92. },
  93. details: function() {
  94. var e = navigator.userAgent.match("(Firefox|Chrome|Safari)/([\\d]+)");
  95. return e ?
  96. {
  97. name: e[1],
  98. version: parseInt(e[2]),
  99. platform: navigator.platform,
  100. } : {}
  101. },
  102. is: function(e) {
  103. return this.details() && this.details().name === e
  104. },
  105. inIframe: function() {
  106. return window.parent !== window
  107. },
  108. aspectRatio: function($elem) {
  109. $elem = $elem || $("#player");
  110. var e = $elem.width() / $elem.height();
  111. return isFinite(e) ? e : 0
  112. },
  113. userAgent: function() {
  114. return window.navigator.userAgent
  115. },
  116. isMobile: function() {
  117. var e = navigator.userAgent || navigator.vendor || window.opera;
  118. return (
  119. /(android|bb\d+|meego).+mobile|android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
  120. e
  121. ) ||
  122. /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
  123. e.substr(0, 4)
  124. )
  125. )
  126. },
  127. isLandscape: function() {
  128. return this.isMobile && this.aspectRatio() > 1
  129. },
  130. isSmallScreen: function() {
  131. var e = screen.width / window.devicePixelRatio;
  132. return e < 240
  133. },
  134. detectIE: function() {
  135. var e = window.navigator.userAgent,
  136. t = e.indexOf("MSIE ");
  137. return t !== -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)
  138. },
  139. detectSafari: function() {
  140. var e = window.navigator.userAgent,
  141. t = e.indexOf("Safari");
  142. return t !== -1 && !this.detectOpera() && !this.detectChrome() //xzw add detectOpera
  143. },
  144. detectFirefox: function() {
  145. var e = window.navigator.userAgent;
  146. return e.indexOf("Firefox") !== -1
  147. },
  148. detectChrome: function() {
  149. var e = window.navigator.userAgent;
  150. return e.indexOf("Chrome") !== -1 && !this.detectOpera()
  151. },
  152. detectOpera: function() {
  153. var e = window.navigator.userAgent;
  154. return e.indexOf("OPR") !== -1
  155. },
  156. detectIOS: function() {
  157. return this.detectIPhone() || this.detectIPad() || this.detectIPod()
  158. },
  159. detectIPad: function() {
  160. var e = window.navigator.userAgent,
  161. t = /iPad/;
  162. return t.test(e)
  163. },
  164. detectIPod: function() {
  165. var e = window.navigator.userAgent,
  166. t = /iPod/;
  167. return t.test(e)
  168. },
  169. detectIPhone: function() {
  170. var e = window.navigator.userAgent,
  171. t = /iPhone/;
  172. return t.test(e)
  173. },
  174. detectAndroid: function() {
  175. var e = window.navigator.userAgent;
  176. return e.indexOf("Android") !== -1
  177. },
  178. detectAndroidMobile: function() {
  179. var e = window.navigator.userAgent;
  180. return this.detectAndroid() && e.indexOf("Mobile") !== -1
  181. },
  182. detectSamsungNative: function() {
  183. var e = window.navigator.userAgent;
  184. return (
  185. e.indexOf("SM-G900H") !== -1 ||
  186. e.indexOf("GT-I9500") !== -1 ||
  187. e.indexOf("SM-N900") !== -1
  188. )
  189. },
  190. detectSamsungS6: function() {
  191. var e = window.navigator.userAgent;
  192. return e.indexOf("SM-G92") !== -1
  193. },
  194. /************************************************************徐世廷*************************************************************/
  195. detectHUAWEI5X: function() {
  196. return -1 !== window.navigator.userAgent.indexOf("KIW-TL00H")
  197. },
  198. /*******************************************************************************************************************************/
  199. detectWebVR: function() {
  200. return !(!window.navigator.getVRDisplays || !window.VRDisplay)
  201. },
  202. getVRDisplay: function() {
  203. var e = $.Deferred();
  204. return this.detectWebVR() ?
  205. (navigator.getVRDisplays().then(function(t) {
  206. t.length >= 1 && e.resolve(t[0]), e.reject(null);
  207. }),
  208. e) :
  209. e.reject(null)
  210. },
  211. iosVersion: function() {
  212. if (!this.detectIOS()) throw new DeviceMismatchException("Did not detect an iDevice")
  213. var e = /((?:\d+\_?){1,3}) like Mac OS/,
  214. t = "_";
  215. return mobileVersion(e, t)
  216. },
  217. androidVersion: function() {
  218. if (!this.detectAndroid())
  219. throw new DeviceMismatchException("Did not detect an Android based device")
  220. var e = /Android ((?:\d+\.?){1,3})/,
  221. t = ".";
  222. return mobileVersion(e, t)
  223. },
  224. valueFromCookie: function(e, t) {
  225. var i = new RegExp(e + "=([0-9a-f]+)(; ?|$)").exec(document.cookie);
  226. if (!i) return t
  227. var n = i[1];
  228. return "boolean" == typeof t ?
  229. "true" === n || "1" === n :
  230. "number" == typeof t ?
  231. parseFloat(n) :
  232. n
  233. },
  234. valueFromHash: function(e, t) {
  235. var i = new RegExp("[#&?]" + e + "=([^#&?]*)"),
  236. n = i.exec(window.location.href);
  237. if (!n) return t
  238. var r = n[1];
  239. return "boolean" == typeof t ?
  240. "true" === r || "1" === r :
  241. "number" == typeof t ?
  242. parseFloat(r) :
  243. window.decodeURIComponent(r)
  244. },
  245. //-------许钟文:-------------------------------------------------
  246. getProjectNum: function() {
  247. //获取场景projectNum
  248. if (window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") {
  249. return window.__ProjectNum
  250. }
  251. var number = window.location.href.substring(window.location.href.indexOf("=") + 1);
  252. if (number.indexOf("&") != -1) {
  253. number = number.substring(0, number.indexOf("&"));
  254. }
  255. if (number.indexOf("#") != -1) {
  256. number = number.substring(0, number.indexOf("#"));
  257. }
  258. return number
  259. },
  260. urlHasValue: function(key, isGetValue) {
  261. // debugger
  262. // if (getValue) { //得到类似n=1 的 1
  263. // var b = window.location.href.substring(window.location.href.indexOf("?") + 1);
  264. // var a = b.indexOf('&' + t + "=");
  265. // if (a > -1) {
  266. // var s = b.substring(a + ('&' + t + "=").length);
  267. // s.indexOf("&") > -1 && (s = s.substring(0, s.indexOf("&")));
  268. // s.indexOf("#") > -1 && (s = s.substring(0, s.indexOf("#")));
  269. // return s;
  270. // } else return false;
  271. // } else return window.location.search.match("&" + t + "|\\?" + t) != null; //window.location.href.substring(window.location.href.indexOf("?") + 1).indexOf('&' + t) > -1;
  272. //const value = window.location.search.match("&" + t + "|\\?" + t)
  273. if (key === "m" && window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") {
  274. return window.__ProjectNum
  275. }
  276. let querys = window.location.search.substr(1).split("&");
  277. if (isGetValue) {
  278. for (let i = 0; i < querys.length; i++) {
  279. let keypair = querys[i].split("=");
  280. if (keypair.length === 2 && keypair[0] === key) {
  281. return keypair[1]
  282. }
  283. }
  284. return ""
  285. } else {
  286. //return window.location.search.match("&" + key + "|\\?" + key) != null 有bug
  287. for (let i = 0; i < querys.length; i++) {
  288. let keypair = querys[i].split("=");
  289. if (keypair[0] == key) {
  290. return true
  291. }
  292. }
  293. return false
  294. }
  295. },
  296. /**
  297. * 获取查询参数的值
  298. * @param {String} key
  299. * @returns String
  300. */
  301. urlQueryValue(key) {
  302. return this.urlHasValue(key, true) || ""
  303. },
  304. /**
  305. * 获取hash参数的值
  306. * @param {String} key
  307. * @returns String
  308. */
  309. urlHashValue(key) {
  310. let querys = window.location.hash.substr(1).replace('/?', '').split("&");
  311. for (let i = 0; i < querys.length; i++) {
  312. let keypair = querys[i].split("=");
  313. if (keypair.length === 2 && keypair[0] === key) {
  314. return keypair[1]
  315. }
  316. }
  317. return ""
  318. },
  319. /**
  320. * 判断是否存在hash
  321. * @param {String} key
  322. * @returns Boolean
  323. */
  324. urlIsHasHash(key) {
  325. let querys = window.location.hash.substr(1).replace('/?', '').split("&");
  326. return querys.includes(key)
  327. },
  328. islongPhone: function() {
  329. //是否是刘海全面屏幕 仅仅根据比例判断 - -
  330. //screen.height == 812 && screen.width == 375)
  331. var r = screen.height / screen.width; //可能横屏
  332. return this.isMobile() && (r > 1.99 || r < 0.502512) //18/9=2.165 //???
  333. },
  334. detectWeixin: function() {
  335. //微信 包括PC的微信
  336. return window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
  337. },
  338. detectWeixinMiniProgram: function() {
  339. return window.navigator.userAgent.match("miniProgram")
  340. },
  341. detectEdge: function() {
  342. return window.navigator.userAgent.indexOf("Edge") > -1
  343. },
  344. detectApp: function() {
  345. return this.urlHasValue("app")
  346. },
  347. /**
  348. * 判断标签页是否切换状态
  349. */
  350. isTabHidden: function() {
  351. var prefixes = ["webkit", "moz", "ms", "o"];
  352. if ("hidden" in document) return document.hidden
  353. for (var i = 0; i < prefixes.length; i++) {
  354. if (prefixes[i] + "Hidden" in document) return document[prefixes[i] + "Hidden"]
  355. }
  356. return false
  357. },
  358. };
  359. //xzw add
  360. const config$1 = {//配置参数 不可修改
  361. displayMode:{
  362. showPointCloud:{
  363. atPano:{
  364. showPoint : true,
  365. showSkybox: false,
  366. pointUsePanoTex : false
  367. },
  368. transition:{
  369. showPoint: true,
  370. showSkybox: false,
  371. pointUsePanoTex: false
  372. },
  373. canLeavePano: true //是否能离开pano位置
  374. },
  375. showPanos:{
  376. atPano:{
  377. showPoint : false,
  378. showSkybox: true,
  379. pointUsePanoTex : false
  380. },
  381. transition:{
  382. //showPoint: true,
  383. showSkybox: true,
  384. //pointUsePanoTex: true //是否使用全景贴图
  385. },
  386. canLeavePano: false
  387. },
  388. showBoth:{
  389. atPano:{
  390. showPoint : true,
  391. showSkybox: true,
  392. pointUsePanoTex : false //?
  393. },
  394. transition:{
  395. showPoint: true,
  396. showSkybox: true,
  397. pointUsePanoTex: true
  398. },
  399. canLeavePano: true //是否能离开pano位置 离开后自动变为showPointCloud
  400. },
  401. //test:
  402. pointUsePanoTex:{ //---静止时调点云
  403. atPano:{
  404. showPoint : true,
  405. showSkybox: false,
  406. pointUsePanoTex : true
  407. },
  408. transition:{
  409. showPoint: true,
  410. showSkybox: true,
  411. pointUsePanoTex: true //是否使用全景贴图
  412. },
  413. canLeavePano: false
  414. },
  415. },
  416. urls:{
  417. //localTextures:'../resources/textures/',
  418. prefix: 'https://laser-oss.4dkankan.com',//oss
  419. prefix2: 'https://testlaser.4dkankan.com',
  420. prefix3: 'https://4dkk.4dage.com',
  421. prefix4: 'https://uat-laser.4dkankan.com/',//test.4dkankan
  422. },
  423. /* transitionsTime:{
  424. flyTime : 1000 // 毫秒/米
  425. panoToPano: 1000,
  426. flyIn:1000,
  427. flyOut:1000,
  428. } */
  429. transitionsTime:{
  430. flyMinTime : 500 /* * 3 */, // 毫秒/米
  431. flytimeDistanceMultiplier: 150/* * 3 */,
  432. panoToPanoMax: 2000/* * 3 */,
  433. flyIn:1000,
  434. flyOut:1000
  435. }
  436. ,
  437. moveSpeedAdujust : 0.5 //越小越慢
  438. ,
  439. view:{
  440. fov:70, //navvis:50
  441. near:0.1,
  442. far: 10000,
  443. },
  444. map:{//mapViewer
  445. mapHeight : -1000,//要比点云低。最低
  446. cameraHeight : 1000, //最高 ,注意(如sitemodel)其他的物体不能超过这个高度
  447. },
  448. pointDensity:{
  449. magnifier:{
  450. maxLevelPercent: 1,
  451. pointBudget : 8*1000*1000,
  452. },
  453. panorama:{//显示全景时的漫游。因为点只能显示1个像素的大小,所以必须很密集,但又要限制点的数量
  454. maxLevelPercent: 0.6,
  455. pointBudget : /* 4*1000*1000// */browser.isMobile() ? 0.1*1000*1000 : 0.4*1000*1000, //点云总最大数
  456. },
  457. fourViewports:{//分四屏时防止卡顿
  458. maxLevelPercent: 0.4,
  459. pointBudget :1*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  460. },
  461. fourViewportsMain:{//分四屏时防止卡顿
  462. maxLevelPercent: 0.8,
  463. pointBudget :1*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  464. }
  465. ,
  466. panoEdit:{
  467. maxLevelPercent: 1, //在远处时由于pointBudget限制而展示稀疏,凑近时就变为最高质量了
  468. pointBudget :1*1000*1000, //避免卡顿
  469. },
  470. low:{//highPerformance
  471. maxLevelPercent: 0.4, //最小为0
  472. percentByUser:true, //如果用户定义了percent,使用用户的
  473. pointBudget : 1*1000*1000,
  474. },
  475. middle:{//balanced //不同场景相同级别所产生的numVisibleNodes和numVisiblePoints不同,如果分层比较细,可能要到level8才能看清,那么level5看到的点就很大且很少,如隧道t-e2Kb2iU
  476. maxLevelPercent: 0.7,
  477. percentByUser:true,
  478. pointBudget:browser.isMobile() ? 4*1000*1000 : 2*1000*1000,
  479. },
  480. high:{//highQuality
  481. maxLevelPercent: 1,
  482. percentByUser:true,
  483. pointBudget:browser.isMobile() ? 8*1000*1000 : 4*1000*1000,
  484. }
  485. //browser.isMobile() 时要不要限制下pointBudget,还是让用户自己调低质量?
  486. //minNodeSize?
  487. //数值由testLevelSteps得来,其中nodeMaxLevel为2时,low和middle的都是1,如果真有这么低的点云就单独处理下。
  488. //多个viewport尽量保证pointBudget一样,或者pointBudget不能太低于所需,否则会反复加载了又清除
  489. },
  490. clip:{
  491. color: '#FFC266', //map
  492. },
  493. panoFieldRadius : 10, //当前位置多远范围内可以切全景模式
  494. measure:{
  495. color:'#00C8AF',
  496. default:{
  497. color:"#64C8BB",//"#00c7b2",
  498. opacity:0.7
  499. },
  500. highlight:{
  501. color:'#00C8AF',//"#00c7b2",
  502. opacity:1
  503. },
  504. guide:{
  505. color:'#FFFFFF',
  506. opacity:1
  507. }
  508. ,
  509. backColor:'#333333',
  510. lineWidth: 4,
  511. textColor: "#FFFFFF"
  512. },
  513. material:{//初始化
  514. pointSize: 0.1,
  515. realPointSize : 0.1,//实际上的ui滑动条默认大小(兼容旧的版本)
  516. minSize: 0.1,
  517. maxSize: 10000,
  518. pointSizeType: 'ATTENUATED', //'ADAPTIVE'//'ADAPTIVE' \ FIXED //ADAPTIVE的在小房间里大小会不太匹配,但在远景似乎更好
  519. /*
  520. ATTENUATED : 衰减 真实大小,靠近时感觉是点云一点点变多,缝隙变小
  521. ADAPTIVE: 自适应 大小根据level变化,越高越小。靠近时感觉点云由大慢慢细分成小份。这个感觉更佳但是navvis为何不用这个
  522. */
  523. absolutePanoramaSize: 1.3 ,//全景漫游时的size 是fixed的模式
  524. //sizeAtPanoRtEDL : 2000,
  525. pointColor:'#ffffff',
  526. //sizeAddAtPanoRtEDL : 0.5, //全景模式静止时的size
  527. //ADAPTIVE : 字会失真扭曲
  528. //'ATTENUATED' 往旁边看有缝隙、点在浮动
  529. //navvis的shader在哪里 为什么不会抖动
  530. }
  531. ,
  532. renderLayers:{//渲染层,方便分批渲染管理,替代scene的创建。数字不代表顺序。(数字不能太大)
  533. bg: 20,
  534. bg2: 21,
  535. skybox: 1,
  536. pointcloud: 11,
  537. sceneObjects:0,//default
  538. model : 2,
  539. measure:4,
  540. magnifier:5,
  541. magnifierContent:16,
  542. volume:6,
  543. transformationTool:7,
  544. map:8,
  545. mapObjects:9,//default
  546. bothMapAndScene: 3,
  547. siteModeOnlyMapVisi:12,//只能mapViewer可见
  548. siteModelMapUnvisi:13,//只有mapViewer不可见
  549. siteModeSideVisi:14,//只有侧面可见
  550. layer1: 10,// 备用1
  551. layer2: 15,// 备用2
  552. },
  553. renderOrders:{ //会影响到绘制、pick时的顺序。
  554. model:10
  555. },
  556. siteModel:{
  557. names:{
  558. 'building': '建筑',
  559. 'floor':'楼层',
  560. 'room':'房间'
  561. },
  562. floorHeightDefault: 5,//一层楼的高度
  563. },
  564. panosEdit:{
  565. },
  566. tiling: {
  567. panoPreRenderRepeatDelay: 2500,
  568. panoPreRenderDelay: 500,
  569. preRenderTourPanos: browser.valueFromHash("tileprerender", 0),
  570. tilingFlagNames: ["usetiles", "tiles"],
  571. maxNavPanoQuality: browser.valueFromHash("maxtileq", null),
  572. maxZoomPanoQuality: browser.valueFromHash("maxztileq", null),
  573. overlayStyle: browser.valueFromHash("tileoverlay", 0),
  574. uploadIntervalDelay: browser.valueFromHash("tileupdelay", 10),
  575. initialIntervalDelay: browser.valueFromHash("itiledelay", 0),
  576. maxNonBaseUploadsPerFrame: browser.valueFromHash("maxnbtpf", 2),
  577. maxBaseUploadsPerFrame: browser.valueFromHash("maxbtpf", 6),
  578. customCompression: browser.valueFromHash("tilecustcomp", 0),
  579. mobileHighQualityOverride: !1,
  580. allowUltraHighResolution: !0
  581. },
  582. navigation: {
  583. panoScores: !1,
  584. mouseDirection: !0,
  585. filterStrictness: .75,
  586. angleFactor: -30,
  587. directionFactor: 10,
  588. distanceFactor: -1,
  589. optionalityFactor: 3
  590. }
  591. ,
  592. axis : { 'x':{color:'#d0021b'/* 'red' */}, 'y':{ color:'#86c542' /* 'green' */}, 'z': {color:'#3399c8' /* 'blue' */}},
  593. highQualityMaxZoom: 2,
  594. ultraHighQualityMaxZoom: 3,
  595. clickMaxDragDis:5,
  596. clickMaxPressTime:500, //ms
  597. doubleClickTime:200,//双击间隔时间
  598. background: '#232323',
  599. mapBG:'#F5F5F5', //地图的clearColor
  600. colors: { //from navvis
  601. red: [213,0,0],
  602. pink: [197,17,98],
  603. purple: [170,0,255],
  604. "deep purple": [98,0,234],
  605. blue: [ 41,98,255],
  606. "light blue": [ 0,145,234],
  607. cyan: [ 0,184,212],
  608. teal: [ 0,191,165],
  609. green: [0,200,83],
  610. "light green": [ 100,221,23],
  611. lime: [ 174,234,0],
  612. yellow: [ 255,214,0],
  613. amber: [ 255,171,0],
  614. orange: [ 255,109,0],
  615. "deep orange": [ 255,61,0],
  616. },
  617. };
  618. config$1.OrthoCameraLimit = {
  619. standard:{
  620. zoom:{min:0.001, max:500}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  621. posBound:{
  622. min: {x:-1e5, y:-1e5,z: config$1.map.cameraHeight},
  623. max: {x:1e5, y:1e5, z:1 / 0 }
  624. }
  625. },
  626. expand:{ //范围再大些,用于编辑空间模型等(但是万一中心点靠近地图边缘的话,就很容易扭曲了)
  627. zoom:{min:0.0004, max:100}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  628. posBound:{
  629. min: {x:-5000000, y:-1000000,z:config$1.map.cameraHeight},
  630. max: {x:5000000, y:1000000, z:1 / 0 }
  631. }//40075017
  632. }
  633. };
  634. /* 显示模式:
  635. 1只显示点云: 滚轮为前进后退,方向键可以行走。进入漫游点时自动变为混合(这样全景可以弥补缝隙),过渡时只显示点云。
  636. 2只显示全景: 不能任意行走。 过渡时显示贴图材质非edl的点云(否则有折痕不贴合)。
  637. 3混合:都显示。 不能任意行走。过渡时显示贴图材质非edl的点云(因为只显示点云的话不太美,点云很碎,不细腻)
  638. */
  639. window.testLevelSteps = function(steps){//[0.4,0.7,1]
  640. if(!steps){
  641. let s = Potree.config.pointDensity;
  642. steps = [s.low.maxLevelPercent, s.middle.maxLevelPercent, s.high.maxLevelPercent, ];
  643. }
  644. let max = 1;
  645. while(++max<=12){
  646. let r1 = steps.map(e=>e * max);
  647. let r2 = steps.map(e=>Math.round(e * max));
  648. console.log(`当nodeMaxLevel为${max}时,每一级的level分别为${r2}, (小数:${r1})`);
  649. }
  650. console.log('请检查每一层的三个level是否有重复');
  651. };
  652. function getPrefix(){
  653. let u = window.location.href.split('//');
  654. let v = u[1].split('/');
  655. return v[0]
  656. }
  657. let settings = {//设置 可修改
  658. editType : '',
  659. number: '', //场景序号
  660. originDatasetId:'',//场景原本的数据集id,应该就是数据集第一个吧
  661. isOfficial:false,
  662. webSite:'testdata',//'data', //不同环境对应的静态文件的地址不同
  663. isLocal:false, //是否本地 局域网版本
  664. libsUrl:'../libs/',
  665. displayMode:'',
  666. isTest :browser.urlHasValue('test'),
  667. prefix: getPrefix(),
  668. pointDensity: '', UserPointDensity:'',//pointDensity会随着进入不同的模块而自动改变,UserPointDensity记录了用户的设置
  669. UserDensityPercent:null,//点云密度百分比
  670. ifShowMarker:true,//显示漫游点
  671. floorplanType:{},//平面图类型 'default' | 'diy' 不同数据集不同{datasetId:...}
  672. floorplanEnable:false,
  673. floorplanEnables:{},
  674. floorplanRequests:{},//开始加载了的
  675. mapEnable:true,//地图区域是否加载地图
  676. cameraFar : config$1.view.far, //相机最远范围 1-300
  677. //limitFar: true, //是否使用setting的cameraFar来限制(如在点云裁剪时为false)
  678. showPanoMesh:false, //显示小球,
  679. dblToFocusPoint:false,//调试时如果需要双击飞向某个点云的点,就打开。此时不在漫游点的话单击将无法漫游。//因和单击漫游冲突
  680. unableNavigate : false,//进入如裁剪界面时 禁止漫游
  681. sizeFitToLevel: false,//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  682. zoom:{
  683. enabled : true,
  684. min:1,
  685. max: config$1.highQualityMaxZoom,
  686. activationThreshold: 1.1,
  687. },
  688. navConstantly:true,
  689. navTileClass: browser.isMobile() ? '1k' : '2k', //默认加载到
  690. tileClass:'4k', //最高可达
  691. /* loadTilesWhenUnfocus:false, //页面unfocus时也仍在加载tiles
  692. loadPointsWhenUnfocus:true, //页面unfocus时也仍在加载点云 */
  693. //initialShowPano:true
  694. drawEntityData: false,
  695. zoomFromPointert:{//定点缩放(包括点云模式、全景模式、地图)
  696. whenPanos:true,
  697. whenPointCloud:true,
  698. map:true,
  699. },
  700. rotAroundPoint:true,//点云模式是否能绕intersectPoint旋转
  701. tourTestCameraMove:false, //测试镜头时,不移动真实的镜头, 只移动frustum
  702. cameraAniSmoothRatio : 20, //镜头动画平滑系数,越高越平滑
  703. urls : $.extend({}, config$1.urls),
  704. useDepthTex: true,//使用深度贴图,但不代表一定有(得到的intersect更快速准确和稳定) SS-t-7DUfWAUZ3V
  705. //matUseDepth:false,
  706. //panoEdit:
  707. datasetsPanos:{},
  708. //mergeModel:
  709. boundAddObjs:false,
  710. intersectOnObjs:false,
  711. intersectWhenHover:true,
  712. notAdditiveBlending:false, //点云是否使用普通的blend, 否则会曝光过渡
  713. precision:2 // 两位小数
  714. };
  715. //JSON.parse(localStorage.getItem('setting'))
  716. settings.isLocalhost = settings.prefix.includes('localhost');
  717. // threejs.org/license
  718. const REVISION = '124';
  719. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  720. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  721. const CullFaceNone = 0;
  722. const CullFaceBack = 1;
  723. const CullFaceFront = 2;
  724. const CullFaceFrontBack = 3;
  725. const BasicShadowMap = 0;
  726. const PCFShadowMap = 1;
  727. const PCFSoftShadowMap = 2;
  728. const VSMShadowMap = 3;
  729. const FrontSide = 0;
  730. const BackSide = 1;
  731. const DoubleSide = 2;
  732. const FlatShading = 1;
  733. const SmoothShading = 2;
  734. const NoBlending = 0;
  735. const NormalBlending = 1;
  736. const AdditiveBlending = 2;
  737. const SubtractiveBlending = 3;
  738. const MultiplyBlending = 4;
  739. const CustomBlending = 5;
  740. const AddEquation = 100;
  741. const SubtractEquation = 101;
  742. const ReverseSubtractEquation = 102;
  743. const MinEquation = 103;
  744. const MaxEquation = 104;
  745. const ZeroFactor = 200;
  746. const OneFactor = 201;
  747. const SrcColorFactor = 202;
  748. const OneMinusSrcColorFactor = 203;
  749. const SrcAlphaFactor = 204;
  750. const OneMinusSrcAlphaFactor = 205;
  751. const DstAlphaFactor = 206;
  752. const OneMinusDstAlphaFactor = 207;
  753. const DstColorFactor = 208;
  754. const OneMinusDstColorFactor = 209;
  755. const SrcAlphaSaturateFactor = 210;
  756. const NeverDepth = 0;
  757. const AlwaysDepth = 1;
  758. const LessDepth = 2;
  759. const LessEqualDepth = 3;
  760. const EqualDepth = 4;
  761. const GreaterEqualDepth = 5;
  762. const GreaterDepth = 6;
  763. const NotEqualDepth = 7;
  764. const MultiplyOperation = 0;
  765. const MixOperation = 1;
  766. const AddOperation = 2;
  767. const NoToneMapping = 0;
  768. const LinearToneMapping = 1;
  769. const ReinhardToneMapping = 2;
  770. const CineonToneMapping = 3;
  771. const ACESFilmicToneMapping = 4;
  772. const CustomToneMapping = 5;
  773. const UVMapping = 300;
  774. const CubeReflectionMapping = 301;
  775. const CubeRefractionMapping = 302;
  776. const EquirectangularReflectionMapping = 303;
  777. const EquirectangularRefractionMapping = 304;
  778. const CubeUVReflectionMapping = 306;
  779. const CubeUVRefractionMapping = 307;
  780. const RepeatWrapping = 1000;
  781. const ClampToEdgeWrapping = 1001;
  782. const MirroredRepeatWrapping = 1002;
  783. const NearestFilter = 1003;
  784. const NearestMipmapNearestFilter = 1004;
  785. const NearestMipMapNearestFilter = 1004;
  786. const NearestMipmapLinearFilter = 1005;
  787. const NearestMipMapLinearFilter = 1005;
  788. const LinearFilter = 1006;
  789. const LinearMipmapNearestFilter = 1007;
  790. const LinearMipMapNearestFilter = 1007;
  791. const LinearMipmapLinearFilter = 1008;
  792. const LinearMipMapLinearFilter = 1008;
  793. const UnsignedByteType = 1009;
  794. const ByteType = 1010;
  795. const ShortType = 1011;
  796. const UnsignedShortType = 1012;
  797. const IntType = 1013;
  798. const UnsignedIntType = 1014;
  799. const FloatType = 1015;
  800. const HalfFloatType = 1016;
  801. const UnsignedShort4444Type = 1017;
  802. const UnsignedShort5551Type = 1018;
  803. const UnsignedShort565Type = 1019;
  804. const UnsignedInt248Type$1 = 1020;
  805. const AlphaFormat = 1021;
  806. const RGBFormat = 1022;
  807. const RGBAFormat = 1023;
  808. const LuminanceFormat = 1024;
  809. const LuminanceAlphaFormat = 1025;
  810. const RGBEFormat = RGBAFormat;
  811. const DepthFormat = 1026;
  812. const DepthStencilFormat = 1027;
  813. const RedFormat = 1028;
  814. const RedIntegerFormat = 1029;
  815. const RGFormat = 1030;
  816. const RGIntegerFormat = 1031;
  817. const RGBIntegerFormat = 1032;
  818. const RGBAIntegerFormat = 1033;
  819. const RGB_S3TC_DXT1_Format = 33776;
  820. const RGBA_S3TC_DXT1_Format$1 = 33777;
  821. const RGBA_S3TC_DXT3_Format = 33778;
  822. const RGBA_S3TC_DXT5_Format$1 = 33779;
  823. const RGB_PVRTC_4BPPV1_Format = 35840;
  824. const RGB_PVRTC_2BPPV1_Format = 35841;
  825. const RGBA_PVRTC_4BPPV1_Format = 35842;
  826. const RGBA_PVRTC_2BPPV1_Format = 35843;
  827. const RGB_ETC1_Format = 36196;
  828. const RGB_ETC2_Format = 37492;
  829. const RGBA_ETC2_EAC_Format = 37496;
  830. const RGBA_ASTC_4x4_Format = 37808;
  831. const RGBA_ASTC_5x4_Format = 37809;
  832. const RGBA_ASTC_5x5_Format = 37810;
  833. const RGBA_ASTC_6x5_Format = 37811;
  834. const RGBA_ASTC_6x6_Format = 37812;
  835. const RGBA_ASTC_8x5_Format = 37813;
  836. const RGBA_ASTC_8x6_Format = 37814;
  837. const RGBA_ASTC_8x8_Format = 37815;
  838. const RGBA_ASTC_10x5_Format = 37816;
  839. const RGBA_ASTC_10x6_Format = 37817;
  840. const RGBA_ASTC_10x8_Format = 37818;
  841. const RGBA_ASTC_10x10_Format = 37819;
  842. const RGBA_ASTC_12x10_Format = 37820;
  843. const RGBA_ASTC_12x12_Format = 37821;
  844. const RGBA_BPTC_Format = 36492;
  845. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  846. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  847. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  848. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  849. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  850. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  851. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  852. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  853. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  854. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  855. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  856. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  857. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  858. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  859. const LoopOnce = 2200;
  860. const LoopRepeat = 2201;
  861. const LoopPingPong = 2202;
  862. const InterpolateDiscrete = 2300;
  863. const InterpolateLinear = 2301;
  864. const InterpolateSmooth = 2302;
  865. const ZeroCurvatureEnding = 2400;
  866. const ZeroSlopeEnding = 2401;
  867. const WrapAroundEnding = 2402;
  868. const NormalAnimationBlendMode = 2500;
  869. const AdditiveAnimationBlendMode = 2501;
  870. const TrianglesDrawMode = 0;
  871. const TriangleStripDrawMode = 1;
  872. const TriangleFanDrawMode = 2;
  873. const LinearEncoding = 3000;
  874. const sRGBEncoding = 3001;
  875. const GammaEncoding = 3007;
  876. const RGBEEncoding = 3002;
  877. const LogLuvEncoding = 3003;
  878. const RGBM7Encoding = 3004;
  879. const RGBM16Encoding = 3005;
  880. const RGBDEncoding = 3006;
  881. const BasicDepthPacking = 3200;
  882. const RGBADepthPacking = 3201;
  883. const TangentSpaceNormalMap = 0;
  884. const ObjectSpaceNormalMap = 1;
  885. const ZeroStencilOp = 0;
  886. const KeepStencilOp = 7680;
  887. const ReplaceStencilOp = 7681;
  888. const IncrementStencilOp = 7682;
  889. const DecrementStencilOp = 7683;
  890. const IncrementWrapStencilOp = 34055;
  891. const DecrementWrapStencilOp = 34056;
  892. const InvertStencilOp = 5386;
  893. const NeverStencilFunc = 512;
  894. const LessStencilFunc = 513;
  895. const EqualStencilFunc = 514;
  896. const LessEqualStencilFunc = 515;
  897. const GreaterStencilFunc = 516;
  898. const NotEqualStencilFunc = 517;
  899. const GreaterEqualStencilFunc = 518;
  900. const AlwaysStencilFunc = 519;
  901. const StaticDrawUsage = 35044;
  902. const DynamicDrawUsage = 35048;
  903. const StreamDrawUsage = 35040;
  904. const StaticReadUsage = 35045;
  905. const DynamicReadUsage = 35049;
  906. const StreamReadUsage = 35041;
  907. const StaticCopyUsage = 35046;
  908. const DynamicCopyUsage = 35050;
  909. const StreamCopyUsage = 35042;
  910. const GLSL1 = '100';
  911. const GLSL3 = '300 es';
  912. /**
  913. * https://github.com/mrdoob/eventdispatcher.js/
  914. */
  915. function EventDispatcher() {}
  916. Object.assign( EventDispatcher.prototype, {
  917. addEventListener: function ( type, listener, importance=0 ) {//add importance
  918. if ( this._listeners === undefined ) this._listeners = {};
  919. const listeners = this._listeners;
  920. if ( listeners[ type ] === undefined ) {
  921. listeners[ type ] = [];
  922. }
  923. if ( !listeners[ type ].some(e=>e.listener == listener ) ) {
  924. //listeners[ type ].push( listener );
  925. listeners[type].push({ listener, importance});
  926. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  927. }
  928. },
  929. hasEventListener: function ( type, listener ) {
  930. if ( this._listeners === undefined ) return false;
  931. const listeners = this._listeners;
  932. return listeners[ type ] !== undefined && listeners[ type ].some(e=>e.listener == listener )
  933. },
  934. removeEventListener: function ( type, listener ) {
  935. if ( this._listeners === undefined ) return;
  936. const listeners = this._listeners;
  937. const listenerArray = listeners[ type ];
  938. if ( listenerArray !== undefined ) {
  939. /* const index = listenerArray.indexOf( listener );
  940. if ( index !== - 1 ) {
  941. listenerArray.splice( index, 1 );
  942. } */
  943. let item = listenerArray.find(e=>e.listener == listener);
  944. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  945. }
  946. },
  947. removeEventListeners(type){//add
  948. if(this._listeners && this._listeners[type] !== undefined){
  949. delete this._listeners[type];
  950. }
  951. } ,
  952. removeAllListeners(){ //add
  953. this._listeners = {};
  954. },
  955. dispatchEvent: function ( event ) {
  956. if(typeof event == 'string'){//add
  957. event = {type:event};
  958. }
  959. if ( this._listeners === undefined ) return;
  960. const listeners = this._listeners;
  961. const listenerArray = listeners[ event.type ];
  962. if ( listenerArray !== undefined ) {
  963. event.target = this;
  964. // Make a copy, in case listeners are removed while iterating.
  965. for(let {listener} of listenerArray.slice(0)){
  966. let result = listener.call(this, event); //add stopContinue
  967. if(result && result.stopContinue){
  968. break
  969. }
  970. }
  971. }
  972. }
  973. } );
  974. const _lut = [];
  975. for ( let i = 0; i < 256; i ++ ) {
  976. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  977. }
  978. let _seed = 1234567;
  979. const MathUtils = {
  980. DEG2RAD: Math.PI / 180,
  981. RAD2DEG: 180 / Math.PI,
  982. generateUUID: function () {
  983. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  984. const d0 = Math.random() * 0xffffffff | 0;
  985. const d1 = Math.random() * 0xffffffff | 0;
  986. const d2 = Math.random() * 0xffffffff | 0;
  987. const d3 = Math.random() * 0xffffffff | 0;
  988. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  989. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  990. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  991. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  992. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  993. return uuid.toUpperCase();
  994. },
  995. clamp: function ( value, min, max ) {
  996. return Math.max( min, Math.min( max, value ) );
  997. },
  998. // compute euclidian modulo of m % n
  999. // https://en.wikipedia.org/wiki/Modulo_operation
  1000. euclideanModulo: function ( n, m ) {
  1001. return ( ( n % m ) + m ) % m;
  1002. },
  1003. // Linear mapping from range <a1, a2> to range <b1, b2>
  1004. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1005. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1006. },
  1007. // https://en.wikipedia.org/wiki/Linear_interpolation
  1008. lerp: function ( x, y, t ) {
  1009. return ( 1 - t ) * x + t * y;
  1010. },
  1011. // http://en.wikipedia.org/wiki/Smoothstep
  1012. smoothstep: function ( x, min, max ) {
  1013. if ( x <= min ) return 0;
  1014. if ( x >= max ) return 1;
  1015. x = ( x - min ) / ( max - min );
  1016. return x * x * ( 3 - 2 * x );
  1017. },
  1018. smootherstep: function ( x, min, max ) {
  1019. if ( x <= min ) return 0;
  1020. if ( x >= max ) return 1;
  1021. x = ( x - min ) / ( max - min );
  1022. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1023. },
  1024. // Random integer from <low, high> interval
  1025. randInt: function ( low, high ) {
  1026. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1027. },
  1028. // Random float from <low, high> interval
  1029. randFloat: function ( low, high ) {
  1030. return low + Math.random() * ( high - low );
  1031. },
  1032. // Random float from <-range/2, range/2> interval
  1033. randFloatSpread: function ( range ) {
  1034. return range * ( 0.5 - Math.random() );
  1035. },
  1036. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  1037. seededRandom: function ( s ) {
  1038. if ( s !== undefined ) _seed = s % 2147483647;
  1039. // Park-Miller algorithm
  1040. _seed = _seed * 16807 % 2147483647;
  1041. return ( _seed - 1 ) / 2147483646;
  1042. },
  1043. degToRad: function ( degrees ) {
  1044. return degrees * MathUtils.DEG2RAD;
  1045. },
  1046. radToDeg: function ( radians ) {
  1047. return radians * MathUtils.RAD2DEG;
  1048. },
  1049. isPowerOfTwo: function ( value ) {
  1050. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1051. },
  1052. ceilPowerOfTwo: function ( value ) {
  1053. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1054. },
  1055. floorPowerOfTwo: function ( value ) {
  1056. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1057. },
  1058. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  1059. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  1060. // rotations are applied to the axes in the order specified by 'order'
  1061. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  1062. // angles are in radians
  1063. const cos = Math.cos;
  1064. const sin = Math.sin;
  1065. const c2 = cos( b / 2 );
  1066. const s2 = sin( b / 2 );
  1067. const c13 = cos( ( a + c ) / 2 );
  1068. const s13 = sin( ( a + c ) / 2 );
  1069. const c1_3 = cos( ( a - c ) / 2 );
  1070. const s1_3 = sin( ( a - c ) / 2 );
  1071. const c3_1 = cos( ( c - a ) / 2 );
  1072. const s3_1 = sin( ( c - a ) / 2 );
  1073. switch ( order ) {
  1074. case 'XYX':
  1075. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1076. break;
  1077. case 'YZY':
  1078. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1079. break;
  1080. case 'ZXZ':
  1081. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1082. break;
  1083. case 'XZX':
  1084. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1085. break;
  1086. case 'YXY':
  1087. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1088. break;
  1089. case 'ZYZ':
  1090. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1091. break;
  1092. default:
  1093. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1094. }
  1095. }
  1096. };
  1097. class Vector2$1 {
  1098. constructor( x = 0, y = 0 ) {
  1099. Object.defineProperty( this, 'isVector2', { value: true } );
  1100. this.x = x;
  1101. this.y = y;
  1102. }
  1103. get width() {
  1104. return this.x;
  1105. }
  1106. set width( value ) {
  1107. this.x = value;
  1108. }
  1109. get height() {
  1110. return this.y;
  1111. }
  1112. set height( value ) {
  1113. this.y = value;
  1114. }
  1115. set( x, y ) {
  1116. this.x = x;
  1117. this.y = y;
  1118. return this;
  1119. }
  1120. setScalar( scalar ) {
  1121. this.x = scalar;
  1122. this.y = scalar;
  1123. return this;
  1124. }
  1125. setX( x ) {
  1126. this.x = x;
  1127. return this;
  1128. }
  1129. setY( y ) {
  1130. this.y = y;
  1131. return this;
  1132. }
  1133. setComponent( index, value ) {
  1134. switch ( index ) {
  1135. case 0: this.x = value; break;
  1136. case 1: this.y = value; break;
  1137. default: throw new Error( 'index is out of range: ' + index );
  1138. }
  1139. return this;
  1140. }
  1141. getComponent( index ) {
  1142. switch ( index ) {
  1143. case 0: return this.x;
  1144. case 1: return this.y;
  1145. default: throw new Error( 'index is out of range: ' + index );
  1146. }
  1147. }
  1148. clone() {
  1149. return new this.constructor( this.x, this.y );
  1150. }
  1151. copy( v ) {
  1152. this.x = v.x;
  1153. this.y = v.y;
  1154. return this;
  1155. }
  1156. add( v, w ) {
  1157. if ( w !== undefined ) {
  1158. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1159. return this.addVectors( v, w );
  1160. }
  1161. this.x += v.x;
  1162. this.y += v.y;
  1163. return this;
  1164. }
  1165. addScalar( s ) {
  1166. this.x += s;
  1167. this.y += s;
  1168. return this;
  1169. }
  1170. addVectors( a, b ) {
  1171. this.x = a.x + b.x;
  1172. this.y = a.y + b.y;
  1173. return this;
  1174. }
  1175. addScaledVector( v, s ) {
  1176. this.x += v.x * s;
  1177. this.y += v.y * s;
  1178. return this;
  1179. }
  1180. sub( v, w ) {
  1181. if ( w !== undefined ) {
  1182. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1183. return this.subVectors( v, w );
  1184. }
  1185. this.x -= v.x;
  1186. this.y -= v.y;
  1187. return this;
  1188. }
  1189. subScalar( s ) {
  1190. this.x -= s;
  1191. this.y -= s;
  1192. return this;
  1193. }
  1194. subVectors( a, b ) {
  1195. this.x = a.x - b.x;
  1196. this.y = a.y - b.y;
  1197. return this;
  1198. }
  1199. multiply( v ) {
  1200. this.x *= v.x;
  1201. this.y *= v.y;
  1202. return this;
  1203. }
  1204. multiplyScalar( scalar ) {
  1205. this.x *= scalar;
  1206. this.y *= scalar;
  1207. return this;
  1208. }
  1209. divide( v ) {
  1210. this.x /= v.x;
  1211. this.y /= v.y;
  1212. return this;
  1213. }
  1214. divideScalar( scalar ) {
  1215. return this.multiplyScalar( 1 / scalar );
  1216. }
  1217. applyMatrix3( m ) {
  1218. const x = this.x, y = this.y;
  1219. const e = m.elements;
  1220. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  1221. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  1222. return this;
  1223. }
  1224. min( v ) {
  1225. this.x = Math.min( this.x, v.x );
  1226. this.y = Math.min( this.y, v.y );
  1227. return this;
  1228. }
  1229. max( v ) {
  1230. this.x = Math.max( this.x, v.x );
  1231. this.y = Math.max( this.y, v.y );
  1232. return this;
  1233. }
  1234. clamp( min, max ) {
  1235. // assumes min < max, componentwise
  1236. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1237. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1238. return this;
  1239. }
  1240. clampScalar( minVal, maxVal ) {
  1241. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1242. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1243. return this;
  1244. }
  1245. clampLength( min, max ) {
  1246. const length = this.length();
  1247. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1248. }
  1249. floor() {
  1250. this.x = Math.floor( this.x );
  1251. this.y = Math.floor( this.y );
  1252. return this;
  1253. }
  1254. ceil() {
  1255. this.x = Math.ceil( this.x );
  1256. this.y = Math.ceil( this.y );
  1257. return this;
  1258. }
  1259. round() {
  1260. this.x = Math.round( this.x );
  1261. this.y = Math.round( this.y );
  1262. return this;
  1263. }
  1264. roundToZero() {
  1265. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1266. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1267. return this;
  1268. }
  1269. negate() {
  1270. this.x = - this.x;
  1271. this.y = - this.y;
  1272. return this;
  1273. }
  1274. dot( v ) {
  1275. return this.x * v.x + this.y * v.y;
  1276. }
  1277. cross( v ) {
  1278. return this.x * v.y - this.y * v.x;
  1279. }
  1280. lengthSq() {
  1281. return this.x * this.x + this.y * this.y;
  1282. }
  1283. length() {
  1284. return Math.sqrt( this.x * this.x + this.y * this.y );
  1285. }
  1286. manhattanLength() {
  1287. return Math.abs( this.x ) + Math.abs( this.y );
  1288. }
  1289. normalize() {
  1290. return this.divideScalar( this.length() || 1 );
  1291. }
  1292. angle() {
  1293. // computes the angle in radians with respect to the positive x-axis
  1294. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1295. return angle;
  1296. }
  1297. distanceTo( v ) {
  1298. return Math.sqrt( this.distanceToSquared( v ) );
  1299. }
  1300. distanceToSquared( v ) {
  1301. const dx = this.x - v.x, dy = this.y - v.y;
  1302. return dx * dx + dy * dy;
  1303. }
  1304. manhattanDistanceTo( v ) {
  1305. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1306. }
  1307. setLength( length ) {
  1308. return this.normalize().multiplyScalar( length );
  1309. }
  1310. lerp( v, alpha ) {
  1311. this.x += ( v.x - this.x ) * alpha;
  1312. this.y += ( v.y - this.y ) * alpha;
  1313. return this;
  1314. }
  1315. lerpVectors( v1, v2, alpha ) {
  1316. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1317. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1318. return this;
  1319. }
  1320. equals( v ) {
  1321. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1322. }
  1323. fromArray( array, offset = 0 ) {
  1324. this.x = array[ offset ];
  1325. this.y = array[ offset + 1 ];
  1326. return this;
  1327. }
  1328. toArray( array = [], offset = 0 ) {
  1329. array[ offset ] = this.x;
  1330. array[ offset + 1 ] = this.y;
  1331. return array;
  1332. }
  1333. fromBufferAttribute( attribute, index, offset ) {
  1334. if ( offset !== undefined ) {
  1335. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  1336. }
  1337. this.x = attribute.getX( index );
  1338. this.y = attribute.getY( index );
  1339. return this;
  1340. }
  1341. rotateAround( center, angle ) {
  1342. const c = Math.cos( angle ), s = Math.sin( angle );
  1343. const x = this.x - center.x;
  1344. const y = this.y - center.y;
  1345. this.x = x * c - y * s + center.x;
  1346. this.y = x * s + y * c + center.y;
  1347. return this;
  1348. }
  1349. random() {
  1350. this.x = Math.random();
  1351. this.y = Math.random();
  1352. return this;
  1353. }
  1354. }
  1355. class Matrix3 {
  1356. constructor() {
  1357. Object.defineProperty( this, 'isMatrix3', { value: true } );
  1358. this.elements = [
  1359. 1, 0, 0,
  1360. 0, 1, 0,
  1361. 0, 0, 1
  1362. ];
  1363. if ( arguments.length > 0 ) {
  1364. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  1365. }
  1366. }
  1367. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1368. const te = this.elements;
  1369. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1370. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1371. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1372. return this;
  1373. }
  1374. identity() {
  1375. this.set(
  1376. 1, 0, 0,
  1377. 0, 1, 0,
  1378. 0, 0, 1
  1379. );
  1380. return this;
  1381. }
  1382. clone() {
  1383. return new this.constructor().fromArray( this.elements );
  1384. }
  1385. copy( m ) {
  1386. const te = this.elements;
  1387. const me = m.elements;
  1388. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1389. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1390. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1391. return this;
  1392. }
  1393. extractBasis( xAxis, yAxis, zAxis ) {
  1394. xAxis.setFromMatrix3Column( this, 0 );
  1395. yAxis.setFromMatrix3Column( this, 1 );
  1396. zAxis.setFromMatrix3Column( this, 2 );
  1397. return this;
  1398. }
  1399. setFromMatrix4( m ) {
  1400. const me = m.elements;
  1401. this.set(
  1402. me[ 0 ], me[ 4 ], me[ 8 ],
  1403. me[ 1 ], me[ 5 ], me[ 9 ],
  1404. me[ 2 ], me[ 6 ], me[ 10 ]
  1405. );
  1406. return this;
  1407. }
  1408. multiply( m ) {
  1409. return this.multiplyMatrices( this, m );
  1410. }
  1411. premultiply( m ) {
  1412. return this.multiplyMatrices( m, this );
  1413. }
  1414. multiplyMatrices( a, b ) {
  1415. const ae = a.elements;
  1416. const be = b.elements;
  1417. const te = this.elements;
  1418. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1419. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1420. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1421. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1422. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1423. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1424. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1425. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1426. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1427. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1428. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1429. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1430. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1431. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1432. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1433. return this;
  1434. }
  1435. multiplyScalar( s ) {
  1436. const te = this.elements;
  1437. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1438. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1439. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1440. return this;
  1441. }
  1442. determinant() {
  1443. const te = this.elements;
  1444. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1445. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1446. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1447. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1448. }
  1449. invert() {
  1450. const te = this.elements,
  1451. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1452. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1453. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1454. t11 = n33 * n22 - n32 * n23,
  1455. t12 = n32 * n13 - n33 * n12,
  1456. t13 = n23 * n12 - n22 * n13,
  1457. det = n11 * t11 + n21 * t12 + n31 * t13;
  1458. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1459. const detInv = 1 / det;
  1460. te[ 0 ] = t11 * detInv;
  1461. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1462. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1463. te[ 3 ] = t12 * detInv;
  1464. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1465. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1466. te[ 6 ] = t13 * detInv;
  1467. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1468. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1469. return this;
  1470. }
  1471. transpose() {
  1472. let tmp;
  1473. const m = this.elements;
  1474. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1475. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1476. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1477. return this;
  1478. }
  1479. getNormalMatrix( matrix4 ) {
  1480. return this.setFromMatrix4( matrix4 ).copy( this ).invert().transpose();
  1481. }
  1482. transposeIntoArray( r ) {
  1483. const m = this.elements;
  1484. r[ 0 ] = m[ 0 ];
  1485. r[ 1 ] = m[ 3 ];
  1486. r[ 2 ] = m[ 6 ];
  1487. r[ 3 ] = m[ 1 ];
  1488. r[ 4 ] = m[ 4 ];
  1489. r[ 5 ] = m[ 7 ];
  1490. r[ 6 ] = m[ 2 ];
  1491. r[ 7 ] = m[ 5 ];
  1492. r[ 8 ] = m[ 8 ];
  1493. return this;
  1494. }
  1495. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1496. const c = Math.cos( rotation );
  1497. const s = Math.sin( rotation );
  1498. this.set(
  1499. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1500. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1501. 0, 0, 1
  1502. );
  1503. return this;
  1504. }
  1505. scale( sx, sy ) {
  1506. const te = this.elements;
  1507. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  1508. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  1509. return this;
  1510. }
  1511. rotate( theta ) {
  1512. const c = Math.cos( theta );
  1513. const s = Math.sin( theta );
  1514. const te = this.elements;
  1515. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  1516. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  1517. te[ 0 ] = c * a11 + s * a21;
  1518. te[ 3 ] = c * a12 + s * a22;
  1519. te[ 6 ] = c * a13 + s * a23;
  1520. te[ 1 ] = - s * a11 + c * a21;
  1521. te[ 4 ] = - s * a12 + c * a22;
  1522. te[ 7 ] = - s * a13 + c * a23;
  1523. return this;
  1524. }
  1525. translate( tx, ty ) {
  1526. const te = this.elements;
  1527. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  1528. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  1529. return this;
  1530. }
  1531. equals( matrix ) {
  1532. const te = this.elements;
  1533. const me = matrix.elements;
  1534. for ( let i = 0; i < 9; i ++ ) {
  1535. if ( te[ i ] !== me[ i ] ) return false;
  1536. }
  1537. return true;
  1538. }
  1539. fromArray( array, offset = 0 ) {
  1540. for ( let i = 0; i < 9; i ++ ) {
  1541. this.elements[ i ] = array[ i + offset ];
  1542. }
  1543. return this;
  1544. }
  1545. toArray( array = [], offset = 0 ) {
  1546. const te = this.elements;
  1547. array[ offset ] = te[ 0 ];
  1548. array[ offset + 1 ] = te[ 1 ];
  1549. array[ offset + 2 ] = te[ 2 ];
  1550. array[ offset + 3 ] = te[ 3 ];
  1551. array[ offset + 4 ] = te[ 4 ];
  1552. array[ offset + 5 ] = te[ 5 ];
  1553. array[ offset + 6 ] = te[ 6 ];
  1554. array[ offset + 7 ] = te[ 7 ];
  1555. array[ offset + 8 ] = te[ 8 ];
  1556. return array;
  1557. }
  1558. }
  1559. let _canvas;
  1560. const ImageUtils = {
  1561. getDataURL: function ( image ) {
  1562. if ( /^data:/i.test( image.src ) ) {
  1563. return image.src;
  1564. }
  1565. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1566. return image.src;
  1567. }
  1568. let canvas;
  1569. if ( image instanceof HTMLCanvasElement ) {
  1570. canvas = image;
  1571. } else {
  1572. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  1573. _canvas.width = image.width;
  1574. _canvas.height = image.height;
  1575. const context = _canvas.getContext( '2d' );
  1576. if ( image instanceof ImageData ) {
  1577. context.putImageData( image, 0, 0 );
  1578. } else {
  1579. context.drawImage( image, 0, 0, image.width, image.height );
  1580. }
  1581. canvas = _canvas;
  1582. }
  1583. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1584. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1585. } else {
  1586. return canvas.toDataURL( 'image/png' );
  1587. }
  1588. }
  1589. };
  1590. let textureId = 0;
  1591. function Texture( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {
  1592. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1593. this.uuid = MathUtils.generateUUID();
  1594. this.name = '';
  1595. this.image = image;
  1596. this.mipmaps = [];
  1597. this.mapping = mapping;
  1598. this.wrapS = wrapS;
  1599. this.wrapT = wrapT;
  1600. this.magFilter = magFilter;
  1601. this.minFilter = minFilter;
  1602. this.anisotropy = anisotropy;
  1603. this.format = format;
  1604. this.internalFormat = null;
  1605. this.type = type;
  1606. this.offset = new Vector2$1( 0, 0 );
  1607. this.repeat = new Vector2$1( 1, 1 );
  1608. this.center = new Vector2$1( 0, 0 );
  1609. this.rotation = 0;
  1610. this.matrixAutoUpdate = true;
  1611. this.matrix = new Matrix3();
  1612. this.generateMipmaps = true;
  1613. this.premultiplyAlpha = false;
  1614. this.flipY = true;
  1615. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1616. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1617. //
  1618. // Also changing the encoding after already used by a Material will not automatically make the Material
  1619. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1620. this.encoding = encoding;
  1621. this.version = 0;
  1622. this.onUpdate = null;
  1623. }
  1624. Texture.DEFAULT_IMAGE = undefined;
  1625. Texture.DEFAULT_MAPPING = UVMapping;
  1626. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  1627. constructor: Texture,
  1628. isTexture: true,
  1629. updateMatrix: function () {
  1630. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1631. },
  1632. clone: function () {
  1633. return new this.constructor().copy( this );
  1634. },
  1635. copy: function ( source ) {
  1636. this.name = source.name;
  1637. this.image = source.image;
  1638. this.mipmaps = source.mipmaps.slice( 0 );
  1639. this.mapping = source.mapping;
  1640. this.wrapS = source.wrapS;
  1641. this.wrapT = source.wrapT;
  1642. this.magFilter = source.magFilter;
  1643. this.minFilter = source.minFilter;
  1644. this.anisotropy = source.anisotropy;
  1645. this.format = source.format;
  1646. this.internalFormat = source.internalFormat;
  1647. this.type = source.type;
  1648. this.offset.copy( source.offset );
  1649. this.repeat.copy( source.repeat );
  1650. this.center.copy( source.center );
  1651. this.rotation = source.rotation;
  1652. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1653. this.matrix.copy( source.matrix );
  1654. this.generateMipmaps = source.generateMipmaps;
  1655. this.premultiplyAlpha = source.premultiplyAlpha;
  1656. this.flipY = source.flipY;
  1657. this.unpackAlignment = source.unpackAlignment;
  1658. this.encoding = source.encoding;
  1659. return this;
  1660. },
  1661. toJSON: function ( meta ) {
  1662. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1663. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1664. return meta.textures[ this.uuid ];
  1665. }
  1666. const output = {
  1667. metadata: {
  1668. version: 4.5,
  1669. type: 'Texture',
  1670. generator: 'Texture.toJSON'
  1671. },
  1672. uuid: this.uuid,
  1673. name: this.name,
  1674. mapping: this.mapping,
  1675. repeat: [ this.repeat.x, this.repeat.y ],
  1676. offset: [ this.offset.x, this.offset.y ],
  1677. center: [ this.center.x, this.center.y ],
  1678. rotation: this.rotation,
  1679. wrap: [ this.wrapS, this.wrapT ],
  1680. format: this.format,
  1681. type: this.type,
  1682. encoding: this.encoding,
  1683. minFilter: this.minFilter,
  1684. magFilter: this.magFilter,
  1685. anisotropy: this.anisotropy,
  1686. flipY: this.flipY,
  1687. premultiplyAlpha: this.premultiplyAlpha,
  1688. unpackAlignment: this.unpackAlignment
  1689. };
  1690. if ( this.image !== undefined ) {
  1691. // TODO: Move to THREE.Image
  1692. const image = this.image;
  1693. if ( image.uuid === undefined ) {
  1694. image.uuid = MathUtils.generateUUID(); // UGH
  1695. }
  1696. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1697. let url;
  1698. if ( Array.isArray( image ) ) {
  1699. // process array of images e.g. CubeTexture
  1700. url = [];
  1701. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1702. // check cube texture with data textures
  1703. if ( image[ i ].isDataTexture ) {
  1704. url.push( serializeImage( image[ i ].image ) );
  1705. } else {
  1706. url.push( serializeImage( image[ i ] ) );
  1707. }
  1708. }
  1709. } else {
  1710. // process single image
  1711. url = serializeImage( image );
  1712. }
  1713. meta.images[ image.uuid ] = {
  1714. uuid: image.uuid,
  1715. url: url
  1716. };
  1717. }
  1718. output.image = image.uuid;
  1719. }
  1720. if ( ! isRootObject ) {
  1721. meta.textures[ this.uuid ] = output;
  1722. }
  1723. return output;
  1724. },
  1725. dispose: function () {
  1726. this.dispatchEvent( { type: 'dispose' } );
  1727. },
  1728. transformUv: function ( uv ) {
  1729. if ( this.mapping !== UVMapping ) return uv;
  1730. uv.applyMatrix3( this.matrix );
  1731. if ( uv.x < 0 || uv.x > 1 ) {
  1732. switch ( this.wrapS ) {
  1733. case RepeatWrapping:
  1734. uv.x = uv.x - Math.floor( uv.x );
  1735. break;
  1736. case ClampToEdgeWrapping:
  1737. uv.x = uv.x < 0 ? 0 : 1;
  1738. break;
  1739. case MirroredRepeatWrapping:
  1740. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1741. uv.x = Math.ceil( uv.x ) - uv.x;
  1742. } else {
  1743. uv.x = uv.x - Math.floor( uv.x );
  1744. }
  1745. break;
  1746. }
  1747. }
  1748. if ( uv.y < 0 || uv.y > 1 ) {
  1749. switch ( this.wrapT ) {
  1750. case RepeatWrapping:
  1751. uv.y = uv.y - Math.floor( uv.y );
  1752. break;
  1753. case ClampToEdgeWrapping:
  1754. uv.y = uv.y < 0 ? 0 : 1;
  1755. break;
  1756. case MirroredRepeatWrapping:
  1757. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1758. uv.y = Math.ceil( uv.y ) - uv.y;
  1759. } else {
  1760. uv.y = uv.y - Math.floor( uv.y );
  1761. }
  1762. break;
  1763. }
  1764. }
  1765. if ( this.flipY ) {
  1766. uv.y = 1 - uv.y;
  1767. }
  1768. return uv;
  1769. }
  1770. } );
  1771. Object.defineProperty( Texture.prototype, 'needsUpdate', {
  1772. set: function ( value ) {
  1773. if ( value === true ) this.version ++;
  1774. }
  1775. } );
  1776. function serializeImage( image ) {
  1777. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1778. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1779. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1780. // default images
  1781. return ImageUtils.getDataURL( image );
  1782. } else {
  1783. if ( image.data ) {
  1784. // images of DataTexture
  1785. return {
  1786. data: Array.prototype.slice.call( image.data ),
  1787. width: image.width,
  1788. height: image.height,
  1789. type: image.data.constructor.name
  1790. };
  1791. } else {
  1792. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1793. return {};
  1794. }
  1795. }
  1796. }
  1797. class Vector4 {
  1798. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1799. Object.defineProperty( this, 'isVector4', { value: true } );
  1800. this.x = x;
  1801. this.y = y;
  1802. this.z = z;
  1803. this.w = w;
  1804. }
  1805. get width() {
  1806. return this.z;
  1807. }
  1808. set width( value ) {
  1809. this.z = value;
  1810. }
  1811. get height() {
  1812. return this.w;
  1813. }
  1814. set height( value ) {
  1815. this.w = value;
  1816. }
  1817. set( x, y, z, w ) {
  1818. this.x = x;
  1819. this.y = y;
  1820. this.z = z;
  1821. this.w = w;
  1822. return this;
  1823. }
  1824. setScalar( scalar ) {
  1825. this.x = scalar;
  1826. this.y = scalar;
  1827. this.z = scalar;
  1828. this.w = scalar;
  1829. return this;
  1830. }
  1831. setX( x ) {
  1832. this.x = x;
  1833. return this;
  1834. }
  1835. setY( y ) {
  1836. this.y = y;
  1837. return this;
  1838. }
  1839. setZ( z ) {
  1840. this.z = z;
  1841. return this;
  1842. }
  1843. setW( w ) {
  1844. this.w = w;
  1845. return this;
  1846. }
  1847. setComponent( index, value ) {
  1848. switch ( index ) {
  1849. case 0: this.x = value; break;
  1850. case 1: this.y = value; break;
  1851. case 2: this.z = value; break;
  1852. case 3: this.w = value; break;
  1853. default: throw new Error( 'index is out of range: ' + index );
  1854. }
  1855. return this;
  1856. }
  1857. getComponent( index ) {
  1858. switch ( index ) {
  1859. case 0: return this.x;
  1860. case 1: return this.y;
  1861. case 2: return this.z;
  1862. case 3: return this.w;
  1863. default: throw new Error( 'index is out of range: ' + index );
  1864. }
  1865. }
  1866. clone() {
  1867. return new this.constructor( this.x, this.y, this.z, this.w );
  1868. }
  1869. copy( v ) {
  1870. this.x = v.x;
  1871. this.y = v.y;
  1872. this.z = v.z;
  1873. this.w = ( v.w !== undefined ) ? v.w : 1;
  1874. return this;
  1875. }
  1876. add( v, w ) {
  1877. if ( w !== undefined ) {
  1878. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1879. return this.addVectors( v, w );
  1880. }
  1881. this.x += v.x;
  1882. this.y += v.y;
  1883. this.z += v.z;
  1884. this.w += v.w;
  1885. return this;
  1886. }
  1887. addScalar( s ) {
  1888. this.x += s;
  1889. this.y += s;
  1890. this.z += s;
  1891. this.w += s;
  1892. return this;
  1893. }
  1894. addVectors( a, b ) {
  1895. this.x = a.x + b.x;
  1896. this.y = a.y + b.y;
  1897. this.z = a.z + b.z;
  1898. this.w = a.w + b.w;
  1899. return this;
  1900. }
  1901. addScaledVector( v, s ) {
  1902. this.x += v.x * s;
  1903. this.y += v.y * s;
  1904. this.z += v.z * s;
  1905. this.w += v.w * s;
  1906. return this;
  1907. }
  1908. sub( v, w ) {
  1909. if ( w !== undefined ) {
  1910. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1911. return this.subVectors( v, w );
  1912. }
  1913. this.x -= v.x;
  1914. this.y -= v.y;
  1915. this.z -= v.z;
  1916. this.w -= v.w;
  1917. return this;
  1918. }
  1919. subScalar( s ) {
  1920. this.x -= s;
  1921. this.y -= s;
  1922. this.z -= s;
  1923. this.w -= s;
  1924. return this;
  1925. }
  1926. subVectors( a, b ) {
  1927. this.x = a.x - b.x;
  1928. this.y = a.y - b.y;
  1929. this.z = a.z - b.z;
  1930. this.w = a.w - b.w;
  1931. return this;
  1932. }
  1933. multiplyScalar( scalar ) {
  1934. this.x *= scalar;
  1935. this.y *= scalar;
  1936. this.z *= scalar;
  1937. this.w *= scalar;
  1938. return this;
  1939. }
  1940. applyMatrix4( m ) {
  1941. const x = this.x, y = this.y, z = this.z, w = this.w;
  1942. const e = m.elements;
  1943. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1944. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1945. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1946. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1947. return this;
  1948. }
  1949. divideScalar( scalar ) {
  1950. return this.multiplyScalar( 1 / scalar );
  1951. }
  1952. setAxisAngleFromQuaternion( q ) {
  1953. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1954. // q is assumed to be normalized
  1955. this.w = 2 * Math.acos( q.w );
  1956. const s = Math.sqrt( 1 - q.w * q.w );
  1957. if ( s < 0.0001 ) {
  1958. this.x = 1;
  1959. this.y = 0;
  1960. this.z = 0;
  1961. } else {
  1962. this.x = q.x / s;
  1963. this.y = q.y / s;
  1964. this.z = q.z / s;
  1965. }
  1966. return this;
  1967. }
  1968. setAxisAngleFromRotationMatrix( m ) {
  1969. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1970. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1971. let angle, x, y, z; // variables for result
  1972. const epsilon = 0.01, // margin to allow for rounding errors
  1973. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1974. te = m.elements,
  1975. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1976. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1977. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1978. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1979. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1980. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1981. // singularity found
  1982. // first check for identity matrix which must have +1 for all terms
  1983. // in leading diagonal and zero in other terms
  1984. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1985. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1986. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1987. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1988. // this singularity is identity matrix so angle = 0
  1989. this.set( 1, 0, 0, 0 );
  1990. return this; // zero angle, arbitrary axis
  1991. }
  1992. // otherwise this singularity is angle = 180
  1993. angle = Math.PI;
  1994. const xx = ( m11 + 1 ) / 2;
  1995. const yy = ( m22 + 1 ) / 2;
  1996. const zz = ( m33 + 1 ) / 2;
  1997. const xy = ( m12 + m21 ) / 4;
  1998. const xz = ( m13 + m31 ) / 4;
  1999. const yz = ( m23 + m32 ) / 4;
  2000. if ( ( xx > yy ) && ( xx > zz ) ) {
  2001. // m11 is the largest diagonal term
  2002. if ( xx < epsilon ) {
  2003. x = 0;
  2004. y = 0.707106781;
  2005. z = 0.707106781;
  2006. } else {
  2007. x = Math.sqrt( xx );
  2008. y = xy / x;
  2009. z = xz / x;
  2010. }
  2011. } else if ( yy > zz ) {
  2012. // m22 is the largest diagonal term
  2013. if ( yy < epsilon ) {
  2014. x = 0.707106781;
  2015. y = 0;
  2016. z = 0.707106781;
  2017. } else {
  2018. y = Math.sqrt( yy );
  2019. x = xy / y;
  2020. z = yz / y;
  2021. }
  2022. } else {
  2023. // m33 is the largest diagonal term so base result on this
  2024. if ( zz < epsilon ) {
  2025. x = 0.707106781;
  2026. y = 0.707106781;
  2027. z = 0;
  2028. } else {
  2029. z = Math.sqrt( zz );
  2030. x = xz / z;
  2031. y = yz / z;
  2032. }
  2033. }
  2034. this.set( x, y, z, angle );
  2035. return this; // return 180 deg rotation
  2036. }
  2037. // as we have reached here there are no singularities so we can handle normally
  2038. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2039. ( m13 - m31 ) * ( m13 - m31 ) +
  2040. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2041. if ( Math.abs( s ) < 0.001 ) s = 1;
  2042. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2043. // caught by singularity test above, but I've left it in just in case
  2044. this.x = ( m32 - m23 ) / s;
  2045. this.y = ( m13 - m31 ) / s;
  2046. this.z = ( m21 - m12 ) / s;
  2047. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2048. return this;
  2049. }
  2050. min( v ) {
  2051. this.x = Math.min( this.x, v.x );
  2052. this.y = Math.min( this.y, v.y );
  2053. this.z = Math.min( this.z, v.z );
  2054. this.w = Math.min( this.w, v.w );
  2055. return this;
  2056. }
  2057. max( v ) {
  2058. this.x = Math.max( this.x, v.x );
  2059. this.y = Math.max( this.y, v.y );
  2060. this.z = Math.max( this.z, v.z );
  2061. this.w = Math.max( this.w, v.w );
  2062. return this;
  2063. }
  2064. clamp( min, max ) {
  2065. // assumes min < max, componentwise
  2066. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2067. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2068. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2069. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2070. return this;
  2071. }
  2072. clampScalar( minVal, maxVal ) {
  2073. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2074. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2075. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2076. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2077. return this;
  2078. }
  2079. clampLength( min, max ) {
  2080. const length = this.length();
  2081. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2082. }
  2083. floor() {
  2084. this.x = Math.floor( this.x );
  2085. this.y = Math.floor( this.y );
  2086. this.z = Math.floor( this.z );
  2087. this.w = Math.floor( this.w );
  2088. return this;
  2089. }
  2090. ceil() {
  2091. this.x = Math.ceil( this.x );
  2092. this.y = Math.ceil( this.y );
  2093. this.z = Math.ceil( this.z );
  2094. this.w = Math.ceil( this.w );
  2095. return this;
  2096. }
  2097. round() {
  2098. this.x = Math.round( this.x );
  2099. this.y = Math.round( this.y );
  2100. this.z = Math.round( this.z );
  2101. this.w = Math.round( this.w );
  2102. return this;
  2103. }
  2104. roundToZero() {
  2105. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2106. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2107. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2108. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2109. return this;
  2110. }
  2111. negate() {
  2112. this.x = - this.x;
  2113. this.y = - this.y;
  2114. this.z = - this.z;
  2115. this.w = - this.w;
  2116. return this;
  2117. }
  2118. dot( v ) {
  2119. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2120. }
  2121. lengthSq() {
  2122. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2123. }
  2124. length() {
  2125. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2126. }
  2127. manhattanLength() {
  2128. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2129. }
  2130. normalize() {
  2131. return this.divideScalar( this.length() || 1 );
  2132. }
  2133. setLength( length ) {
  2134. return this.normalize().multiplyScalar( length );
  2135. }
  2136. lerp( v, alpha ) {
  2137. this.x += ( v.x - this.x ) * alpha;
  2138. this.y += ( v.y - this.y ) * alpha;
  2139. this.z += ( v.z - this.z ) * alpha;
  2140. this.w += ( v.w - this.w ) * alpha;
  2141. return this;
  2142. }
  2143. lerpVectors( v1, v2, alpha ) {
  2144. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2145. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2146. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2147. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2148. return this;
  2149. }
  2150. equals( v ) {
  2151. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2152. }
  2153. fromArray( array, offset = 0 ) {
  2154. this.x = array[ offset ];
  2155. this.y = array[ offset + 1 ];
  2156. this.z = array[ offset + 2 ];
  2157. this.w = array[ offset + 3 ];
  2158. return this;
  2159. }
  2160. toArray( array = [], offset = 0 ) {
  2161. array[ offset ] = this.x;
  2162. array[ offset + 1 ] = this.y;
  2163. array[ offset + 2 ] = this.z;
  2164. array[ offset + 3 ] = this.w;
  2165. return array;
  2166. }
  2167. fromBufferAttribute( attribute, index, offset ) {
  2168. if ( offset !== undefined ) {
  2169. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  2170. }
  2171. this.x = attribute.getX( index );
  2172. this.y = attribute.getY( index );
  2173. this.z = attribute.getZ( index );
  2174. this.w = attribute.getW( index );
  2175. return this;
  2176. }
  2177. random() {
  2178. this.x = Math.random();
  2179. this.y = Math.random();
  2180. this.z = Math.random();
  2181. this.w = Math.random();
  2182. return this;
  2183. }
  2184. }
  2185. /*
  2186. In options, we can specify:
  2187. * Texture parameters for an auto-generated target texture
  2188. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2189. */
  2190. function WebGLRenderTarget( width, height, options ) {
  2191. this.width = width;
  2192. this.height = height;
  2193. this.scissor = new Vector4( 0, 0, width, height );
  2194. this.scissorTest = false;
  2195. this.viewport = new Vector4( 0, 0, width, height );
  2196. options = options || {};
  2197. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2198. this.texture.image = {};
  2199. this.texture.image.width = width;
  2200. this.texture.image.height = height;
  2201. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2202. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2203. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2204. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2205. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2206. }
  2207. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  2208. constructor: WebGLRenderTarget,
  2209. isWebGLRenderTarget: true,
  2210. setSize: function ( width, height ) {
  2211. if ( this.width !== width || this.height !== height ) {
  2212. this.width = width;
  2213. this.height = height;
  2214. this.texture.image.width = width;
  2215. this.texture.image.height = height;
  2216. this.dispose();
  2217. }
  2218. this.viewport.set( 0, 0, width, height );
  2219. this.scissor.set( 0, 0, width, height );
  2220. },
  2221. clone: function () {
  2222. return new this.constructor().copy( this );
  2223. },
  2224. copy: function ( source ) {
  2225. this.width = source.width;
  2226. this.height = source.height;
  2227. this.viewport.copy( source.viewport );
  2228. this.texture = source.texture.clone();
  2229. this.depthBuffer = source.depthBuffer;
  2230. this.stencilBuffer = source.stencilBuffer;
  2231. this.depthTexture = source.depthTexture;
  2232. return this;
  2233. },
  2234. dispose: function () {
  2235. this.dispatchEvent( { type: 'dispose' } );
  2236. }
  2237. } );
  2238. function WebGLMultisampleRenderTarget( width, height, options ) {
  2239. WebGLRenderTarget.call( this, width, height, options );
  2240. this.samples = 4;
  2241. }
  2242. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  2243. constructor: WebGLMultisampleRenderTarget,
  2244. isWebGLMultisampleRenderTarget: true,
  2245. copy: function ( source ) {
  2246. WebGLRenderTarget.prototype.copy.call( this, source );
  2247. this.samples = source.samples;
  2248. return this;
  2249. }
  2250. } );
  2251. class Quaternion {
  2252. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2253. Object.defineProperty( this, 'isQuaternion', { value: true } );
  2254. this._x = x;
  2255. this._y = y;
  2256. this._z = z;
  2257. this._w = w;
  2258. }
  2259. static slerp( qa, qb, qm, t ) {
  2260. return qm.copy( qa ).slerp( qb, t );
  2261. }
  2262. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2263. // fuzz-free, array-based Quaternion SLERP operation
  2264. let x0 = src0[ srcOffset0 + 0 ],
  2265. y0 = src0[ srcOffset0 + 1 ],
  2266. z0 = src0[ srcOffset0 + 2 ],
  2267. w0 = src0[ srcOffset0 + 3 ];
  2268. const x1 = src1[ srcOffset1 + 0 ],
  2269. y1 = src1[ srcOffset1 + 1 ],
  2270. z1 = src1[ srcOffset1 + 2 ],
  2271. w1 = src1[ srcOffset1 + 3 ];
  2272. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2273. let s = 1 - t;
  2274. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2275. dir = ( cos >= 0 ? 1 : - 1 ),
  2276. sqrSin = 1 - cos * cos;
  2277. // Skip the Slerp for tiny steps to avoid numeric problems:
  2278. if ( sqrSin > Number.EPSILON ) {
  2279. const sin = Math.sqrt( sqrSin ),
  2280. len = Math.atan2( sin, cos * dir );
  2281. s = Math.sin( s * len ) / sin;
  2282. t = Math.sin( t * len ) / sin;
  2283. }
  2284. const tDir = t * dir;
  2285. x0 = x0 * s + x1 * tDir;
  2286. y0 = y0 * s + y1 * tDir;
  2287. z0 = z0 * s + z1 * tDir;
  2288. w0 = w0 * s + w1 * tDir;
  2289. // Normalize in case we just did a lerp:
  2290. if ( s === 1 - t ) {
  2291. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2292. x0 *= f;
  2293. y0 *= f;
  2294. z0 *= f;
  2295. w0 *= f;
  2296. }
  2297. }
  2298. dst[ dstOffset ] = x0;
  2299. dst[ dstOffset + 1 ] = y0;
  2300. dst[ dstOffset + 2 ] = z0;
  2301. dst[ dstOffset + 3 ] = w0;
  2302. }
  2303. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2304. const x0 = src0[ srcOffset0 ];
  2305. const y0 = src0[ srcOffset0 + 1 ];
  2306. const z0 = src0[ srcOffset0 + 2 ];
  2307. const w0 = src0[ srcOffset0 + 3 ];
  2308. const x1 = src1[ srcOffset1 ];
  2309. const y1 = src1[ srcOffset1 + 1 ];
  2310. const z1 = src1[ srcOffset1 + 2 ];
  2311. const w1 = src1[ srcOffset1 + 3 ];
  2312. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2313. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2314. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2315. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2316. return dst;
  2317. }
  2318. get x() {
  2319. return this._x;
  2320. }
  2321. set x( value ) {
  2322. this._x = value;
  2323. this._onChangeCallback();
  2324. }
  2325. get y() {
  2326. return this._y;
  2327. }
  2328. set y( value ) {
  2329. this._y = value;
  2330. this._onChangeCallback();
  2331. }
  2332. get z() {
  2333. return this._z;
  2334. }
  2335. set z( value ) {
  2336. this._z = value;
  2337. this._onChangeCallback();
  2338. }
  2339. get w() {
  2340. return this._w;
  2341. }
  2342. set w( value ) {
  2343. this._w = value;
  2344. this._onChangeCallback();
  2345. }
  2346. set( x, y, z, w ) {
  2347. this._x = x;
  2348. this._y = y;
  2349. this._z = z;
  2350. this._w = w;
  2351. this._onChangeCallback();
  2352. return this;
  2353. }
  2354. clone() {
  2355. return new this.constructor( this._x, this._y, this._z, this._w );
  2356. }
  2357. copy( quaternion ) {
  2358. this._x = quaternion.x;
  2359. this._y = quaternion.y;
  2360. this._z = quaternion.z;
  2361. this._w = quaternion.w;
  2362. this._onChangeCallback();
  2363. return this;
  2364. }
  2365. setFromEuler( euler, update ) {
  2366. if ( ! ( euler && euler.isEuler ) ) {
  2367. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2368. }
  2369. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2370. // http://www.mathworks.com/matlabcentral/fileexchange/
  2371. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2372. // content/SpinCalc.m
  2373. const cos = Math.cos;
  2374. const sin = Math.sin;
  2375. const c1 = cos( x / 2 );
  2376. const c2 = cos( y / 2 );
  2377. const c3 = cos( z / 2 );
  2378. const s1 = sin( x / 2 );
  2379. const s2 = sin( y / 2 );
  2380. const s3 = sin( z / 2 );
  2381. switch ( order ) {
  2382. case 'XYZ':
  2383. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2384. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2385. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2386. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2387. break;
  2388. case 'YXZ':
  2389. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2390. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2391. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2392. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2393. break;
  2394. case 'ZXY':
  2395. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2396. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2397. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2398. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2399. break;
  2400. case 'ZYX':
  2401. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2402. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2403. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2404. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2405. break;
  2406. case 'YZX':
  2407. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2408. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2409. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2410. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2411. break;
  2412. case 'XZY':
  2413. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2414. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2415. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2416. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2417. break;
  2418. default:
  2419. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2420. }
  2421. if ( update !== false ) this._onChangeCallback();
  2422. return this;
  2423. }
  2424. setFromAxisAngle( axis, angle ) {
  2425. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2426. // assumes axis is normalized
  2427. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2428. this._x = axis.x * s;
  2429. this._y = axis.y * s;
  2430. this._z = axis.z * s;
  2431. this._w = Math.cos( halfAngle );
  2432. this._onChangeCallback();
  2433. return this;
  2434. }
  2435. setFromRotationMatrix( m ) {
  2436. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2437. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2438. const te = m.elements,
  2439. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2440. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2441. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2442. trace = m11 + m22 + m33;
  2443. if ( trace > 0 ) {
  2444. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2445. this._w = 0.25 / s;
  2446. this._x = ( m32 - m23 ) * s;
  2447. this._y = ( m13 - m31 ) * s;
  2448. this._z = ( m21 - m12 ) * s;
  2449. } else if ( m11 > m22 && m11 > m33 ) {
  2450. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2451. this._w = ( m32 - m23 ) / s;
  2452. this._x = 0.25 * s;
  2453. this._y = ( m12 + m21 ) / s;
  2454. this._z = ( m13 + m31 ) / s;
  2455. } else if ( m22 > m33 ) {
  2456. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2457. this._w = ( m13 - m31 ) / s;
  2458. this._x = ( m12 + m21 ) / s;
  2459. this._y = 0.25 * s;
  2460. this._z = ( m23 + m32 ) / s;
  2461. } else {
  2462. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2463. this._w = ( m21 - m12 ) / s;
  2464. this._x = ( m13 + m31 ) / s;
  2465. this._y = ( m23 + m32 ) / s;
  2466. this._z = 0.25 * s;
  2467. }
  2468. this._onChangeCallback();
  2469. return this;
  2470. }
  2471. setFromUnitVectors( vFrom, vTo ) {
  2472. // assumes direction vectors vFrom and vTo are normalized
  2473. const EPS = 0.000001;
  2474. let r = vFrom.dot( vTo ) + 1;
  2475. if ( r < EPS ) {
  2476. r = 0;
  2477. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2478. this._x = - vFrom.y;
  2479. this._y = vFrom.x;
  2480. this._z = 0;
  2481. this._w = r;
  2482. } else {
  2483. this._x = 0;
  2484. this._y = - vFrom.z;
  2485. this._z = vFrom.y;
  2486. this._w = r;
  2487. }
  2488. } else {
  2489. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2490. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2491. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2492. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2493. this._w = r;
  2494. }
  2495. return this.normalize();
  2496. }
  2497. angleTo( q ) {
  2498. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  2499. }
  2500. rotateTowards( q, step ) {
  2501. const angle = this.angleTo( q );
  2502. if ( angle === 0 ) return this;
  2503. const t = Math.min( 1, step / angle );
  2504. this.slerp( q, t );
  2505. return this;
  2506. }
  2507. identity() {
  2508. return this.set( 0, 0, 0, 1 );
  2509. }
  2510. invert() {
  2511. // quaternion is assumed to have unit length
  2512. return this.conjugate();
  2513. }
  2514. conjugate() {
  2515. this._x *= - 1;
  2516. this._y *= - 1;
  2517. this._z *= - 1;
  2518. this._onChangeCallback();
  2519. return this;
  2520. }
  2521. dot( v ) {
  2522. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2523. }
  2524. lengthSq() {
  2525. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2526. }
  2527. length() {
  2528. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2529. }
  2530. normalize() {
  2531. let l = this.length();
  2532. if ( l === 0 ) {
  2533. this._x = 0;
  2534. this._y = 0;
  2535. this._z = 0;
  2536. this._w = 1;
  2537. } else {
  2538. l = 1 / l;
  2539. this._x = this._x * l;
  2540. this._y = this._y * l;
  2541. this._z = this._z * l;
  2542. this._w = this._w * l;
  2543. }
  2544. this._onChangeCallback();
  2545. return this;
  2546. }
  2547. multiply( q, p ) {
  2548. if ( p !== undefined ) {
  2549. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2550. return this.multiplyQuaternions( q, p );
  2551. }
  2552. return this.multiplyQuaternions( this, q );
  2553. }
  2554. premultiply( q ) {
  2555. return this.multiplyQuaternions( q, this );
  2556. }
  2557. multiplyQuaternions( a, b ) {
  2558. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2559. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2560. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2561. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2562. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2563. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2564. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2565. this._onChangeCallback();
  2566. return this;
  2567. }
  2568. slerp( qb, t ) {
  2569. if ( t === 0 ) return this;
  2570. if ( t === 1 ) return this.copy( qb );
  2571. const x = this._x, y = this._y, z = this._z, w = this._w;
  2572. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2573. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2574. if ( cosHalfTheta < 0 ) {
  2575. this._w = - qb._w;
  2576. this._x = - qb._x;
  2577. this._y = - qb._y;
  2578. this._z = - qb._z;
  2579. cosHalfTheta = - cosHalfTheta;
  2580. } else {
  2581. this.copy( qb );
  2582. }
  2583. if ( cosHalfTheta >= 1.0 ) {
  2584. this._w = w;
  2585. this._x = x;
  2586. this._y = y;
  2587. this._z = z;
  2588. return this;
  2589. }
  2590. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2591. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2592. const s = 1 - t;
  2593. this._w = s * w + t * this._w;
  2594. this._x = s * x + t * this._x;
  2595. this._y = s * y + t * this._y;
  2596. this._z = s * z + t * this._z;
  2597. this.normalize();
  2598. this._onChangeCallback();
  2599. return this;
  2600. }
  2601. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2602. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2603. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2604. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2605. this._w = ( w * ratioA + this._w * ratioB );
  2606. this._x = ( x * ratioA + this._x * ratioB );
  2607. this._y = ( y * ratioA + this._y * ratioB );
  2608. this._z = ( z * ratioA + this._z * ratioB );
  2609. this._onChangeCallback();
  2610. return this;
  2611. }
  2612. equals( quaternion ) {
  2613. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2614. }
  2615. fromArray( array, offset = 0 ) {
  2616. this._x = array[ offset ];
  2617. this._y = array[ offset + 1 ];
  2618. this._z = array[ offset + 2 ];
  2619. this._w = array[ offset + 3 ];
  2620. this._onChangeCallback();
  2621. return this;
  2622. }
  2623. toArray( array = [], offset = 0 ) {
  2624. array[ offset ] = this._x;
  2625. array[ offset + 1 ] = this._y;
  2626. array[ offset + 2 ] = this._z;
  2627. array[ offset + 3 ] = this._w;
  2628. return array;
  2629. }
  2630. fromBufferAttribute( attribute, index ) {
  2631. this._x = attribute.getX( index );
  2632. this._y = attribute.getY( index );
  2633. this._z = attribute.getZ( index );
  2634. this._w = attribute.getW( index );
  2635. return this;
  2636. }
  2637. _onChange( callback ) {
  2638. this._onChangeCallback = callback;
  2639. return this;
  2640. }
  2641. _onChangeCallback() {}
  2642. }
  2643. class Vector3 {
  2644. constructor( x = 0, y = 0, z = 0 ) {
  2645. Object.defineProperty( this, 'isVector3', { value: true } );
  2646. this.x = x;
  2647. this.y = y;
  2648. this.z = z;
  2649. }
  2650. set( x, y, z ) {
  2651. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2652. this.x = x;
  2653. this.y = y;
  2654. this.z = z;
  2655. return this;
  2656. }
  2657. setScalar( scalar ) {
  2658. this.x = scalar;
  2659. this.y = scalar;
  2660. this.z = scalar;
  2661. return this;
  2662. }
  2663. setX( x ) {
  2664. this.x = x;
  2665. return this;
  2666. }
  2667. setY( y ) {
  2668. this.y = y;
  2669. return this;
  2670. }
  2671. setZ( z ) {
  2672. this.z = z;
  2673. return this;
  2674. }
  2675. setComponent( index, value ) {
  2676. switch ( index ) {
  2677. case 0: this.x = value; break;
  2678. case 1: this.y = value; break;
  2679. case 2: this.z = value; break;
  2680. default: throw new Error( 'index is out of range: ' + index );
  2681. }
  2682. return this;
  2683. }
  2684. getComponent( index ) {
  2685. switch ( index ) {
  2686. case 0: return this.x;
  2687. case 1: return this.y;
  2688. case 2: return this.z;
  2689. default: throw new Error( 'index is out of range: ' + index );
  2690. }
  2691. }
  2692. clone() {
  2693. return new this.constructor( this.x, this.y, this.z );
  2694. }
  2695. copy( v ) {
  2696. this.x = v.x;
  2697. this.y = v.y;
  2698. this.z = v.z;
  2699. return this;
  2700. }
  2701. add( v, w ) {
  2702. if ( w !== undefined ) {
  2703. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2704. return this.addVectors( v, w );
  2705. }
  2706. this.x += v.x;
  2707. this.y += v.y;
  2708. this.z += v.z;
  2709. return this;
  2710. }
  2711. addScalar( s ) {
  2712. this.x += s;
  2713. this.y += s;
  2714. this.z += s;
  2715. return this;
  2716. }
  2717. addVectors( a, b ) {
  2718. this.x = a.x + b.x;
  2719. this.y = a.y + b.y;
  2720. this.z = a.z + b.z;
  2721. return this;
  2722. }
  2723. addScaledVector( v, s ) {
  2724. this.x += v.x * s;
  2725. this.y += v.y * s;
  2726. this.z += v.z * s;
  2727. return this;
  2728. }
  2729. sub( v, w ) {
  2730. if ( w !== undefined ) {
  2731. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2732. return this.subVectors( v, w );
  2733. }
  2734. this.x -= v.x;
  2735. this.y -= v.y;
  2736. this.z -= v.z;
  2737. return this;
  2738. }
  2739. subScalar( s ) {
  2740. this.x -= s;
  2741. this.y -= s;
  2742. this.z -= s;
  2743. return this;
  2744. }
  2745. subVectors( a, b ) {
  2746. this.x = a.x - b.x;
  2747. this.y = a.y - b.y;
  2748. this.z = a.z - b.z;
  2749. return this;
  2750. }
  2751. multiply( v, w ) {
  2752. if ( w !== undefined ) {
  2753. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2754. return this.multiplyVectors( v, w );
  2755. }
  2756. this.x *= v.x;
  2757. this.y *= v.y;
  2758. this.z *= v.z;
  2759. return this;
  2760. }
  2761. multiplyScalar( scalar ) {
  2762. this.x *= scalar;
  2763. this.y *= scalar;
  2764. this.z *= scalar;
  2765. return this;
  2766. }
  2767. multiplyVectors( a, b ) {
  2768. this.x = a.x * b.x;
  2769. this.y = a.y * b.y;
  2770. this.z = a.z * b.z;
  2771. return this;
  2772. }
  2773. applyEuler( euler ) {
  2774. if ( ! ( euler && euler.isEuler ) ) {
  2775. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2776. }
  2777. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  2778. }
  2779. applyAxisAngle( axis, angle ) {
  2780. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  2781. }
  2782. applyMatrix3( m ) {
  2783. const x = this.x, y = this.y, z = this.z;
  2784. const e = m.elements;
  2785. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2786. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2787. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2788. return this;
  2789. }
  2790. applyNormalMatrix( m ) {
  2791. return this.applyMatrix3( m ).normalize();
  2792. }
  2793. applyMatrix4( m ) {
  2794. const x = this.x, y = this.y, z = this.z;
  2795. const e = m.elements;
  2796. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2797. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2798. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2799. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2800. return this;
  2801. }
  2802. applyQuaternion( q ) {
  2803. const x = this.x, y = this.y, z = this.z;
  2804. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2805. // calculate quat * vector
  2806. const ix = qw * x + qy * z - qz * y;
  2807. const iy = qw * y + qz * x - qx * z;
  2808. const iz = qw * z + qx * y - qy * x;
  2809. const iw = - qx * x - qy * y - qz * z;
  2810. // calculate result * inverse quat
  2811. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2812. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2813. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2814. return this;
  2815. }
  2816. project( camera ) {
  2817. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2818. }
  2819. unproject( camera ) {
  2820. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2821. }
  2822. transformDirection( m ) {
  2823. // input: THREE.Matrix4 affine matrix
  2824. // vector interpreted as a direction
  2825. const x = this.x, y = this.y, z = this.z;
  2826. const e = m.elements;
  2827. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2828. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2829. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2830. return this.normalize();
  2831. }
  2832. divide( v ) {
  2833. this.x /= v.x;
  2834. this.y /= v.y;
  2835. this.z /= v.z;
  2836. return this;
  2837. }
  2838. divideScalar( scalar ) {
  2839. return this.multiplyScalar( 1 / scalar );
  2840. }
  2841. min( v ) {
  2842. this.x = Math.min( this.x, v.x );
  2843. this.y = Math.min( this.y, v.y );
  2844. this.z = Math.min( this.z, v.z );
  2845. return this;
  2846. }
  2847. max( v ) {
  2848. this.x = Math.max( this.x, v.x );
  2849. this.y = Math.max( this.y, v.y );
  2850. this.z = Math.max( this.z, v.z );
  2851. return this;
  2852. }
  2853. clamp( min, max ) {
  2854. // assumes min < max, componentwise
  2855. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2856. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2857. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2858. return this;
  2859. }
  2860. clampScalar( minVal, maxVal ) {
  2861. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2862. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2863. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2864. return this;
  2865. }
  2866. clampLength( min, max ) {
  2867. const length = this.length();
  2868. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2869. }
  2870. floor() {
  2871. this.x = Math.floor( this.x );
  2872. this.y = Math.floor( this.y );
  2873. this.z = Math.floor( this.z );
  2874. return this;
  2875. }
  2876. ceil() {
  2877. this.x = Math.ceil( this.x );
  2878. this.y = Math.ceil( this.y );
  2879. this.z = Math.ceil( this.z );
  2880. return this;
  2881. }
  2882. round() {
  2883. this.x = Math.round( this.x );
  2884. this.y = Math.round( this.y );
  2885. this.z = Math.round( this.z );
  2886. return this;
  2887. }
  2888. roundToZero() {
  2889. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2890. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2891. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2892. return this;
  2893. }
  2894. negate() {
  2895. this.x = - this.x;
  2896. this.y = - this.y;
  2897. this.z = - this.z;
  2898. return this;
  2899. }
  2900. dot( v ) {
  2901. return this.x * v.x + this.y * v.y + this.z * v.z;
  2902. }
  2903. // TODO lengthSquared?
  2904. lengthSq() {
  2905. return this.x * this.x + this.y * this.y + this.z * this.z;
  2906. }
  2907. length() {
  2908. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2909. }
  2910. manhattanLength() {
  2911. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2912. }
  2913. normalize() {
  2914. return this.divideScalar( this.length() || 1 );
  2915. }
  2916. setLength( length ) {
  2917. return this.normalize().multiplyScalar( length );
  2918. }
  2919. lerp( v, alpha ) {
  2920. this.x += ( v.x - this.x ) * alpha;
  2921. this.y += ( v.y - this.y ) * alpha;
  2922. this.z += ( v.z - this.z ) * alpha;
  2923. return this;
  2924. }
  2925. lerpVectors( v1, v2, alpha ) {
  2926. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2927. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2928. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2929. return this;
  2930. }
  2931. cross( v, w ) {
  2932. if ( w !== undefined ) {
  2933. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2934. return this.crossVectors( v, w );
  2935. }
  2936. return this.crossVectors( this, v );
  2937. }
  2938. crossVectors( a, b ) {
  2939. const ax = a.x, ay = a.y, az = a.z;
  2940. const bx = b.x, by = b.y, bz = b.z;
  2941. this.x = ay * bz - az * by;
  2942. this.y = az * bx - ax * bz;
  2943. this.z = ax * by - ay * bx;
  2944. return this;
  2945. }
  2946. projectOnVector( v ) {
  2947. const denominator = v.lengthSq();
  2948. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2949. const scalar = v.dot( this ) / denominator;
  2950. return this.copy( v ).multiplyScalar( scalar );
  2951. }
  2952. projectOnPlane( planeNormal ) {
  2953. _vector.copy( this ).projectOnVector( planeNormal );
  2954. return this.sub( _vector );
  2955. }
  2956. reflect( normal ) {
  2957. // reflect incident vector off plane orthogonal to normal
  2958. // normal is assumed to have unit length
  2959. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2960. }
  2961. angleTo( v ) {
  2962. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2963. if ( denominator === 0 ) return Math.PI / 2;
  2964. const theta = this.dot( v ) / denominator;
  2965. // clamp, to handle numerical problems
  2966. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  2967. }
  2968. distanceTo( v ) {
  2969. return Math.sqrt( this.distanceToSquared( v ) );
  2970. }
  2971. distanceToSquared( v ) {
  2972. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2973. return dx * dx + dy * dy + dz * dz;
  2974. }
  2975. manhattanDistanceTo( v ) {
  2976. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2977. }
  2978. setFromSpherical( s ) {
  2979. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2980. }
  2981. setFromSphericalCoords( radius, phi, theta ) {
  2982. const sinPhiRadius = Math.sin( phi ) * radius;
  2983. this.x = sinPhiRadius * Math.sin( theta );
  2984. this.y = Math.cos( phi ) * radius;
  2985. this.z = sinPhiRadius * Math.cos( theta );
  2986. return this;
  2987. }
  2988. setFromCylindrical( c ) {
  2989. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2990. }
  2991. setFromCylindricalCoords( radius, theta, y ) {
  2992. this.x = radius * Math.sin( theta );
  2993. this.y = y;
  2994. this.z = radius * Math.cos( theta );
  2995. return this;
  2996. }
  2997. setFromMatrixPosition( m ) {
  2998. const e = m.elements;
  2999. this.x = e[ 12 ];
  3000. this.y = e[ 13 ];
  3001. this.z = e[ 14 ];
  3002. return this;
  3003. }
  3004. setFromMatrixScale( m ) {
  3005. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3006. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3007. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3008. this.x = sx;
  3009. this.y = sy;
  3010. this.z = sz;
  3011. return this;
  3012. }
  3013. setFromMatrixColumn( m, index ) {
  3014. return this.fromArray( m.elements, index * 4 );
  3015. }
  3016. setFromMatrix3Column( m, index ) {
  3017. return this.fromArray( m.elements, index * 3 );
  3018. }
  3019. equals( v ) {
  3020. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3021. }
  3022. fromArray( array, offset = 0 ) {
  3023. this.x = array[ offset ];
  3024. this.y = array[ offset + 1 ];
  3025. this.z = array[ offset + 2 ];
  3026. return this;
  3027. }
  3028. toArray( array = [], offset = 0 ) {
  3029. array[ offset ] = this.x;
  3030. array[ offset + 1 ] = this.y;
  3031. array[ offset + 2 ] = this.z;
  3032. return array;
  3033. }
  3034. fromBufferAttribute( attribute, index, offset ) {
  3035. if ( offset !== undefined ) {
  3036. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  3037. }
  3038. this.x = attribute.getX( index );
  3039. this.y = attribute.getY( index );
  3040. this.z = attribute.getZ( index );
  3041. return this;
  3042. }
  3043. random() {
  3044. this.x = Math.random();
  3045. this.y = Math.random();
  3046. this.z = Math.random();
  3047. return this;
  3048. }
  3049. }
  3050. const _vector = /*@__PURE__*/ new Vector3();
  3051. const _quaternion = /*@__PURE__*/ new Quaternion();
  3052. class Box3 {
  3053. constructor( min, max ) {
  3054. Object.defineProperty( this, 'isBox3', { value: true } );
  3055. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  3056. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  3057. }
  3058. set( min, max ) {
  3059. this.min.copy( min );
  3060. this.max.copy( max );
  3061. return this;
  3062. }
  3063. setFromArray( array ) {
  3064. let minX = + Infinity;
  3065. let minY = + Infinity;
  3066. let minZ = + Infinity;
  3067. let maxX = - Infinity;
  3068. let maxY = - Infinity;
  3069. let maxZ = - Infinity;
  3070. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3071. const x = array[ i ];
  3072. const y = array[ i + 1 ];
  3073. const z = array[ i + 2 ];
  3074. if ( x < minX ) minX = x;
  3075. if ( y < minY ) minY = y;
  3076. if ( z < minZ ) minZ = z;
  3077. if ( x > maxX ) maxX = x;
  3078. if ( y > maxY ) maxY = y;
  3079. if ( z > maxZ ) maxZ = z;
  3080. }
  3081. this.min.set( minX, minY, minZ );
  3082. this.max.set( maxX, maxY, maxZ );
  3083. return this;
  3084. }
  3085. setFromBufferAttribute( attribute ) {
  3086. let minX = + Infinity;
  3087. let minY = + Infinity;
  3088. let minZ = + Infinity;
  3089. let maxX = - Infinity;
  3090. let maxY = - Infinity;
  3091. let maxZ = - Infinity;
  3092. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3093. const x = attribute.getX( i );
  3094. const y = attribute.getY( i );
  3095. const z = attribute.getZ( i );
  3096. if ( x < minX ) minX = x;
  3097. if ( y < minY ) minY = y;
  3098. if ( z < minZ ) minZ = z;
  3099. if ( x > maxX ) maxX = x;
  3100. if ( y > maxY ) maxY = y;
  3101. if ( z > maxZ ) maxZ = z;
  3102. }
  3103. this.min.set( minX, minY, minZ );
  3104. this.max.set( maxX, maxY, maxZ );
  3105. return this;
  3106. }
  3107. setFromPoints( points ) {
  3108. this.makeEmpty();
  3109. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3110. this.expandByPoint( points[ i ] );
  3111. }
  3112. return this;
  3113. }
  3114. setFromCenterAndSize( center, size ) {
  3115. const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  3116. this.min.copy( center ).sub( halfSize );
  3117. this.max.copy( center ).add( halfSize );
  3118. return this;
  3119. }
  3120. setFromObject( object ) {
  3121. this.makeEmpty();
  3122. return this.expandByObject( object );
  3123. }
  3124. clone() {
  3125. return new this.constructor().copy( this );
  3126. }
  3127. copy( box ) {
  3128. this.min.copy( box.min );
  3129. this.max.copy( box.max );
  3130. return this;
  3131. }
  3132. makeEmpty() {
  3133. this.min.x = this.min.y = this.min.z = + Infinity;
  3134. this.max.x = this.max.y = this.max.z = - Infinity;
  3135. return this;
  3136. }
  3137. isEmpty() {
  3138. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3139. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3140. }
  3141. getCenter( target ) {
  3142. if ( target === undefined ) {
  3143. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  3144. target = new Vector3();
  3145. }
  3146. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3147. }
  3148. getSize( target ) {
  3149. if ( target === undefined ) {
  3150. console.warn( 'THREE.Box3: .getSize() target is now required' );
  3151. target = new Vector3();
  3152. }
  3153. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3154. }
  3155. expandByPoint( point ) {
  3156. this.min.min( point );
  3157. this.max.max( point );
  3158. return this;
  3159. }
  3160. expandByVector( vector ) {
  3161. this.min.sub( vector );
  3162. this.max.add( vector );
  3163. return this;
  3164. }
  3165. expandByScalar( scalar ) {
  3166. this.min.addScalar( - scalar );
  3167. this.max.addScalar( scalar );
  3168. return this;
  3169. }
  3170. expandByObject( object ) {
  3171. // Computes the world-axis-aligned bounding box of an object (including its children),
  3172. // accounting for both the object's, and children's, world transforms
  3173. object.updateWorldMatrix( false, false );
  3174. const geometry = object.geometry;
  3175. if ( geometry !== undefined ) {
  3176. if ( geometry.boundingBox === null ) {
  3177. geometry.computeBoundingBox();
  3178. }
  3179. _box.copy( geometry.boundingBox );
  3180. _box.applyMatrix4( object.matrixWorld );
  3181. this.union( _box );
  3182. }
  3183. const children = object.children;
  3184. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3185. this.expandByObject( children[ i ] );
  3186. }
  3187. return this;
  3188. }
  3189. containsPoint( point ) {
  3190. return point.x < this.min.x || point.x > this.max.x ||
  3191. point.y < this.min.y || point.y > this.max.y ||
  3192. point.z < this.min.z || point.z > this.max.z ? false : true;
  3193. }
  3194. containsBox( box ) {
  3195. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3196. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3197. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3198. }
  3199. getParameter( point, target ) {
  3200. // This can potentially have a divide by zero if the box
  3201. // has a size dimension of 0.
  3202. if ( target === undefined ) {
  3203. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  3204. target = new Vector3();
  3205. }
  3206. return target.set(
  3207. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3208. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3209. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3210. );
  3211. }
  3212. intersectsBox( box ) {
  3213. // using 6 splitting planes to rule out intersections.
  3214. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3215. box.max.y < this.min.y || box.min.y > this.max.y ||
  3216. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3217. }
  3218. intersectsSphere( sphere ) {
  3219. // Find the point on the AABB closest to the sphere center.
  3220. this.clampPoint( sphere.center, _vector$1 );
  3221. // If that point is inside the sphere, the AABB and sphere intersect.
  3222. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3223. }
  3224. intersectsPlane( plane ) {
  3225. // We compute the minimum and maximum dot product values. If those values
  3226. // are on the same side (back or front) of the plane, then there is no intersection.
  3227. let min, max;
  3228. if ( plane.normal.x > 0 ) {
  3229. min = plane.normal.x * this.min.x;
  3230. max = plane.normal.x * this.max.x;
  3231. } else {
  3232. min = plane.normal.x * this.max.x;
  3233. max = plane.normal.x * this.min.x;
  3234. }
  3235. if ( plane.normal.y > 0 ) {
  3236. min += plane.normal.y * this.min.y;
  3237. max += plane.normal.y * this.max.y;
  3238. } else {
  3239. min += plane.normal.y * this.max.y;
  3240. max += plane.normal.y * this.min.y;
  3241. }
  3242. if ( plane.normal.z > 0 ) {
  3243. min += plane.normal.z * this.min.z;
  3244. max += plane.normal.z * this.max.z;
  3245. } else {
  3246. min += plane.normal.z * this.max.z;
  3247. max += plane.normal.z * this.min.z;
  3248. }
  3249. return ( min <= - plane.constant && max >= - plane.constant );
  3250. }
  3251. intersectsTriangle( triangle ) {
  3252. if ( this.isEmpty() ) {
  3253. return false;
  3254. }
  3255. // compute box center and extents
  3256. this.getCenter( _center );
  3257. _extents.subVectors( this.max, _center );
  3258. // translate triangle to aabb origin
  3259. _v0.subVectors( triangle.a, _center );
  3260. _v1.subVectors( triangle.b, _center );
  3261. _v2.subVectors( triangle.c, _center );
  3262. // compute edge vectors for triangle
  3263. _f0.subVectors( _v1, _v0 );
  3264. _f1.subVectors( _v2, _v1 );
  3265. _f2.subVectors( _v0, _v2 );
  3266. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3267. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  3268. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3269. let axes = [
  3270. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3271. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3272. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3273. ];
  3274. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  3275. return false;
  3276. }
  3277. // test 3 face normals from the aabb
  3278. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3279. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  3280. return false;
  3281. }
  3282. // finally testing the face normal of the triangle
  3283. // use already existing triangle edge vectors here
  3284. _triangleNormal.crossVectors( _f0, _f1 );
  3285. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3286. return satForAxes( axes, _v0, _v1, _v2, _extents );
  3287. }
  3288. clampPoint( point, target ) {
  3289. if ( target === undefined ) {
  3290. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  3291. target = new Vector3();
  3292. }
  3293. return target.copy( point ).clamp( this.min, this.max );
  3294. }
  3295. distanceToPoint( point ) {
  3296. const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  3297. return clampedPoint.sub( point ).length();
  3298. }
  3299. getBoundingSphere( target ) {
  3300. if ( target === undefined ) {
  3301. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  3302. //target = new Sphere(); // removed to avoid cyclic dependency
  3303. }
  3304. this.getCenter( target.center );
  3305. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  3306. return target;
  3307. }
  3308. intersect( box ) {
  3309. this.min.max( box.min );
  3310. this.max.min( box.max );
  3311. // 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.
  3312. if ( this.isEmpty() ) this.makeEmpty();
  3313. return this;
  3314. }
  3315. union( box ) {
  3316. this.min.min( box.min );
  3317. this.max.max( box.max );
  3318. return this;
  3319. }
  3320. applyMatrix4( matrix ) {
  3321. // transform of empty box is an empty box.
  3322. if ( this.isEmpty() ) return this;
  3323. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3324. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3325. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3326. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3327. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3328. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3329. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3330. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3331. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3332. this.setFromPoints( _points );
  3333. return this;
  3334. }
  3335. translate( offset ) {
  3336. this.min.add( offset );
  3337. this.max.add( offset );
  3338. return this;
  3339. }
  3340. equals( box ) {
  3341. return box.min.equals( this.min ) && box.max.equals( this.max );
  3342. }
  3343. }
  3344. function satForAxes( axes, v0, v1, v2, extents ) {
  3345. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3346. _testAxis.fromArray( axes, i );
  3347. // project the aabb onto the seperating axis
  3348. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3349. // project all 3 vertices of the triangle onto the seperating axis
  3350. const p0 = v0.dot( _testAxis );
  3351. const p1 = v1.dot( _testAxis );
  3352. const p2 = v2.dot( _testAxis );
  3353. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3354. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3355. // points of the projected triangle are outside the projected half-length of the aabb
  3356. // the axis is seperating and we can exit
  3357. return false;
  3358. }
  3359. }
  3360. return true;
  3361. }
  3362. const _points = [
  3363. /*@__PURE__*/ new Vector3(),
  3364. /*@__PURE__*/ new Vector3(),
  3365. /*@__PURE__*/ new Vector3(),
  3366. /*@__PURE__*/ new Vector3(),
  3367. /*@__PURE__*/ new Vector3(),
  3368. /*@__PURE__*/ new Vector3(),
  3369. /*@__PURE__*/ new Vector3(),
  3370. /*@__PURE__*/ new Vector3()
  3371. ];
  3372. const _vector$1 = /*@__PURE__*/ new Vector3();
  3373. const _box = /*@__PURE__*/ new Box3();
  3374. // triangle centered vertices
  3375. const _v0 = /*@__PURE__*/ new Vector3();
  3376. const _v1 = /*@__PURE__*/ new Vector3();
  3377. const _v2 = /*@__PURE__*/ new Vector3();
  3378. // triangle edge vectors
  3379. const _f0 = /*@__PURE__*/ new Vector3();
  3380. const _f1 = /*@__PURE__*/ new Vector3();
  3381. const _f2 = /*@__PURE__*/ new Vector3();
  3382. const _center = /*@__PURE__*/ new Vector3();
  3383. const _extents = /*@__PURE__*/ new Vector3();
  3384. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3385. const _testAxis = /*@__PURE__*/ new Vector3();
  3386. const _box$1 = /*@__PURE__*/ new Box3();
  3387. class Sphere {
  3388. constructor( center, radius ) {
  3389. this.center = ( center !== undefined ) ? center : new Vector3();
  3390. this.radius = ( radius !== undefined ) ? radius : - 1;
  3391. }
  3392. set( center, radius ) {
  3393. this.center.copy( center );
  3394. this.radius = radius;
  3395. return this;
  3396. }
  3397. setFromPoints( points, optionalCenter ) {
  3398. const center = this.center;
  3399. if ( optionalCenter !== undefined ) {
  3400. center.copy( optionalCenter );
  3401. } else {
  3402. _box$1.setFromPoints( points ).getCenter( center );
  3403. }
  3404. let maxRadiusSq = 0;
  3405. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3406. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3407. }
  3408. this.radius = Math.sqrt( maxRadiusSq );
  3409. return this;
  3410. }
  3411. clone() {
  3412. return new this.constructor().copy( this );
  3413. }
  3414. copy( sphere ) {
  3415. this.center.copy( sphere.center );
  3416. this.radius = sphere.radius;
  3417. return this;
  3418. }
  3419. isEmpty() {
  3420. return ( this.radius < 0 );
  3421. }
  3422. makeEmpty() {
  3423. this.center.set( 0, 0, 0 );
  3424. this.radius = - 1;
  3425. return this;
  3426. }
  3427. containsPoint( point ) {
  3428. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3429. }
  3430. distanceToPoint( point ) {
  3431. return ( point.distanceTo( this.center ) - this.radius );
  3432. }
  3433. intersectsSphere( sphere ) {
  3434. const radiusSum = this.radius + sphere.radius;
  3435. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3436. }
  3437. intersectsBox( box ) {
  3438. return box.intersectsSphere( this );
  3439. }
  3440. intersectsPlane( plane ) {
  3441. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3442. }
  3443. clampPoint( point, target ) {
  3444. const deltaLengthSq = this.center.distanceToSquared( point );
  3445. if ( target === undefined ) {
  3446. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  3447. target = new Vector3();
  3448. }
  3449. target.copy( point );
  3450. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3451. target.sub( this.center ).normalize();
  3452. target.multiplyScalar( this.radius ).add( this.center );
  3453. }
  3454. return target;
  3455. }
  3456. getBoundingBox( target ) {
  3457. if ( target === undefined ) {
  3458. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  3459. target = new Box3();
  3460. }
  3461. if ( this.isEmpty() ) {
  3462. // Empty sphere produces empty bounding box
  3463. target.makeEmpty();
  3464. return target;
  3465. }
  3466. target.set( this.center, this.center );
  3467. target.expandByScalar( this.radius );
  3468. return target;
  3469. }
  3470. applyMatrix4( matrix ) {
  3471. this.center.applyMatrix4( matrix );
  3472. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3473. return this;
  3474. }
  3475. translate( offset ) {
  3476. this.center.add( offset );
  3477. return this;
  3478. }
  3479. equals( sphere ) {
  3480. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3481. }
  3482. }
  3483. const _vector$2 = /*@__PURE__*/ new Vector3();
  3484. const _segCenter = /*@__PURE__*/ new Vector3();
  3485. const _segDir = /*@__PURE__*/ new Vector3();
  3486. const _diff = /*@__PURE__*/ new Vector3();
  3487. const _edge1 = /*@__PURE__*/ new Vector3();
  3488. const _edge2 = /*@__PURE__*/ new Vector3();
  3489. const _normal = /*@__PURE__*/ new Vector3();
  3490. class Ray {
  3491. constructor( origin, direction ) {
  3492. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  3493. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  3494. }
  3495. set( origin, direction ) {
  3496. this.origin.copy( origin );
  3497. this.direction.copy( direction );
  3498. return this;
  3499. }
  3500. clone() {
  3501. return new this.constructor().copy( this );
  3502. }
  3503. copy( ray ) {
  3504. this.origin.copy( ray.origin );
  3505. this.direction.copy( ray.direction );
  3506. return this;
  3507. }
  3508. at( t, target ) {
  3509. if ( target === undefined ) {
  3510. console.warn( 'THREE.Ray: .at() target is now required' );
  3511. target = new Vector3();
  3512. }
  3513. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3514. }
  3515. lookAt( v ) {
  3516. this.direction.copy( v ).sub( this.origin ).normalize();
  3517. return this;
  3518. }
  3519. recast( t ) {
  3520. this.origin.copy( this.at( t, _vector$2 ) );
  3521. return this;
  3522. }
  3523. closestPointToPoint( point, target ) {
  3524. if ( target === undefined ) {
  3525. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  3526. target = new Vector3();
  3527. }
  3528. target.subVectors( point, this.origin );
  3529. const directionDistance = target.dot( this.direction );
  3530. if ( directionDistance < 0 ) {
  3531. return target.copy( this.origin );
  3532. }
  3533. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3534. }
  3535. distanceToPoint( point ) {
  3536. return Math.sqrt( this.distanceSqToPoint( point ) );
  3537. }
  3538. distanceSqToPoint( point ) {
  3539. const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  3540. // point behind the ray
  3541. if ( directionDistance < 0 ) {
  3542. return this.origin.distanceToSquared( point );
  3543. }
  3544. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3545. return _vector$2.distanceToSquared( point );
  3546. }
  3547. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3548. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3549. // It returns the min distance between the ray and the segment
  3550. // defined by v0 and v1
  3551. // It can also set two optional targets :
  3552. // - The closest point on the ray
  3553. // - The closest point on the segment
  3554. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3555. _segDir.copy( v1 ).sub( v0 ).normalize();
  3556. _diff.copy( this.origin ).sub( _segCenter );
  3557. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3558. const a01 = - this.direction.dot( _segDir );
  3559. const b0 = _diff.dot( this.direction );
  3560. const b1 = - _diff.dot( _segDir );
  3561. const c = _diff.lengthSq();
  3562. const det = Math.abs( 1 - a01 * a01 );
  3563. let s0, s1, sqrDist, extDet;
  3564. if ( det > 0 ) {
  3565. // The ray and segment are not parallel.
  3566. s0 = a01 * b1 - b0;
  3567. s1 = a01 * b0 - b1;
  3568. extDet = segExtent * det;
  3569. if ( s0 >= 0 ) {
  3570. if ( s1 >= - extDet ) {
  3571. if ( s1 <= extDet ) {
  3572. // region 0
  3573. // Minimum at interior points of ray and segment.
  3574. const invDet = 1 / det;
  3575. s0 *= invDet;
  3576. s1 *= invDet;
  3577. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3578. } else {
  3579. // region 1
  3580. s1 = segExtent;
  3581. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3582. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3583. }
  3584. } else {
  3585. // region 5
  3586. s1 = - segExtent;
  3587. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3588. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3589. }
  3590. } else {
  3591. if ( s1 <= - extDet ) {
  3592. // region 4
  3593. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3594. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3595. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3596. } else if ( s1 <= extDet ) {
  3597. // region 3
  3598. s0 = 0;
  3599. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3600. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3601. } else {
  3602. // region 2
  3603. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3604. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3605. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3606. }
  3607. }
  3608. } else {
  3609. // Ray and segment are parallel.
  3610. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3611. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3612. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3613. }
  3614. if ( optionalPointOnRay ) {
  3615. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3616. }
  3617. if ( optionalPointOnSegment ) {
  3618. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3619. }
  3620. return sqrDist;
  3621. }
  3622. intersectSphere( sphere, target ) {
  3623. _vector$2.subVectors( sphere.center, this.origin );
  3624. const tca = _vector$2.dot( this.direction );
  3625. const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  3626. const radius2 = sphere.radius * sphere.radius;
  3627. if ( d2 > radius2 ) return null;
  3628. const thc = Math.sqrt( radius2 - d2 );
  3629. // t0 = first intersect point - entrance on front of sphere
  3630. const t0 = tca - thc;
  3631. // t1 = second intersect point - exit point on back of sphere
  3632. const t1 = tca + thc;
  3633. // test to see if both t0 and t1 are behind the ray - if so, return null
  3634. if ( t0 < 0 && t1 < 0 ) return null;
  3635. // test to see if t0 is behind the ray:
  3636. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3637. // in order to always return an intersect point that is in front of the ray.
  3638. if ( t0 < 0 ) return this.at( t1, target );
  3639. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3640. return this.at( t0, target );
  3641. }
  3642. intersectsSphere( sphere ) {
  3643. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3644. }
  3645. distanceToPlane( plane ) {
  3646. const denominator = plane.normal.dot( this.direction );
  3647. if ( denominator === 0 ) {
  3648. // line is coplanar, return origin
  3649. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3650. return 0;
  3651. }
  3652. // Null is preferable to undefined since undefined means.... it is undefined
  3653. return null;
  3654. }
  3655. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3656. // Return if the ray never intersects the plane
  3657. return t >= 0 ? t : null;
  3658. }
  3659. intersectPlane( plane, target ) {
  3660. const t = this.distanceToPlane( plane );
  3661. if ( t === null ) {
  3662. return null;
  3663. }
  3664. return this.at( t, target );
  3665. }
  3666. intersectsPlane( plane ) {
  3667. // check if the ray lies on the plane first
  3668. const distToPoint = plane.distanceToPoint( this.origin );
  3669. if ( distToPoint === 0 ) {
  3670. return true;
  3671. }
  3672. const denominator = plane.normal.dot( this.direction );
  3673. if ( denominator * distToPoint < 0 ) {
  3674. return true;
  3675. }
  3676. // ray origin is behind the plane (and is pointing behind it)
  3677. return false;
  3678. }
  3679. intersectBox( box, target ) {
  3680. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3681. const invdirx = 1 / this.direction.x,
  3682. invdiry = 1 / this.direction.y,
  3683. invdirz = 1 / this.direction.z;
  3684. const origin = this.origin;
  3685. if ( invdirx >= 0 ) {
  3686. tmin = ( box.min.x - origin.x ) * invdirx;
  3687. tmax = ( box.max.x - origin.x ) * invdirx;
  3688. } else {
  3689. tmin = ( box.max.x - origin.x ) * invdirx;
  3690. tmax = ( box.min.x - origin.x ) * invdirx;
  3691. }
  3692. if ( invdiry >= 0 ) {
  3693. tymin = ( box.min.y - origin.y ) * invdiry;
  3694. tymax = ( box.max.y - origin.y ) * invdiry;
  3695. } else {
  3696. tymin = ( box.max.y - origin.y ) * invdiry;
  3697. tymax = ( box.min.y - origin.y ) * invdiry;
  3698. }
  3699. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3700. // These lines also handle the case where tmin or tmax is NaN
  3701. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3702. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3703. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3704. if ( invdirz >= 0 ) {
  3705. tzmin = ( box.min.z - origin.z ) * invdirz;
  3706. tzmax = ( box.max.z - origin.z ) * invdirz;
  3707. } else {
  3708. tzmin = ( box.max.z - origin.z ) * invdirz;
  3709. tzmax = ( box.min.z - origin.z ) * invdirz;
  3710. }
  3711. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3712. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3713. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3714. //return point closest to the ray (positive side)
  3715. if ( tmax < 0 ) return null;
  3716. return this.at( tmin >= 0 ? tmin : tmax, target );
  3717. }
  3718. intersectsBox( box ) {
  3719. return this.intersectBox( box, _vector$2 ) !== null;
  3720. }
  3721. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3722. // Compute the offset origin, edges, and normal.
  3723. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3724. _edge1.subVectors( b, a );
  3725. _edge2.subVectors( c, a );
  3726. _normal.crossVectors( _edge1, _edge2 );
  3727. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3728. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3729. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3730. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3731. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3732. let DdN = this.direction.dot( _normal );
  3733. let sign;
  3734. if ( DdN > 0 ) {
  3735. if ( backfaceCulling ) return null;
  3736. sign = 1;
  3737. } else if ( DdN < 0 ) {
  3738. sign = - 1;
  3739. DdN = - DdN;
  3740. } else {
  3741. return null;
  3742. }
  3743. _diff.subVectors( this.origin, a );
  3744. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3745. // b1 < 0, no intersection
  3746. if ( DdQxE2 < 0 ) {
  3747. return null;
  3748. }
  3749. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3750. // b2 < 0, no intersection
  3751. if ( DdE1xQ < 0 ) {
  3752. return null;
  3753. }
  3754. // b1+b2 > 1, no intersection
  3755. if ( DdQxE2 + DdE1xQ > DdN ) {
  3756. return null;
  3757. }
  3758. // Line intersects triangle, check if ray does.
  3759. const QdN = - sign * _diff.dot( _normal );
  3760. // t < 0, no intersection
  3761. if ( QdN < 0 ) {
  3762. return null;
  3763. }
  3764. // Ray intersects triangle.
  3765. return this.at( QdN / DdN, target );
  3766. }
  3767. applyMatrix4( matrix4 ) {
  3768. this.origin.applyMatrix4( matrix4 );
  3769. this.direction.transformDirection( matrix4 );
  3770. return this;
  3771. }
  3772. equals( ray ) {
  3773. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3774. }
  3775. }
  3776. class Matrix4 {
  3777. constructor() {
  3778. Object.defineProperty( this, 'isMatrix4', { value: true } );
  3779. this.elements = [
  3780. 1, 0, 0, 0,
  3781. 0, 1, 0, 0,
  3782. 0, 0, 1, 0,
  3783. 0, 0, 0, 1
  3784. ];
  3785. if ( arguments.length > 0 ) {
  3786. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3787. }
  3788. }
  3789. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3790. const te = this.elements;
  3791. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3792. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3793. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3794. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3795. return this;
  3796. }
  3797. identity() {
  3798. this.set(
  3799. 1, 0, 0, 0,
  3800. 0, 1, 0, 0,
  3801. 0, 0, 1, 0,
  3802. 0, 0, 0, 1
  3803. );
  3804. return this;
  3805. }
  3806. clone() {
  3807. return new Matrix4().fromArray( this.elements );
  3808. }
  3809. copy( m ) {
  3810. const te = this.elements;
  3811. const me = m.elements;
  3812. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3813. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3814. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3815. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3816. return this;
  3817. }
  3818. copyPosition( m ) {
  3819. const te = this.elements, me = m.elements;
  3820. te[ 12 ] = me[ 12 ];
  3821. te[ 13 ] = me[ 13 ];
  3822. te[ 14 ] = me[ 14 ];
  3823. return this;
  3824. }
  3825. extractBasis( xAxis, yAxis, zAxis ) {
  3826. xAxis.setFromMatrixColumn( this, 0 );
  3827. yAxis.setFromMatrixColumn( this, 1 );
  3828. zAxis.setFromMatrixColumn( this, 2 );
  3829. return this;
  3830. }
  3831. makeBasis( xAxis, yAxis, zAxis ) {
  3832. this.set(
  3833. xAxis.x, yAxis.x, zAxis.x, 0,
  3834. xAxis.y, yAxis.y, zAxis.y, 0,
  3835. xAxis.z, yAxis.z, zAxis.z, 0,
  3836. 0, 0, 0, 1
  3837. );
  3838. return this;
  3839. }
  3840. extractRotation( m ) {
  3841. // this method does not support reflection matrices
  3842. const te = this.elements;
  3843. const me = m.elements;
  3844. const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length();
  3845. const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length();
  3846. const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length();
  3847. te[ 0 ] = me[ 0 ] * scaleX;
  3848. te[ 1 ] = me[ 1 ] * scaleX;
  3849. te[ 2 ] = me[ 2 ] * scaleX;
  3850. te[ 3 ] = 0;
  3851. te[ 4 ] = me[ 4 ] * scaleY;
  3852. te[ 5 ] = me[ 5 ] * scaleY;
  3853. te[ 6 ] = me[ 6 ] * scaleY;
  3854. te[ 7 ] = 0;
  3855. te[ 8 ] = me[ 8 ] * scaleZ;
  3856. te[ 9 ] = me[ 9 ] * scaleZ;
  3857. te[ 10 ] = me[ 10 ] * scaleZ;
  3858. te[ 11 ] = 0;
  3859. te[ 12 ] = 0;
  3860. te[ 13 ] = 0;
  3861. te[ 14 ] = 0;
  3862. te[ 15 ] = 1;
  3863. return this;
  3864. }
  3865. makeRotationFromEuler( euler ) {
  3866. if ( ! ( euler && euler.isEuler ) ) {
  3867. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3868. }
  3869. const te = this.elements;
  3870. const x = euler.x, y = euler.y, z = euler.z;
  3871. const a = Math.cos( x ), b = Math.sin( x );
  3872. const c = Math.cos( y ), d = Math.sin( y );
  3873. const e = Math.cos( z ), f = Math.sin( z );
  3874. if ( euler.order === 'XYZ' ) {
  3875. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3876. te[ 0 ] = c * e;
  3877. te[ 4 ] = - c * f;
  3878. te[ 8 ] = d;
  3879. te[ 1 ] = af + be * d;
  3880. te[ 5 ] = ae - bf * d;
  3881. te[ 9 ] = - b * c;
  3882. te[ 2 ] = bf - ae * d;
  3883. te[ 6 ] = be + af * d;
  3884. te[ 10 ] = a * c;
  3885. } else if ( euler.order === 'YXZ' ) {
  3886. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3887. te[ 0 ] = ce + df * b;
  3888. te[ 4 ] = de * b - cf;
  3889. te[ 8 ] = a * d;
  3890. te[ 1 ] = a * f;
  3891. te[ 5 ] = a * e;
  3892. te[ 9 ] = - b;
  3893. te[ 2 ] = cf * b - de;
  3894. te[ 6 ] = df + ce * b;
  3895. te[ 10 ] = a * c;
  3896. } else if ( euler.order === 'ZXY' ) {
  3897. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3898. te[ 0 ] = ce - df * b;
  3899. te[ 4 ] = - a * f;
  3900. te[ 8 ] = de + cf * b;
  3901. te[ 1 ] = cf + de * b;
  3902. te[ 5 ] = a * e;
  3903. te[ 9 ] = df - ce * b;
  3904. te[ 2 ] = - a * d;
  3905. te[ 6 ] = b;
  3906. te[ 10 ] = a * c;
  3907. } else if ( euler.order === 'ZYX' ) {
  3908. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3909. te[ 0 ] = c * e;
  3910. te[ 4 ] = be * d - af;
  3911. te[ 8 ] = ae * d + bf;
  3912. te[ 1 ] = c * f;
  3913. te[ 5 ] = bf * d + ae;
  3914. te[ 9 ] = af * d - be;
  3915. te[ 2 ] = - d;
  3916. te[ 6 ] = b * c;
  3917. te[ 10 ] = a * c;
  3918. } else if ( euler.order === 'YZX' ) {
  3919. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3920. te[ 0 ] = c * e;
  3921. te[ 4 ] = bd - ac * f;
  3922. te[ 8 ] = bc * f + ad;
  3923. te[ 1 ] = f;
  3924. te[ 5 ] = a * e;
  3925. te[ 9 ] = - b * e;
  3926. te[ 2 ] = - d * e;
  3927. te[ 6 ] = ad * f + bc;
  3928. te[ 10 ] = ac - bd * f;
  3929. } else if ( euler.order === 'XZY' ) {
  3930. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3931. te[ 0 ] = c * e;
  3932. te[ 4 ] = - f;
  3933. te[ 8 ] = d * e;
  3934. te[ 1 ] = ac * f + bd;
  3935. te[ 5 ] = a * e;
  3936. te[ 9 ] = ad * f - bc;
  3937. te[ 2 ] = bc * f - ad;
  3938. te[ 6 ] = b * e;
  3939. te[ 10 ] = bd * f + ac;
  3940. }
  3941. // bottom row
  3942. te[ 3 ] = 0;
  3943. te[ 7 ] = 0;
  3944. te[ 11 ] = 0;
  3945. // last column
  3946. te[ 12 ] = 0;
  3947. te[ 13 ] = 0;
  3948. te[ 14 ] = 0;
  3949. te[ 15 ] = 1;
  3950. return this;
  3951. }
  3952. makeRotationFromQuaternion( q ) {
  3953. return this.compose( _zero, q, _one );
  3954. }
  3955. lookAt( eye, target, up ) {
  3956. const te = this.elements;
  3957. _z.subVectors( eye, target );
  3958. if ( _z.lengthSq() === 0 ) {
  3959. // eye and target are in the same position
  3960. _z.z = 1;
  3961. }
  3962. _z.normalize();
  3963. _x.crossVectors( up, _z );
  3964. if ( _x.lengthSq() === 0 ) {
  3965. // up and z are parallel
  3966. if ( Math.abs( up.z ) === 1 ) {
  3967. _z.x += 0.0001;
  3968. } else {
  3969. _z.z += 0.0001;
  3970. }
  3971. _z.normalize();
  3972. _x.crossVectors( up, _z );
  3973. }
  3974. _x.normalize();
  3975. _y.crossVectors( _z, _x );
  3976. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3977. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3978. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3979. return this;
  3980. }
  3981. multiply( m, n ) {
  3982. if ( n !== undefined ) {
  3983. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3984. return this.multiplyMatrices( m, n );
  3985. }
  3986. return this.multiplyMatrices( this, m );
  3987. }
  3988. premultiply( m ) {
  3989. return this.multiplyMatrices( m, this );
  3990. }
  3991. multiplyMatrices( a, b ) {
  3992. const ae = a.elements;
  3993. const be = b.elements;
  3994. const te = this.elements;
  3995. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3996. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3997. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3998. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3999. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4000. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4001. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4002. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4003. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4004. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4005. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4006. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4007. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4008. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4009. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4010. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4011. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4012. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4013. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4014. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4015. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4016. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4017. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4018. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4019. return this;
  4020. }
  4021. multiplyScalar( s ) {
  4022. const te = this.elements;
  4023. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4024. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4025. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4026. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4027. return this;
  4028. }
  4029. determinant() {
  4030. const te = this.elements;
  4031. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4032. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4033. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4034. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4035. //TODO: make this more efficient
  4036. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4037. return (
  4038. n41 * (
  4039. + n14 * n23 * n32
  4040. - n13 * n24 * n32
  4041. - n14 * n22 * n33
  4042. + n12 * n24 * n33
  4043. + n13 * n22 * n34
  4044. - n12 * n23 * n34
  4045. ) +
  4046. n42 * (
  4047. + n11 * n23 * n34
  4048. - n11 * n24 * n33
  4049. + n14 * n21 * n33
  4050. - n13 * n21 * n34
  4051. + n13 * n24 * n31
  4052. - n14 * n23 * n31
  4053. ) +
  4054. n43 * (
  4055. + n11 * n24 * n32
  4056. - n11 * n22 * n34
  4057. - n14 * n21 * n32
  4058. + n12 * n21 * n34
  4059. + n14 * n22 * n31
  4060. - n12 * n24 * n31
  4061. ) +
  4062. n44 * (
  4063. - n13 * n22 * n31
  4064. - n11 * n23 * n32
  4065. + n11 * n22 * n33
  4066. + n13 * n21 * n32
  4067. - n12 * n21 * n33
  4068. + n12 * n23 * n31
  4069. )
  4070. );
  4071. }
  4072. transpose() {
  4073. const te = this.elements;
  4074. let tmp;
  4075. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4076. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4077. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4078. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4079. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4080. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4081. return this;
  4082. }
  4083. setPosition( x, y, z ) {
  4084. const te = this.elements;
  4085. if ( x.isVector3 ) {
  4086. te[ 12 ] = x.x;
  4087. te[ 13 ] = x.y;
  4088. te[ 14 ] = x.z;
  4089. } else {
  4090. te[ 12 ] = x;
  4091. te[ 13 ] = y;
  4092. te[ 14 ] = z;
  4093. }
  4094. return this;
  4095. }
  4096. invert() {
  4097. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4098. const te = this.elements,
  4099. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4100. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4101. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4102. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4103. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4104. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4105. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4106. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4107. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4108. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4109. const detInv = 1 / det;
  4110. te[ 0 ] = t11 * detInv;
  4111. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4112. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4113. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4114. te[ 4 ] = t12 * detInv;
  4115. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4116. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4117. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4118. te[ 8 ] = t13 * detInv;
  4119. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4120. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4121. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4122. te[ 12 ] = t14 * detInv;
  4123. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4124. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4125. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4126. return this;
  4127. }
  4128. scale( v ) {
  4129. const te = this.elements;
  4130. const x = v.x, y = v.y, z = v.z;
  4131. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4132. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4133. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4134. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4135. return this;
  4136. }
  4137. getMaxScaleOnAxis() {
  4138. const te = this.elements;
  4139. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4140. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4141. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4142. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4143. }
  4144. makeTranslation( x, y, z ) {
  4145. this.set(
  4146. 1, 0, 0, x,
  4147. 0, 1, 0, y,
  4148. 0, 0, 1, z,
  4149. 0, 0, 0, 1
  4150. );
  4151. return this;
  4152. }
  4153. makeRotationX( theta ) {
  4154. const c = Math.cos( theta ), s = Math.sin( theta );
  4155. this.set(
  4156. 1, 0, 0, 0,
  4157. 0, c, - s, 0,
  4158. 0, s, c, 0,
  4159. 0, 0, 0, 1
  4160. );
  4161. return this;
  4162. }
  4163. makeRotationY( theta ) {
  4164. const c = Math.cos( theta ), s = Math.sin( theta );
  4165. this.set(
  4166. c, 0, s, 0,
  4167. 0, 1, 0, 0,
  4168. - s, 0, c, 0,
  4169. 0, 0, 0, 1
  4170. );
  4171. return this;
  4172. }
  4173. makeRotationZ( theta ) {
  4174. const c = Math.cos( theta ), s = Math.sin( theta );
  4175. this.set(
  4176. c, - s, 0, 0,
  4177. s, c, 0, 0,
  4178. 0, 0, 1, 0,
  4179. 0, 0, 0, 1
  4180. );
  4181. return this;
  4182. }
  4183. makeRotationAxis( axis, angle ) {
  4184. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4185. const c = Math.cos( angle );
  4186. const s = Math.sin( angle );
  4187. const t = 1 - c;
  4188. const x = axis.x, y = axis.y, z = axis.z;
  4189. const tx = t * x, ty = t * y;
  4190. this.set(
  4191. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4192. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4193. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4194. 0, 0, 0, 1
  4195. );
  4196. return this;
  4197. }
  4198. makeScale( x, y, z ) {
  4199. this.set(
  4200. x, 0, 0, 0,
  4201. 0, y, 0, 0,
  4202. 0, 0, z, 0,
  4203. 0, 0, 0, 1
  4204. );
  4205. return this;
  4206. }
  4207. makeShear( x, y, z ) {
  4208. this.set(
  4209. 1, y, z, 0,
  4210. x, 1, z, 0,
  4211. x, y, 1, 0,
  4212. 0, 0, 0, 1
  4213. );
  4214. return this;
  4215. }
  4216. compose( position, quaternion, scale ) {
  4217. const te = this.elements;
  4218. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4219. const x2 = x + x, y2 = y + y, z2 = z + z;
  4220. const xx = x * x2, xy = x * y2, xz = x * z2;
  4221. const yy = y * y2, yz = y * z2, zz = z * z2;
  4222. const wx = w * x2, wy = w * y2, wz = w * z2;
  4223. const sx = scale.x, sy = scale.y, sz = scale.z;
  4224. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4225. te[ 1 ] = ( xy + wz ) * sx;
  4226. te[ 2 ] = ( xz - wy ) * sx;
  4227. te[ 3 ] = 0;
  4228. te[ 4 ] = ( xy - wz ) * sy;
  4229. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4230. te[ 6 ] = ( yz + wx ) * sy;
  4231. te[ 7 ] = 0;
  4232. te[ 8 ] = ( xz + wy ) * sz;
  4233. te[ 9 ] = ( yz - wx ) * sz;
  4234. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4235. te[ 11 ] = 0;
  4236. te[ 12 ] = position.x;
  4237. te[ 13 ] = position.y;
  4238. te[ 14 ] = position.z;
  4239. te[ 15 ] = 1;
  4240. return this;
  4241. }
  4242. decompose( position, quaternion, scale ) {
  4243. const te = this.elements;
  4244. let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4245. const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4246. const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4247. // if determine is negative, we need to invert one scale
  4248. const det = this.determinant();
  4249. if ( det < 0 ) sx = - sx;
  4250. position.x = te[ 12 ];
  4251. position.y = te[ 13 ];
  4252. position.z = te[ 14 ];
  4253. // scale the rotation part
  4254. _m1.copy( this );
  4255. const invSX = 1 / sx;
  4256. const invSY = 1 / sy;
  4257. const invSZ = 1 / sz;
  4258. _m1.elements[ 0 ] *= invSX;
  4259. _m1.elements[ 1 ] *= invSX;
  4260. _m1.elements[ 2 ] *= invSX;
  4261. _m1.elements[ 4 ] *= invSY;
  4262. _m1.elements[ 5 ] *= invSY;
  4263. _m1.elements[ 6 ] *= invSY;
  4264. _m1.elements[ 8 ] *= invSZ;
  4265. _m1.elements[ 9 ] *= invSZ;
  4266. _m1.elements[ 10 ] *= invSZ;
  4267. quaternion.setFromRotationMatrix( _m1 );
  4268. scale.x = sx;
  4269. scale.y = sy;
  4270. scale.z = sz;
  4271. return this;
  4272. }
  4273. makePerspective( left, right, top, bottom, near, far ) {
  4274. if ( far === undefined ) {
  4275. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4276. }
  4277. const te = this.elements;
  4278. const x = 2 * near / ( right - left );
  4279. const y = 2 * near / ( top - bottom );
  4280. const a = ( right + left ) / ( right - left );
  4281. const b = ( top + bottom ) / ( top - bottom );
  4282. const c = - ( far + near ) / ( far - near );
  4283. const d = - 2 * far * near / ( far - near );
  4284. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4285. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4286. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4287. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4288. return this;
  4289. }
  4290. makeOrthographic( left, right, top, bottom, near, far ) {
  4291. const te = this.elements;
  4292. const w = 1.0 / ( right - left );
  4293. const h = 1.0 / ( top - bottom );
  4294. const p = 1.0 / ( far - near );
  4295. const x = ( right + left ) * w;
  4296. const y = ( top + bottom ) * h;
  4297. const z = ( far + near ) * p;
  4298. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4299. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4300. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4301. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4302. return this;
  4303. }
  4304. equals( matrix ) {
  4305. const te = this.elements;
  4306. const me = matrix.elements;
  4307. for ( let i = 0; i < 16; i ++ ) {
  4308. if ( te[ i ] !== me[ i ] ) return false;
  4309. }
  4310. return true;
  4311. }
  4312. fromArray( array, offset = 0 ) {
  4313. for ( let i = 0; i < 16; i ++ ) {
  4314. this.elements[ i ] = array[ i + offset ];
  4315. }
  4316. return this;
  4317. }
  4318. toArray( array = [], offset = 0 ) {
  4319. const te = this.elements;
  4320. array[ offset ] = te[ 0 ];
  4321. array[ offset + 1 ] = te[ 1 ];
  4322. array[ offset + 2 ] = te[ 2 ];
  4323. array[ offset + 3 ] = te[ 3 ];
  4324. array[ offset + 4 ] = te[ 4 ];
  4325. array[ offset + 5 ] = te[ 5 ];
  4326. array[ offset + 6 ] = te[ 6 ];
  4327. array[ offset + 7 ] = te[ 7 ];
  4328. array[ offset + 8 ] = te[ 8 ];
  4329. array[ offset + 9 ] = te[ 9 ];
  4330. array[ offset + 10 ] = te[ 10 ];
  4331. array[ offset + 11 ] = te[ 11 ];
  4332. array[ offset + 12 ] = te[ 12 ];
  4333. array[ offset + 13 ] = te[ 13 ];
  4334. array[ offset + 14 ] = te[ 14 ];
  4335. array[ offset + 15 ] = te[ 15 ];
  4336. return array;
  4337. }
  4338. }
  4339. const _v1$1 = /*@__PURE__*/ new Vector3();
  4340. const _m1 = /*@__PURE__*/ new Matrix4();
  4341. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4342. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4343. const _x = /*@__PURE__*/ new Vector3();
  4344. const _y = /*@__PURE__*/ new Vector3();
  4345. const _z = /*@__PURE__*/ new Vector3();
  4346. class Euler {
  4347. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4348. Object.defineProperty( this, 'isEuler', { value: true } );
  4349. this._x = x;
  4350. this._y = y;
  4351. this._z = z;
  4352. this._order = order;
  4353. }
  4354. get x() {
  4355. return this._x;
  4356. }
  4357. set x( value ) {
  4358. this._x = value;
  4359. this._onChangeCallback();
  4360. }
  4361. get y() {
  4362. return this._y;
  4363. }
  4364. set y( value ) {
  4365. this._y = value;
  4366. this._onChangeCallback();
  4367. }
  4368. get z() {
  4369. return this._z;
  4370. }
  4371. set z( value ) {
  4372. this._z = value;
  4373. this._onChangeCallback();
  4374. }
  4375. get order() {
  4376. return this._order;
  4377. }
  4378. set order( value ) {
  4379. this._order = value;
  4380. this._onChangeCallback();
  4381. }
  4382. set( x, y, z, order ) {
  4383. this._x = x;
  4384. this._y = y;
  4385. this._z = z;
  4386. this._order = order || this._order;
  4387. this._onChangeCallback();
  4388. return this;
  4389. }
  4390. clone() {
  4391. return new this.constructor( this._x, this._y, this._z, this._order );
  4392. }
  4393. copy( euler ) {
  4394. this._x = euler._x;
  4395. this._y = euler._y;
  4396. this._z = euler._z;
  4397. this._order = euler._order;
  4398. this._onChangeCallback();
  4399. return this;
  4400. }
  4401. setFromRotationMatrix( m, order, update ) {
  4402. const clamp = MathUtils.clamp;
  4403. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4404. const te = m.elements;
  4405. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4406. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4407. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4408. order = order || this._order;
  4409. switch ( order ) {
  4410. case 'XYZ':
  4411. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4412. if ( Math.abs( m13 ) < 0.9999999 ) {
  4413. this._x = Math.atan2( - m23, m33 );
  4414. this._z = Math.atan2( - m12, m11 );
  4415. } else {
  4416. this._x = Math.atan2( m32, m22 );
  4417. this._z = 0;
  4418. }
  4419. break;
  4420. case 'YXZ':
  4421. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4422. if ( Math.abs( m23 ) < 0.9999999 ) {
  4423. this._y = Math.atan2( m13, m33 );
  4424. this._z = Math.atan2( m21, m22 );
  4425. } else {
  4426. this._y = Math.atan2( - m31, m11 );
  4427. this._z = 0;
  4428. }
  4429. break;
  4430. case 'ZXY':
  4431. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4432. if ( Math.abs( m32 ) < 0.9999999 ) {
  4433. this._y = Math.atan2( - m31, m33 );
  4434. this._z = Math.atan2( - m12, m22 );
  4435. } else {
  4436. this._y = 0;
  4437. this._z = Math.atan2( m21, m11 );
  4438. }
  4439. break;
  4440. case 'ZYX':
  4441. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4442. if ( Math.abs( m31 ) < 0.9999999 ) {
  4443. this._x = Math.atan2( m32, m33 );
  4444. this._z = Math.atan2( m21, m11 );
  4445. } else {
  4446. this._x = 0;
  4447. this._z = Math.atan2( - m12, m22 );
  4448. }
  4449. break;
  4450. case 'YZX':
  4451. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4452. if ( Math.abs( m21 ) < 0.9999999 ) {
  4453. this._x = Math.atan2( - m23, m22 );
  4454. this._y = Math.atan2( - m31, m11 );
  4455. } else {
  4456. this._x = 0;
  4457. this._y = Math.atan2( m13, m33 );
  4458. }
  4459. break;
  4460. case 'XZY':
  4461. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4462. if ( Math.abs( m12 ) < 0.9999999 ) {
  4463. this._x = Math.atan2( m32, m22 );
  4464. this._y = Math.atan2( m13, m11 );
  4465. } else {
  4466. this._x = Math.atan2( - m23, m33 );
  4467. this._y = 0;
  4468. }
  4469. break;
  4470. default:
  4471. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4472. }
  4473. this._order = order;
  4474. if ( update !== false ) this._onChangeCallback();
  4475. return this;
  4476. }
  4477. setFromQuaternion( q, order, update ) {
  4478. _matrix.makeRotationFromQuaternion( q );
  4479. return this.setFromRotationMatrix( _matrix, order, update );
  4480. }
  4481. setFromVector3( v, order ) {
  4482. return this.set( v.x, v.y, v.z, order || this._order );
  4483. }
  4484. reorder( newOrder ) {
  4485. // WARNING: this discards revolution information -bhouston
  4486. _quaternion$1.setFromEuler( this );
  4487. return this.setFromQuaternion( _quaternion$1, newOrder );
  4488. }
  4489. equals( euler ) {
  4490. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4491. }
  4492. fromArray( array ) {
  4493. this._x = array[ 0 ];
  4494. this._y = array[ 1 ];
  4495. this._z = array[ 2 ];
  4496. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4497. this._onChangeCallback();
  4498. return this;
  4499. }
  4500. toArray( array = [], offset = 0 ) {
  4501. array[ offset ] = this._x;
  4502. array[ offset + 1 ] = this._y;
  4503. array[ offset + 2 ] = this._z;
  4504. array[ offset + 3 ] = this._order;
  4505. return array;
  4506. }
  4507. toVector3( optionalResult ) {
  4508. if ( optionalResult ) {
  4509. return optionalResult.set( this._x, this._y, this._z );
  4510. } else {
  4511. return new Vector3( this._x, this._y, this._z );
  4512. }
  4513. }
  4514. _onChange( callback ) {
  4515. this._onChangeCallback = callback;
  4516. return this;
  4517. }
  4518. _onChangeCallback() {}
  4519. }
  4520. Euler.DefaultOrder = 'XYZ';
  4521. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4522. const _matrix = /*@__PURE__*/ new Matrix4();
  4523. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  4524. class Layers {
  4525. constructor() {
  4526. this.mask = 1 | 0;
  4527. }
  4528. set( channel ) {
  4529. this.mask = 1 << channel | 0;
  4530. }
  4531. enable( channel ) {
  4532. this.mask |= 1 << channel | 0;
  4533. }
  4534. enableAll() {
  4535. this.mask = 0xffffffff | 0;
  4536. }
  4537. toggle( channel ) {
  4538. this.mask ^= 1 << channel | 0;
  4539. }
  4540. disable( channel ) {
  4541. this.mask &= ~ ( 1 << channel | 0 );
  4542. }
  4543. disableAll() {
  4544. this.mask = 0;
  4545. }
  4546. test( layers ) {
  4547. return ( this.mask & layers.mask ) !== 0;
  4548. }
  4549. }
  4550. let _object3DId = 0;
  4551. const _v1$2 = new Vector3();
  4552. const _q1 = new Quaternion();
  4553. const _m1$1 = new Matrix4();
  4554. const _target = new Vector3();
  4555. const _position = new Vector3();
  4556. const _scale = new Vector3();
  4557. const _quaternion$2 = new Quaternion();
  4558. const _xAxis = new Vector3( 1, 0, 0 );
  4559. const _yAxis = new Vector3( 0, 1, 0 );
  4560. const _zAxis = new Vector3( 0, 0, 1 );
  4561. const _addedEvent = { type: 'added' };
  4562. const _removedEvent = { type: 'removed' };
  4563. function Object3D() {
  4564. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4565. this.uuid = MathUtils.generateUUID();
  4566. this.name = '';
  4567. this.type = 'Object3D';
  4568. this.parent = null;
  4569. this.children = [];
  4570. this.up = Object3D.DefaultUp.clone();
  4571. const position = new Vector3();
  4572. const rotation = new Euler();
  4573. const quaternion = new Quaternion();
  4574. const scale = new Vector3( 1, 1, 1 );
  4575. function onRotationChange() {
  4576. quaternion.setFromEuler( rotation, false );
  4577. }
  4578. function onQuaternionChange() {
  4579. rotation.setFromQuaternion( quaternion, undefined, false );
  4580. }
  4581. rotation._onChange( onRotationChange );
  4582. quaternion._onChange( onQuaternionChange );
  4583. Object.defineProperties( this, {
  4584. position: {
  4585. configurable: true,
  4586. enumerable: true,
  4587. value: position
  4588. },
  4589. rotation: {
  4590. configurable: true,
  4591. enumerable: true,
  4592. value: rotation
  4593. },
  4594. quaternion: {
  4595. configurable: true,
  4596. enumerable: true,
  4597. value: quaternion
  4598. },
  4599. scale: {
  4600. configurable: true,
  4601. enumerable: true,
  4602. value: scale
  4603. },
  4604. modelViewMatrix: {
  4605. value: new Matrix4()
  4606. },
  4607. normalMatrix: {
  4608. value: new Matrix3()
  4609. }
  4610. } );
  4611. this.matrix = new Matrix4();
  4612. this.matrixWorld = new Matrix4();
  4613. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4614. this.matrixWorldNeedsUpdate = false;
  4615. this.layers = new Layers();
  4616. this.visible = true;
  4617. this.castShadow = false;
  4618. this.receiveShadow = false;
  4619. this.frustumCulled = true;
  4620. this.renderOrder = 0;
  4621. this.animations = [];
  4622. this.userData = {};
  4623. }
  4624. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4625. Object3D.DefaultMatrixAutoUpdate = true;
  4626. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  4627. constructor: Object3D,
  4628. isObject3D: true,
  4629. onBeforeRender: function () {},
  4630. onAfterRender: function () {},
  4631. applyMatrix4: function ( matrix ) {
  4632. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4633. this.matrix.premultiply( matrix );
  4634. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4635. },
  4636. applyQuaternion: function ( q ) {
  4637. this.quaternion.premultiply( q );
  4638. return this;
  4639. },
  4640. setRotationFromAxisAngle: function ( axis, angle ) {
  4641. // assumes axis is normalized
  4642. this.quaternion.setFromAxisAngle( axis, angle );
  4643. },
  4644. setRotationFromEuler: function ( euler ) {
  4645. this.quaternion.setFromEuler( euler, true );
  4646. },
  4647. setRotationFromMatrix: function ( m ) {
  4648. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4649. this.quaternion.setFromRotationMatrix( m );
  4650. },
  4651. setRotationFromQuaternion: function ( q ) {
  4652. // assumes q is normalized
  4653. this.quaternion.copy( q );
  4654. },
  4655. rotateOnAxis: function ( axis, angle ) {
  4656. // rotate object on axis in object space
  4657. // axis is assumed to be normalized
  4658. _q1.setFromAxisAngle( axis, angle );
  4659. this.quaternion.multiply( _q1 );
  4660. return this;
  4661. },
  4662. rotateOnWorldAxis: function ( axis, angle ) {
  4663. // rotate object on axis in world space
  4664. // axis is assumed to be normalized
  4665. // method assumes no rotated parent
  4666. _q1.setFromAxisAngle( axis, angle );
  4667. this.quaternion.premultiply( _q1 );
  4668. return this;
  4669. },
  4670. rotateX: function ( angle ) {
  4671. return this.rotateOnAxis( _xAxis, angle );
  4672. },
  4673. rotateY: function ( angle ) {
  4674. return this.rotateOnAxis( _yAxis, angle );
  4675. },
  4676. rotateZ: function ( angle ) {
  4677. return this.rotateOnAxis( _zAxis, angle );
  4678. },
  4679. translateOnAxis: function ( axis, distance ) {
  4680. // translate object by distance along axis in object space
  4681. // axis is assumed to be normalized
  4682. _v1$2.copy( axis ).applyQuaternion( this.quaternion );
  4683. this.position.add( _v1$2.multiplyScalar( distance ) );
  4684. return this;
  4685. },
  4686. translateX: function ( distance ) {
  4687. return this.translateOnAxis( _xAxis, distance );
  4688. },
  4689. translateY: function ( distance ) {
  4690. return this.translateOnAxis( _yAxis, distance );
  4691. },
  4692. translateZ: function ( distance ) {
  4693. return this.translateOnAxis( _zAxis, distance );
  4694. },
  4695. localToWorld: function ( vector ) {
  4696. return vector.applyMatrix4( this.matrixWorld );
  4697. },
  4698. worldToLocal: function ( vector ) {
  4699. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4700. },
  4701. lookAt: function ( x, y, z ) {
  4702. // This method does not support objects having non-uniformly-scaled parent(s)
  4703. if ( x.isVector3 ) {
  4704. _target.copy( x );
  4705. } else {
  4706. _target.set( x, y, z );
  4707. }
  4708. const parent = this.parent;
  4709. this.updateWorldMatrix( true, false );
  4710. _position.setFromMatrixPosition( this.matrixWorld );
  4711. if ( this.isCamera || this.isLight ) {
  4712. _m1$1.lookAt( _position, _target, this.up );
  4713. } else {
  4714. _m1$1.lookAt( _target, _position, this.up );
  4715. }
  4716. this.quaternion.setFromRotationMatrix( _m1$1 );
  4717. if ( parent ) {
  4718. _m1$1.extractRotation( parent.matrixWorld );
  4719. _q1.setFromRotationMatrix( _m1$1 );
  4720. this.quaternion.premultiply( _q1.invert() );
  4721. }
  4722. },
  4723. add: function ( object ) {
  4724. if ( arguments.length > 1 ) {
  4725. for ( let i = 0; i < arguments.length; i ++ ) {
  4726. this.add( arguments[ i ] );
  4727. }
  4728. return this;
  4729. }
  4730. if ( object === this ) {
  4731. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4732. return this;
  4733. }
  4734. if ( object && object.isObject3D ) {
  4735. if ( object.parent !== null ) {
  4736. object.parent.remove( object );
  4737. }
  4738. object.parent = this;
  4739. this.children.push( object );
  4740. object.dispatchEvent( _addedEvent );
  4741. } else {
  4742. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4743. }
  4744. return this;
  4745. },
  4746. remove: function ( object ) {
  4747. if ( arguments.length > 1 ) {
  4748. for ( let i = 0; i < arguments.length; i ++ ) {
  4749. this.remove( arguments[ i ] );
  4750. }
  4751. return this;
  4752. }
  4753. const index = this.children.indexOf( object );
  4754. if ( index !== - 1 ) {
  4755. object.parent = null;
  4756. this.children.splice( index, 1 );
  4757. object.dispatchEvent( _removedEvent );
  4758. }
  4759. return this;
  4760. },
  4761. clear: function () {
  4762. for ( let i = 0; i < this.children.length; i ++ ) {
  4763. const object = this.children[ i ];
  4764. object.parent = null;
  4765. object.dispatchEvent( _removedEvent );
  4766. }
  4767. this.children.length = 0;
  4768. return this;
  4769. },
  4770. attach: function ( object ) {
  4771. // adds object as a child of this, while maintaining the object's world transform
  4772. this.updateWorldMatrix( true, false );
  4773. _m1$1.copy( this.matrixWorld ).invert();
  4774. if ( object.parent !== null ) {
  4775. object.parent.updateWorldMatrix( true, false );
  4776. _m1$1.multiply( object.parent.matrixWorld );
  4777. }
  4778. object.applyMatrix4( _m1$1 );
  4779. object.updateWorldMatrix( false, false );
  4780. this.add( object );
  4781. return this;
  4782. },
  4783. getObjectById: function ( id ) {
  4784. return this.getObjectByProperty( 'id', id );
  4785. },
  4786. getObjectByName: function ( name ) {
  4787. return this.getObjectByProperty( 'name', name );
  4788. },
  4789. getObjectByProperty: function ( name, value ) {
  4790. if ( this[ name ] === value ) return this;
  4791. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4792. const child = this.children[ i ];
  4793. const object = child.getObjectByProperty( name, value );
  4794. if ( object !== undefined ) {
  4795. return object;
  4796. }
  4797. }
  4798. return undefined;
  4799. },
  4800. getWorldPosition: function ( target ) {
  4801. if ( target === undefined ) {
  4802. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4803. target = new Vector3();
  4804. }
  4805. this.updateWorldMatrix( true, false );
  4806. return target.setFromMatrixPosition( this.matrixWorld );
  4807. },
  4808. getWorldQuaternion: function ( target ) {
  4809. if ( target === undefined ) {
  4810. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4811. target = new Quaternion();
  4812. }
  4813. this.updateWorldMatrix( true, false );
  4814. this.matrixWorld.decompose( _position, target, _scale );
  4815. return target;
  4816. },
  4817. getWorldScale: function ( target ) {
  4818. if ( target === undefined ) {
  4819. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4820. target = new Vector3();
  4821. }
  4822. this.updateWorldMatrix( true, false );
  4823. this.matrixWorld.decompose( _position, _quaternion$2, target );
  4824. return target;
  4825. },
  4826. getWorldDirection: function ( target ) {
  4827. if ( target === undefined ) {
  4828. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4829. target = new Vector3();
  4830. }
  4831. this.updateWorldMatrix( true, false );
  4832. const e = this.matrixWorld.elements;
  4833. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4834. },
  4835. raycast: function () {},
  4836. traverse: function ( callback ) {
  4837. let result = callback( this );
  4838. if(result && result.stopContinue){//xzw add
  4839. return
  4840. }
  4841. const children = this.children;
  4842. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4843. children[ i ].traverse( callback );
  4844. }
  4845. },
  4846. traverseVisible: function ( callback ) {
  4847. if ( this.visible === false ) return;
  4848. callback( this );
  4849. const children = this.children;
  4850. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4851. children[ i ].traverseVisible( callback );
  4852. }
  4853. },
  4854. traverseAncestors: function ( callback ) {
  4855. const parent = this.parent;
  4856. if ( parent !== null ) {
  4857. callback( parent );
  4858. parent.traverseAncestors( callback );
  4859. }
  4860. },
  4861. updateMatrix: function () {
  4862. this.matrix.compose( this.position, this.quaternion, this.scale );
  4863. this.matrixWorldNeedsUpdate = true;
  4864. },
  4865. updateMatrixWorld: function ( force ) {
  4866. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4867. if ( this.matrixWorldNeedsUpdate || force ) {
  4868. if ( this.parent === null ) {
  4869. this.matrixWorld.copy( this.matrix );
  4870. } else {
  4871. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4872. }
  4873. this.matrixWorldNeedsUpdate = false;
  4874. force = true;
  4875. }
  4876. // update children
  4877. const children = this.children;
  4878. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4879. children[ i ].updateMatrixWorld( force );
  4880. }
  4881. },
  4882. updateWorldMatrix: function ( updateParents, updateChildren ) {
  4883. const parent = this.parent;
  4884. if ( updateParents === true && parent !== null ) {
  4885. parent.updateWorldMatrix( true, false );
  4886. }
  4887. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4888. if ( this.parent === null ) {
  4889. this.matrixWorld.copy( this.matrix );
  4890. } else {
  4891. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4892. }
  4893. // update children
  4894. if ( updateChildren === true ) {
  4895. const children = this.children;
  4896. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4897. children[ i ].updateWorldMatrix( false, true );
  4898. }
  4899. }
  4900. },
  4901. toJSON: function ( meta ) {
  4902. // meta is a string when called from JSON.stringify
  4903. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4904. const output = {};
  4905. // meta is a hash used to collect geometries, materials.
  4906. // not providing it implies that this is the root object
  4907. // being serialized.
  4908. if ( isRootObject ) {
  4909. // initialize meta obj
  4910. meta = {
  4911. geometries: {},
  4912. materials: {},
  4913. textures: {},
  4914. images: {},
  4915. shapes: {},
  4916. skeletons: {},
  4917. animations: {}
  4918. };
  4919. output.metadata = {
  4920. version: 4.5,
  4921. type: 'Object',
  4922. generator: 'Object3D.toJSON'
  4923. };
  4924. }
  4925. // standard Object3D serialization
  4926. const object = {};
  4927. object.uuid = this.uuid;
  4928. object.type = this.type;
  4929. if ( this.name !== '' ) object.name = this.name;
  4930. if ( this.castShadow === true ) object.castShadow = true;
  4931. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4932. if ( this.visible === false ) object.visible = false;
  4933. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4934. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4935. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4936. object.layers = this.layers.mask;
  4937. object.matrix = this.matrix.toArray();
  4938. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4939. // object specific properties
  4940. if ( this.isInstancedMesh ) {
  4941. object.type = 'InstancedMesh';
  4942. object.count = this.count;
  4943. object.instanceMatrix = this.instanceMatrix.toJSON();
  4944. }
  4945. //
  4946. function serialize( library, element ) {
  4947. if ( library[ element.uuid ] === undefined ) {
  4948. library[ element.uuid ] = element.toJSON( meta );
  4949. }
  4950. return element.uuid;
  4951. }
  4952. if ( this.isMesh || this.isLine || this.isPoints ) {
  4953. object.geometry = serialize( meta.geometries, this.geometry );
  4954. const parameters = this.geometry.parameters;
  4955. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4956. const shapes = parameters.shapes;
  4957. if ( Array.isArray( shapes ) ) {
  4958. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4959. const shape = shapes[ i ];
  4960. serialize( meta.shapes, shape );
  4961. }
  4962. } else {
  4963. serialize( meta.shapes, shapes );
  4964. }
  4965. }
  4966. }
  4967. if ( this.isSkinnedMesh ) {
  4968. object.bindMode = this.bindMode;
  4969. object.bindMatrix = this.bindMatrix.toArray();
  4970. if ( this.skeleton !== undefined ) {
  4971. serialize( meta.skeletons, this.skeleton );
  4972. object.skeleton = this.skeleton.uuid;
  4973. }
  4974. }
  4975. if ( this.material !== undefined ) {
  4976. if ( Array.isArray( this.material ) ) {
  4977. const uuids = [];
  4978. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4979. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4980. }
  4981. object.material = uuids;
  4982. } else {
  4983. object.material = serialize( meta.materials, this.material );
  4984. }
  4985. }
  4986. //
  4987. if ( this.children.length > 0 ) {
  4988. object.children = [];
  4989. for ( let i = 0; i < this.children.length; i ++ ) {
  4990. object.children.push( this.children[ i ].toJSON( meta ).object );
  4991. }
  4992. }
  4993. //
  4994. if ( this.animations.length > 0 ) {
  4995. object.animations = [];
  4996. for ( let i = 0; i < this.animations.length; i ++ ) {
  4997. const animation = this.animations[ i ];
  4998. object.animations.push( serialize( meta.animations, animation ) );
  4999. }
  5000. }
  5001. if ( isRootObject ) {
  5002. const geometries = extractFromCache( meta.geometries );
  5003. const materials = extractFromCache( meta.materials );
  5004. const textures = extractFromCache( meta.textures );
  5005. const images = extractFromCache( meta.images );
  5006. const shapes = extractFromCache( meta.shapes );
  5007. const skeletons = extractFromCache( meta.skeletons );
  5008. const animations = extractFromCache( meta.animations );
  5009. if ( geometries.length > 0 ) output.geometries = geometries;
  5010. if ( materials.length > 0 ) output.materials = materials;
  5011. if ( textures.length > 0 ) output.textures = textures;
  5012. if ( images.length > 0 ) output.images = images;
  5013. if ( shapes.length > 0 ) output.shapes = shapes;
  5014. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  5015. if ( animations.length > 0 ) output.animations = animations;
  5016. }
  5017. output.object = object;
  5018. return output;
  5019. // extract data from the cache hash
  5020. // remove metadata on each item
  5021. // and return as array
  5022. function extractFromCache( cache ) {
  5023. const values = [];
  5024. for ( const key in cache ) {
  5025. const data = cache[ key ];
  5026. delete data.metadata;
  5027. values.push( data );
  5028. }
  5029. return values;
  5030. }
  5031. },
  5032. clone: function ( recursive ) {
  5033. return new this.constructor().copy( this, recursive );
  5034. },
  5035. copy: function ( source, recursive = true ) {
  5036. this.name = source.name;
  5037. this.up.copy( source.up );
  5038. this.position.copy( source.position );
  5039. this.rotation.order = source.rotation.order;
  5040. this.quaternion.copy( source.quaternion );
  5041. this.scale.copy( source.scale );
  5042. this.matrix.copy( source.matrix );
  5043. this.matrixWorld.copy( source.matrixWorld );
  5044. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5045. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5046. this.layers.mask = source.layers.mask;
  5047. this.visible = source.visible;
  5048. this.castShadow = source.castShadow;
  5049. this.receiveShadow = source.receiveShadow;
  5050. this.frustumCulled = source.frustumCulled;
  5051. this.renderOrder = source.renderOrder;
  5052. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5053. if ( recursive === true ) {
  5054. for ( let i = 0; i < source.children.length; i ++ ) {
  5055. const child = source.children[ i ];
  5056. this.add( child.clone() );
  5057. }
  5058. }
  5059. return this;
  5060. }
  5061. } );
  5062. const _vector1 = /*@__PURE__*/ new Vector3();
  5063. const _vector2 = /*@__PURE__*/ new Vector3();
  5064. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  5065. class Plane {
  5066. constructor( normal, constant ) {
  5067. Object.defineProperty( this, 'isPlane', { value: true } );
  5068. // normal is assumed to be normalized
  5069. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5070. this.constant = ( constant !== undefined ) ? constant : 0;
  5071. }
  5072. set( normal, constant ) {
  5073. this.normal.copy( normal );
  5074. this.constant = constant;
  5075. return this;
  5076. }
  5077. setComponents( x, y, z, w ) {
  5078. this.normal.set( x, y, z );
  5079. this.constant = w;
  5080. return this;
  5081. }
  5082. setFromNormalAndCoplanarPoint( normal, point ) {
  5083. this.normal.copy( normal );
  5084. this.constant = - point.dot( this.normal );
  5085. return this;
  5086. }
  5087. setFromCoplanarPoints( a, b, c ) {
  5088. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  5089. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5090. this.setFromNormalAndCoplanarPoint( normal, a );
  5091. return this;
  5092. }
  5093. clone() {
  5094. return new this.constructor().copy( this );
  5095. }
  5096. copy( plane ) {
  5097. this.normal.copy( plane.normal );
  5098. this.constant = plane.constant;
  5099. return this;
  5100. }
  5101. normalize() {
  5102. // Note: will lead to a divide by zero if the plane is invalid.
  5103. const inverseNormalLength = 1.0 / this.normal.length();
  5104. this.normal.multiplyScalar( inverseNormalLength );
  5105. this.constant *= inverseNormalLength;
  5106. return this;
  5107. }
  5108. negate() {
  5109. this.constant *= - 1;
  5110. this.normal.negate();
  5111. return this;
  5112. }
  5113. distanceToPoint( point ) {
  5114. return this.normal.dot( point ) + this.constant;
  5115. }
  5116. distanceToSphere( sphere ) {
  5117. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5118. }
  5119. projectPoint( point, target ) {
  5120. if ( target === undefined ) {
  5121. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  5122. target = new Vector3();
  5123. }
  5124. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5125. }
  5126. intersectLine( line, target ) {
  5127. if ( target === undefined ) {
  5128. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  5129. target = new Vector3();
  5130. }
  5131. const direction = line.delta( _vector1 );
  5132. const denominator = this.normal.dot( direction );
  5133. if ( denominator === 0 ) {
  5134. // line is coplanar, return origin
  5135. if ( this.distanceToPoint( line.start ) === 0 ) {
  5136. return target.copy( line.start );
  5137. }
  5138. // Unsure if this is the correct method to handle this case.
  5139. return undefined;
  5140. }
  5141. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5142. if ( t < 0 || t > 1 ) {
  5143. return undefined;
  5144. }
  5145. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  5146. }
  5147. intersectsLine( line ) {
  5148. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5149. const startSign = this.distanceToPoint( line.start );
  5150. const endSign = this.distanceToPoint( line.end );
  5151. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5152. }
  5153. intersectsBox( box ) {
  5154. return box.intersectsPlane( this );
  5155. }
  5156. intersectsSphere( sphere ) {
  5157. return sphere.intersectsPlane( this );
  5158. }
  5159. coplanarPoint( target ) {
  5160. if ( target === undefined ) {
  5161. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  5162. target = new Vector3();
  5163. }
  5164. return target.copy( this.normal ).multiplyScalar( - this.constant );
  5165. }
  5166. applyMatrix4( matrix, optionalNormalMatrix ) {
  5167. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  5168. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  5169. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5170. this.constant = - referencePoint.dot( normal );
  5171. return this;
  5172. }
  5173. translate( offset ) {
  5174. this.constant -= offset.dot( this.normal );
  5175. return this;
  5176. }
  5177. equals( plane ) {
  5178. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5179. }
  5180. }
  5181. const _v0$1 = /*@__PURE__*/ new Vector3();
  5182. const _v1$3 = /*@__PURE__*/ new Vector3();
  5183. const _v2$1 = /*@__PURE__*/ new Vector3();
  5184. const _v3 = /*@__PURE__*/ new Vector3();
  5185. const _vab = /*@__PURE__*/ new Vector3();
  5186. const _vac = /*@__PURE__*/ new Vector3();
  5187. const _vbc = /*@__PURE__*/ new Vector3();
  5188. const _vap = /*@__PURE__*/ new Vector3();
  5189. const _vbp = /*@__PURE__*/ new Vector3();
  5190. const _vcp = /*@__PURE__*/ new Vector3();
  5191. class Triangle {
  5192. constructor( a, b, c ) {
  5193. this.a = ( a !== undefined ) ? a : new Vector3();
  5194. this.b = ( b !== undefined ) ? b : new Vector3();
  5195. this.c = ( c !== undefined ) ? c : new Vector3();
  5196. }
  5197. static getNormal( a, b, c, target ) {
  5198. if ( target === undefined ) {
  5199. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  5200. target = new Vector3();
  5201. }
  5202. target.subVectors( c, b );
  5203. _v0$1.subVectors( a, b );
  5204. target.cross( _v0$1 );
  5205. const targetLengthSq = target.lengthSq();
  5206. if ( targetLengthSq > 0 ) {
  5207. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5208. }
  5209. return target.set( 0, 0, 0 );
  5210. }
  5211. // static/instance method to calculate barycentric coordinates
  5212. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5213. static getBarycoord( point, a, b, c, target ) {
  5214. _v0$1.subVectors( c, a );
  5215. _v1$3.subVectors( b, a );
  5216. _v2$1.subVectors( point, a );
  5217. const dot00 = _v0$1.dot( _v0$1 );
  5218. const dot01 = _v0$1.dot( _v1$3 );
  5219. const dot02 = _v0$1.dot( _v2$1 );
  5220. const dot11 = _v1$3.dot( _v1$3 );
  5221. const dot12 = _v1$3.dot( _v2$1 );
  5222. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5223. if ( target === undefined ) {
  5224. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  5225. target = new Vector3();
  5226. }
  5227. // collinear or singular triangle
  5228. if ( denom === 0 ) {
  5229. // arbitrary location outside of triangle?
  5230. // not sure if this is the best idea, maybe should be returning undefined
  5231. return target.set( - 2, - 1, - 1 );
  5232. }
  5233. const invDenom = 1 / denom;
  5234. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5235. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5236. // barycentric coordinates must always sum to 1
  5237. return target.set( 1 - u - v, v, u );
  5238. }
  5239. static containsPoint( point, a, b, c ) {
  5240. this.getBarycoord( point, a, b, c, _v3 );
  5241. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  5242. }
  5243. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5244. this.getBarycoord( point, p1, p2, p3, _v3 );
  5245. target.set( 0, 0 );
  5246. target.addScaledVector( uv1, _v3.x );
  5247. target.addScaledVector( uv2, _v3.y );
  5248. target.addScaledVector( uv3, _v3.z );
  5249. return target;
  5250. }
  5251. static isFrontFacing( a, b, c, direction ) {
  5252. _v0$1.subVectors( c, b );
  5253. _v1$3.subVectors( a, b );
  5254. // strictly front facing
  5255. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5256. }
  5257. set( a, b, c ) {
  5258. this.a.copy( a );
  5259. this.b.copy( b );
  5260. this.c.copy( c );
  5261. return this;
  5262. }
  5263. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5264. this.a.copy( points[ i0 ] );
  5265. this.b.copy( points[ i1 ] );
  5266. this.c.copy( points[ i2 ] );
  5267. return this;
  5268. }
  5269. clone() {
  5270. return new this.constructor().copy( this );
  5271. }
  5272. copy( triangle ) {
  5273. this.a.copy( triangle.a );
  5274. this.b.copy( triangle.b );
  5275. this.c.copy( triangle.c );
  5276. return this;
  5277. }
  5278. getArea() {
  5279. _v0$1.subVectors( this.c, this.b );
  5280. _v1$3.subVectors( this.a, this.b );
  5281. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5282. }
  5283. getMidpoint( target ) {
  5284. if ( target === undefined ) {
  5285. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  5286. target = new Vector3();
  5287. }
  5288. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5289. }
  5290. getNormal( target ) {
  5291. return Triangle.getNormal( this.a, this.b, this.c, target );
  5292. }
  5293. getPlane( target ) {
  5294. if ( target === undefined ) {
  5295. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  5296. target = new Plane();
  5297. }
  5298. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5299. }
  5300. getBarycoord( point, target ) {
  5301. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5302. }
  5303. getUV( point, uv1, uv2, uv3, target ) {
  5304. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5305. }
  5306. containsPoint( point ) {
  5307. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5308. }
  5309. isFrontFacing( direction ) {
  5310. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5311. }
  5312. intersectsBox( box ) {
  5313. return box.intersectsTriangle( this );
  5314. }
  5315. closestPointToPoint( p, target ) {
  5316. if ( target === undefined ) {
  5317. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  5318. target = new Vector3();
  5319. }
  5320. const a = this.a, b = this.b, c = this.c;
  5321. let v, w;
  5322. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5323. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5324. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5325. // basically, we're distinguishing which of the voronoi regions of the triangle
  5326. // the point lies in with the minimum amount of redundant computation.
  5327. _vab.subVectors( b, a );
  5328. _vac.subVectors( c, a );
  5329. _vap.subVectors( p, a );
  5330. const d1 = _vab.dot( _vap );
  5331. const d2 = _vac.dot( _vap );
  5332. if ( d1 <= 0 && d2 <= 0 ) {
  5333. // vertex region of A; barycentric coords (1, 0, 0)
  5334. return target.copy( a );
  5335. }
  5336. _vbp.subVectors( p, b );
  5337. const d3 = _vab.dot( _vbp );
  5338. const d4 = _vac.dot( _vbp );
  5339. if ( d3 >= 0 && d4 <= d3 ) {
  5340. // vertex region of B; barycentric coords (0, 1, 0)
  5341. return target.copy( b );
  5342. }
  5343. const vc = d1 * d4 - d3 * d2;
  5344. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5345. v = d1 / ( d1 - d3 );
  5346. // edge region of AB; barycentric coords (1-v, v, 0)
  5347. return target.copy( a ).addScaledVector( _vab, v );
  5348. }
  5349. _vcp.subVectors( p, c );
  5350. const d5 = _vab.dot( _vcp );
  5351. const d6 = _vac.dot( _vcp );
  5352. if ( d6 >= 0 && d5 <= d6 ) {
  5353. // vertex region of C; barycentric coords (0, 0, 1)
  5354. return target.copy( c );
  5355. }
  5356. const vb = d5 * d2 - d1 * d6;
  5357. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5358. w = d2 / ( d2 - d6 );
  5359. // edge region of AC; barycentric coords (1-w, 0, w)
  5360. return target.copy( a ).addScaledVector( _vac, w );
  5361. }
  5362. const va = d3 * d6 - d5 * d4;
  5363. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5364. _vbc.subVectors( c, b );
  5365. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5366. // edge region of BC; barycentric coords (0, 1-w, w)
  5367. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5368. }
  5369. // face region
  5370. const denom = 1 / ( va + vb + vc );
  5371. // u = va * denom
  5372. v = vb * denom;
  5373. w = vc * denom;
  5374. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5375. }
  5376. equals( triangle ) {
  5377. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5378. }
  5379. }
  5380. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5381. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5382. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5383. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5384. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5385. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5386. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5387. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5388. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5389. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5390. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5391. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5392. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5393. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5394. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5395. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5396. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5397. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5398. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5399. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5400. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5401. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5402. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5403. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5404. const _hslA = { h: 0, s: 0, l: 0 };
  5405. const _hslB = { h: 0, s: 0, l: 0 };
  5406. function hue2rgb( p, q, t ) {
  5407. if ( t < 0 ) t += 1;
  5408. if ( t > 1 ) t -= 1;
  5409. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5410. if ( t < 1 / 2 ) return q;
  5411. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5412. return p;
  5413. }
  5414. function SRGBToLinear( c ) {
  5415. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5416. }
  5417. function LinearToSRGB( c ) {
  5418. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5419. }
  5420. class Color {
  5421. constructor( r, g, b ) {
  5422. Object.defineProperty( this, 'isColor', { value: true } );
  5423. if ( g === undefined && b === undefined ) {
  5424. // r is THREE.Color, hex or string
  5425. return this.set( r );
  5426. }
  5427. return this.setRGB( r, g, b );
  5428. }
  5429. set( value ) {
  5430. if ( value && value.isColor ) {
  5431. this.copy( value );
  5432. } else if ( typeof value === 'number' ) {
  5433. this.setHex( value );
  5434. } else if ( typeof value === 'string' ) {
  5435. this.setStyle( value );
  5436. }
  5437. return this;
  5438. }
  5439. setScalar( scalar ) {
  5440. this.r = scalar;
  5441. this.g = scalar;
  5442. this.b = scalar;
  5443. return this;
  5444. }
  5445. setHex( hex ) {
  5446. hex = Math.floor( hex );
  5447. this.r = ( hex >> 16 & 255 ) / 255;
  5448. this.g = ( hex >> 8 & 255 ) / 255;
  5449. this.b = ( hex & 255 ) / 255;
  5450. return this;
  5451. }
  5452. setRGB( r, g, b ) {
  5453. this.r = r;
  5454. this.g = g;
  5455. this.b = b;
  5456. return this;
  5457. }
  5458. setHSL( h, s, l ) {
  5459. // h,s,l ranges are in 0.0 - 1.0
  5460. h = MathUtils.euclideanModulo( h, 1 );
  5461. s = MathUtils.clamp( s, 0, 1 );
  5462. l = MathUtils.clamp( l, 0, 1 );
  5463. if ( s === 0 ) {
  5464. this.r = this.g = this.b = l;
  5465. } else {
  5466. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5467. const q = ( 2 * l ) - p;
  5468. this.r = hue2rgb( q, p, h + 1 / 3 );
  5469. this.g = hue2rgb( q, p, h );
  5470. this.b = hue2rgb( q, p, h - 1 / 3 );
  5471. }
  5472. return this;
  5473. }
  5474. setStyle( style ) {
  5475. function handleAlpha( string ) {
  5476. if ( string === undefined ) return;
  5477. if ( parseFloat( string ) < 1 ) {
  5478. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5479. }
  5480. }
  5481. let m;
  5482. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  5483. // rgb / hsl
  5484. let color;
  5485. const name = m[ 1 ];
  5486. const components = m[ 2 ];
  5487. switch ( name ) {
  5488. case 'rgb':
  5489. case 'rgba':
  5490. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5491. // rgb(255,0,0) rgba(255,0,0,0.5)
  5492. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5493. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5494. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5495. handleAlpha( color[ 4 ] );
  5496. return this;
  5497. }
  5498. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5499. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5500. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5501. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5502. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5503. handleAlpha( color[ 4 ] );
  5504. return this;
  5505. }
  5506. break;
  5507. case 'hsl':
  5508. case 'hsla':
  5509. if ( color = /^(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5510. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5511. const h = parseFloat( color[ 1 ] ) / 360;
  5512. const s = parseInt( color[ 2 ], 10 ) / 100;
  5513. const l = parseInt( color[ 3 ], 10 ) / 100;
  5514. handleAlpha( color[ 4 ] );
  5515. return this.setHSL( h, s, l );
  5516. }
  5517. break;
  5518. }
  5519. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5520. // hex color
  5521. const hex = m[ 1 ];
  5522. const size = hex.length;
  5523. if ( size === 3 ) {
  5524. // #ff0
  5525. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5526. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5527. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5528. return this;
  5529. } else if ( size === 6 ) {
  5530. // #ff0000
  5531. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5532. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5533. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5534. return this;
  5535. }
  5536. }
  5537. if ( style && style.length > 0 ) {
  5538. return this.setColorName( style );
  5539. }
  5540. return this;
  5541. }
  5542. setColorName( style ) {
  5543. // color keywords
  5544. const hex = _colorKeywords[ style ];
  5545. if ( hex !== undefined ) {
  5546. // red
  5547. this.setHex( hex );
  5548. } else {
  5549. // unknown color
  5550. console.warn( 'THREE.Color: Unknown color ' + style );
  5551. }
  5552. return this;
  5553. }
  5554. clone() {
  5555. return new this.constructor( this.r, this.g, this.b );
  5556. }
  5557. copy( color ) {
  5558. this.r = color.r;
  5559. this.g = color.g;
  5560. this.b = color.b;
  5561. return this;
  5562. }
  5563. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5564. this.r = Math.pow( color.r, gammaFactor );
  5565. this.g = Math.pow( color.g, gammaFactor );
  5566. this.b = Math.pow( color.b, gammaFactor );
  5567. return this;
  5568. }
  5569. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5570. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5571. this.r = Math.pow( color.r, safeInverse );
  5572. this.g = Math.pow( color.g, safeInverse );
  5573. this.b = Math.pow( color.b, safeInverse );
  5574. return this;
  5575. }
  5576. convertGammaToLinear( gammaFactor ) {
  5577. this.copyGammaToLinear( this, gammaFactor );
  5578. return this;
  5579. }
  5580. convertLinearToGamma( gammaFactor ) {
  5581. this.copyLinearToGamma( this, gammaFactor );
  5582. return this;
  5583. }
  5584. copySRGBToLinear( color ) {
  5585. this.r = SRGBToLinear( color.r );
  5586. this.g = SRGBToLinear( color.g );
  5587. this.b = SRGBToLinear( color.b );
  5588. return this;
  5589. }
  5590. copyLinearToSRGB( color ) {
  5591. this.r = LinearToSRGB( color.r );
  5592. this.g = LinearToSRGB( color.g );
  5593. this.b = LinearToSRGB( color.b );
  5594. return this;
  5595. }
  5596. convertSRGBToLinear() {
  5597. this.copySRGBToLinear( this );
  5598. return this;
  5599. }
  5600. convertLinearToSRGB() {
  5601. this.copyLinearToSRGB( this );
  5602. return this;
  5603. }
  5604. getHex() {
  5605. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5606. }
  5607. getHexString() {
  5608. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5609. }
  5610. getHSL( target ) {
  5611. // h,s,l ranges are in 0.0 - 1.0
  5612. if ( target === undefined ) {
  5613. console.warn( 'THREE.Color: .getHSL() target is now required' );
  5614. target = { h: 0, s: 0, l: 0 };
  5615. }
  5616. const r = this.r, g = this.g, b = this.b;
  5617. const max = Math.max( r, g, b );
  5618. const min = Math.min( r, g, b );
  5619. let hue, saturation;
  5620. const lightness = ( min + max ) / 2.0;
  5621. if ( min === max ) {
  5622. hue = 0;
  5623. saturation = 0;
  5624. } else {
  5625. const delta = max - min;
  5626. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5627. switch ( max ) {
  5628. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5629. case g: hue = ( b - r ) / delta + 2; break;
  5630. case b: hue = ( r - g ) / delta + 4; break;
  5631. }
  5632. hue /= 6;
  5633. }
  5634. target.h = hue;
  5635. target.s = saturation;
  5636. target.l = lightness;
  5637. return target;
  5638. }
  5639. getStyle() {
  5640. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5641. }
  5642. offsetHSL( h, s, l ) {
  5643. this.getHSL( _hslA );
  5644. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5645. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5646. return this;
  5647. }
  5648. add( color ) {
  5649. this.r += color.r;
  5650. this.g += color.g;
  5651. this.b += color.b;
  5652. return this;
  5653. }
  5654. addColors( color1, color2 ) {
  5655. this.r = color1.r + color2.r;
  5656. this.g = color1.g + color2.g;
  5657. this.b = color1.b + color2.b;
  5658. return this;
  5659. }
  5660. addScalar( s ) {
  5661. this.r += s;
  5662. this.g += s;
  5663. this.b += s;
  5664. return this;
  5665. }
  5666. sub( color ) {
  5667. this.r = Math.max( 0, this.r - color.r );
  5668. this.g = Math.max( 0, this.g - color.g );
  5669. this.b = Math.max( 0, this.b - color.b );
  5670. return this;
  5671. }
  5672. multiply( color ) {
  5673. this.r *= color.r;
  5674. this.g *= color.g;
  5675. this.b *= color.b;
  5676. return this;
  5677. }
  5678. multiplyScalar( s ) {
  5679. this.r *= s;
  5680. this.g *= s;
  5681. this.b *= s;
  5682. return this;
  5683. }
  5684. lerp( color, alpha ) {
  5685. this.r += ( color.r - this.r ) * alpha;
  5686. this.g += ( color.g - this.g ) * alpha;
  5687. this.b += ( color.b - this.b ) * alpha;
  5688. return this;
  5689. }
  5690. lerpHSL( color, alpha ) {
  5691. this.getHSL( _hslA );
  5692. color.getHSL( _hslB );
  5693. const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  5694. const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  5695. const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  5696. this.setHSL( h, s, l );
  5697. return this;
  5698. }
  5699. equals( c ) {
  5700. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5701. }
  5702. fromArray( array, offset = 0 ) {
  5703. this.r = array[ offset ];
  5704. this.g = array[ offset + 1 ];
  5705. this.b = array[ offset + 2 ];
  5706. return this;
  5707. }
  5708. toArray( array = [], offset = 0 ) {
  5709. array[ offset ] = this.r;
  5710. array[ offset + 1 ] = this.g;
  5711. array[ offset + 2 ] = this.b;
  5712. return array;
  5713. }
  5714. fromBufferAttribute( attribute, index ) {
  5715. this.r = attribute.getX( index );
  5716. this.g = attribute.getY( index );
  5717. this.b = attribute.getZ( index );
  5718. if ( attribute.normalized === true ) {
  5719. // assuming Uint8Array
  5720. this.r /= 255;
  5721. this.g /= 255;
  5722. this.b /= 255;
  5723. }
  5724. return this;
  5725. }
  5726. toJSON() {
  5727. return this.getHex();
  5728. }
  5729. }
  5730. Color.NAMES = _colorKeywords;
  5731. Color.prototype.r = 1;
  5732. Color.prototype.g = 1;
  5733. Color.prototype.b = 1;
  5734. class Face3 {
  5735. constructor( a, b, c, normal, color, materialIndex = 0 ) {
  5736. this.a = a;
  5737. this.b = b;
  5738. this.c = c;
  5739. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  5740. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5741. this.color = ( color && color.isColor ) ? color : new Color();
  5742. this.vertexColors = Array.isArray( color ) ? color : [];
  5743. this.materialIndex = materialIndex;
  5744. }
  5745. clone() {
  5746. return new this.constructor().copy( this );
  5747. }
  5748. copy( source ) {
  5749. this.a = source.a;
  5750. this.b = source.b;
  5751. this.c = source.c;
  5752. this.normal.copy( source.normal );
  5753. this.color.copy( source.color );
  5754. this.materialIndex = source.materialIndex;
  5755. for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5756. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5757. }
  5758. for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5759. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5760. }
  5761. return this;
  5762. }
  5763. }
  5764. let materialId = 0;
  5765. function Material() {
  5766. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5767. this.uuid = MathUtils.generateUUID();
  5768. this.name = '';
  5769. this.type = 'Material';
  5770. this.fog = true;
  5771. this.blending = NormalBlending;
  5772. this.side = FrontSide;
  5773. this.flatShading = false;
  5774. this.vertexColors = false;
  5775. this.opacity = 1;
  5776. this.transparent = false;
  5777. this.blendSrc = SrcAlphaFactor;
  5778. this.blendDst = OneMinusSrcAlphaFactor;
  5779. this.blendEquation = AddEquation;
  5780. this.blendSrcAlpha = null;
  5781. this.blendDstAlpha = null;
  5782. this.blendEquationAlpha = null;
  5783. this.depthFunc = LessEqualDepth;
  5784. this.depthTest = true;
  5785. this.depthWrite = true;
  5786. this.stencilWriteMask = 0xff;
  5787. this.stencilFunc = AlwaysStencilFunc;
  5788. this.stencilRef = 0;
  5789. this.stencilFuncMask = 0xff;
  5790. this.stencilFail = KeepStencilOp;
  5791. this.stencilZFail = KeepStencilOp;
  5792. this.stencilZPass = KeepStencilOp;
  5793. this.stencilWrite = false;
  5794. this.clippingPlanes = null;
  5795. this.clipIntersection = false;
  5796. this.clipShadows = false;
  5797. this.shadowSide = null;
  5798. this.colorWrite = true;
  5799. this.precision = null; // override the renderer's default precision for this material
  5800. this.polygonOffset = false;
  5801. this.polygonOffsetFactor = 0;
  5802. this.polygonOffsetUnits = 0;
  5803. this.dithering = false;
  5804. this.alphaTest = 0;
  5805. this.premultipliedAlpha = false;
  5806. this.visible = true;
  5807. this.toneMapped = true;
  5808. this.userData = {};
  5809. this.version = 0;
  5810. }
  5811. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5812. constructor: Material,
  5813. isMaterial: true,
  5814. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  5815. customProgramCacheKey: function () {
  5816. return this.onBeforeCompile.toString();
  5817. },
  5818. setValues: function ( values ) {
  5819. if ( values === undefined ) return;
  5820. for ( const key in values ) {
  5821. const newValue = values[ key ];
  5822. if ( newValue === undefined ) {
  5823. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5824. continue;
  5825. }
  5826. // for backward compatability if shading is set in the constructor
  5827. if ( key === 'shading' ) {
  5828. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5829. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5830. continue;
  5831. }
  5832. const currentValue = this[ key ];
  5833. if ( currentValue === undefined ) {
  5834. //console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5835. continue;
  5836. }
  5837. if ( currentValue && currentValue.isColor ) {
  5838. currentValue.set( newValue );
  5839. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5840. currentValue.copy( newValue );
  5841. } else {
  5842. this[ key ] = newValue;
  5843. }
  5844. }
  5845. },
  5846. toJSON: function ( meta ) {
  5847. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5848. if ( isRoot ) {
  5849. meta = {
  5850. textures: {},
  5851. images: {}
  5852. };
  5853. }
  5854. const data = {
  5855. metadata: {
  5856. version: 4.5,
  5857. type: 'Material',
  5858. generator: 'Material.toJSON'
  5859. }
  5860. };
  5861. // standard Material serialization
  5862. data.uuid = this.uuid;
  5863. data.type = this.type;
  5864. if ( this.name !== '' ) data.name = this.name;
  5865. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5866. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5867. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5868. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  5869. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5870. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5871. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5872. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5873. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5874. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5875. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5876. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5877. }
  5878. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5879. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5880. }
  5881. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5882. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5883. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5884. }
  5885. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5886. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5887. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5888. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5889. if ( this.aoMap && this.aoMap.isTexture ) {
  5890. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5891. data.aoMapIntensity = this.aoMapIntensity;
  5892. }
  5893. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5894. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5895. data.bumpScale = this.bumpScale;
  5896. }
  5897. if ( this.normalMap && this.normalMap.isTexture ) {
  5898. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5899. data.normalMapType = this.normalMapType;
  5900. data.normalScale = this.normalScale.toArray();
  5901. }
  5902. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5903. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5904. data.displacementScale = this.displacementScale;
  5905. data.displacementBias = this.displacementBias;
  5906. }
  5907. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5908. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5909. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5910. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5911. if ( this.envMap && this.envMap.isTexture ) {
  5912. data.envMap = this.envMap.toJSON( meta ).uuid;
  5913. data.reflectivity = this.reflectivity; // Scale behind envMap
  5914. data.refractionRatio = this.refractionRatio;
  5915. if ( this.combine !== undefined ) data.combine = this.combine;
  5916. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5917. }
  5918. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5919. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5920. }
  5921. if ( this.size !== undefined ) data.size = this.size;
  5922. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5923. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5924. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5925. if ( this.side !== FrontSide ) data.side = this.side;
  5926. if ( this.vertexColors ) data.vertexColors = true;
  5927. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5928. if ( this.transparent === true ) data.transparent = this.transparent;
  5929. data.depthFunc = this.depthFunc;
  5930. data.depthTest = this.depthTest;
  5931. data.depthWrite = this.depthWrite;
  5932. data.stencilWrite = this.stencilWrite;
  5933. data.stencilWriteMask = this.stencilWriteMask;
  5934. data.stencilFunc = this.stencilFunc;
  5935. data.stencilRef = this.stencilRef;
  5936. data.stencilFuncMask = this.stencilFuncMask;
  5937. data.stencilFail = this.stencilFail;
  5938. data.stencilZFail = this.stencilZFail;
  5939. data.stencilZPass = this.stencilZPass;
  5940. // rotation (SpriteMaterial)
  5941. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5942. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5943. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5944. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5945. if ( this.lineWidth && this.lineWidth !== 1 ) data.lineWidth = this.lineWidth;
  5946. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5947. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5948. if ( this.scale !== undefined ) data.scale = this.scale;
  5949. if ( this.dithering === true ) data.dithering = true;
  5950. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5951. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5952. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5953. if ( this.wireframelineWidth > 1 ) data.wireframelineWidth = this.wireframelineWidth;
  5954. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5955. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5956. if ( this.morphTargets === true ) data.morphTargets = true;
  5957. if ( this.morphNormals === true ) data.morphNormals = true;
  5958. if ( this.skinning === true ) data.skinning = true;
  5959. if ( this.visible === false ) data.visible = false;
  5960. if ( this.toneMapped === false ) data.toneMapped = false;
  5961. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5962. // TODO: Copied from Object3D.toJSON
  5963. function extractFromCache( cache ) {
  5964. const values = [];
  5965. for ( const key in cache ) {
  5966. const data = cache[ key ];
  5967. delete data.metadata;
  5968. values.push( data );
  5969. }
  5970. return values;
  5971. }
  5972. if ( isRoot ) {
  5973. const textures = extractFromCache( meta.textures );
  5974. const images = extractFromCache( meta.images );
  5975. if ( textures.length > 0 ) data.textures = textures;
  5976. if ( images.length > 0 ) data.images = images;
  5977. }
  5978. return data;
  5979. },
  5980. clone: function () {
  5981. return new this.constructor().copy( this );
  5982. },
  5983. copy: function ( source ) {
  5984. this.name = source.name;
  5985. this.fog = source.fog;
  5986. this.blending = source.blending;
  5987. this.side = source.side;
  5988. this.flatShading = source.flatShading;
  5989. this.vertexColors = source.vertexColors;
  5990. this.opacity = source.opacity;
  5991. this.transparent = source.transparent;
  5992. this.blendSrc = source.blendSrc;
  5993. this.blendDst = source.blendDst;
  5994. this.blendEquation = source.blendEquation;
  5995. this.blendSrcAlpha = source.blendSrcAlpha;
  5996. this.blendDstAlpha = source.blendDstAlpha;
  5997. this.blendEquationAlpha = source.blendEquationAlpha;
  5998. this.depthFunc = source.depthFunc;
  5999. this.depthTest = source.depthTest;
  6000. this.depthWrite = source.depthWrite;
  6001. this.stencilWriteMask = source.stencilWriteMask;
  6002. this.stencilFunc = source.stencilFunc;
  6003. this.stencilRef = source.stencilRef;
  6004. this.stencilFuncMask = source.stencilFuncMask;
  6005. this.stencilFail = source.stencilFail;
  6006. this.stencilZFail = source.stencilZFail;
  6007. this.stencilZPass = source.stencilZPass;
  6008. this.stencilWrite = source.stencilWrite;
  6009. const srcPlanes = source.clippingPlanes;
  6010. let dstPlanes = null;
  6011. if ( srcPlanes !== null ) {
  6012. const n = srcPlanes.length;
  6013. dstPlanes = new Array( n );
  6014. for ( let i = 0; i !== n; ++ i ) {
  6015. dstPlanes[ i ] = srcPlanes[ i ].clone();
  6016. }
  6017. }
  6018. this.clippingPlanes = dstPlanes;
  6019. this.clipIntersection = source.clipIntersection;
  6020. this.clipShadows = source.clipShadows;
  6021. this.shadowSide = source.shadowSide;
  6022. this.colorWrite = source.colorWrite;
  6023. this.precision = source.precision;
  6024. this.polygonOffset = source.polygonOffset;
  6025. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6026. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6027. this.dithering = source.dithering;
  6028. this.alphaTest = source.alphaTest;
  6029. this.premultipliedAlpha = source.premultipliedAlpha;
  6030. this.visible = source.visible;
  6031. this.toneMapped = source.toneMapped;
  6032. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6033. return this;
  6034. },
  6035. dispose: function () {
  6036. this.dispatchEvent( { type: 'dispose' } );
  6037. }
  6038. } );
  6039. Object.defineProperty( Material.prototype, 'needsUpdate', {
  6040. set: function ( value ) {
  6041. if ( value === true ) this.version ++;
  6042. }
  6043. } );
  6044. /**
  6045. * parameters = {
  6046. * color: <hex>,
  6047. * opacity: <float>,
  6048. * map: new THREE.Texture( <Image> ),
  6049. *
  6050. * lightMap: new THREE.Texture( <Image> ),
  6051. * lightMapIntensity: <float>
  6052. *
  6053. * aoMap: new THREE.Texture( <Image> ),
  6054. * aoMapIntensity: <float>
  6055. *
  6056. * specularMap: new THREE.Texture( <Image> ),
  6057. *
  6058. * alphaMap: new THREE.Texture( <Image> ),
  6059. *
  6060. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6061. * combine: THREE.Multiply,
  6062. * reflectivity: <float>,
  6063. * refractionRatio: <float>,
  6064. *
  6065. * depthTest: <bool>,
  6066. * depthWrite: <bool>,
  6067. *
  6068. * wireframe: <boolean>,
  6069. * wireframelineWidth: <float>,
  6070. *
  6071. * skinning: <bool>,
  6072. * morphTargets: <bool>
  6073. * }
  6074. */
  6075. function MeshBasicMaterial( parameters ) {
  6076. Material.call( this );
  6077. this.type = 'MeshBasicMaterial';
  6078. this.color = new Color( 0xffffff ); // emissive
  6079. this.map = null;
  6080. this.lightMap = null;
  6081. this.lightMapIntensity = 1.0;
  6082. this.aoMap = null;
  6083. this.aoMapIntensity = 1.0;
  6084. this.specularMap = null;
  6085. this.alphaMap = null;
  6086. this.envMap = null;
  6087. this.combine = MultiplyOperation;
  6088. this.reflectivity = 1;
  6089. this.refractionRatio = 0.98;
  6090. this.wireframe = false;
  6091. this.wireframelineWidth = 1;
  6092. this.wireframeLinecap = 'round';
  6093. this.wireframeLinejoin = 'round';
  6094. this.skinning = false;
  6095. this.morphTargets = false;
  6096. this.setValues( parameters );
  6097. }
  6098. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  6099. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6100. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6101. MeshBasicMaterial.prototype.copy = function ( source ) {
  6102. Material.prototype.copy.call( this, source );
  6103. this.color.copy( source.color );
  6104. this.map = source.map;
  6105. this.lightMap = source.lightMap;
  6106. this.lightMapIntensity = source.lightMapIntensity;
  6107. this.aoMap = source.aoMap;
  6108. this.aoMapIntensity = source.aoMapIntensity;
  6109. this.specularMap = source.specularMap;
  6110. this.alphaMap = source.alphaMap;
  6111. this.envMap = source.envMap;
  6112. this.combine = source.combine;
  6113. this.reflectivity = source.reflectivity;
  6114. this.refractionRatio = source.refractionRatio;
  6115. this.wireframe = source.wireframe;
  6116. this.wireframelineWidth = source.wireframelineWidth;
  6117. this.wireframeLinecap = source.wireframeLinecap;
  6118. this.wireframeLinejoin = source.wireframeLinejoin;
  6119. this.skinning = source.skinning;
  6120. this.morphTargets = source.morphTargets;
  6121. return this;
  6122. };
  6123. const _vector$3 = new Vector3();
  6124. const _vector2$1 = new Vector2$1();
  6125. function BufferAttribute( array, itemSize, normalized ) {
  6126. if ( Array.isArray( array ) ) {
  6127. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  6128. }
  6129. this.name = '';
  6130. this.array = array;
  6131. this.itemSize = itemSize;
  6132. this.count = array !== undefined ? array.length / itemSize : 0;
  6133. this.normalized = normalized === true;
  6134. this.usage = StaticDrawUsage;
  6135. this.updateRange = { offset: 0, count: - 1 };
  6136. this.version = 0;
  6137. }
  6138. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  6139. set: function ( value ) {
  6140. if ( value === true ) this.version ++;
  6141. }
  6142. } );
  6143. Object.assign( BufferAttribute.prototype, {
  6144. isBufferAttribute: true,
  6145. onUploadCallback: function () {},
  6146. setUsage: function ( value ) {
  6147. this.usage = value;
  6148. return this;
  6149. },
  6150. copy: function ( source ) {
  6151. this.name = source.name;
  6152. this.array = new source.array.constructor( source.array );
  6153. this.itemSize = source.itemSize;
  6154. this.count = source.count;
  6155. this.normalized = source.normalized;
  6156. this.usage = source.usage;
  6157. return this;
  6158. },
  6159. copyAt: function ( index1, attribute, index2 ) {
  6160. index1 *= this.itemSize;
  6161. index2 *= attribute.itemSize;
  6162. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6163. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6164. }
  6165. return this;
  6166. },
  6167. copyArray: function ( array ) {
  6168. this.array.set( array );
  6169. return this;
  6170. },
  6171. copyColorsArray: function ( colors ) {
  6172. const array = this.array;
  6173. let offset = 0;
  6174. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  6175. let color = colors[ i ];
  6176. if ( color === undefined ) {
  6177. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  6178. color = new Color();
  6179. }
  6180. array[ offset ++ ] = color.r;
  6181. array[ offset ++ ] = color.g;
  6182. array[ offset ++ ] = color.b;
  6183. }
  6184. return this;
  6185. },
  6186. copyVector2sArray: function ( vectors ) {
  6187. const array = this.array;
  6188. let offset = 0;
  6189. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6190. let vector = vectors[ i ];
  6191. if ( vector === undefined ) {
  6192. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  6193. vector = new Vector2$1();
  6194. }
  6195. array[ offset ++ ] = vector.x;
  6196. array[ offset ++ ] = vector.y;
  6197. }
  6198. return this;
  6199. },
  6200. copyVector3sArray: function ( vectors ) {
  6201. const array = this.array;
  6202. let offset = 0;
  6203. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6204. let vector = vectors[ i ];
  6205. if ( vector === undefined ) {
  6206. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  6207. vector = new Vector3();
  6208. }
  6209. array[ offset ++ ] = vector.x;
  6210. array[ offset ++ ] = vector.y;
  6211. array[ offset ++ ] = vector.z;
  6212. }
  6213. return this;
  6214. },
  6215. copyVector4sArray: function ( vectors ) {
  6216. const array = this.array;
  6217. let offset = 0;
  6218. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6219. let vector = vectors[ i ];
  6220. if ( vector === undefined ) {
  6221. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  6222. vector = new Vector4();
  6223. }
  6224. array[ offset ++ ] = vector.x;
  6225. array[ offset ++ ] = vector.y;
  6226. array[ offset ++ ] = vector.z;
  6227. array[ offset ++ ] = vector.w;
  6228. }
  6229. return this;
  6230. },
  6231. applyMatrix3: function ( m ) {
  6232. if ( this.itemSize === 2 ) {
  6233. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6234. _vector2$1.fromBufferAttribute( this, i );
  6235. _vector2$1.applyMatrix3( m );
  6236. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6237. }
  6238. } else if ( this.itemSize === 3 ) {
  6239. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6240. _vector$3.fromBufferAttribute( this, i );
  6241. _vector$3.applyMatrix3( m );
  6242. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6243. }
  6244. }
  6245. return this;
  6246. },
  6247. applyMatrix4: function ( m ) {
  6248. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6249. _vector$3.x = this.getX( i );
  6250. _vector$3.y = this.getY( i );
  6251. _vector$3.z = this.getZ( i );
  6252. _vector$3.applyMatrix4( m );
  6253. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6254. }
  6255. return this;
  6256. },
  6257. applyNormalMatrix: function ( m ) {
  6258. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6259. _vector$3.x = this.getX( i );
  6260. _vector$3.y = this.getY( i );
  6261. _vector$3.z = this.getZ( i );
  6262. _vector$3.applyNormalMatrix( m );
  6263. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6264. }
  6265. return this;
  6266. },
  6267. transformDirection: function ( m ) {
  6268. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6269. _vector$3.x = this.getX( i );
  6270. _vector$3.y = this.getY( i );
  6271. _vector$3.z = this.getZ( i );
  6272. _vector$3.transformDirection( m );
  6273. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6274. }
  6275. return this;
  6276. },
  6277. set: function ( value, offset = 0 ) {
  6278. this.array.set( value, offset );
  6279. return this;
  6280. },
  6281. getX: function ( index ) {
  6282. return this.array[ index * this.itemSize ];
  6283. },
  6284. setX: function ( index, x ) {
  6285. this.array[ index * this.itemSize ] = x;
  6286. return this;
  6287. },
  6288. getY: function ( index ) {
  6289. return this.array[ index * this.itemSize + 1 ];
  6290. },
  6291. setY: function ( index, y ) {
  6292. this.array[ index * this.itemSize + 1 ] = y;
  6293. return this;
  6294. },
  6295. getZ: function ( index ) {
  6296. return this.array[ index * this.itemSize + 2 ];
  6297. },
  6298. setZ: function ( index, z ) {
  6299. this.array[ index * this.itemSize + 2 ] = z;
  6300. return this;
  6301. },
  6302. getW: function ( index ) {
  6303. return this.array[ index * this.itemSize + 3 ];
  6304. },
  6305. setW: function ( index, w ) {
  6306. this.array[ index * this.itemSize + 3 ] = w;
  6307. return this;
  6308. },
  6309. setXY: function ( index, x, y ) {
  6310. index *= this.itemSize;
  6311. this.array[ index + 0 ] = x;
  6312. this.array[ index + 1 ] = y;
  6313. return this;
  6314. },
  6315. setXYZ: function ( index, x, y, z ) {
  6316. index *= this.itemSize;
  6317. this.array[ index + 0 ] = x;
  6318. this.array[ index + 1 ] = y;
  6319. this.array[ index + 2 ] = z;
  6320. return this;
  6321. },
  6322. setXYZW: function ( index, x, y, z, w ) {
  6323. index *= this.itemSize;
  6324. this.array[ index + 0 ] = x;
  6325. this.array[ index + 1 ] = y;
  6326. this.array[ index + 2 ] = z;
  6327. this.array[ index + 3 ] = w;
  6328. return this;
  6329. },
  6330. onUpload: function ( callback ) {
  6331. this.onUploadCallback = callback;
  6332. return this;
  6333. },
  6334. clone: function () {
  6335. return new this.constructor( this.array, this.itemSize ).copy( this );
  6336. },
  6337. toJSON: function () {
  6338. return {
  6339. itemSize: this.itemSize,
  6340. type: this.array.constructor.name,
  6341. array: Array.prototype.slice.call( this.array ),
  6342. normalized: this.normalized
  6343. };
  6344. }
  6345. } );
  6346. //
  6347. function Int8BufferAttribute( array, itemSize, normalized ) {
  6348. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  6349. }
  6350. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6351. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6352. function Uint8BufferAttribute( array, itemSize, normalized ) {
  6353. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  6354. }
  6355. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6356. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6357. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  6358. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  6359. }
  6360. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6361. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6362. function Int16BufferAttribute( array, itemSize, normalized ) {
  6363. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  6364. }
  6365. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6366. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6367. function Uint16BufferAttribute( array, itemSize, normalized ) {
  6368. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  6369. }
  6370. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6371. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6372. function Int32BufferAttribute( array, itemSize, normalized ) {
  6373. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  6374. }
  6375. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6376. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6377. function Uint32BufferAttribute( array, itemSize, normalized ) {
  6378. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  6379. }
  6380. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6381. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6382. function Float16BufferAttribute( array, itemSize, normalized ) {
  6383. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  6384. }
  6385. Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6386. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  6387. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6388. function Float32BufferAttribute( array, itemSize, normalized ) {
  6389. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  6390. }
  6391. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6392. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6393. function Float64BufferAttribute( array, itemSize, normalized ) {
  6394. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  6395. }
  6396. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6397. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6398. class DirectGeometry {
  6399. constructor() {
  6400. this.vertices = [];
  6401. this.normals = [];
  6402. this.colors = [];
  6403. this.uvs = [];
  6404. this.uvs2 = [];
  6405. this.groups = [];
  6406. this.morphTargets = {};
  6407. this.skinWeights = [];
  6408. this.skinIndices = [];
  6409. // this.lineDistances = [];
  6410. this.boundingBox = null;
  6411. this.boundingSphere = null;
  6412. // update flags
  6413. this.verticesNeedUpdate = false;
  6414. this.normalsNeedUpdate = false;
  6415. this.colorsNeedUpdate = false;
  6416. this.uvsNeedUpdate = false;
  6417. this.groupsNeedUpdate = false;
  6418. }
  6419. computeGroups( geometry ) {
  6420. const groups = [];
  6421. let group, i;
  6422. let materialIndex = undefined;
  6423. const faces = geometry.faces;
  6424. for ( i = 0; i < faces.length; i ++ ) {
  6425. const face = faces[ i ];
  6426. // materials
  6427. if ( face.materialIndex !== materialIndex ) {
  6428. materialIndex = face.materialIndex;
  6429. if ( group !== undefined ) {
  6430. group.count = ( i * 3 ) - group.start;
  6431. groups.push( group );
  6432. }
  6433. group = {
  6434. start: i * 3,
  6435. materialIndex: materialIndex
  6436. };
  6437. }
  6438. }
  6439. if ( group !== undefined ) {
  6440. group.count = ( i * 3 ) - group.start;
  6441. groups.push( group );
  6442. }
  6443. this.groups = groups;
  6444. }
  6445. fromGeometry( geometry ) {
  6446. const faces = geometry.faces;
  6447. const vertices = geometry.vertices;
  6448. const faceVertexUvs = geometry.faceVertexUvs;
  6449. const hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6450. const hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6451. // morphs
  6452. const morphTargets = geometry.morphTargets;
  6453. const morphTargetsLength = morphTargets.length;
  6454. let morphTargetsPosition;
  6455. if ( morphTargetsLength > 0 ) {
  6456. morphTargetsPosition = [];
  6457. for ( let i = 0; i < morphTargetsLength; i ++ ) {
  6458. morphTargetsPosition[ i ] = {
  6459. name: morphTargets[ i ].name,
  6460. data: []
  6461. };
  6462. }
  6463. this.morphTargets.position = morphTargetsPosition;
  6464. }
  6465. const morphNormals = geometry.morphNormals;
  6466. const morphNormalsLength = morphNormals.length;
  6467. let morphTargetsNormal;
  6468. if ( morphNormalsLength > 0 ) {
  6469. morphTargetsNormal = [];
  6470. for ( let i = 0; i < morphNormalsLength; i ++ ) {
  6471. morphTargetsNormal[ i ] = {
  6472. name: morphNormals[ i ].name,
  6473. data: []
  6474. };
  6475. }
  6476. this.morphTargets.normal = morphTargetsNormal;
  6477. }
  6478. // skins
  6479. const skinIndices = geometry.skinIndices;
  6480. const skinWeights = geometry.skinWeights;
  6481. const hasSkinIndices = skinIndices.length === vertices.length;
  6482. const hasSkinWeights = skinWeights.length === vertices.length;
  6483. //
  6484. if ( vertices.length > 0 && faces.length === 0 ) {
  6485. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  6486. }
  6487. for ( let i = 0; i < faces.length; i ++ ) {
  6488. const face = faces[ i ];
  6489. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6490. const vertexNormals = face.vertexNormals;
  6491. if ( vertexNormals.length === 3 ) {
  6492. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6493. } else {
  6494. const normal = face.normal;
  6495. this.normals.push( normal, normal, normal );
  6496. }
  6497. const vertexColors = face.vertexColors;
  6498. if ( vertexColors.length === 3 ) {
  6499. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6500. } else {
  6501. const color = face.color;
  6502. this.colors.push( color, color, color );
  6503. }
  6504. if ( hasFaceVertexUv === true ) {
  6505. const vertexUvs = faceVertexUvs[ 0 ][ i ];
  6506. if ( vertexUvs !== undefined ) {
  6507. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6508. } else {
  6509. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6510. this.uvs.push( new Vector2$1(), new Vector2$1(), new Vector2$1() );
  6511. }
  6512. }
  6513. if ( hasFaceVertexUv2 === true ) {
  6514. const vertexUvs = faceVertexUvs[ 1 ][ i ];
  6515. if ( vertexUvs !== undefined ) {
  6516. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6517. } else {
  6518. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6519. this.uvs2.push( new Vector2$1(), new Vector2$1(), new Vector2$1() );
  6520. }
  6521. }
  6522. // morphs
  6523. for ( let j = 0; j < morphTargetsLength; j ++ ) {
  6524. const morphTarget = morphTargets[ j ].vertices;
  6525. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6526. }
  6527. for ( let j = 0; j < morphNormalsLength; j ++ ) {
  6528. const morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6529. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  6530. }
  6531. // skins
  6532. if ( hasSkinIndices ) {
  6533. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6534. }
  6535. if ( hasSkinWeights ) {
  6536. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6537. }
  6538. }
  6539. this.computeGroups( geometry );
  6540. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6541. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6542. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6543. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6544. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6545. if ( geometry.boundingSphere !== null ) {
  6546. this.boundingSphere = geometry.boundingSphere.clone();
  6547. }
  6548. if ( geometry.boundingBox !== null ) {
  6549. this.boundingBox = geometry.boundingBox.clone();
  6550. }
  6551. return this;
  6552. }
  6553. }
  6554. function arrayMax( array ) {
  6555. if ( array.length === 0 ) return - Infinity;
  6556. let max = array[ 0 ];
  6557. for ( let i = 1, l = array.length; i < l; ++ i ) {
  6558. if ( array[ i ] > max ) max = array[ i ];
  6559. }
  6560. return max;
  6561. }
  6562. const TYPED_ARRAYS = {
  6563. Int8Array: Int8Array,
  6564. Uint8Array: Uint8Array,
  6565. // Workaround for IE11 pre KB2929437. See #11440
  6566. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  6567. Int16Array: Int16Array,
  6568. Uint16Array: Uint16Array,
  6569. Int32Array: Int32Array,
  6570. Uint32Array: Uint32Array,
  6571. Float32Array: Float32Array,
  6572. Float64Array: Float64Array
  6573. };
  6574. function getTypedArray( type, buffer ) {
  6575. return new TYPED_ARRAYS[ type ]( buffer );
  6576. }
  6577. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6578. const _m1$2 = new Matrix4();
  6579. const _obj = new Object3D();
  6580. const _offset = new Vector3();
  6581. const _box$2 = new Box3();
  6582. const _boxMorphTargets = new Box3();
  6583. const _vector$4 = new Vector3();
  6584. function BufferGeometry() {
  6585. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  6586. this.uuid = MathUtils.generateUUID();
  6587. this.name = '';
  6588. this.type = 'BufferGeometry';
  6589. this.index = null;
  6590. this.attributes = {};
  6591. this.morphAttributes = {};
  6592. this.morphTargetsRelative = false;
  6593. this.groups = [];
  6594. this.boundingBox = null;
  6595. this.boundingSphere = null;
  6596. this.drawRange = { start: 0, count: Infinity };
  6597. this.userData = {};
  6598. }
  6599. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6600. constructor: BufferGeometry,
  6601. isBufferGeometry: true,
  6602. getIndex: function () {
  6603. return this.index;
  6604. },
  6605. setIndex: function ( index ) {
  6606. if ( Array.isArray( index ) ) {
  6607. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6608. } else {
  6609. this.index = index;
  6610. }
  6611. return this;
  6612. },
  6613. getAttribute: function ( name ) {
  6614. return this.attributes[ name ];
  6615. },
  6616. setAttribute: function ( name, attribute ) {
  6617. this.attributes[ name ] = attribute;
  6618. return this;
  6619. },
  6620. deleteAttribute: function ( name ) {
  6621. delete this.attributes[ name ];
  6622. return this;
  6623. },
  6624. hasAttribute: function ( name ) {
  6625. return this.attributes[ name ] !== undefined;
  6626. },
  6627. addGroup: function ( start, count, materialIndex = 0 ) {
  6628. this.groups.push( {
  6629. start: start,
  6630. count: count,
  6631. materialIndex: materialIndex
  6632. } );
  6633. },
  6634. clearGroups: function () {
  6635. this.groups = [];
  6636. },
  6637. setDrawRange: function ( start, count ) {
  6638. this.drawRange.start = start;
  6639. this.drawRange.count = count;
  6640. },
  6641. applyMatrix4: function ( matrix ) {
  6642. const position = this.attributes.position;
  6643. if ( position !== undefined ) {
  6644. position.applyMatrix4( matrix );
  6645. position.needsUpdate = true;
  6646. }
  6647. const normal = this.attributes.normal;
  6648. if ( normal !== undefined ) {
  6649. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6650. normal.applyNormalMatrix( normalMatrix );
  6651. normal.needsUpdate = true;
  6652. }
  6653. const tangent = this.attributes.tangent;
  6654. if ( tangent !== undefined ) {
  6655. tangent.transformDirection( matrix );
  6656. tangent.needsUpdate = true;
  6657. }
  6658. if ( this.boundingBox !== null ) {
  6659. this.computeBoundingBox();
  6660. }
  6661. if ( this.boundingSphere !== null ) {
  6662. this.computeBoundingSphere();
  6663. }
  6664. return this;
  6665. },
  6666. rotateX: function ( angle ) {
  6667. // rotate geometry around world x-axis
  6668. _m1$2.makeRotationX( angle );
  6669. this.applyMatrix4( _m1$2 );
  6670. return this;
  6671. },
  6672. rotateY: function ( angle ) {
  6673. // rotate geometry around world y-axis
  6674. _m1$2.makeRotationY( angle );
  6675. this.applyMatrix4( _m1$2 );
  6676. return this;
  6677. },
  6678. rotateZ: function ( angle ) {
  6679. // rotate geometry around world z-axis
  6680. _m1$2.makeRotationZ( angle );
  6681. this.applyMatrix4( _m1$2 );
  6682. return this;
  6683. },
  6684. translate: function ( x, y, z ) {
  6685. // translate geometry
  6686. _m1$2.makeTranslation( x, y, z );
  6687. this.applyMatrix4( _m1$2 );
  6688. return this;
  6689. },
  6690. scale: function ( x, y, z ) {
  6691. // scale geometry
  6692. _m1$2.makeScale( x, y, z );
  6693. this.applyMatrix4( _m1$2 );
  6694. return this;
  6695. },
  6696. lookAt: function ( vector ) {
  6697. _obj.lookAt( vector );
  6698. _obj.updateMatrix();
  6699. this.applyMatrix4( _obj.matrix );
  6700. return this;
  6701. },
  6702. center: function () {
  6703. this.computeBoundingBox();
  6704. this.boundingBox.getCenter( _offset ).negate();
  6705. this.translate( _offset.x, _offset.y, _offset.z );
  6706. return this;
  6707. },
  6708. setFromObject: function ( object ) {
  6709. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6710. const geometry = object.geometry;
  6711. if ( object.isPoints || object.isLine ) {
  6712. const positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  6713. const colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  6714. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6715. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6716. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6717. const lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  6718. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6719. }
  6720. if ( geometry.boundingSphere !== null ) {
  6721. this.boundingSphere = geometry.boundingSphere.clone();
  6722. }
  6723. if ( geometry.boundingBox !== null ) {
  6724. this.boundingBox = geometry.boundingBox.clone();
  6725. }
  6726. } else if ( object.isMesh ) {
  6727. if ( geometry && geometry.isGeometry ) {
  6728. this.fromGeometry( geometry );
  6729. }
  6730. }
  6731. return this;
  6732. },
  6733. setFromPoints: function ( points ) {
  6734. const position = [];
  6735. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6736. const point = points[ i ];
  6737. position.push( point.x, point.y, point.z || 0 );
  6738. }
  6739. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6740. return this;
  6741. },
  6742. updateFromObject: function ( object ) {
  6743. let geometry = object.geometry;
  6744. if ( object.isMesh ) {
  6745. let direct = geometry.__directGeometry;
  6746. if ( geometry.elementsNeedUpdate === true ) {
  6747. direct = undefined;
  6748. geometry.elementsNeedUpdate = false;
  6749. }
  6750. if ( direct === undefined ) {
  6751. return this.fromGeometry( geometry );
  6752. }
  6753. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6754. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6755. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6756. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6757. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6758. geometry.verticesNeedUpdate = false;
  6759. geometry.normalsNeedUpdate = false;
  6760. geometry.colorsNeedUpdate = false;
  6761. geometry.uvsNeedUpdate = false;
  6762. geometry.groupsNeedUpdate = false;
  6763. geometry = direct;
  6764. }
  6765. if ( geometry.verticesNeedUpdate === true ) {
  6766. const attribute = this.attributes.position;
  6767. if ( attribute !== undefined ) {
  6768. attribute.copyVector3sArray( geometry.vertices );
  6769. attribute.needsUpdate = true;
  6770. }
  6771. geometry.verticesNeedUpdate = false;
  6772. }
  6773. if ( geometry.normalsNeedUpdate === true ) {
  6774. const attribute = this.attributes.normal;
  6775. if ( attribute !== undefined ) {
  6776. attribute.copyVector3sArray( geometry.normals );
  6777. attribute.needsUpdate = true;
  6778. }
  6779. geometry.normalsNeedUpdate = false;
  6780. }
  6781. if ( geometry.colorsNeedUpdate === true ) {
  6782. const attribute = this.attributes.color;
  6783. if ( attribute !== undefined ) {
  6784. attribute.copyColorsArray( geometry.colors );
  6785. attribute.needsUpdate = true;
  6786. }
  6787. geometry.colorsNeedUpdate = false;
  6788. }
  6789. if ( geometry.uvsNeedUpdate ) {
  6790. const attribute = this.attributes.uv;
  6791. if ( attribute !== undefined ) {
  6792. attribute.copyVector2sArray( geometry.uvs );
  6793. attribute.needsUpdate = true;
  6794. }
  6795. geometry.uvsNeedUpdate = false;
  6796. }
  6797. if ( geometry.lineDistancesNeedUpdate ) {
  6798. const attribute = this.attributes.lineDistance;
  6799. if ( attribute !== undefined ) {
  6800. attribute.copyArray( geometry.lineDistances );
  6801. attribute.needsUpdate = true;
  6802. }
  6803. geometry.lineDistancesNeedUpdate = false;
  6804. }
  6805. if ( geometry.groupsNeedUpdate ) {
  6806. geometry.computeGroups( object.geometry );
  6807. this.groups = geometry.groups;
  6808. geometry.groupsNeedUpdate = false;
  6809. }
  6810. return this;
  6811. },
  6812. fromGeometry: function ( geometry ) {
  6813. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  6814. return this.fromDirectGeometry( geometry.__directGeometry );
  6815. },
  6816. fromDirectGeometry: function ( geometry ) {
  6817. const positions = new Float32Array( geometry.vertices.length * 3 );
  6818. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6819. if ( geometry.normals.length > 0 ) {
  6820. const normals = new Float32Array( geometry.normals.length * 3 );
  6821. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6822. }
  6823. if ( geometry.colors.length > 0 ) {
  6824. const colors = new Float32Array( geometry.colors.length * 3 );
  6825. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6826. }
  6827. if ( geometry.uvs.length > 0 ) {
  6828. const uvs = new Float32Array( geometry.uvs.length * 2 );
  6829. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6830. }
  6831. if ( geometry.uvs2.length > 0 ) {
  6832. const uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6833. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6834. }
  6835. // groups
  6836. this.groups = geometry.groups;
  6837. // morphs
  6838. for ( const name in geometry.morphTargets ) {
  6839. const array = [];
  6840. const morphTargets = geometry.morphTargets[ name ];
  6841. for ( let i = 0, l = morphTargets.length; i < l; i ++ ) {
  6842. const morphTarget = morphTargets[ i ];
  6843. const attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  6844. attribute.name = morphTarget.name;
  6845. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  6846. }
  6847. this.morphAttributes[ name ] = array;
  6848. }
  6849. // skinning
  6850. if ( geometry.skinIndices.length > 0 ) {
  6851. const skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  6852. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6853. }
  6854. if ( geometry.skinWeights.length > 0 ) {
  6855. const skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  6856. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6857. }
  6858. //
  6859. if ( geometry.boundingSphere !== null ) {
  6860. this.boundingSphere = geometry.boundingSphere.clone();
  6861. }
  6862. if ( geometry.boundingBox !== null ) {
  6863. this.boundingBox = geometry.boundingBox.clone();
  6864. }
  6865. return this;
  6866. },
  6867. computeBoundingBox: function () {
  6868. if ( this.boundingBox === null ) {
  6869. this.boundingBox = new Box3();
  6870. }
  6871. const position = this.attributes.position;
  6872. const morphAttributesPosition = this.morphAttributes.position;
  6873. if ( position && position.isGLBufferAttribute ) {
  6874. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6875. this.boundingBox.set(
  6876. new Vector3( - Infinity, - Infinity, - Infinity ),
  6877. new Vector3( + Infinity, + Infinity, + Infinity )
  6878. );
  6879. return;
  6880. }
  6881. if ( position !== undefined ) {
  6882. this.boundingBox.setFromBufferAttribute( position );
  6883. // process morph attributes if present
  6884. if ( morphAttributesPosition ) {
  6885. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6886. const morphAttribute = morphAttributesPosition[ i ];
  6887. _box$2.setFromBufferAttribute( morphAttribute );
  6888. if ( this.morphTargetsRelative ) {
  6889. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  6890. this.boundingBox.expandByPoint( _vector$4 );
  6891. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  6892. this.boundingBox.expandByPoint( _vector$4 );
  6893. } else {
  6894. this.boundingBox.expandByPoint( _box$2.min );
  6895. this.boundingBox.expandByPoint( _box$2.max );
  6896. }
  6897. }
  6898. }
  6899. } else {
  6900. this.boundingBox.makeEmpty();
  6901. }
  6902. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6903. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6904. }
  6905. },
  6906. computeBoundingSphere: function () {
  6907. if ( this.boundingSphere === null ) {
  6908. this.boundingSphere = new Sphere();
  6909. }
  6910. const position = this.attributes.position;
  6911. const morphAttributesPosition = this.morphAttributes.position;
  6912. if ( position && position.isGLBufferAttribute ) {
  6913. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6914. this.boundingSphere.set( new Vector3(), Infinity );
  6915. return;
  6916. }
  6917. if ( position ) {
  6918. // first, find the center of the bounding sphere
  6919. const center = this.boundingSphere.center;
  6920. _box$2.setFromBufferAttribute( position );
  6921. // process morph attributes if present
  6922. if ( morphAttributesPosition ) {
  6923. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6924. const morphAttribute = morphAttributesPosition[ i ];
  6925. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6926. if ( this.morphTargetsRelative ) {
  6927. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  6928. _box$2.expandByPoint( _vector$4 );
  6929. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  6930. _box$2.expandByPoint( _vector$4 );
  6931. } else {
  6932. _box$2.expandByPoint( _boxMorphTargets.min );
  6933. _box$2.expandByPoint( _boxMorphTargets.max );
  6934. }
  6935. }
  6936. }
  6937. _box$2.getCenter( center );
  6938. // second, try to find a boundingSphere with a radius smaller than the
  6939. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6940. let maxRadiusSq = 0;
  6941. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6942. _vector$4.fromBufferAttribute( position, i );
  6943. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6944. }
  6945. // process morph attributes if present
  6946. if ( morphAttributesPosition ) {
  6947. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6948. const morphAttribute = morphAttributesPosition[ i ];
  6949. const morphTargetsRelative = this.morphTargetsRelative;
  6950. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6951. _vector$4.fromBufferAttribute( morphAttribute, j );
  6952. if ( morphTargetsRelative ) {
  6953. _offset.fromBufferAttribute( position, j );
  6954. _vector$4.add( _offset );
  6955. }
  6956. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6957. }
  6958. }
  6959. }
  6960. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6961. if ( isNaN( this.boundingSphere.radius ) ) {
  6962. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6963. }
  6964. }
  6965. },
  6966. computeFaceNormals: function () {
  6967. // backwards compatibility
  6968. },
  6969. computeVertexNormals: function () {
  6970. const index = this.index;
  6971. const positionAttribute = this.getAttribute( 'position' );
  6972. if ( positionAttribute !== undefined ) {
  6973. let normalAttribute = this.getAttribute( 'normal' );
  6974. if ( normalAttribute === undefined ) {
  6975. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6976. this.setAttribute( 'normal', normalAttribute );
  6977. } else {
  6978. // reset existing normals to zero
  6979. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6980. normalAttribute.setXYZ( i, 0, 0, 0 );
  6981. }
  6982. }
  6983. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6984. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6985. const cb = new Vector3(), ab = new Vector3();
  6986. // indexed elements
  6987. if ( index ) {
  6988. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6989. const vA = index.getX( i + 0 );
  6990. const vB = index.getX( i + 1 );
  6991. const vC = index.getX( i + 2 );
  6992. pA.fromBufferAttribute( positionAttribute, vA );
  6993. pB.fromBufferAttribute( positionAttribute, vB );
  6994. pC.fromBufferAttribute( positionAttribute, vC );
  6995. cb.subVectors( pC, pB );
  6996. ab.subVectors( pA, pB );
  6997. cb.cross( ab );
  6998. nA.fromBufferAttribute( normalAttribute, vA );
  6999. nB.fromBufferAttribute( normalAttribute, vB );
  7000. nC.fromBufferAttribute( normalAttribute, vC );
  7001. nA.add( cb );
  7002. nB.add( cb );
  7003. nC.add( cb );
  7004. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  7005. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  7006. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  7007. }
  7008. } else {
  7009. // non-indexed elements (unconnected triangle soup)
  7010. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  7011. pA.fromBufferAttribute( positionAttribute, i + 0 );
  7012. pB.fromBufferAttribute( positionAttribute, i + 1 );
  7013. pC.fromBufferAttribute( positionAttribute, i + 2 );
  7014. cb.subVectors( pC, pB );
  7015. ab.subVectors( pA, pB );
  7016. cb.cross( ab );
  7017. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  7018. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  7019. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  7020. }
  7021. }
  7022. this.normalizeNormals();
  7023. normalAttribute.needsUpdate = true;
  7024. }
  7025. },
  7026. merge: function ( geometry, offset ) {
  7027. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  7028. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7029. return;
  7030. }
  7031. if ( offset === undefined ) {
  7032. offset = 0;
  7033. console.warn(
  7034. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  7035. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  7036. );
  7037. }
  7038. const attributes = this.attributes;
  7039. for ( const key in attributes ) {
  7040. if ( geometry.attributes[ key ] === undefined ) continue;
  7041. const attribute1 = attributes[ key ];
  7042. const attributeArray1 = attribute1.array;
  7043. const attribute2 = geometry.attributes[ key ];
  7044. const attributeArray2 = attribute2.array;
  7045. const attributeOffset = attribute2.itemSize * offset;
  7046. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  7047. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  7048. attributeArray1[ j ] = attributeArray2[ i ];
  7049. }
  7050. }
  7051. return this;
  7052. },
  7053. normalizeNormals: function () {
  7054. const normals = this.attributes.normal;
  7055. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  7056. _vector$4.fromBufferAttribute( normals, i );
  7057. _vector$4.normalize();
  7058. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  7059. }
  7060. },
  7061. toNonIndexed: function () {
  7062. function convertBufferAttribute( attribute, indices ) {
  7063. const array = attribute.array;
  7064. const itemSize = attribute.itemSize;
  7065. const normalized = attribute.normalized;
  7066. const array2 = new array.constructor( indices.length * itemSize );
  7067. let index = 0, index2 = 0;
  7068. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  7069. index = indices[ i ] * itemSize;
  7070. for ( let j = 0; j < itemSize; j ++ ) {
  7071. array2[ index2 ++ ] = array[ index ++ ];
  7072. }
  7073. }
  7074. return new BufferAttribute( array2, itemSize, normalized );
  7075. }
  7076. //
  7077. if ( this.index === null ) {
  7078. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7079. return this;
  7080. }
  7081. const geometry2 = new BufferGeometry();
  7082. const indices = this.index.array;
  7083. const attributes = this.attributes;
  7084. // attributes
  7085. for ( const name in attributes ) {
  7086. const attribute = attributes[ name ];
  7087. const newAttribute = convertBufferAttribute( attribute, indices );
  7088. geometry2.setAttribute( name, newAttribute );
  7089. }
  7090. // morph attributes
  7091. const morphAttributes = this.morphAttributes;
  7092. for ( const name in morphAttributes ) {
  7093. const morphArray = [];
  7094. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7095. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  7096. const attribute = morphAttribute[ i ];
  7097. const newAttribute = convertBufferAttribute( attribute, indices );
  7098. morphArray.push( newAttribute );
  7099. }
  7100. geometry2.morphAttributes[ name ] = morphArray;
  7101. }
  7102. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  7103. // groups
  7104. const groups = this.groups;
  7105. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7106. const group = groups[ i ];
  7107. geometry2.addGroup( group.start, group.count, group.materialIndex );
  7108. }
  7109. return geometry2;
  7110. },
  7111. toJSON: function () {
  7112. const data = {
  7113. metadata: {
  7114. version: 4.5,
  7115. type: 'BufferGeometry',
  7116. generator: 'BufferGeometry.toJSON'
  7117. }
  7118. };
  7119. // standard BufferGeometry serialization
  7120. data.uuid = this.uuid;
  7121. data.type = this.type;
  7122. if ( this.name !== '' ) data.name = this.name;
  7123. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7124. if ( this.parameters !== undefined ) {
  7125. const parameters = this.parameters;
  7126. for ( const key in parameters ) {
  7127. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7128. }
  7129. return data;
  7130. }
  7131. data.data = { attributes: {} };
  7132. const index = this.index;
  7133. if ( index !== null ) {
  7134. data.data.index = {
  7135. type: index.array.constructor.name,
  7136. array: Array.prototype.slice.call( index.array )
  7137. };
  7138. }
  7139. const attributes = this.attributes;
  7140. for ( const key in attributes ) {
  7141. const attribute = attributes[ key ];
  7142. const attributeData = attribute.toJSON( data.data );
  7143. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  7144. data.data.attributes[ key ] = attributeData;
  7145. }
  7146. const morphAttributes = {};
  7147. let hasMorphAttributes = false;
  7148. for ( const key in this.morphAttributes ) {
  7149. const attributeArray = this.morphAttributes[ key ];
  7150. const array = [];
  7151. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  7152. const attribute = attributeArray[ i ];
  7153. const attributeData = attribute.toJSON( data.data );
  7154. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  7155. array.push( attributeData );
  7156. }
  7157. if ( array.length > 0 ) {
  7158. morphAttributes[ key ] = array;
  7159. hasMorphAttributes = true;
  7160. }
  7161. }
  7162. if ( hasMorphAttributes ) {
  7163. data.data.morphAttributes = morphAttributes;
  7164. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7165. }
  7166. const groups = this.groups;
  7167. if ( groups.length > 0 ) {
  7168. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7169. }
  7170. const boundingSphere = this.boundingSphere;
  7171. if ( boundingSphere !== null ) {
  7172. data.data.boundingSphere = {
  7173. center: boundingSphere.center.toArray(),
  7174. radius: boundingSphere.radius
  7175. };
  7176. }
  7177. return data;
  7178. },
  7179. clone: function () {
  7180. /*
  7181. // Handle primitives
  7182. const parameters = this.parameters;
  7183. if ( parameters !== undefined ) {
  7184. const values = [];
  7185. for ( const key in parameters ) {
  7186. values.push( parameters[ key ] );
  7187. }
  7188. const geometry = Object.create( this.constructor.prototype );
  7189. this.constructor.apply( geometry, values );
  7190. return geometry;
  7191. }
  7192. return new this.constructor().copy( this );
  7193. */
  7194. return new BufferGeometry().copy( this );
  7195. },
  7196. copy: function ( source ) {
  7197. // reset
  7198. this.index = null;
  7199. this.attributes = {};
  7200. this.morphAttributes = {};
  7201. this.groups = [];
  7202. this.boundingBox = null;
  7203. this.boundingSphere = null;
  7204. // used for storing cloned, shared data
  7205. const data = {};
  7206. // name
  7207. this.name = source.name;
  7208. // index
  7209. const index = source.index;
  7210. if ( index !== null ) {
  7211. this.setIndex( index.clone( data ) );
  7212. }
  7213. // attributes
  7214. const attributes = source.attributes;
  7215. for ( const name in attributes ) {
  7216. const attribute = attributes[ name ];
  7217. this.setAttribute( name, attribute.clone( data ) );
  7218. }
  7219. // morph attributes
  7220. const morphAttributes = source.morphAttributes;
  7221. for ( const name in morphAttributes ) {
  7222. const array = [];
  7223. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7224. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  7225. array.push( morphAttribute[ i ].clone( data ) );
  7226. }
  7227. this.morphAttributes[ name ] = array;
  7228. }
  7229. this.morphTargetsRelative = source.morphTargetsRelative;
  7230. // groups
  7231. const groups = source.groups;
  7232. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7233. const group = groups[ i ];
  7234. this.addGroup( group.start, group.count, group.materialIndex );
  7235. }
  7236. // bounding box
  7237. const boundingBox = source.boundingBox;
  7238. if ( boundingBox !== null ) {
  7239. this.boundingBox = boundingBox.clone();
  7240. }
  7241. // bounding sphere
  7242. const boundingSphere = source.boundingSphere;
  7243. if ( boundingSphere !== null ) {
  7244. this.boundingSphere = boundingSphere.clone();
  7245. }
  7246. // draw range
  7247. this.drawRange.start = source.drawRange.start;
  7248. this.drawRange.count = source.drawRange.count;
  7249. // user data
  7250. this.userData = source.userData;
  7251. return this;
  7252. },
  7253. dispose: function () {
  7254. this.dispatchEvent( { type: 'dispose' } );
  7255. }
  7256. } );
  7257. const _inverseMatrix = new Matrix4();
  7258. const _ray = new Ray();
  7259. const _sphere = new Sphere();
  7260. const _vA = new Vector3();
  7261. const _vB = new Vector3();
  7262. const _vC = new Vector3();
  7263. const _tempA = new Vector3();
  7264. const _tempB = new Vector3();
  7265. const _tempC = new Vector3();
  7266. const _morphA = new Vector3();
  7267. const _morphB = new Vector3();
  7268. const _morphC = new Vector3();
  7269. const _uvA = new Vector2$1();
  7270. const _uvB = new Vector2$1();
  7271. const _uvC = new Vector2$1();
  7272. const _intersectionPoint = new Vector3();
  7273. const _intersectionPointWorld = new Vector3();
  7274. function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  7275. Object3D.call( this );
  7276. this.type = 'Mesh';
  7277. this.geometry = geometry;
  7278. this.material = material;
  7279. this.updateMorphTargets();
  7280. }
  7281. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7282. constructor: Mesh,
  7283. isMesh: true,
  7284. copy: function ( source ) {
  7285. Object3D.prototype.copy.call( this, source );
  7286. if ( source.morphTargetInfluences !== undefined ) {
  7287. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7288. }
  7289. if ( source.morphTargetDictionary !== undefined ) {
  7290. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  7291. }
  7292. this.material = source.material;
  7293. this.geometry = source.geometry;
  7294. return this;
  7295. },
  7296. updateMorphTargets: function () {
  7297. const geometry = this.geometry;
  7298. if ( geometry.isBufferGeometry ) {
  7299. const morphAttributes = geometry.morphAttributes;
  7300. const keys = Object.keys( morphAttributes );
  7301. if ( keys.length > 0 ) {
  7302. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  7303. if ( morphAttribute !== undefined ) {
  7304. this.morphTargetInfluences = [];
  7305. this.morphTargetDictionary = {};
  7306. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  7307. const name = morphAttribute[ m ].name || String( m );
  7308. this.morphTargetInfluences.push( 0 );
  7309. this.morphTargetDictionary[ name ] = m;
  7310. }
  7311. }
  7312. }
  7313. } else {
  7314. const morphTargets = geometry.morphTargets;
  7315. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  7316. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7317. }
  7318. }
  7319. },
  7320. raycast: function ( raycaster, intersects ) {
  7321. const geometry = this.geometry;
  7322. const material = this.material;
  7323. const matrixWorld = this.matrixWorld;
  7324. if ( material === undefined ) return;
  7325. // Checking boundingSphere distance to ray
  7326. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7327. _sphere.copy( geometry.boundingSphere );
  7328. _sphere.applyMatrix4( matrixWorld );
  7329. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  7330. //
  7331. _inverseMatrix.copy( matrixWorld ).invert();
  7332. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  7333. // Check boundingBox before continuing
  7334. if ( geometry.boundingBox !== null ) {
  7335. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
  7336. }
  7337. let intersection;
  7338. if ( geometry.isBufferGeometry ) {
  7339. const index = geometry.index;
  7340. const position = geometry.attributes.position;
  7341. const morphPosition = geometry.morphAttributes.position;
  7342. const morphTargetsRelative = geometry.morphTargetsRelative;
  7343. const uv = geometry.attributes.uv;
  7344. const uv2 = geometry.attributes.uv2;
  7345. const groups = geometry.groups;
  7346. const drawRange = geometry.drawRange;
  7347. if ( index !== null ) {
  7348. // indexed buffer geometry
  7349. if ( Array.isArray( material ) ) {
  7350. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7351. const group = groups[ i ];
  7352. const groupMaterial = material[ group.materialIndex ];
  7353. const start = Math.max( group.start, drawRange.start );
  7354. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7355. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7356. const a = index.getX( j );
  7357. const b = index.getX( j + 1 );
  7358. const c = index.getX( j + 2 );
  7359. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7360. if ( intersection ) {
  7361. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7362. intersection.face.materialIndex = group.materialIndex;
  7363. intersects.push( intersection );
  7364. }
  7365. }
  7366. }
  7367. } else {
  7368. const start = Math.max( 0, drawRange.start );
  7369. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7370. for ( let i = start, il = end; i < il; i += 3 ) {
  7371. const a = index.getX( i );
  7372. const b = index.getX( i + 1 );
  7373. const c = index.getX( i + 2 );
  7374. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7375. if ( intersection ) {
  7376. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7377. intersects.push( intersection );
  7378. }
  7379. }
  7380. }
  7381. } else if ( position !== undefined ) {
  7382. // non-indexed buffer geometry
  7383. if ( Array.isArray( material ) ) {
  7384. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7385. const group = groups[ i ];
  7386. const groupMaterial = material[ group.materialIndex ];
  7387. const start = Math.max( group.start, drawRange.start );
  7388. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7389. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7390. const a = j;
  7391. const b = j + 1;
  7392. const c = j + 2;
  7393. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7394. if ( intersection ) {
  7395. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7396. intersection.face.materialIndex = group.materialIndex;
  7397. intersects.push( intersection );
  7398. }
  7399. }
  7400. }
  7401. } else {
  7402. const start = Math.max( 0, drawRange.start );
  7403. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7404. for ( let i = start, il = end; i < il; i += 3 ) {
  7405. const a = i;
  7406. const b = i + 1;
  7407. const c = i + 2;
  7408. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7409. if ( intersection ) {
  7410. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7411. intersects.push( intersection );
  7412. }
  7413. }
  7414. }
  7415. }
  7416. } else if ( geometry.isGeometry ) {
  7417. const isMultiMaterial = Array.isArray( material );
  7418. const vertices = geometry.vertices;
  7419. const faces = geometry.faces;
  7420. let uvs;
  7421. const faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  7422. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  7423. for ( let f = 0, fl = faces.length; f < fl; f ++ ) {
  7424. const face = faces[ f ];
  7425. const faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  7426. if ( faceMaterial === undefined ) continue;
  7427. const fvA = vertices[ face.a ];
  7428. const fvB = vertices[ face.b ];
  7429. const fvC = vertices[ face.c ];
  7430. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  7431. if ( intersection ) {
  7432. if ( uvs && uvs[ f ] ) {
  7433. const uvs_f = uvs[ f ];
  7434. _uvA.copy( uvs_f[ 0 ] );
  7435. _uvB.copy( uvs_f[ 1 ] );
  7436. _uvC.copy( uvs_f[ 2 ] );
  7437. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2$1() );
  7438. }
  7439. intersection.face = face;
  7440. intersection.faceIndex = f;
  7441. intersects.push( intersection );
  7442. }
  7443. }
  7444. }
  7445. }
  7446. } );
  7447. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7448. let intersect;
  7449. if ( material.side === BackSide ) {
  7450. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7451. } else {
  7452. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  7453. }
  7454. if ( intersect === null ) return null;
  7455. _intersectionPointWorld.copy( point );
  7456. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7457. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7458. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7459. return {
  7460. distance: distance,
  7461. point: _intersectionPointWorld.clone(),
  7462. object: object
  7463. };
  7464. }
  7465. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  7466. _vA.fromBufferAttribute( position, a );
  7467. _vB.fromBufferAttribute( position, b );
  7468. _vC.fromBufferAttribute( position, c );
  7469. const morphInfluences = object.morphTargetInfluences;
  7470. if ( material.morphTargets && morphPosition && morphInfluences ) {
  7471. _morphA.set( 0, 0, 0 );
  7472. _morphB.set( 0, 0, 0 );
  7473. _morphC.set( 0, 0, 0 );
  7474. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  7475. const influence = morphInfluences[ i ];
  7476. const morphAttribute = morphPosition[ i ];
  7477. if ( influence === 0 ) continue;
  7478. _tempA.fromBufferAttribute( morphAttribute, a );
  7479. _tempB.fromBufferAttribute( morphAttribute, b );
  7480. _tempC.fromBufferAttribute( morphAttribute, c );
  7481. if ( morphTargetsRelative ) {
  7482. _morphA.addScaledVector( _tempA, influence );
  7483. _morphB.addScaledVector( _tempB, influence );
  7484. _morphC.addScaledVector( _tempC, influence );
  7485. } else {
  7486. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  7487. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  7488. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  7489. }
  7490. }
  7491. _vA.add( _morphA );
  7492. _vB.add( _morphB );
  7493. _vC.add( _morphC );
  7494. }
  7495. if ( object.isSkinnedMesh ) {
  7496. object.boneTransform( a, _vA );
  7497. object.boneTransform( b, _vB );
  7498. object.boneTransform( c, _vC );
  7499. }
  7500. const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  7501. if ( intersection ) {
  7502. if ( uv ) {
  7503. _uvA.fromBufferAttribute( uv, a );
  7504. _uvB.fromBufferAttribute( uv, b );
  7505. _uvC.fromBufferAttribute( uv, c );
  7506. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2$1() );
  7507. }
  7508. if ( uv2 ) {
  7509. _uvA.fromBufferAttribute( uv2, a );
  7510. _uvB.fromBufferAttribute( uv2, b );
  7511. _uvC.fromBufferAttribute( uv2, c );
  7512. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2$1() );
  7513. }
  7514. const face = new Face3( a, b, c );
  7515. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  7516. intersection.face = face;
  7517. }
  7518. return intersection;
  7519. }
  7520. class BoxBufferGeometry extends BufferGeometry {
  7521. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7522. super();
  7523. this.type = 'BoxBufferGeometry';
  7524. this.parameters = {
  7525. width: width,
  7526. height: height,
  7527. depth: depth,
  7528. widthSegments: widthSegments,
  7529. heightSegments: heightSegments,
  7530. depthSegments: depthSegments
  7531. };
  7532. const scope = this;
  7533. // segments
  7534. widthSegments = Math.floor( widthSegments );
  7535. heightSegments = Math.floor( heightSegments );
  7536. depthSegments = Math.floor( depthSegments );
  7537. // buffers
  7538. const indices = [];
  7539. const vertices = [];
  7540. const normals = [];
  7541. const uvs = [];
  7542. // helper variables
  7543. let numberOfVertices = 0;
  7544. let groupStart = 0;
  7545. // build each side of the box geometry
  7546. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7547. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7548. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7549. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7550. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7551. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7552. // build geometry
  7553. this.setIndex( indices );
  7554. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7555. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7556. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7557. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7558. const segmentWidth = width / gridX;
  7559. const segmentHeight = height / gridY;
  7560. const widthHalf = width / 2;
  7561. const heightHalf = height / 2;
  7562. const depthHalf = depth / 2;
  7563. const gridX1 = gridX + 1;
  7564. const gridY1 = gridY + 1;
  7565. let vertexCounter = 0;
  7566. let groupCount = 0;
  7567. const vector = new Vector3();
  7568. // generate vertices, normals and uvs
  7569. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7570. const y = iy * segmentHeight - heightHalf;
  7571. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7572. const x = ix * segmentWidth - widthHalf;
  7573. // set values to correct vector component
  7574. vector[ u ] = x * udir;
  7575. vector[ v ] = y * vdir;
  7576. vector[ w ] = depthHalf;
  7577. // now apply vector to vertex buffer
  7578. vertices.push( vector.x, vector.y, vector.z );
  7579. // set values to correct vector component
  7580. vector[ u ] = 0;
  7581. vector[ v ] = 0;
  7582. vector[ w ] = depth > 0 ? 1 : - 1;
  7583. // now apply vector to normal buffer
  7584. normals.push( vector.x, vector.y, vector.z );
  7585. // uvs
  7586. uvs.push( ix / gridX );
  7587. uvs.push( 1 - ( iy / gridY ) );
  7588. // counters
  7589. vertexCounter += 1;
  7590. }
  7591. }
  7592. // indices
  7593. // 1. you need three indices to draw a single face
  7594. // 2. a single segment consists of two faces
  7595. // 3. so we need to generate six (2*3) indices per segment
  7596. for ( let iy = 0; iy < gridY; iy ++ ) {
  7597. for ( let ix = 0; ix < gridX; ix ++ ) {
  7598. const a = numberOfVertices + ix + gridX1 * iy;
  7599. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7600. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7601. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7602. // faces
  7603. indices.push( a, b, d );
  7604. indices.push( b, c, d );
  7605. // increase counter
  7606. groupCount += 6;
  7607. }
  7608. }
  7609. // add a group to the geometry. this will ensure multi material support
  7610. scope.addGroup( groupStart, groupCount, materialIndex );
  7611. // calculate new start value for groups
  7612. groupStart += groupCount;
  7613. // update total number of vertices
  7614. numberOfVertices += vertexCounter;
  7615. }
  7616. }
  7617. }
  7618. /**
  7619. * Uniform Utilities
  7620. */
  7621. function cloneUniforms( src ) {
  7622. const dst = {};
  7623. for ( const u in src ) {
  7624. dst[ u ] = {};
  7625. for ( const p in src[ u ] ) {
  7626. const property = src[ u ][ p ];
  7627. if ( property && ( property.isColor ||
  7628. property.isMatrix3 || property.isMatrix4 ||
  7629. property.isVector2 || property.isVector3 || property.isVector4 ||
  7630. property.isTexture ) ) {
  7631. dst[ u ][ p ] = property.clone();
  7632. } else if ( Array.isArray( property ) ) {
  7633. dst[ u ][ p ] = property.slice();
  7634. } else {
  7635. dst[ u ][ p ] = property;
  7636. }
  7637. }
  7638. }
  7639. return dst;
  7640. }
  7641. function mergeUniforms( uniforms ) {
  7642. const merged = {};
  7643. for ( let u = 0; u < uniforms.length; u ++ ) {
  7644. const tmp = cloneUniforms( uniforms[ u ] );
  7645. for ( const p in tmp ) {
  7646. merged[ p ] = tmp[ p ];
  7647. }
  7648. }
  7649. return merged;
  7650. }
  7651. // Legacy
  7652. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7653. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7654. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7655. /**
  7656. * parameters = {
  7657. * defines: { "label" : "value" },
  7658. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7659. *
  7660. * fragmentShader: <string>,
  7661. * vertexShader: <string>,
  7662. *
  7663. * wireframe: <boolean>,
  7664. * wireframelineWidth: <float>,
  7665. *
  7666. * lights: <bool>,
  7667. *
  7668. * skinning: <bool>,
  7669. * morphTargets: <bool>,
  7670. * morphNormals: <bool>
  7671. * }
  7672. */
  7673. function ShaderMaterial( parameters ) {
  7674. Material.call( this );
  7675. this.type = 'ShaderMaterial';
  7676. this.defines = {};
  7677. this.uniforms = {};
  7678. this.vertexShader = default_vertex;
  7679. this.fragmentShader = default_fragment;
  7680. this.lineWidth = 1;
  7681. this.wireframe = false;
  7682. this.wireframelineWidth = 1;
  7683. this.fog = false; // set to use scene fog
  7684. this.lights = false; // set to use scene lights
  7685. this.clipping = false; // set to use user-defined clipping planes
  7686. this.skinning = false; // set to use skinning attribute streams
  7687. this.morphTargets = false; // set to use morph targets
  7688. this.morphNormals = false; // set to use morph normals
  7689. this.extensions = {
  7690. derivatives: false, // set to use derivatives
  7691. fragDepth: false, // set to use fragment depth values
  7692. drawBuffers: false, // set to use draw buffers
  7693. shaderTextureLOD: false // set to use shader texture LOD
  7694. };
  7695. // When rendered geometry doesn't include these attributes but the material does,
  7696. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7697. this.defaultAttributeValues = {
  7698. 'color': [ 1, 1, 1 ],
  7699. 'uv': [ 0, 0 ],
  7700. 'uv2': [ 0, 0 ]
  7701. };
  7702. this.index0AttributeName = undefined;
  7703. this.uniformsNeedUpdate = false;
  7704. this.glslVersion = null;
  7705. if ( parameters !== undefined ) {
  7706. if ( parameters.attributes !== undefined ) {
  7707. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  7708. }
  7709. this.setValues( parameters );
  7710. }
  7711. }
  7712. ShaderMaterial.prototype = Object.create( Material.prototype );
  7713. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7714. ShaderMaterial.prototype.isShaderMaterial = true;
  7715. ShaderMaterial.prototype.copy = function ( source ) {
  7716. Material.prototype.copy.call( this, source );
  7717. this.fragmentShader = source.fragmentShader;
  7718. this.vertexShader = source.vertexShader;
  7719. this.uniforms = cloneUniforms( source.uniforms );
  7720. this.defines = Object.assign( {}, source.defines );
  7721. this.wireframe = source.wireframe;
  7722. this.wireframelineWidth = source.wireframelineWidth;
  7723. this.lights = source.lights;
  7724. this.clipping = source.clipping;
  7725. this.skinning = source.skinning;
  7726. this.morphTargets = source.morphTargets;
  7727. this.morphNormals = source.morphNormals;
  7728. this.extensions = Object.assign( {}, source.extensions );
  7729. this.glslVersion = source.glslVersion;
  7730. return this;
  7731. };
  7732. ShaderMaterial.prototype.toJSON = function ( meta ) {
  7733. const data = Material.prototype.toJSON.call( this, meta );
  7734. data.glslVersion = this.glslVersion;
  7735. data.uniforms = {};
  7736. for ( const name in this.uniforms ) {
  7737. const uniform = this.uniforms[ name ];
  7738. const value = uniform.value;
  7739. if ( value && value.isTexture ) {
  7740. data.uniforms[ name ] = {
  7741. type: 't',
  7742. value: value.toJSON( meta ).uuid
  7743. };
  7744. } else if ( value && value.isColor ) {
  7745. data.uniforms[ name ] = {
  7746. type: 'c',
  7747. value: value.getHex()
  7748. };
  7749. } else if ( value && value.isVector2 ) {
  7750. data.uniforms[ name ] = {
  7751. type: 'v2',
  7752. value: value.toArray()
  7753. };
  7754. } else if ( value && value.isVector3 ) {
  7755. data.uniforms[ name ] = {
  7756. type: 'v3',
  7757. value: value.toArray()
  7758. };
  7759. } else if ( value && value.isVector4 ) {
  7760. data.uniforms[ name ] = {
  7761. type: 'v4',
  7762. value: value.toArray()
  7763. };
  7764. } else if ( value && value.isMatrix3 ) {
  7765. data.uniforms[ name ] = {
  7766. type: 'm3',
  7767. value: value.toArray()
  7768. };
  7769. } else if ( value && value.isMatrix4 ) {
  7770. data.uniforms[ name ] = {
  7771. type: 'm4',
  7772. value: value.toArray()
  7773. };
  7774. } else {
  7775. data.uniforms[ name ] = {
  7776. value: value
  7777. };
  7778. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7779. }
  7780. }
  7781. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7782. data.vertexShader = this.vertexShader;
  7783. data.fragmentShader = this.fragmentShader;
  7784. const extensions = {};
  7785. for ( const key in this.extensions ) {
  7786. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7787. }
  7788. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7789. return data;
  7790. };
  7791. function Camera() {
  7792. Object3D.call( this );
  7793. this.type = 'Camera';
  7794. this.matrixWorldInverse = new Matrix4();
  7795. this.projectionMatrix = new Matrix4();
  7796. this.projectionMatrixInverse = new Matrix4();
  7797. }
  7798. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7799. constructor: Camera,
  7800. isCamera: true,
  7801. copy: function ( source, recursive ) {
  7802. Object3D.prototype.copy.call( this, source, recursive );
  7803. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7804. this.projectionMatrix.copy( source.projectionMatrix );
  7805. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7806. return this;
  7807. },
  7808. getWorldDirection: function ( target ) {
  7809. if ( target === undefined ) {
  7810. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  7811. target = new Vector3();
  7812. }
  7813. this.updateWorldMatrix( true, false );
  7814. const e = this.matrixWorld.elements;
  7815. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7816. },
  7817. updateMatrixWorld: function ( force ) {
  7818. Object3D.prototype.updateMatrixWorld.call( this, force );
  7819. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7820. },
  7821. updateWorldMatrix: function ( updateParents, updateChildren ) {
  7822. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  7823. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7824. },
  7825. clone: function () {
  7826. return new this.constructor().copy( this );
  7827. }
  7828. } );
  7829. function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7830. Camera.call( this );
  7831. this.type = 'PerspectiveCamera';
  7832. this.fov = fov;
  7833. this.zoom = 1;
  7834. this.near = near;
  7835. this.far = far;
  7836. this.focus = 10;
  7837. this.aspect = aspect;
  7838. this.view = null;
  7839. this.filmGauge = 35; // width of the film (default in millimeters)
  7840. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7841. this.updateProjectionMatrix();
  7842. }
  7843. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  7844. constructor: PerspectiveCamera,
  7845. isPerspectiveCamera: true,
  7846. copy: function ( source, recursive ) {
  7847. Camera.prototype.copy.call( this, source, recursive );
  7848. this.fov = source.fov;
  7849. this.zoom = source.zoom;
  7850. this.near = source.near;
  7851. this.far = source.far;
  7852. this.focus = source.focus;
  7853. this.aspect = source.aspect;
  7854. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7855. this.filmGauge = source.filmGauge;
  7856. this.filmOffset = source.filmOffset;
  7857. return this;
  7858. },
  7859. /**
  7860. * Sets the FOV by focal length in respect to the current .filmGauge.
  7861. *
  7862. * The default film gauge is 35, so that the focal length can be specified for
  7863. * a 35mm (full frame) camera.
  7864. *
  7865. * Values for focal length and film gauge must have the same unit.
  7866. */
  7867. setFocalLength: function ( focalLength ) {
  7868. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7869. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7870. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  7871. this.updateProjectionMatrix();
  7872. },
  7873. /**
  7874. * Calculates the focal length from the current .fov and .filmGauge.
  7875. */
  7876. getFocalLength: function () {
  7877. const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  7878. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7879. },
  7880. getEffectiveFOV: function () {
  7881. return MathUtils.RAD2DEG * 2 * Math.atan(
  7882. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7883. },
  7884. getFilmWidth: function () {
  7885. // film not completely covered in portrait format (aspect < 1)
  7886. return this.filmGauge * Math.min( this.aspect, 1 );
  7887. },
  7888. getFilmHeight: function () {
  7889. // film not completely covered in landscape format (aspect > 1)
  7890. return this.filmGauge / Math.max( this.aspect, 1 );
  7891. },
  7892. /**
  7893. * Sets an offset in a larger frustum. This is useful for multi-window or
  7894. * multi-monitor/multi-machine setups.
  7895. *
  7896. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7897. * the monitors are in grid like this
  7898. *
  7899. * +---+---+---+
  7900. * | A | B | C |
  7901. * +---+---+---+
  7902. * | D | E | F |
  7903. * +---+---+---+
  7904. *
  7905. * then for each monitor you would call it like this
  7906. *
  7907. * const w = 1920;
  7908. * const h = 1080;
  7909. * const fullWidth = w * 3;
  7910. * const fullHeight = h * 2;
  7911. *
  7912. * --A--
  7913. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7914. * --B--
  7915. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7916. * --C--
  7917. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7918. * --D--
  7919. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7920. * --E--
  7921. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7922. * --F--
  7923. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7924. *
  7925. * Note there is no reason monitors have to be the same size or in a grid.
  7926. */
  7927. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  7928. this.aspect = fullWidth / fullHeight;
  7929. if ( this.view === null ) {
  7930. this.view = {
  7931. enabled: true,
  7932. fullWidth: 1,
  7933. fullHeight: 1,
  7934. offsetX: 0,
  7935. offsetY: 0,
  7936. width: 1,
  7937. height: 1
  7938. };
  7939. }
  7940. this.view.enabled = true;
  7941. this.view.fullWidth = fullWidth;
  7942. this.view.fullHeight = fullHeight;
  7943. this.view.offsetX = x;
  7944. this.view.offsetY = y;
  7945. this.view.width = width;
  7946. this.view.height = height;
  7947. this.updateProjectionMatrix();
  7948. },
  7949. clearViewOffset: function () {
  7950. if ( this.view !== null ) {
  7951. this.view.enabled = false;
  7952. }
  7953. this.updateProjectionMatrix();
  7954. },
  7955. updateProjectionMatrix: function () {
  7956. const near = this.near;
  7957. let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7958. let height = 2 * top;
  7959. let width = this.aspect * height;
  7960. let left = - 0.5 * width;
  7961. const view = this.view;
  7962. if ( this.view !== null && this.view.enabled ) {
  7963. const fullWidth = view.fullWidth,
  7964. fullHeight = view.fullHeight;
  7965. left += view.offsetX * width / fullWidth;
  7966. top -= view.offsetY * height / fullHeight;
  7967. width *= view.width / fullWidth;
  7968. height *= view.height / fullHeight;
  7969. }
  7970. const skew = this.filmOffset;
  7971. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7972. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7973. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7974. },
  7975. toJSON: function ( meta ) {
  7976. const data = Object3D.prototype.toJSON.call( this, meta );
  7977. data.object.fov = this.fov;
  7978. data.object.zoom = this.zoom;
  7979. data.object.near = this.near;
  7980. data.object.far = this.far;
  7981. data.object.focus = this.focus;
  7982. data.object.aspect = this.aspect;
  7983. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7984. data.object.filmGauge = this.filmGauge;
  7985. data.object.filmOffset = this.filmOffset;
  7986. return data;
  7987. }
  7988. } );
  7989. const fov = 90, aspect = 1;
  7990. function CubeCamera( near, far, renderTarget ) {
  7991. Object3D.call( this );
  7992. this.type = 'CubeCamera';
  7993. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7994. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7995. return;
  7996. }
  7997. this.renderTarget = renderTarget;
  7998. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7999. cameraPX.layers = this.layers;
  8000. cameraPX.up.set( 0, - 1, 0 );
  8001. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  8002. this.add( cameraPX );
  8003. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  8004. cameraNX.layers = this.layers;
  8005. cameraNX.up.set( 0, - 1, 0 );
  8006. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  8007. this.add( cameraNX );
  8008. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  8009. cameraPY.layers = this.layers;
  8010. cameraPY.up.set( 0, 0, 1 );
  8011. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  8012. this.add( cameraPY );
  8013. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  8014. cameraNY.layers = this.layers;
  8015. cameraNY.up.set( 0, 0, - 1 );
  8016. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  8017. this.add( cameraNY );
  8018. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  8019. cameraPZ.layers = this.layers;
  8020. cameraPZ.up.set( 0, - 1, 0 );
  8021. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  8022. this.add( cameraPZ );
  8023. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  8024. cameraNZ.layers = this.layers;
  8025. cameraNZ.up.set( 0, - 1, 0 );
  8026. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  8027. this.add( cameraNZ );
  8028. this.update = function ( renderer, scene ) {
  8029. if ( this.parent === null ) this.updateMatrixWorld();
  8030. const currentXrEnabled = renderer.xr.enabled;
  8031. const currentRenderTarget = renderer.getRenderTarget();
  8032. renderer.xr.enabled = false;
  8033. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8034. renderTarget.texture.generateMipmaps = false;
  8035. renderer.setRenderTarget( renderTarget, 0 );
  8036. renderer.render( scene, cameraPX );
  8037. renderer.setRenderTarget( renderTarget, 1 );
  8038. renderer.render( scene, cameraNX );
  8039. renderer.setRenderTarget( renderTarget, 2 );
  8040. renderer.render( scene, cameraPY );
  8041. renderer.setRenderTarget( renderTarget, 3 );
  8042. renderer.render( scene, cameraNY );
  8043. renderer.setRenderTarget( renderTarget, 4 );
  8044. renderer.render( scene, cameraPZ );
  8045. renderTarget.texture.generateMipmaps = generateMipmaps;
  8046. renderer.setRenderTarget( renderTarget, 5 );
  8047. renderer.render( scene, cameraNZ );
  8048. renderer.setRenderTarget( currentRenderTarget );
  8049. renderer.xr.enabled = currentXrEnabled;
  8050. };
  8051. }
  8052. CubeCamera.prototype = Object.create( Object3D.prototype );
  8053. CubeCamera.prototype.constructor = CubeCamera;
  8054. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8055. images = images !== undefined ? images : [];
  8056. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8057. format = format !== undefined ? format : RGBFormat;
  8058. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8059. this.flipY = false;
  8060. // Why CubeTexture._needsFlipEnvMap is necessary:
  8061. //
  8062. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8063. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8064. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8065. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8066. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  8067. // when using WebGLCubeRenderTarget.texture as a cube texture.
  8068. this._needsFlipEnvMap = true;
  8069. }
  8070. CubeTexture.prototype = Object.create( Texture.prototype );
  8071. CubeTexture.prototype.constructor = CubeTexture;
  8072. CubeTexture.prototype.isCubeTexture = true;
  8073. Object.defineProperty( CubeTexture.prototype, 'images', {
  8074. get: function () {
  8075. return this.image;
  8076. },
  8077. set: function ( value ) {
  8078. this.image = value;
  8079. }
  8080. } );
  8081. function WebGLCubeRenderTarget( size, options, dummy ) {
  8082. if ( Number.isInteger( options ) ) {
  8083. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  8084. options = dummy;
  8085. }
  8086. WebGLRenderTarget.call( this, size, size, options );
  8087. options = options || {};
  8088. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  8089. this.texture._needsFlipEnvMap = false;
  8090. }
  8091. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  8092. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8093. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8094. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  8095. this.texture.type = texture.type;
  8096. this.texture.format = RGBAFormat; // see #18859
  8097. this.texture.encoding = texture.encoding;
  8098. this.texture.generateMipmaps = texture.generateMipmaps;
  8099. this.texture.minFilter = texture.minFilter;
  8100. this.texture.magFilter = texture.magFilter;
  8101. const shader = {
  8102. uniforms: {
  8103. tEquirect: { value: null },
  8104. },
  8105. vertexShader: /* glsl */`
  8106. varying vec3 vWorldDirection;
  8107. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8108. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8109. }
  8110. void main() {
  8111. vWorldDirection = transformDirection( position, modelMatrix );
  8112. #include <begin_vertex>
  8113. #include <project_vertex>
  8114. }
  8115. `,
  8116. fragmentShader: /* glsl */`
  8117. uniform sampler2D tEquirect;
  8118. varying vec3 vWorldDirection;
  8119. #include <common>
  8120. void main() {
  8121. vec3 direction = normalize( vWorldDirection );
  8122. vec2 sampleUV = equirectUv( direction );
  8123. gl_FragColor = texture2D( tEquirect, sampleUV );
  8124. }
  8125. `
  8126. };
  8127. const geometry = new BoxBufferGeometry( 5, 5, 5 );
  8128. const material = new ShaderMaterial( {
  8129. name: 'CubemapFromEquirect',
  8130. uniforms: cloneUniforms( shader.uniforms ),
  8131. vertexShader: shader.vertexShader,
  8132. fragmentShader: shader.fragmentShader,
  8133. side: BackSide,
  8134. blending: NoBlending
  8135. } );
  8136. material.uniforms.tEquirect.value = texture;
  8137. const mesh = new Mesh( geometry, material );
  8138. const currentMinFilter = texture.minFilter;
  8139. // Avoid blurred poles
  8140. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  8141. const camera = new CubeCamera( 1, 10, this );
  8142. camera.update( renderer, mesh );
  8143. texture.minFilter = currentMinFilter;
  8144. mesh.geometry.dispose();
  8145. mesh.material.dispose();
  8146. return this;
  8147. };
  8148. WebGLCubeRenderTarget.prototype.clear = function ( renderer, color, depth, stencil ) {
  8149. const currentRenderTarget = renderer.getRenderTarget();
  8150. for ( let i = 0; i < 6; i ++ ) {
  8151. renderer.setRenderTarget( this, i );
  8152. renderer.clear( color, depth, stencil );
  8153. }
  8154. renderer.setRenderTarget( currentRenderTarget );
  8155. };
  8156. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  8157. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8158. this.image = { data: data || null, width: width || 1, height: height || 1 };
  8159. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8160. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8161. this.generateMipmaps = false;
  8162. this.flipY = false;
  8163. this.unpackAlignment = 1;
  8164. this.needsUpdate = true;
  8165. }
  8166. DataTexture.prototype = Object.create( Texture.prototype );
  8167. DataTexture.prototype.constructor = DataTexture;
  8168. DataTexture.prototype.isDataTexture = true;
  8169. const _sphere$1 = /*@__PURE__*/ new Sphere();
  8170. const _vector$5 = /*@__PURE__*/ new Vector3();
  8171. class Frustum {
  8172. constructor( p0, p1, p2, p3, p4, p5 ) {
  8173. this.planes = [
  8174. ( p0 !== undefined ) ? p0 : new Plane(),
  8175. ( p1 !== undefined ) ? p1 : new Plane(),
  8176. ( p2 !== undefined ) ? p2 : new Plane(),
  8177. ( p3 !== undefined ) ? p3 : new Plane(),
  8178. ( p4 !== undefined ) ? p4 : new Plane(),
  8179. ( p5 !== undefined ) ? p5 : new Plane()
  8180. ];
  8181. }
  8182. set( p0, p1, p2, p3, p4, p5 ) {
  8183. const planes = this.planes;
  8184. planes[ 0 ].copy( p0 );
  8185. planes[ 1 ].copy( p1 );
  8186. planes[ 2 ].copy( p2 );
  8187. planes[ 3 ].copy( p3 );
  8188. planes[ 4 ].copy( p4 );
  8189. planes[ 5 ].copy( p5 );
  8190. return this;
  8191. }
  8192. clone() {
  8193. return new this.constructor().copy( this );
  8194. }
  8195. copy( frustum ) {
  8196. const planes = this.planes;
  8197. for ( let i = 0; i < 6; i ++ ) {
  8198. planes[ i ].copy( frustum.planes[ i ] );
  8199. }
  8200. return this;
  8201. }
  8202. setFromProjectionMatrix( m ) {
  8203. const planes = this.planes;
  8204. const me = m.elements;
  8205. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8206. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8207. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8208. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8209. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8210. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8211. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8212. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8213. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8214. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8215. return this;
  8216. }
  8217. intersectsObject( object ) {
  8218. const geometry = object.geometry;
  8219. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8220. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8221. return this.intersectsSphere( _sphere$1 );
  8222. }
  8223. intersectsSprite( sprite ) {
  8224. _sphere$1.center.set( 0, 0, 0 );
  8225. _sphere$1.radius = 0.7071067811865476;
  8226. _sphere$1.applyMatrix4( sprite.matrixWorld );
  8227. return this.intersectsSphere( _sphere$1 );
  8228. }
  8229. intersectsSphere( sphere ) {
  8230. const planes = this.planes;
  8231. const center = sphere.center;
  8232. const negRadius = - sphere.radius;
  8233. for ( let i = 0; i < 6; i ++ ) {
  8234. const distance = planes[ i ].distanceToPoint( center );
  8235. if ( distance < negRadius ) {
  8236. return false;
  8237. }
  8238. }
  8239. return true;
  8240. }
  8241. intersectsBox( box ) {
  8242. const planes = this.planes;
  8243. for ( let i = 0; i < 6; i ++ ) {
  8244. const plane = planes[ i ];
  8245. // corner at max distance
  8246. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8247. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8248. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8249. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  8250. return false;
  8251. }
  8252. }
  8253. return true;
  8254. }
  8255. containsPoint( point ) {
  8256. const planes = this.planes;
  8257. for ( let i = 0; i < 6; i ++ ) {
  8258. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8259. return false;
  8260. }
  8261. }
  8262. return true;
  8263. }
  8264. }
  8265. function WebGLAnimation() {
  8266. let context = null;
  8267. let isAnimating = false;
  8268. let animationLoop = null;
  8269. let requestId = null;
  8270. function onAnimationFrame( time, frame ) {
  8271. animationLoop( time, frame );
  8272. requestId = context.requestAnimationFrame( onAnimationFrame );
  8273. }
  8274. return {
  8275. start: function () {
  8276. if ( isAnimating === true ) return;
  8277. if ( animationLoop === null ) return;
  8278. requestId = context.requestAnimationFrame( onAnimationFrame );
  8279. isAnimating = true;
  8280. },
  8281. stop: function () {
  8282. context.cancelAnimationFrame( requestId );
  8283. isAnimating = false;
  8284. },
  8285. setAnimationLoop: function ( callback ) {
  8286. animationLoop = callback;
  8287. },
  8288. setContext: function ( value ) {
  8289. context = value;
  8290. }
  8291. };
  8292. }
  8293. function WebGLAttributes( gl, capabilities ) {
  8294. const isWebGL2 = capabilities.isWebGL2;
  8295. const buffers = new WeakMap();
  8296. function createBuffer( attribute, bufferType ) {
  8297. const array = attribute.array;
  8298. const usage = attribute.usage;
  8299. const buffer = gl.createBuffer();
  8300. gl.bindBuffer( bufferType, buffer );
  8301. gl.bufferData( bufferType, array, usage );
  8302. attribute.onUploadCallback();
  8303. let type = 5126;
  8304. if ( array instanceof Float32Array ) {
  8305. type = 5126;
  8306. } else if ( array instanceof Float64Array ) {
  8307. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8308. } else if ( array instanceof Uint16Array ) {
  8309. if ( attribute.isFloat16BufferAttribute ) {
  8310. if ( isWebGL2 ) {
  8311. type = 5131;
  8312. } else {
  8313. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8314. }
  8315. } else {
  8316. type = 5123;
  8317. }
  8318. } else if ( array instanceof Int16Array ) {
  8319. type = 5122;
  8320. } else if ( array instanceof Uint32Array ) {
  8321. type = 5125;
  8322. } else if ( array instanceof Int32Array ) {
  8323. type = 5124;
  8324. } else if ( array instanceof Int8Array ) {
  8325. type = 5120;
  8326. } else if ( array instanceof Uint8Array ) {
  8327. type = 5121;
  8328. }
  8329. return {
  8330. buffer: buffer,
  8331. type: type,
  8332. bytesPerElement: array.BYTES_PER_ELEMENT,
  8333. version: attribute.version
  8334. };
  8335. }
  8336. function updateBuffer( buffer, attribute, bufferType ) {
  8337. const array = attribute.array;
  8338. const updateRange = attribute.updateRange;
  8339. gl.bindBuffer( bufferType, buffer );
  8340. if ( updateRange.count === - 1 ) {
  8341. // Not using update ranges
  8342. gl.bufferSubData( bufferType, 0, array );
  8343. } else {
  8344. if ( isWebGL2 ) {
  8345. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8346. array, updateRange.offset, updateRange.count );
  8347. } else {
  8348. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8349. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8350. }
  8351. updateRange.count = - 1; // reset range
  8352. }
  8353. }
  8354. //
  8355. function get( attribute ) {
  8356. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8357. return buffers.get( attribute );
  8358. }
  8359. function remove( attribute ) {
  8360. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8361. const data = buffers.get( attribute );
  8362. if ( data ) {
  8363. gl.deleteBuffer( data.buffer );
  8364. buffers.delete( attribute );
  8365. }
  8366. }
  8367. function update( attribute, bufferType ) {
  8368. if ( attribute.isGLBufferAttribute ) {
  8369. const cached = buffers.get( attribute );
  8370. if ( ! cached || cached.version < attribute.version ) {
  8371. buffers.set( attribute, {
  8372. buffer: attribute.buffer,
  8373. type: attribute.type,
  8374. bytesPerElement: attribute.elementSize,
  8375. version: attribute.version
  8376. } );
  8377. }
  8378. return;
  8379. }
  8380. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8381. const data = buffers.get( attribute );
  8382. if ( data === undefined ) {
  8383. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8384. } else if ( data.version < attribute.version ) {
  8385. updateBuffer( data.buffer, attribute, bufferType );
  8386. data.version = attribute.version;
  8387. }
  8388. }
  8389. return {
  8390. get: get,
  8391. remove: remove,
  8392. update: update
  8393. };
  8394. }
  8395. class PlaneBufferGeometry extends BufferGeometry {
  8396. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8397. super();
  8398. this.type = 'PlaneBufferGeometry';
  8399. this.parameters = {
  8400. width: width,
  8401. height: height,
  8402. widthSegments: widthSegments,
  8403. heightSegments: heightSegments
  8404. };
  8405. const width_half = width / 2;
  8406. const height_half = height / 2;
  8407. const gridX = Math.floor( widthSegments );
  8408. const gridY = Math.floor( heightSegments );
  8409. const gridX1 = gridX + 1;
  8410. const gridY1 = gridY + 1;
  8411. const segment_width = width / gridX;
  8412. const segment_height = height / gridY;
  8413. //
  8414. const indices = [];
  8415. const vertices = [];
  8416. const normals = [];
  8417. const uvs = [];
  8418. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8419. const y = iy * segment_height - height_half;
  8420. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8421. const x = ix * segment_width - width_half;
  8422. vertices.push( x, - y, 0 );
  8423. normals.push( 0, 0, 1 );
  8424. uvs.push( ix / gridX );
  8425. uvs.push( 1 - ( iy / gridY ) );
  8426. }
  8427. }
  8428. for ( let iy = 0; iy < gridY; iy ++ ) {
  8429. for ( let ix = 0; ix < gridX; ix ++ ) {
  8430. const a = ix + gridX1 * iy;
  8431. const b = ix + gridX1 * ( iy + 1 );
  8432. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8433. const d = ( ix + 1 ) + gridX1 * iy;
  8434. indices.push( a, b, d );
  8435. indices.push( b, c, d );
  8436. }
  8437. }
  8438. this.setIndex( indices );
  8439. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8440. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8441. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8442. }
  8443. }
  8444. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8445. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8446. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8447. 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( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  8448. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8449. var begin_vertex = "vec3 transformed = vec3( position );";
  8450. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8451. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\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\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\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}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\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 vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\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#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  8452. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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";
  8453. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8454. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8455. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8456. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8457. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8458. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8459. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8460. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  8461. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(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}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\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#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\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 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  8462. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  8463. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8464. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8465. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8466. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8467. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8468. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8469. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  8470. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\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";
  8471. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  8472. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  8473. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  8474. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\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";
  8475. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8476. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8477. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  8478. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  8479. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  8480. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8481. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8482. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8483. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\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};\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};\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};\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 ltc_1;\tuniform sampler2D ltc_2;\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";
  8484. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\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\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 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 roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, 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\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  8485. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8486. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  8487. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8488. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial 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\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  8489. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  8490. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\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 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\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\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}";
  8491. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8492. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * 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 defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  8493. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  8494. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8495. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8496. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8497. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  8498. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8499. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8500. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8501. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8502. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8503. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8504. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  8505. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  8506. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  8507. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8508. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8509. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  8510. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8511. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
  8512. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  8513. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  8514. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8515. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8516. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8517. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  8518. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8519. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8520. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\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";
  8521. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8522. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  8523. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8524. 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";
  8525. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  8526. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  8527. 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\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  8528. 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";
  8529. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8530. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8531. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8532. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8533. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8534. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8535. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  8536. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8537. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8538. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  8539. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8540. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8541. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8542. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  8543. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8544. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  8545. 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>\nvarying vec2 vHighPrecisionZW;\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\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8546. 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>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8547. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8548. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8549. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8550. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  8551. 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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8552. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8553. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_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\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8554. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8555. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\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\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8556. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\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_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8557. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_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 <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8558. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <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#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8559. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_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 <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8560. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8561. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8562. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8563. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_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#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8564. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8565. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\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>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  8566. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_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\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8567. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_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\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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8568. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_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 <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8569. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8570. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8571. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_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\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8572. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8573. const ShaderChunk = {
  8574. alphamap_fragment: alphamap_fragment,
  8575. alphamap_pars_fragment: alphamap_pars_fragment,
  8576. alphatest_fragment: alphatest_fragment,
  8577. aomap_fragment: aomap_fragment,
  8578. aomap_pars_fragment: aomap_pars_fragment,
  8579. begin_vertex: begin_vertex,
  8580. beginnormal_vertex: beginnormal_vertex,
  8581. bsdfs: bsdfs,
  8582. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8583. clipping_planes_fragment: clipping_planes_fragment,
  8584. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8585. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8586. clipping_planes_vertex: clipping_planes_vertex,
  8587. color_fragment: color_fragment,
  8588. color_pars_fragment: color_pars_fragment,
  8589. color_pars_vertex: color_pars_vertex,
  8590. color_vertex: color_vertex,
  8591. common: common,
  8592. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8593. defaultnormal_vertex: defaultnormal_vertex,
  8594. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8595. displacementmap_vertex: displacementmap_vertex,
  8596. emissivemap_fragment: emissivemap_fragment,
  8597. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8598. encodings_fragment: encodings_fragment,
  8599. encodings_pars_fragment: encodings_pars_fragment,
  8600. envmap_fragment: envmap_fragment,
  8601. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8602. envmap_pars_fragment: envmap_pars_fragment,
  8603. envmap_pars_vertex: envmap_pars_vertex,
  8604. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8605. envmap_vertex: envmap_vertex,
  8606. fog_vertex: fog_vertex,
  8607. fog_pars_vertex: fog_pars_vertex,
  8608. fog_fragment: fog_fragment,
  8609. fog_pars_fragment: fog_pars_fragment,
  8610. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8611. lightmap_fragment: lightmap_fragment,
  8612. lightmap_pars_fragment: lightmap_pars_fragment,
  8613. lights_lambert_vertex: lights_lambert_vertex,
  8614. lights_pars_begin: lights_pars_begin,
  8615. lights_toon_fragment: lights_toon_fragment,
  8616. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8617. lights_phong_fragment: lights_phong_fragment,
  8618. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8619. lights_physical_fragment: lights_physical_fragment,
  8620. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8621. lights_fragment_begin: lights_fragment_begin,
  8622. lights_fragment_maps: lights_fragment_maps,
  8623. lights_fragment_end: lights_fragment_end,
  8624. logdepthbuf_fragment: logdepthbuf_fragment,
  8625. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8626. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8627. logdepthbuf_vertex: logdepthbuf_vertex,
  8628. map_fragment: map_fragment,
  8629. map_pars_fragment: map_pars_fragment,
  8630. map_particle_fragment: map_particle_fragment,
  8631. map_particle_pars_fragment: map_particle_pars_fragment,
  8632. metalnessmap_fragment: metalnessmap_fragment,
  8633. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8634. morphnormal_vertex: morphnormal_vertex,
  8635. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8636. morphtarget_vertex: morphtarget_vertex,
  8637. normal_fragment_begin: normal_fragment_begin,
  8638. normal_fragment_maps: normal_fragment_maps,
  8639. normalmap_pars_fragment: normalmap_pars_fragment,
  8640. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8641. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8642. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8643. packing: packing,
  8644. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8645. project_vertex: project_vertex,
  8646. dithering_fragment: dithering_fragment,
  8647. dithering_pars_fragment: dithering_pars_fragment,
  8648. roughnessmap_fragment: roughnessmap_fragment,
  8649. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8650. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8651. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8652. shadowmap_vertex: shadowmap_vertex,
  8653. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8654. skinbase_vertex: skinbase_vertex,
  8655. skinning_pars_vertex: skinning_pars_vertex,
  8656. skinning_vertex: skinning_vertex,
  8657. skinnormal_vertex: skinnormal_vertex,
  8658. specularmap_fragment: specularmap_fragment,
  8659. specularmap_pars_fragment: specularmap_pars_fragment,
  8660. tonemapping_fragment: tonemapping_fragment,
  8661. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8662. transmissionmap_fragment: transmissionmap_fragment,
  8663. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8664. uv_pars_fragment: uv_pars_fragment,
  8665. uv_pars_vertex: uv_pars_vertex,
  8666. uv_vertex: uv_vertex,
  8667. uv2_pars_fragment: uv2_pars_fragment,
  8668. uv2_pars_vertex: uv2_pars_vertex,
  8669. uv2_vertex: uv2_vertex,
  8670. worldpos_vertex: worldpos_vertex,
  8671. background_frag: background_frag,
  8672. background_vert: background_vert,
  8673. cube_frag: cube_frag,
  8674. cube_vert: cube_vert,
  8675. depth_frag: depth_frag,
  8676. depth_vert: depth_vert,
  8677. distanceRGBA_frag: distanceRGBA_frag,
  8678. distanceRGBA_vert: distanceRGBA_vert,
  8679. equirect_frag: equirect_frag,
  8680. equirect_vert: equirect_vert,
  8681. linedashed_frag: linedashed_frag,
  8682. linedashed_vert: linedashed_vert,
  8683. meshbasic_frag: meshbasic_frag,
  8684. meshbasic_vert: meshbasic_vert,
  8685. meshlambert_frag: meshlambert_frag,
  8686. meshlambert_vert: meshlambert_vert,
  8687. meshmatcap_frag: meshmatcap_frag,
  8688. meshmatcap_vert: meshmatcap_vert,
  8689. meshtoon_frag: meshtoon_frag,
  8690. meshtoon_vert: meshtoon_vert,
  8691. meshphong_frag: meshphong_frag,
  8692. meshphong_vert: meshphong_vert,
  8693. meshphysical_frag: meshphysical_frag,
  8694. meshphysical_vert: meshphysical_vert,
  8695. normal_frag: normal_frag,
  8696. normal_vert: normal_vert,
  8697. points_frag: points_frag,
  8698. points_vert: points_vert,
  8699. shadow_frag: shadow_frag,
  8700. shadow_vert: shadow_vert,
  8701. sprite_frag: sprite_frag,
  8702. sprite_vert: sprite_vert
  8703. };
  8704. /**
  8705. * Uniforms library for shared webgl shaders
  8706. */
  8707. const UniformsLib = {
  8708. common: {
  8709. diffuse: { value: new Color( 0xeeeeee ) },
  8710. opacity: { value: 1.0 },
  8711. map: { value: null },
  8712. uvTransform: { value: new Matrix3() },
  8713. uv2Transform: { value: new Matrix3() },
  8714. alphaMap: { value: null },
  8715. },
  8716. specularmap: {
  8717. specularMap: { value: null },
  8718. },
  8719. envmap: {
  8720. envMap: { value: null },
  8721. flipEnvMap: { value: - 1 },
  8722. reflectivity: { value: 1.0 },
  8723. refractionRatio: { value: 0.98 },
  8724. maxMipLevel: { value: 0 }
  8725. },
  8726. aomap: {
  8727. aoMap: { value: null },
  8728. aoMapIntensity: { value: 1 }
  8729. },
  8730. lightmap: {
  8731. lightMap: { value: null },
  8732. lightMapIntensity: { value: 1 }
  8733. },
  8734. emissivemap: {
  8735. emissiveMap: { value: null }
  8736. },
  8737. bumpmap: {
  8738. bumpMap: { value: null },
  8739. bumpScale: { value: 1 }
  8740. },
  8741. normalmap: {
  8742. normalMap: { value: null },
  8743. normalScale: { value: new Vector2$1( 1, 1 ) }
  8744. },
  8745. displacementmap: {
  8746. displacementMap: { value: null },
  8747. displacementScale: { value: 1 },
  8748. displacementBias: { value: 0 }
  8749. },
  8750. roughnessmap: {
  8751. roughnessMap: { value: null }
  8752. },
  8753. metalnessmap: {
  8754. metalnessMap: { value: null }
  8755. },
  8756. gradientmap: {
  8757. gradientMap: { value: null }
  8758. },
  8759. fog: {
  8760. fogDensity: { value: 0.00025 },
  8761. fogNear: { value: 1 },
  8762. fogFar: { value: 2000 },
  8763. fogColor: { value: new Color( 0xffffff ) }
  8764. },
  8765. lights: {
  8766. ambientLightColor: { value: [] },
  8767. lightProbe: { value: [] },
  8768. directionalLights: { value: [], properties: {
  8769. direction: {},
  8770. color: {}
  8771. } },
  8772. directionalLightShadows: { value: [], properties: {
  8773. shadowBias: {},
  8774. shadowNormalBias: {},
  8775. shadowRadius: {},
  8776. shadowMapSize: {}
  8777. } },
  8778. directionalShadowMap: { value: [] },
  8779. directionalShadowMatrix: { value: [] },
  8780. spotLights: { value: [], properties: {
  8781. color: {},
  8782. position: {},
  8783. direction: {},
  8784. distance: {},
  8785. coneCos: {},
  8786. penumbraCos: {},
  8787. decay: {}
  8788. } },
  8789. spotLightShadows: { value: [], properties: {
  8790. shadowBias: {},
  8791. shadowNormalBias: {},
  8792. shadowRadius: {},
  8793. shadowMapSize: {}
  8794. } },
  8795. spotShadowMap: { value: [] },
  8796. spotShadowMatrix: { value: [] },
  8797. pointLights: { value: [], properties: {
  8798. color: {},
  8799. position: {},
  8800. decay: {},
  8801. distance: {}
  8802. } },
  8803. pointLightShadows: { value: [], properties: {
  8804. shadowBias: {},
  8805. shadowNormalBias: {},
  8806. shadowRadius: {},
  8807. shadowMapSize: {},
  8808. shadowCameraNear: {},
  8809. shadowCameraFar: {}
  8810. } },
  8811. pointShadowMap: { value: [] },
  8812. pointShadowMatrix: { value: [] },
  8813. hemisphereLights: { value: [], properties: {
  8814. direction: {},
  8815. skyColor: {},
  8816. groundColor: {}
  8817. } },
  8818. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8819. rectAreaLights: { value: [], properties: {
  8820. color: {},
  8821. position: {},
  8822. width: {},
  8823. height: {}
  8824. } },
  8825. ltc_1: { value: null },
  8826. ltc_2: { value: null }
  8827. },
  8828. points: {
  8829. diffuse: { value: new Color( 0xeeeeee ) },
  8830. opacity: { value: 1.0 },
  8831. size: { value: 1.0 },
  8832. scale: { value: 1.0 },
  8833. map: { value: null },
  8834. alphaMap: { value: null },
  8835. uvTransform: { value: new Matrix3() }
  8836. },
  8837. sprite: {
  8838. diffuse: { value: new Color( 0xeeeeee ) },
  8839. opacity: { value: 1.0 },
  8840. center: { value: new Vector2$1( 0.5, 0.5 ) },
  8841. rotation: { value: 0.0 },
  8842. map: { value: null },
  8843. alphaMap: { value: null },
  8844. uvTransform: { value: new Matrix3() }
  8845. }
  8846. };
  8847. const ShaderLib = {
  8848. basic: {
  8849. uniforms: mergeUniforms( [
  8850. UniformsLib.common,
  8851. UniformsLib.specularmap,
  8852. UniformsLib.envmap,
  8853. UniformsLib.aomap,
  8854. UniformsLib.lightmap,
  8855. UniformsLib.fog
  8856. ] ),
  8857. vertexShader: ShaderChunk.meshbasic_vert,
  8858. fragmentShader: ShaderChunk.meshbasic_frag
  8859. },
  8860. lambert: {
  8861. uniforms: mergeUniforms( [
  8862. UniformsLib.common,
  8863. UniformsLib.specularmap,
  8864. UniformsLib.envmap,
  8865. UniformsLib.aomap,
  8866. UniformsLib.lightmap,
  8867. UniformsLib.emissivemap,
  8868. UniformsLib.fog,
  8869. UniformsLib.lights,
  8870. {
  8871. emissive: { value: new Color( 0x000000 ) }
  8872. }
  8873. ] ),
  8874. vertexShader: ShaderChunk.meshlambert_vert,
  8875. fragmentShader: ShaderChunk.meshlambert_frag
  8876. },
  8877. phong: {
  8878. uniforms: mergeUniforms( [
  8879. UniformsLib.common,
  8880. UniformsLib.specularmap,
  8881. UniformsLib.envmap,
  8882. UniformsLib.aomap,
  8883. UniformsLib.lightmap,
  8884. UniformsLib.emissivemap,
  8885. UniformsLib.bumpmap,
  8886. UniformsLib.normalmap,
  8887. UniformsLib.displacementmap,
  8888. UniformsLib.fog,
  8889. UniformsLib.lights,
  8890. {
  8891. emissive: { value: new Color( 0x000000 ) },
  8892. specular: { value: new Color( 0x111111 ) },
  8893. shininess: { value: 30 }
  8894. }
  8895. ] ),
  8896. vertexShader: ShaderChunk.meshphong_vert,
  8897. fragmentShader: ShaderChunk.meshphong_frag
  8898. },
  8899. standard: {
  8900. uniforms: mergeUniforms( [
  8901. UniformsLib.common,
  8902. UniformsLib.envmap,
  8903. UniformsLib.aomap,
  8904. UniformsLib.lightmap,
  8905. UniformsLib.emissivemap,
  8906. UniformsLib.bumpmap,
  8907. UniformsLib.normalmap,
  8908. UniformsLib.displacementmap,
  8909. UniformsLib.roughnessmap,
  8910. UniformsLib.metalnessmap,
  8911. UniformsLib.fog,
  8912. UniformsLib.lights,
  8913. {
  8914. emissive: { value: new Color( 0x000000 ) },
  8915. roughness: { value: 1.0 },
  8916. metalness: { value: 0.0 },
  8917. envMapIntensity: { value: 1 } // temporary
  8918. }
  8919. ] ),
  8920. vertexShader: ShaderChunk.meshphysical_vert,
  8921. fragmentShader: ShaderChunk.meshphysical_frag
  8922. },
  8923. toon: {
  8924. uniforms: mergeUniforms( [
  8925. UniformsLib.common,
  8926. UniformsLib.aomap,
  8927. UniformsLib.lightmap,
  8928. UniformsLib.emissivemap,
  8929. UniformsLib.bumpmap,
  8930. UniformsLib.normalmap,
  8931. UniformsLib.displacementmap,
  8932. UniformsLib.gradientmap,
  8933. UniformsLib.fog,
  8934. UniformsLib.lights,
  8935. {
  8936. emissive: { value: new Color( 0x000000 ) }
  8937. }
  8938. ] ),
  8939. vertexShader: ShaderChunk.meshtoon_vert,
  8940. fragmentShader: ShaderChunk.meshtoon_frag
  8941. },
  8942. matcap: {
  8943. uniforms: mergeUniforms( [
  8944. UniformsLib.common,
  8945. UniformsLib.bumpmap,
  8946. UniformsLib.normalmap,
  8947. UniformsLib.displacementmap,
  8948. UniformsLib.fog,
  8949. {
  8950. matcap: { value: null }
  8951. }
  8952. ] ),
  8953. vertexShader: ShaderChunk.meshmatcap_vert,
  8954. fragmentShader: ShaderChunk.meshmatcap_frag
  8955. },
  8956. points: {
  8957. uniforms: mergeUniforms( [
  8958. UniformsLib.points,
  8959. UniformsLib.fog
  8960. ] ),
  8961. vertexShader: ShaderChunk.points_vert,
  8962. fragmentShader: ShaderChunk.points_frag
  8963. },
  8964. dashed: {
  8965. uniforms: mergeUniforms( [
  8966. UniformsLib.common,
  8967. UniformsLib.fog,
  8968. {
  8969. scale: { value: 1 },
  8970. dashSize: { value: 1 },
  8971. totalSize: { value: 2 }
  8972. }
  8973. ] ),
  8974. vertexShader: ShaderChunk.linedashed_vert,
  8975. fragmentShader: ShaderChunk.linedashed_frag
  8976. },
  8977. depth: {
  8978. uniforms: mergeUniforms( [
  8979. UniformsLib.common,
  8980. UniformsLib.displacementmap
  8981. ] ),
  8982. vertexShader: ShaderChunk.depth_vert,
  8983. fragmentShader: ShaderChunk.depth_frag
  8984. },
  8985. normal: {
  8986. uniforms: mergeUniforms( [
  8987. UniformsLib.common,
  8988. UniformsLib.bumpmap,
  8989. UniformsLib.normalmap,
  8990. UniformsLib.displacementmap,
  8991. {
  8992. opacity: { value: 1.0 }
  8993. }
  8994. ] ),
  8995. vertexShader: ShaderChunk.normal_vert,
  8996. fragmentShader: ShaderChunk.normal_frag
  8997. },
  8998. sprite: {
  8999. uniforms: mergeUniforms( [
  9000. UniformsLib.sprite,
  9001. UniformsLib.fog
  9002. ] ),
  9003. vertexShader: ShaderChunk.sprite_vert,
  9004. fragmentShader: ShaderChunk.sprite_frag
  9005. },
  9006. background: {
  9007. uniforms: {
  9008. uvTransform: { value: new Matrix3() },
  9009. t2D: { value: null },
  9010. },
  9011. vertexShader: ShaderChunk.background_vert,
  9012. fragmentShader: ShaderChunk.background_frag
  9013. },
  9014. /* -------------------------------------------------------------------------
  9015. // Cube map shader
  9016. ------------------------------------------------------------------------- */
  9017. cube: {
  9018. uniforms: mergeUniforms( [
  9019. UniformsLib.envmap,
  9020. {
  9021. opacity: { value: 1.0 }
  9022. }
  9023. ] ),
  9024. vertexShader: ShaderChunk.cube_vert,
  9025. fragmentShader: ShaderChunk.cube_frag
  9026. },
  9027. equirect: {
  9028. uniforms: {
  9029. tEquirect: { value: null },
  9030. },
  9031. vertexShader: ShaderChunk.equirect_vert,
  9032. fragmentShader: ShaderChunk.equirect_frag
  9033. },
  9034. distanceRGBA: {
  9035. uniforms: mergeUniforms( [
  9036. UniformsLib.common,
  9037. UniformsLib.displacementmap,
  9038. {
  9039. referencePosition: { value: new Vector3() },
  9040. nearDistance: { value: 1 },
  9041. farDistance: { value: 1000 }
  9042. }
  9043. ] ),
  9044. vertexShader: ShaderChunk.distanceRGBA_vert,
  9045. fragmentShader: ShaderChunk.distanceRGBA_frag
  9046. },
  9047. shadow: {
  9048. uniforms: mergeUniforms( [
  9049. UniformsLib.lights,
  9050. UniformsLib.fog,
  9051. {
  9052. color: { value: new Color( 0x00000 ) },
  9053. opacity: { value: 1.0 }
  9054. },
  9055. ] ),
  9056. vertexShader: ShaderChunk.shadow_vert,
  9057. fragmentShader: ShaderChunk.shadow_frag
  9058. }
  9059. };
  9060. ShaderLib.physical = {
  9061. uniforms: mergeUniforms( [
  9062. ShaderLib.standard.uniforms,
  9063. {
  9064. clearcoat: { value: 0 },
  9065. clearcoatMap: { value: null },
  9066. clearcoatRoughness: { value: 0 },
  9067. clearcoatRoughnessMap: { value: null },
  9068. clearcoatNormalScale: { value: new Vector2$1( 1, 1 ) },
  9069. clearcoatNormalMap: { value: null },
  9070. sheen: { value: new Color( 0x000000 ) },
  9071. transmission: { value: 0 },
  9072. transmissionMap: { value: null },
  9073. }
  9074. ] ),
  9075. vertexShader: ShaderChunk.meshphysical_vert,
  9076. fragmentShader: ShaderChunk.meshphysical_frag
  9077. };
  9078. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  9079. const clearColor = new Color( 0x000000 );
  9080. let clearAlpha = 0;
  9081. let planeMesh;
  9082. let boxMesh;
  9083. let currentBackground = null;
  9084. let currentBackgroundVersion = 0;
  9085. let currentTonemapping = null;
  9086. function render( renderList, scene, camera, forceClear ) {
  9087. let background = scene.isScene === true ? scene.background : null;
  9088. if ( background && background.isTexture ) {
  9089. background = cubemaps.get( background );
  9090. }
  9091. // Ignore background in AR
  9092. // TODO: Reconsider this.
  9093. const xr = renderer.xr;
  9094. const session = xr.getSession && xr.getSession();
  9095. if ( session && session.environmentBlendMode === 'additive' ) {
  9096. background = null;
  9097. }
  9098. if ( background === null ) {
  9099. setClear( clearColor, clearAlpha );
  9100. } else if ( background && background.isColor ) {
  9101. setClear( background, 1 );
  9102. forceClear = true;
  9103. }
  9104. if ( renderer.autoClear || forceClear ) {
  9105. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9106. }
  9107. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
  9108. if ( boxMesh === undefined ) {
  9109. boxMesh = new Mesh(
  9110. new BoxBufferGeometry( 1, 1, 1 ),
  9111. new ShaderMaterial( {
  9112. name: 'BackgroundCubeMaterial',
  9113. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  9114. vertexShader: ShaderLib.cube.vertexShader,
  9115. fragmentShader: ShaderLib.cube.fragmentShader,
  9116. side: BackSide,
  9117. depthTest: false,
  9118. depthWrite: false,
  9119. fog: false
  9120. } )
  9121. );
  9122. boxMesh.geometry.deleteAttribute( 'normal' );
  9123. boxMesh.geometry.deleteAttribute( 'uv' );
  9124. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9125. this.matrixWorld.copyPosition( camera.matrixWorld );
  9126. };
  9127. // enable code injection for non-built-in material
  9128. Object.defineProperty( boxMesh.material, 'envMap', {
  9129. get: function () {
  9130. return this.uniforms.envMap.value;
  9131. }
  9132. } );
  9133. objects.update( boxMesh );
  9134. }
  9135. if ( background.isWebGLCubeRenderTarget ) {
  9136. // TODO Deprecate
  9137. background = background.texture;
  9138. }
  9139. boxMesh.material.uniforms.envMap.value = background;
  9140. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  9141. if ( currentBackground !== background ||
  9142. currentBackgroundVersion !== background.version ||
  9143. currentTonemapping !== renderer.toneMapping ) {
  9144. boxMesh.material.needsUpdate = true;
  9145. currentBackground = background;
  9146. currentBackgroundVersion = background.version;
  9147. currentTonemapping = renderer.toneMapping;
  9148. }
  9149. // push to the pre-sorted opaque render list
  9150. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9151. } else if ( background && background.isTexture ) {
  9152. if ( planeMesh === undefined ) {
  9153. planeMesh = new Mesh(
  9154. new PlaneBufferGeometry( 2, 2 ),
  9155. new ShaderMaterial( {
  9156. name: 'BackgroundMaterial',
  9157. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9158. vertexShader: ShaderLib.background.vertexShader,
  9159. fragmentShader: ShaderLib.background.fragmentShader,
  9160. side: FrontSide,
  9161. depthTest: false,
  9162. depthWrite: false,
  9163. fog: false
  9164. } )
  9165. );
  9166. planeMesh.geometry.deleteAttribute( 'normal' );
  9167. // enable code injection for non-built-in material
  9168. Object.defineProperty( planeMesh.material, 'map', {
  9169. get: function () {
  9170. return this.uniforms.t2D.value;
  9171. }
  9172. } );
  9173. objects.update( planeMesh );
  9174. }
  9175. planeMesh.material.uniforms.t2D.value = background;
  9176. if ( background.matrixAutoUpdate === true ) {
  9177. background.updateMatrix();
  9178. }
  9179. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9180. if ( currentBackground !== background ||
  9181. currentBackgroundVersion !== background.version ||
  9182. currentTonemapping !== renderer.toneMapping ) {
  9183. planeMesh.material.needsUpdate = true;
  9184. currentBackground = background;
  9185. currentBackgroundVersion = background.version;
  9186. currentTonemapping = renderer.toneMapping;
  9187. }
  9188. // push to the pre-sorted opaque render list
  9189. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9190. }
  9191. }
  9192. function setClear( color, alpha ) {
  9193. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9194. }
  9195. return {
  9196. getClearColor: function () {
  9197. return clearColor;
  9198. },
  9199. setClearColor: function ( color, alpha = 1 ) {
  9200. clearColor.set( color );
  9201. clearAlpha = alpha;
  9202. setClear( clearColor, clearAlpha );
  9203. },
  9204. getClearAlpha: function () {
  9205. return clearAlpha;
  9206. },
  9207. setClearAlpha: function ( alpha ) {
  9208. clearAlpha = alpha;
  9209. setClear( clearColor, clearAlpha );
  9210. },
  9211. render: render
  9212. };
  9213. }
  9214. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9215. const maxVertexAttributes = gl.getParameter( 34921 );
  9216. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9217. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9218. const bindingStates = {};
  9219. const defaultState = createBindingState( null );
  9220. let currentState = defaultState;
  9221. function setup( object, material, program, geometry, index ) {
  9222. let updateBuffers = false;
  9223. if ( vaoAvailable ) {
  9224. const state = getBindingState( geometry, program, material );
  9225. if ( currentState !== state ) {
  9226. currentState = state;
  9227. bindVertexArrayObject( currentState.object );
  9228. }
  9229. updateBuffers = needsUpdate( geometry, index );
  9230. if ( updateBuffers ) saveCache( geometry, index );
  9231. } else {
  9232. const wireframe = ( material.wireframe === true );
  9233. if ( currentState.geometry !== geometry.id ||
  9234. currentState.program !== program.id ||
  9235. currentState.wireframe !== wireframe ) {
  9236. currentState.geometry = geometry.id;
  9237. currentState.program = program.id;
  9238. currentState.wireframe = wireframe;
  9239. updateBuffers = true;
  9240. }
  9241. }
  9242. if ( object.isInstancedMesh === true ) {
  9243. updateBuffers = true;
  9244. }
  9245. if ( index !== null ) {
  9246. attributes.update( index, 34963 );
  9247. }
  9248. if ( updateBuffers ) {
  9249. setupVertexAttributes( object, material, program, geometry );
  9250. if ( index !== null ) {
  9251. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  9252. }
  9253. }
  9254. }
  9255. function createVertexArrayObject() {
  9256. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9257. return extension.createVertexArrayOES();
  9258. }
  9259. function bindVertexArrayObject( vao ) {
  9260. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9261. return extension.bindVertexArrayOES( vao );
  9262. }
  9263. function deleteVertexArrayObject( vao ) {
  9264. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9265. return extension.deleteVertexArrayOES( vao );
  9266. }
  9267. function getBindingState( geometry, program, material ) {
  9268. const wireframe = ( material.wireframe === true );
  9269. let programMap = bindingStates[ geometry.id ];
  9270. if ( programMap === undefined ) {
  9271. programMap = {};
  9272. bindingStates[ geometry.id ] = programMap;
  9273. }
  9274. let stateMap = programMap[ program.id ];
  9275. if ( stateMap === undefined ) {
  9276. stateMap = {};
  9277. programMap[ program.id ] = stateMap;
  9278. }
  9279. let state = stateMap[ wireframe ];
  9280. if ( state === undefined ) {
  9281. state = createBindingState( createVertexArrayObject() );
  9282. stateMap[ wireframe ] = state;
  9283. }
  9284. return state;
  9285. }
  9286. function createBindingState( vao ) {
  9287. const newAttributes = [];
  9288. const enabledAttributes = [];
  9289. const attributeDivisors = [];
  9290. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9291. newAttributes[ i ] = 0;
  9292. enabledAttributes[ i ] = 0;
  9293. attributeDivisors[ i ] = 0;
  9294. }
  9295. return {
  9296. // for backward compatibility on non-VAO support browser
  9297. geometry: null,
  9298. program: null,
  9299. wireframe: false,
  9300. newAttributes: newAttributes,
  9301. enabledAttributes: enabledAttributes,
  9302. attributeDivisors: attributeDivisors,
  9303. object: vao,
  9304. attributes: {},
  9305. index: null
  9306. };
  9307. }
  9308. function needsUpdate( geometry, index ) {
  9309. const cachedAttributes = currentState.attributes;
  9310. const geometryAttributes = geometry.attributes;
  9311. let attributesNum = 0;
  9312. for ( const key in geometryAttributes ) {
  9313. const cachedAttribute = cachedAttributes[ key ];
  9314. const geometryAttribute = geometryAttributes[ key ];
  9315. if ( cachedAttribute === undefined ) return true;
  9316. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9317. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  9318. attributesNum ++;
  9319. }
  9320. if ( currentState.attributesNum !== attributesNum ) return true;
  9321. if ( currentState.index !== index ) return true;
  9322. return false;
  9323. }
  9324. function saveCache( geometry, index ) {
  9325. const cache = {};
  9326. const attributes = geometry.attributes;
  9327. let attributesNum = 0;
  9328. for ( const key in attributes ) {
  9329. const attribute = attributes[ key ];
  9330. const data = {};
  9331. data.attribute = attribute;
  9332. if ( attribute.data ) {
  9333. data.data = attribute.data;
  9334. }
  9335. cache[ key ] = data;
  9336. attributesNum ++;
  9337. }
  9338. currentState.attributes = cache;
  9339. currentState.attributesNum = attributesNum;
  9340. currentState.index = index;
  9341. }
  9342. function initAttributes() {
  9343. const newAttributes = currentState.newAttributes;
  9344. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9345. newAttributes[ i ] = 0;
  9346. }
  9347. }
  9348. function enableAttribute( attribute ) {
  9349. enableAttributeAndDivisor( attribute, 0 );
  9350. }
  9351. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9352. const newAttributes = currentState.newAttributes;
  9353. const enabledAttributes = currentState.enabledAttributes;
  9354. const attributeDivisors = currentState.attributeDivisors;
  9355. newAttributes[ attribute ] = 1;
  9356. if ( enabledAttributes[ attribute ] === 0 ) {
  9357. gl.enableVertexAttribArray( attribute );
  9358. enabledAttributes[ attribute ] = 1;
  9359. }
  9360. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9361. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9362. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9363. attributeDivisors[ attribute ] = meshPerAttribute;
  9364. }
  9365. }
  9366. function disableUnusedAttributes() {
  9367. const newAttributes = currentState.newAttributes;
  9368. const enabledAttributes = currentState.enabledAttributes;
  9369. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9370. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9371. gl.disableVertexAttribArray( i );
  9372. enabledAttributes[ i ] = 0;
  9373. }
  9374. }
  9375. }
  9376. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9377. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  9378. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9379. } else {
  9380. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9381. }
  9382. }
  9383. function setupVertexAttributes( object, material, program, geometry ) {
  9384. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9385. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9386. }
  9387. initAttributes();
  9388. const geometryAttributes = geometry.attributes;
  9389. const programAttributes = program.getAttributes();
  9390. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9391. for ( const name in programAttributes ) {
  9392. const programAttribute = programAttributes[ name ];
  9393. if ( programAttribute >= 0 ) {
  9394. const geometryAttribute = geometryAttributes[ name ];
  9395. if ( geometryAttribute !== undefined ) {
  9396. const normalized = geometryAttribute.normalized;
  9397. const size = geometryAttribute.itemSize;
  9398. const attribute = attributes.get( geometryAttribute );
  9399. // TODO Attribute may not be available on context restore
  9400. if ( attribute === undefined ) continue;
  9401. const buffer = attribute.buffer;
  9402. const type = attribute.type;
  9403. const bytesPerElement = attribute.bytesPerElement;
  9404. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9405. const data = geometryAttribute.data;
  9406. const stride = data.stride;
  9407. const offset = geometryAttribute.offset;
  9408. if ( data && data.isInstancedInterleavedBuffer ) {
  9409. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  9410. if ( geometry._maxInstanceCount === undefined ) {
  9411. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9412. }
  9413. } else {
  9414. enableAttribute( programAttribute );
  9415. }
  9416. gl.bindBuffer( 34962, buffer );
  9417. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  9418. } else {
  9419. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9420. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  9421. if ( geometry._maxInstanceCount === undefined ) {
  9422. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9423. }
  9424. } else {
  9425. enableAttribute( programAttribute );
  9426. }
  9427. gl.bindBuffer( 34962, buffer );
  9428. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  9429. }
  9430. } else if ( name === 'instanceMatrix' ) {
  9431. const attribute = attributes.get( object.instanceMatrix );
  9432. // TODO Attribute may not be available on context restore
  9433. if ( attribute === undefined ) continue;
  9434. const buffer = attribute.buffer;
  9435. const type = attribute.type;
  9436. enableAttributeAndDivisor( programAttribute + 0, 1 );
  9437. enableAttributeAndDivisor( programAttribute + 1, 1 );
  9438. enableAttributeAndDivisor( programAttribute + 2, 1 );
  9439. enableAttributeAndDivisor( programAttribute + 3, 1 );
  9440. gl.bindBuffer( 34962, buffer );
  9441. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  9442. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  9443. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  9444. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  9445. } else if ( name === 'instanceColor' ) {
  9446. const attribute = attributes.get( object.instanceColor );
  9447. // TODO Attribute may not be available on context restore
  9448. if ( attribute === undefined ) continue;
  9449. const buffer = attribute.buffer;
  9450. const type = attribute.type;
  9451. enableAttributeAndDivisor( programAttribute, 1 );
  9452. gl.bindBuffer( 34962, buffer );
  9453. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  9454. } else if ( materialDefaultAttributeValues !== undefined ) {
  9455. const value = materialDefaultAttributeValues[ name ];
  9456. if ( value !== undefined ) {
  9457. switch ( value.length ) {
  9458. case 2:
  9459. gl.vertexAttrib2fv( programAttribute, value );
  9460. break;
  9461. case 3:
  9462. gl.vertexAttrib3fv( programAttribute, value );
  9463. break;
  9464. case 4:
  9465. gl.vertexAttrib4fv( programAttribute, value );
  9466. break;
  9467. default:
  9468. gl.vertexAttrib1fv( programAttribute, value );
  9469. }
  9470. }
  9471. }
  9472. }
  9473. }
  9474. disableUnusedAttributes();
  9475. }
  9476. function dispose() {
  9477. reset();
  9478. for ( const geometryId in bindingStates ) {
  9479. const programMap = bindingStates[ geometryId ];
  9480. for ( const programId in programMap ) {
  9481. const stateMap = programMap[ programId ];
  9482. for ( const wireframe in stateMap ) {
  9483. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9484. delete stateMap[ wireframe ];
  9485. }
  9486. delete programMap[ programId ];
  9487. }
  9488. delete bindingStates[ geometryId ];
  9489. }
  9490. }
  9491. function releaseStatesOfGeometry( geometry ) {
  9492. if ( bindingStates[ geometry.id ] === undefined ) return;
  9493. const programMap = bindingStates[ geometry.id ];
  9494. for ( const programId in programMap ) {
  9495. const stateMap = programMap[ programId ];
  9496. for ( const wireframe in stateMap ) {
  9497. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9498. delete stateMap[ wireframe ];
  9499. }
  9500. delete programMap[ programId ];
  9501. }
  9502. delete bindingStates[ geometry.id ];
  9503. }
  9504. function releaseStatesOfProgram( program ) {
  9505. for ( const geometryId in bindingStates ) {
  9506. const programMap = bindingStates[ geometryId ];
  9507. if ( programMap[ program.id ] === undefined ) continue;
  9508. const stateMap = programMap[ program.id ];
  9509. for ( const wireframe in stateMap ) {
  9510. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9511. delete stateMap[ wireframe ];
  9512. }
  9513. delete programMap[ program.id ];
  9514. }
  9515. }
  9516. function reset() {
  9517. resetDefaultState();
  9518. if ( currentState === defaultState ) return;
  9519. currentState = defaultState;
  9520. bindVertexArrayObject( currentState.object );
  9521. }
  9522. // for backward-compatilibity
  9523. function resetDefaultState() {
  9524. defaultState.geometry = null;
  9525. defaultState.program = null;
  9526. defaultState.wireframe = false;
  9527. }
  9528. return {
  9529. setup: setup,
  9530. reset: reset,
  9531. resetDefaultState: resetDefaultState,
  9532. dispose: dispose,
  9533. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9534. releaseStatesOfProgram: releaseStatesOfProgram,
  9535. initAttributes: initAttributes,
  9536. enableAttribute: enableAttribute,
  9537. disableUnusedAttributes: disableUnusedAttributes
  9538. };
  9539. }
  9540. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9541. const isWebGL2 = capabilities.isWebGL2;
  9542. let mode;
  9543. function setMode( value ) {
  9544. mode = value;
  9545. }
  9546. function render( start, count ) {
  9547. gl.drawArrays( mode, start, count );
  9548. info.update( count, mode, 1 );
  9549. }
  9550. function renderInstances( start, count, primcount ) {
  9551. if ( primcount === 0 ) return;
  9552. let extension, methodName;
  9553. if ( isWebGL2 ) {
  9554. extension = gl;
  9555. methodName = 'drawArraysInstanced';
  9556. } else {
  9557. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9558. methodName = 'drawArraysInstancedANGLE';
  9559. if ( extension === null ) {
  9560. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9561. return;
  9562. }
  9563. }
  9564. extension[ methodName ]( mode, start, count, primcount );
  9565. info.update( count, mode, primcount );
  9566. }
  9567. //
  9568. this.setMode = setMode;
  9569. this.render = render;
  9570. this.renderInstances = renderInstances;
  9571. }
  9572. function WebGLCapabilities( gl, extensions, parameters ) {
  9573. let maxAnisotropy;
  9574. function getMaxAnisotropy() {
  9575. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9576. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9577. if ( extension !== null ) {
  9578. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9579. } else {
  9580. maxAnisotropy = 0;
  9581. }
  9582. return maxAnisotropy;
  9583. }
  9584. function getMaxPrecision( precision ) {
  9585. if ( precision === 'highp' ) {
  9586. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9587. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9588. return 'highp';
  9589. }
  9590. precision = 'mediump';
  9591. }
  9592. if ( precision === 'mediump' ) {
  9593. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9594. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9595. return 'mediump';
  9596. }
  9597. }
  9598. return 'lowp';
  9599. }
  9600. /* eslint-disable no-undef */
  9601. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  9602. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  9603. /* eslint-enable no-undef */
  9604. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9605. const maxPrecision = getMaxPrecision( precision );
  9606. if ( maxPrecision !== precision ) {
  9607. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9608. precision = maxPrecision;
  9609. }
  9610. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9611. const maxTextures = gl.getParameter( 34930 );
  9612. const maxVertexTextures = gl.getParameter( 35660 );
  9613. const maxTextureSize = gl.getParameter( 3379 );
  9614. const maxCubemapSize = gl.getParameter( 34076 );
  9615. const maxAttributes = gl.getParameter( 34921 );
  9616. const maxVertexUniforms = gl.getParameter( 36347 );
  9617. const maxVaryings = gl.getParameter( 36348 );
  9618. const maxFragmentUniforms = gl.getParameter( 36349 );
  9619. const vertexTextures = maxVertexTextures > 0;
  9620. const floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  9621. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9622. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9623. return {
  9624. isWebGL2: isWebGL2,
  9625. getMaxAnisotropy: getMaxAnisotropy,
  9626. getMaxPrecision: getMaxPrecision,
  9627. precision: precision,
  9628. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9629. maxTextures: maxTextures,
  9630. maxVertexTextures: maxVertexTextures,
  9631. maxTextureSize: maxTextureSize,
  9632. maxCubemapSize: maxCubemapSize,
  9633. maxAttributes: maxAttributes,
  9634. maxVertexUniforms: maxVertexUniforms,
  9635. maxVaryings: maxVaryings,
  9636. maxFragmentUniforms: maxFragmentUniforms,
  9637. vertexTextures: vertexTextures,
  9638. floatFragmentTextures: floatFragmentTextures,
  9639. floatVertexTextures: floatVertexTextures,
  9640. maxSamples: maxSamples
  9641. };
  9642. }
  9643. function WebGLClipping( properties ) {
  9644. const scope = this;
  9645. let globalState = null,
  9646. numGlobalPlanes = 0,
  9647. localClippingEnabled = false,
  9648. renderingShadows = false;
  9649. const plane = new Plane(),
  9650. viewNormalMatrix = new Matrix3(),
  9651. uniform = { value: null, needsUpdate: false };
  9652. this.uniform = uniform;
  9653. this.numPlanes = 0;
  9654. this.numIntersection = 0;
  9655. this.init = function ( planes, enableLocalClipping, camera ) {
  9656. const enabled =
  9657. planes.length !== 0 ||
  9658. enableLocalClipping ||
  9659. // enable state of previous frame - the clipping code has to
  9660. // run another frame in order to reset the state:
  9661. numGlobalPlanes !== 0 ||
  9662. localClippingEnabled;
  9663. localClippingEnabled = enableLocalClipping;
  9664. globalState = projectPlanes( planes, camera, 0 );
  9665. numGlobalPlanes = planes.length;
  9666. return enabled;
  9667. };
  9668. this.beginShadows = function () {
  9669. renderingShadows = true;
  9670. projectPlanes( null );
  9671. };
  9672. this.endShadows = function () {
  9673. renderingShadows = false;
  9674. resetGlobalState();
  9675. };
  9676. this.setState = function ( material, camera, useCache ) {
  9677. const planes = material.clippingPlanes,
  9678. clipIntersection = material.clipIntersection,
  9679. clipShadows = material.clipShadows;
  9680. const materialProperties = properties.get( material );
  9681. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9682. // there's no local clipping
  9683. if ( renderingShadows ) {
  9684. // there's no global clipping
  9685. projectPlanes( null );
  9686. } else {
  9687. resetGlobalState();
  9688. }
  9689. } else {
  9690. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9691. lGlobal = nGlobal * 4;
  9692. let dstArray = materialProperties.clippingState || null;
  9693. uniform.value = dstArray; // ensure unique state
  9694. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9695. for ( let i = 0; i !== lGlobal; ++ i ) {
  9696. dstArray[ i ] = globalState[ i ];
  9697. }
  9698. materialProperties.clippingState = dstArray;
  9699. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9700. this.numPlanes += nGlobal;
  9701. }
  9702. };
  9703. function resetGlobalState() {
  9704. if ( uniform.value !== globalState ) {
  9705. uniform.value = globalState;
  9706. uniform.needsUpdate = numGlobalPlanes > 0;
  9707. }
  9708. scope.numPlanes = numGlobalPlanes;
  9709. scope.numIntersection = 0;
  9710. }
  9711. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9712. const nPlanes = planes !== null ? planes.length : 0;
  9713. let dstArray = null;
  9714. if ( nPlanes !== 0 ) {
  9715. dstArray = uniform.value;
  9716. if ( skipTransform !== true || dstArray === null ) {
  9717. const flatSize = dstOffset + nPlanes * 4,
  9718. viewMatrix = camera.matrixWorldInverse;
  9719. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9720. if ( dstArray === null || dstArray.length < flatSize ) {
  9721. dstArray = new Float32Array( flatSize );
  9722. }
  9723. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9724. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9725. plane.normal.toArray( dstArray, i4 );
  9726. dstArray[ i4 + 3 ] = plane.constant;
  9727. }
  9728. }
  9729. uniform.value = dstArray;
  9730. uniform.needsUpdate = true;
  9731. }
  9732. scope.numPlanes = nPlanes;
  9733. scope.numIntersection = 0;
  9734. return dstArray;
  9735. }
  9736. }
  9737. function WebGLCubeMaps( renderer ) {
  9738. let cubemaps = new WeakMap();
  9739. function mapTextureMapping( texture, mapping ) {
  9740. if ( mapping === EquirectangularReflectionMapping ) {
  9741. texture.mapping = CubeReflectionMapping;
  9742. } else if ( mapping === EquirectangularRefractionMapping ) {
  9743. texture.mapping = CubeRefractionMapping;
  9744. }
  9745. return texture;
  9746. }
  9747. function get( texture ) {
  9748. if ( texture && texture.isTexture ) {
  9749. const mapping = texture.mapping;
  9750. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9751. if ( cubemaps.has( texture ) ) {
  9752. const cubemap = cubemaps.get( texture ).texture;
  9753. return mapTextureMapping( cubemap, texture.mapping );
  9754. } else {
  9755. const image = texture.image;
  9756. if ( image && image.height > 0 ) {
  9757. const currentRenderList = renderer.getRenderList();
  9758. const currentRenderTarget = renderer.getRenderTarget();
  9759. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9760. renderTarget.fromEquirectangularTexture( renderer, texture );
  9761. cubemaps.set( texture, renderTarget );
  9762. renderer.setRenderTarget( currentRenderTarget );
  9763. renderer.setRenderList( currentRenderList );
  9764. texture.addEventListener( 'dispose', onTextureDispose );
  9765. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9766. } else {
  9767. // image not yet ready. try the conversion next frame
  9768. return null;
  9769. }
  9770. }
  9771. }
  9772. }
  9773. return texture;
  9774. }
  9775. function onTextureDispose( event ) {
  9776. const texture = event.target;
  9777. texture.removeEventListener( 'dispose', onTextureDispose );
  9778. const cubemap = cubemaps.get( texture );
  9779. if ( cubemap !== undefined ) {
  9780. cubemaps.delete( texture );
  9781. cubemap.dispose();
  9782. }
  9783. }
  9784. function dispose() {
  9785. cubemaps = new WeakMap();
  9786. }
  9787. return {
  9788. get: get,
  9789. dispose: dispose
  9790. };
  9791. }
  9792. function WebGLExtensions( gl ) {
  9793. const extensions = {};
  9794. return {
  9795. has: function ( name ) {
  9796. if ( extensions[ name ] !== undefined ) {
  9797. return extensions[ name ] !== null;
  9798. }
  9799. let extension;
  9800. switch ( name ) {
  9801. case 'WEBGL_depth_texture':
  9802. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9803. break;
  9804. case 'EXT_texture_filter_anisotropic':
  9805. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9806. break;
  9807. case 'WEBGL_compressed_texture_s3tc':
  9808. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9809. break;
  9810. case 'WEBGL_compressed_texture_pvrtc':
  9811. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9812. break;
  9813. default:
  9814. extension = gl.getExtension( name );
  9815. }
  9816. extensions[ name ] = extension;
  9817. return extension !== null;
  9818. },
  9819. get: function ( name ) {
  9820. if ( ! this.has( name ) ) {
  9821. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9822. }
  9823. return extensions[ name ];
  9824. }
  9825. };
  9826. }
  9827. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9828. const geometries = new WeakMap();
  9829. const wireframeAttributes = new WeakMap();
  9830. function onGeometryDispose( event ) {
  9831. const geometry = event.target;
  9832. const buffergeometry = geometries.get( geometry );
  9833. if ( buffergeometry.index !== null ) {
  9834. attributes.remove( buffergeometry.index );
  9835. }
  9836. for ( const name in buffergeometry.attributes ) {
  9837. attributes.remove( buffergeometry.attributes[ name ] );
  9838. }
  9839. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9840. geometries.delete( geometry );
  9841. const attribute = wireframeAttributes.get( buffergeometry );
  9842. if ( attribute ) {
  9843. attributes.remove( attribute );
  9844. wireframeAttributes.delete( buffergeometry );
  9845. }
  9846. bindingStates.releaseStatesOfGeometry( buffergeometry );
  9847. if ( geometry.isInstancedBufferGeometry === true ) {
  9848. delete geometry._maxInstanceCount;
  9849. }
  9850. //
  9851. info.memory.geometries --;
  9852. }
  9853. function get( object, geometry ) {
  9854. let buffergeometry = geometries.get( geometry );
  9855. if ( buffergeometry ) return buffergeometry;
  9856. geometry.addEventListener( 'dispose', onGeometryDispose );
  9857. if ( geometry.isBufferGeometry ) {
  9858. buffergeometry = geometry;
  9859. } else if ( geometry.isGeometry ) {
  9860. if ( geometry._bufferGeometry === undefined ) {
  9861. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9862. }
  9863. buffergeometry = geometry._bufferGeometry;
  9864. }
  9865. geometries.set( geometry, buffergeometry );
  9866. info.memory.geometries ++;
  9867. return buffergeometry;
  9868. }
  9869. function update( geometry ) {
  9870. const geometryAttributes = geometry.attributes;
  9871. // Updating index buffer in VAO now. See WebGLBindingStates.
  9872. for ( const name in geometryAttributes ) {
  9873. attributes.update( geometryAttributes[ name ], 34962 );
  9874. }
  9875. // morph targets
  9876. const morphAttributes = geometry.morphAttributes;
  9877. for ( const name in morphAttributes ) {
  9878. const array = morphAttributes[ name ];
  9879. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9880. attributes.update( array[ i ], 34962 );
  9881. }
  9882. }
  9883. }
  9884. function updateWireframeAttribute( geometry ) {
  9885. const indices = [];
  9886. const geometryIndex = geometry.index;
  9887. const geometryPosition = geometry.attributes.position;
  9888. let version = 0;
  9889. if ( geometryIndex !== null ) {
  9890. const array = geometryIndex.array;
  9891. version = geometryIndex.version;
  9892. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9893. const a = array[ i + 0 ];
  9894. const b = array[ i + 1 ];
  9895. const c = array[ i + 2 ];
  9896. indices.push( a, b, b, c, c, a );
  9897. }
  9898. } else {
  9899. const array = geometryPosition.array;
  9900. version = geometryPosition.version;
  9901. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9902. const a = i + 0;
  9903. const b = i + 1;
  9904. const c = i + 2;
  9905. indices.push( a, b, b, c, c, a );
  9906. }
  9907. }
  9908. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9909. attribute.version = version;
  9910. // Updating index buffer in VAO now. See WebGLBindingStates
  9911. //
  9912. const previousAttribute = wireframeAttributes.get( geometry );
  9913. if ( previousAttribute ) attributes.remove( previousAttribute );
  9914. //
  9915. wireframeAttributes.set( geometry, attribute );
  9916. }
  9917. function getWireframeAttribute( geometry ) {
  9918. const currentAttribute = wireframeAttributes.get( geometry );
  9919. if ( currentAttribute ) {
  9920. const geometryIndex = geometry.index;
  9921. if ( geometryIndex !== null ) {
  9922. // if the attribute is obsolete, create a new one
  9923. if ( currentAttribute.version < geometryIndex.version ) {
  9924. updateWireframeAttribute( geometry );
  9925. }
  9926. }
  9927. } else {
  9928. updateWireframeAttribute( geometry );
  9929. }
  9930. return wireframeAttributes.get( geometry );
  9931. }
  9932. return {
  9933. get: get,
  9934. update: update,
  9935. getWireframeAttribute: getWireframeAttribute
  9936. };
  9937. }
  9938. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9939. const isWebGL2 = capabilities.isWebGL2;
  9940. let mode;
  9941. function setMode( value ) {
  9942. mode = value;
  9943. }
  9944. let type, bytesPerElement;
  9945. function setIndex( value ) {
  9946. type = value.type;
  9947. bytesPerElement = value.bytesPerElement;
  9948. }
  9949. function render( start, count ) {
  9950. gl.drawElements( mode, count, type, start * bytesPerElement );
  9951. info.update( count, mode, 1 );
  9952. }
  9953. function renderInstances( start, count, primcount ) {
  9954. if ( primcount === 0 ) return;
  9955. let extension, methodName;
  9956. if ( isWebGL2 ) {
  9957. extension = gl;
  9958. methodName = 'drawElementsInstanced';
  9959. } else {
  9960. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9961. methodName = 'drawElementsInstancedANGLE';
  9962. if ( extension === null ) {
  9963. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9964. return;
  9965. }
  9966. }
  9967. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9968. info.update( count, mode, primcount );
  9969. }
  9970. //
  9971. this.setMode = setMode;
  9972. this.setIndex = setIndex;
  9973. this.render = render;
  9974. this.renderInstances = renderInstances;
  9975. }
  9976. function WebGLInfo( gl ) {
  9977. const memory = {
  9978. geometries: 0,
  9979. textures: 0
  9980. };
  9981. const render = {
  9982. frame: 0,
  9983. calls: 0,
  9984. triangles: 0,
  9985. points: 0,
  9986. lines: 0
  9987. };
  9988. function update( count, mode, instanceCount ) {
  9989. render.calls ++;
  9990. switch ( mode ) {
  9991. case 4:
  9992. render.triangles += instanceCount * ( count / 3 );
  9993. break;
  9994. case 1:
  9995. render.lines += instanceCount * ( count / 2 );
  9996. break;
  9997. case 3:
  9998. render.lines += instanceCount * ( count - 1 );
  9999. break;
  10000. case 2:
  10001. render.lines += instanceCount * count;
  10002. break;
  10003. case 0:
  10004. render.points += instanceCount * count;
  10005. break;
  10006. default:
  10007. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10008. break;
  10009. }
  10010. }
  10011. function reset() {
  10012. render.frame ++;
  10013. render.calls = 0;
  10014. render.triangles = 0;
  10015. render.points = 0;
  10016. render.lines = 0;
  10017. }
  10018. return {
  10019. memory: memory,
  10020. render: render,
  10021. programs: null,
  10022. autoReset: true,
  10023. reset: reset,
  10024. update: update
  10025. };
  10026. }
  10027. function numericalSort( a, b ) {
  10028. return a[ 0 ] - b[ 0 ];
  10029. }
  10030. function absNumericalSort( a, b ) {
  10031. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10032. }
  10033. function WebGLMorphtargets( gl ) {
  10034. const influencesList = {};
  10035. const morphInfluences = new Float32Array( 8 );
  10036. const workInfluences = [];
  10037. for ( let i = 0; i < 8; i ++ ) {
  10038. workInfluences[ i ] = [ i, 0 ];
  10039. }
  10040. function update( object, geometry, material, program ) {
  10041. const objectInfluences = object.morphTargetInfluences;
  10042. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10043. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10044. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10045. let influences = influencesList[ geometry.id ];
  10046. if ( influences === undefined ) {
  10047. // initialise list
  10048. influences = [];
  10049. for ( let i = 0; i < length; i ++ ) {
  10050. influences[ i ] = [ i, 0 ];
  10051. }
  10052. influencesList[ geometry.id ] = influences;
  10053. }
  10054. // Collect influences
  10055. for ( let i = 0; i < length; i ++ ) {
  10056. const influence = influences[ i ];
  10057. influence[ 0 ] = i;
  10058. influence[ 1 ] = objectInfluences[ i ];
  10059. }
  10060. influences.sort( absNumericalSort );
  10061. for ( let i = 0; i < 8; i ++ ) {
  10062. if ( i < length && influences[ i ][ 1 ] ) {
  10063. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10064. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10065. } else {
  10066. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10067. workInfluences[ i ][ 1 ] = 0;
  10068. }
  10069. }
  10070. workInfluences.sort( numericalSort );
  10071. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10072. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10073. let morphInfluencesSum = 0;
  10074. for ( let i = 0; i < 8; i ++ ) {
  10075. const influence = workInfluences[ i ];
  10076. const index = influence[ 0 ];
  10077. const value = influence[ 1 ];
  10078. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10079. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10080. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10081. }
  10082. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10083. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10084. }
  10085. morphInfluences[ i ] = value;
  10086. morphInfluencesSum += value;
  10087. } else {
  10088. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10089. geometry.deleteAttribute( 'morphTarget' + i );
  10090. }
  10091. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10092. geometry.deleteAttribute( 'morphNormal' + i );
  10093. }
  10094. morphInfluences[ i ] = 0;
  10095. }
  10096. }
  10097. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10098. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10099. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10100. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10101. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10102. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10103. }
  10104. return {
  10105. update: update
  10106. };
  10107. }
  10108. function WebGLObjects( gl, geometries, attributes, info ) {
  10109. let updateMap = new WeakMap();
  10110. function update( object ) {
  10111. const frame = info.render.frame;
  10112. const geometry = object.geometry;
  10113. const buffergeometry = geometries.get( object, geometry );
  10114. // Update once per frame
  10115. if ( updateMap.get( buffergeometry ) !== frame ) {
  10116. if ( geometry.isGeometry ) {
  10117. buffergeometry.updateFromObject( object );
  10118. }
  10119. geometries.update( buffergeometry );
  10120. updateMap.set( buffergeometry, frame );
  10121. }
  10122. if ( object.isInstancedMesh ) {
  10123. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10124. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10125. }
  10126. attributes.update( object.instanceMatrix, 34962 );
  10127. if ( object.instanceColor !== null ) {
  10128. attributes.update( object.instanceColor, 34962 );
  10129. }
  10130. }
  10131. return buffergeometry;
  10132. }
  10133. function dispose() {
  10134. updateMap = new WeakMap();
  10135. }
  10136. function onInstancedMeshDispose( event ) {
  10137. const instancedMesh = event.target;
  10138. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10139. attributes.remove( instancedMesh.instanceMatrix );
  10140. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10141. }
  10142. return {
  10143. update: update,
  10144. dispose: dispose
  10145. };
  10146. }
  10147. function DataTexture2DArray( data = null, width = 1, height = 1, depth = 1 ) {
  10148. Texture.call( this, null );
  10149. this.image = { data, width, height, depth };
  10150. this.magFilter = NearestFilter;
  10151. this.minFilter = NearestFilter;
  10152. this.wrapR = ClampToEdgeWrapping;
  10153. this.generateMipmaps = false;
  10154. this.flipY = false;
  10155. this.needsUpdate = true;
  10156. }
  10157. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  10158. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10159. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10160. function DataTexture3D( data = null, width = 1, height = 1, depth = 1 ) {
  10161. // We're going to add .setXXX() methods for setting properties later.
  10162. // Users can still set in DataTexture3D directly.
  10163. //
  10164. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10165. // texture.anisotropy = 16;
  10166. //
  10167. // See #14839
  10168. Texture.call( this, null );
  10169. this.image = { data, width, height, depth };
  10170. this.magFilter = NearestFilter;
  10171. this.minFilter = NearestFilter;
  10172. this.wrapR = ClampToEdgeWrapping;
  10173. this.generateMipmaps = false;
  10174. this.flipY = false;
  10175. this.needsUpdate = true;
  10176. }
  10177. DataTexture3D.prototype = Object.create( Texture.prototype );
  10178. DataTexture3D.prototype.constructor = DataTexture3D;
  10179. DataTexture3D.prototype.isDataTexture3D = true;
  10180. /**
  10181. * Uniforms of a program.
  10182. * Those form a tree structure with a special top-level container for the root,
  10183. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10184. *
  10185. *
  10186. * Properties of inner nodes including the top-level container:
  10187. *
  10188. * .seq - array of nested uniforms
  10189. * .map - nested uniforms by name
  10190. *
  10191. *
  10192. * Methods of all nodes except the top-level container:
  10193. *
  10194. * .setValue( gl, value, [textures] )
  10195. *
  10196. * uploads a uniform value(s)
  10197. * the 'textures' parameter is needed for sampler uniforms
  10198. *
  10199. *
  10200. * Static methods of the top-level container (textures factorizations):
  10201. *
  10202. * .upload( gl, seq, values, textures )
  10203. *
  10204. * sets uniforms in 'seq' to 'values[id].value'
  10205. *
  10206. * .seqWithValue( seq, values ) : filteredSeq
  10207. *
  10208. * filters 'seq' entries with corresponding entry in values
  10209. *
  10210. *
  10211. * Methods of the top-level container (textures factorizations):
  10212. *
  10213. * .setValue( gl, name, value, textures )
  10214. *
  10215. * sets uniform with name 'name' to 'value'
  10216. *
  10217. * .setOptional( gl, obj, prop )
  10218. *
  10219. * like .set for an optional property of the object
  10220. *
  10221. */
  10222. const emptyTexture = new Texture();
  10223. const emptyTexture2dArray = new DataTexture2DArray();
  10224. const emptyTexture3d = new DataTexture3D();
  10225. const emptyCubeTexture = new CubeTexture();
  10226. // --- Utilities ---
  10227. // Array Caches (provide typed arrays for temporary by size)
  10228. const arrayCacheF32 = [];
  10229. const arrayCacheI32 = [];
  10230. // Float32Array caches used for uploading Matrix uniforms
  10231. const mat4array = new Float32Array( 16 );
  10232. const mat3array = new Float32Array( 9 );
  10233. const mat2array = new Float32Array( 4 );
  10234. // Flattening for arrays of vectors and matrices
  10235. function flatten( array, nBlocks, blockSize ) {
  10236. const firstElem = array[ 0 ];
  10237. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10238. // unoptimized: ! isNaN( firstElem )
  10239. // see http://jacksondunstan.com/articles/983
  10240. const n = nBlocks * blockSize;
  10241. let r = arrayCacheF32[ n ];
  10242. if ( r === undefined ) {
  10243. r = new Float32Array( n );
  10244. arrayCacheF32[ n ] = r;
  10245. }
  10246. if ( nBlocks !== 0 ) {
  10247. firstElem.toArray( r, 0 );
  10248. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10249. offset += blockSize;
  10250. array[ i ].toArray( r, offset );
  10251. }
  10252. }
  10253. return r;
  10254. }
  10255. function arraysEqual( a, b ) {
  10256. if ( a.length !== b.length ) return false;
  10257. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10258. if ( a[ i ] !== b[ i ] ) return false;
  10259. }
  10260. return true;
  10261. }
  10262. function copyArray( a, b ) {
  10263. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10264. a[ i ] = b[ i ];
  10265. }
  10266. }
  10267. // Texture unit allocation
  10268. function allocTexUnits( textures, n ) {
  10269. let r = arrayCacheI32[ n ];
  10270. if ( r === undefined ) {
  10271. r = new Int32Array( n );
  10272. arrayCacheI32[ n ] = r;
  10273. }
  10274. for ( let i = 0; i !== n; ++ i ) {
  10275. r[ i ] = textures.allocateTextureUnit();
  10276. }
  10277. return r;
  10278. }
  10279. // --- Setters ---
  10280. // Note: Defining these methods externally, because they come in a bunch
  10281. // and this way their names minify.
  10282. // Single scalar
  10283. function setValueV1f( gl, v ) {
  10284. const cache = this.cache;
  10285. if ( cache[ 0 ] === v ) return;
  10286. gl.uniform1f( this.addr, v );
  10287. cache[ 0 ] = v;
  10288. }
  10289. // Single float vector (from flat array or THREE.VectorN)
  10290. function setValueV2f( gl, v ) {
  10291. const cache = this.cache;
  10292. if ( v.x !== undefined ) {
  10293. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10294. gl.uniform2f( this.addr, v.x, v.y );
  10295. cache[ 0 ] = v.x;
  10296. cache[ 1 ] = v.y;
  10297. }
  10298. } else {
  10299. if ( arraysEqual( cache, v ) ) return;
  10300. gl.uniform2fv( this.addr, v );
  10301. copyArray( cache, v );
  10302. }
  10303. }
  10304. function setValueV3f( gl, v ) {
  10305. const cache = this.cache;
  10306. if ( v.x !== undefined ) {
  10307. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10308. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10309. cache[ 0 ] = v.x;
  10310. cache[ 1 ] = v.y;
  10311. cache[ 2 ] = v.z;
  10312. }
  10313. } else if ( v.r !== undefined ) {
  10314. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10315. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10316. cache[ 0 ] = v.r;
  10317. cache[ 1 ] = v.g;
  10318. cache[ 2 ] = v.b;
  10319. }
  10320. } else {
  10321. if ( arraysEqual( cache, v ) ) return;
  10322. gl.uniform3fv( this.addr, v );
  10323. copyArray( cache, v );
  10324. }
  10325. }
  10326. function setValueV4f( gl, v ) {
  10327. const cache = this.cache;
  10328. if ( v.x !== undefined ) {
  10329. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10330. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10331. cache[ 0 ] = v.x;
  10332. cache[ 1 ] = v.y;
  10333. cache[ 2 ] = v.z;
  10334. cache[ 3 ] = v.w;
  10335. }
  10336. } else {
  10337. if ( arraysEqual( cache, v ) ) return;
  10338. gl.uniform4fv( this.addr, v );
  10339. copyArray( cache, v );
  10340. }
  10341. }
  10342. // Single matrix (from flat array or MatrixN)
  10343. function setValueM2( gl, v ) {
  10344. const cache = this.cache;
  10345. const elements = v.elements;
  10346. if ( elements === undefined ) {
  10347. if ( arraysEqual( cache, v ) ) return;
  10348. gl.uniformMatrix2fv( this.addr, false, v );
  10349. copyArray( cache, v );
  10350. } else {
  10351. if ( arraysEqual( cache, elements ) ) return;
  10352. mat2array.set( elements );
  10353. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10354. copyArray( cache, elements );
  10355. }
  10356. }
  10357. function setValueM3( gl, v ) {
  10358. const cache = this.cache;
  10359. const elements = v.elements;
  10360. if ( elements === undefined ) {
  10361. if ( arraysEqual( cache, v ) ) return;
  10362. gl.uniformMatrix3fv( this.addr, false, v );
  10363. copyArray( cache, v );
  10364. } else {
  10365. if ( arraysEqual( cache, elements ) ) return;
  10366. mat3array.set( elements );
  10367. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10368. copyArray( cache, elements );
  10369. }
  10370. }
  10371. function setValueM4( gl, v ) {
  10372. const cache = this.cache;
  10373. const elements = v.elements;
  10374. if ( elements === undefined ) {
  10375. if ( arraysEqual( cache, v ) ) return;
  10376. gl.uniformMatrix4fv( this.addr, false, v );
  10377. copyArray( cache, v );
  10378. } else {
  10379. if ( arraysEqual( cache, elements ) ) return;
  10380. mat4array.set( elements );
  10381. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10382. copyArray( cache, elements );
  10383. }
  10384. }
  10385. // Single texture (2D / Cube)
  10386. function setValueT1( gl, v, textures ) {
  10387. const cache = this.cache;
  10388. const unit = textures.allocateTextureUnit();
  10389. if ( cache[ 0 ] !== unit ) {
  10390. gl.uniform1i( this.addr, unit );
  10391. cache[ 0 ] = unit;
  10392. }
  10393. textures.safeSetTexture2D( v || emptyTexture, unit );
  10394. }
  10395. function setValueT2DArray1( gl, v, textures ) {
  10396. const cache = this.cache;
  10397. const unit = textures.allocateTextureUnit();
  10398. if ( cache[ 0 ] !== unit ) {
  10399. gl.uniform1i( this.addr, unit );
  10400. cache[ 0 ] = unit;
  10401. }
  10402. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10403. }
  10404. function setValueT3D1( gl, v, textures ) {
  10405. const cache = this.cache;
  10406. const unit = textures.allocateTextureUnit();
  10407. if ( cache[ 0 ] !== unit ) {
  10408. gl.uniform1i( this.addr, unit );
  10409. cache[ 0 ] = unit;
  10410. }
  10411. textures.setTexture3D( v || emptyTexture3d, unit );
  10412. }
  10413. function setValueT6( gl, v, textures ) {
  10414. const cache = this.cache;
  10415. const unit = textures.allocateTextureUnit();
  10416. if ( cache[ 0 ] !== unit ) {
  10417. gl.uniform1i( this.addr, unit );
  10418. cache[ 0 ] = unit;
  10419. }
  10420. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10421. }
  10422. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10423. function setValueV1i( gl, v ) {
  10424. const cache = this.cache;
  10425. if ( cache[ 0 ] === v ) return;
  10426. gl.uniform1i( this.addr, v );
  10427. cache[ 0 ] = v;
  10428. }
  10429. function setValueV2i( gl, v ) {
  10430. const cache = this.cache;
  10431. if ( arraysEqual( cache, v ) ) return;
  10432. gl.uniform2iv( this.addr, v );
  10433. copyArray( cache, v );
  10434. }
  10435. function setValueV3i( gl, v ) {
  10436. const cache = this.cache;
  10437. if ( arraysEqual( cache, v ) ) return;
  10438. gl.uniform3iv( this.addr, v );
  10439. copyArray( cache, v );
  10440. }
  10441. function setValueV4i( gl, v ) {
  10442. const cache = this.cache;
  10443. if ( arraysEqual( cache, v ) ) return;
  10444. gl.uniform4iv( this.addr, v );
  10445. copyArray( cache, v );
  10446. }
  10447. // uint
  10448. function setValueV1ui( gl, v ) {
  10449. const cache = this.cache;
  10450. if ( cache[ 0 ] === v ) return;
  10451. gl.uniform1ui( this.addr, v );
  10452. cache[ 0 ] = v;
  10453. }
  10454. // Helper to pick the right setter for the singular case
  10455. function getSingularSetter( type ) {
  10456. switch ( type ) {
  10457. case 0x1406: return setValueV1f; // FLOAT
  10458. case 0x8b50: return setValueV2f; // _VEC2
  10459. case 0x8b51: return setValueV3f; // _VEC3
  10460. case 0x8b52: return setValueV4f; // _VEC4
  10461. case 0x8b5a: return setValueM2; // _MAT2
  10462. case 0x8b5b: return setValueM3; // _MAT3
  10463. case 0x8b5c: return setValueM4; // _MAT4
  10464. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10465. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10466. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10467. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10468. case 0x1405: return setValueV1ui; // UINT
  10469. case 0x8b5e: // SAMPLER_2D
  10470. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10471. case 0x8dca: // INT_SAMPLER_2D
  10472. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10473. case 0x8b62: // SAMPLER_2D_SHADOW
  10474. return setValueT1;
  10475. case 0x8b5f: // SAMPLER_3D
  10476. case 0x8dcb: // INT_SAMPLER_3D
  10477. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10478. return setValueT3D1;
  10479. case 0x8b60: // SAMPLER_CUBE
  10480. case 0x8dcc: // INT_SAMPLER_CUBE
  10481. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10482. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10483. return setValueT6;
  10484. case 0x8dc1: // SAMPLER_2D_ARRAY
  10485. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10486. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10487. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10488. return setValueT2DArray1;
  10489. }
  10490. }
  10491. // Array of scalars
  10492. function setValueV1fArray( gl, v ) {
  10493. gl.uniform1fv( this.addr, v );
  10494. }
  10495. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10496. function setValueV1iArray( gl, v ) {
  10497. gl.uniform1iv( this.addr, v );
  10498. }
  10499. function setValueV2iArray( gl, v ) {
  10500. gl.uniform2iv( this.addr, v );
  10501. }
  10502. function setValueV3iArray( gl, v ) {
  10503. gl.uniform3iv( this.addr, v );
  10504. }
  10505. function setValueV4iArray( gl, v ) {
  10506. gl.uniform4iv( this.addr, v );
  10507. }
  10508. // Array of vectors (flat or from THREE classes)
  10509. function setValueV2fArray( gl, v ) {
  10510. const data = flatten( v, this.size, 2 );
  10511. gl.uniform2fv( this.addr, data );
  10512. }
  10513. function setValueV3fArray( gl, v ) {
  10514. const data = flatten( v, this.size, 3 );
  10515. gl.uniform3fv( this.addr, data );
  10516. }
  10517. function setValueV4fArray( gl, v ) {
  10518. const data = flatten( v, this.size, 4 );
  10519. gl.uniform4fv( this.addr, data );
  10520. }
  10521. // Array of matrices (flat or from THREE clases)
  10522. function setValueM2Array( gl, v ) {
  10523. const data = flatten( v, this.size, 4 );
  10524. gl.uniformMatrix2fv( this.addr, false, data );
  10525. }
  10526. function setValueM3Array( gl, v ) {
  10527. const data = flatten( v, this.size, 9 );
  10528. gl.uniformMatrix3fv( this.addr, false, data );
  10529. }
  10530. function setValueM4Array( gl, v ) {
  10531. const data = flatten( v, this.size, 16 );
  10532. gl.uniformMatrix4fv( this.addr, false, data );
  10533. }
  10534. // Array of textures (2D / Cube)
  10535. function setValueT1Array( gl, v, textures ) {
  10536. const n = v.length;
  10537. const units = allocTexUnits( textures, n );
  10538. gl.uniform1iv( this.addr, units );
  10539. for ( let i = 0; i !== n; ++ i ) {
  10540. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10541. }
  10542. }
  10543. function setValueT6Array( gl, v, textures ) {
  10544. const n = v.length;
  10545. const units = allocTexUnits( textures, n );
  10546. gl.uniform1iv( this.addr, units );
  10547. for ( let i = 0; i !== n; ++ i ) {
  10548. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10549. }
  10550. }
  10551. // Helper to pick the right setter for a pure (bottom-level) array
  10552. function getPureArraySetter( type ) {
  10553. switch ( type ) {
  10554. case 0x1406: return setValueV1fArray; // FLOAT
  10555. case 0x8b50: return setValueV2fArray; // _VEC2
  10556. case 0x8b51: return setValueV3fArray; // _VEC3
  10557. case 0x8b52: return setValueV4fArray; // _VEC4
  10558. case 0x8b5a: return setValueM2Array; // _MAT2
  10559. case 0x8b5b: return setValueM3Array; // _MAT3
  10560. case 0x8b5c: return setValueM4Array; // _MAT4
  10561. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10562. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10563. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10564. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10565. case 0x8b5e: // SAMPLER_2D
  10566. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10567. case 0x8dca: // INT_SAMPLER_2D
  10568. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10569. case 0x8b62: // SAMPLER_2D_SHADOW
  10570. return setValueT1Array;
  10571. case 0x8b60: // SAMPLER_CUBE
  10572. case 0x8dcc: // INT_SAMPLER_CUBE
  10573. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10574. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10575. return setValueT6Array;
  10576. }
  10577. }
  10578. // --- Uniform Classes ---
  10579. function SingleUniform( id, activeInfo, addr ) {
  10580. this.id = id;
  10581. this.addr = addr;
  10582. this.cache = [];
  10583. this.setValue = getSingularSetter( activeInfo.type );
  10584. // this.path = activeInfo.name; // DEBUG
  10585. }
  10586. function PureArrayUniform( id, activeInfo, addr ) {
  10587. this.id = id;
  10588. this.addr = addr;
  10589. this.cache = [];
  10590. this.size = activeInfo.size;
  10591. this.setValue = getPureArraySetter( activeInfo.type );
  10592. // this.path = activeInfo.name; // DEBUG
  10593. }
  10594. PureArrayUniform.prototype.updateCache = function ( data ) {
  10595. const cache = this.cache;
  10596. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10597. this.cache = new Float32Array( data.length );
  10598. }
  10599. copyArray( cache, data );
  10600. };
  10601. function StructuredUniform( id ) {
  10602. this.id = id;
  10603. this.seq = [];
  10604. this.map = {};
  10605. }
  10606. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10607. const seq = this.seq;
  10608. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10609. const u = seq[ i ];
  10610. u.setValue( gl, value[ u.id ], textures );
  10611. }
  10612. };
  10613. // --- Top-level ---
  10614. // Parser - builds up the property tree from the path strings
  10615. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10616. // extracts
  10617. // - the identifier (member name or array index)
  10618. // - followed by an optional right bracket (found when array index)
  10619. // - followed by an optional left bracket or dot (type of subscript)
  10620. //
  10621. // Note: These portions can be read in a non-overlapping fashion and
  10622. // allow straightforward parsing of the hierarchy that WebGL encodes
  10623. // in the uniform names.
  10624. function addUniform( container, uniformObject ) {
  10625. container.seq.push( uniformObject );
  10626. container.map[ uniformObject.id ] = uniformObject;
  10627. }
  10628. function parseUniform( activeInfo, addr, container ) {
  10629. const path = activeInfo.name,
  10630. pathLength = path.length;
  10631. // reset RegExp object, because of the early exit of a previous run
  10632. RePathPart.lastIndex = 0;
  10633. while ( true ) {
  10634. const match = RePathPart.exec( path ),
  10635. matchEnd = RePathPart.lastIndex;
  10636. let id = match[ 1 ];
  10637. const idIsIndex = match[ 2 ] === ']',
  10638. subscript = match[ 3 ];
  10639. if ( idIsIndex ) id = id | 0; // convert to integer
  10640. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10641. // bare name or "pure" bottom-level array "[0]" suffix
  10642. addUniform( container, subscript === undefined ?
  10643. new SingleUniform( id, activeInfo, addr ) :
  10644. new PureArrayUniform( id, activeInfo, addr ) );
  10645. break;
  10646. } else {
  10647. // step into inner node / create it in case it doesn't exist
  10648. const map = container.map;
  10649. let next = map[ id ];
  10650. if ( next === undefined ) {
  10651. next = new StructuredUniform( id );
  10652. addUniform( container, next );
  10653. }
  10654. container = next;
  10655. }
  10656. }
  10657. }
  10658. // Root Container
  10659. function WebGLUniforms( gl, program ) {
  10660. this.seq = [];
  10661. this.map = {};
  10662. const n = gl.getProgramParameter( program, 35718 );
  10663. for ( let i = 0; i < n; ++ i ) {
  10664. const info = gl.getActiveUniform( program, i ),
  10665. addr = gl.getUniformLocation( program, info.name );
  10666. parseUniform( info, addr, this );
  10667. }
  10668. }
  10669. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10670. const u = this.map[ name ];
  10671. if ( u !== undefined ) u.setValue( gl, value, textures );
  10672. };
  10673. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10674. const v = object[ name ];
  10675. if ( v !== undefined ) this.setValue( gl, name, v );
  10676. };
  10677. // Static interface
  10678. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10679. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10680. const u = seq[ i ],
  10681. v = values[ u.id ];
  10682. if ( v.needsUpdate !== false ) {
  10683. // note: always updating when .needsUpdate is undefined
  10684. u.setValue( gl, v.value, textures );
  10685. }
  10686. }
  10687. };
  10688. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10689. const r = [];
  10690. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10691. const u = seq[ i ];
  10692. if ( u.id in values ) r.push( u );
  10693. }
  10694. return r;
  10695. };
  10696. function WebGLShader( gl, type, string ) {
  10697. const shader = gl.createShader( type );
  10698. gl.shaderSource( shader, string );
  10699. gl.compileShader( shader );
  10700. return shader;
  10701. }
  10702. let programIdCount = 0;
  10703. function addLineNumbers( string ) {
  10704. const lines = string.split( '\n' );
  10705. for ( let i = 0; i < lines.length; i ++ ) {
  10706. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10707. }
  10708. return lines.join( '\n' );
  10709. }
  10710. function getEncodingComponents( encoding ) {
  10711. switch ( encoding ) {
  10712. case LinearEncoding:
  10713. return [ 'Linear', '( value )' ];
  10714. case sRGBEncoding:
  10715. return [ 'sRGB', '( value )' ];
  10716. case RGBEEncoding:
  10717. return [ 'RGBE', '( value )' ];
  10718. case RGBM7Encoding:
  10719. return [ 'RGBM', '( value, 7.0 )' ];
  10720. case RGBM16Encoding:
  10721. return [ 'RGBM', '( value, 16.0 )' ];
  10722. case RGBDEncoding:
  10723. return [ 'RGBD', '( value, 256.0 )' ];
  10724. case GammaEncoding:
  10725. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10726. case LogLuvEncoding:
  10727. return [ 'LogLuv', '( value )' ];
  10728. default:
  10729. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10730. return [ 'Linear', '( value )' ];
  10731. }
  10732. }
  10733. function getShaderErrors( gl, shader, type ) {
  10734. const status = gl.getShaderParameter( shader, 35713 );
  10735. const log = gl.getShaderInfoLog( shader ).trim();
  10736. if ( status && log === '' ) return '';
  10737. // --enable-privileged-webgl-extension
  10738. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10739. const source = gl.getShaderSource( shader );
  10740. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  10741. }
  10742. function getTexelDecodingFunction( functionName, encoding ) {
  10743. const components = getEncodingComponents( encoding );
  10744. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10745. }
  10746. function getTexelEncodingFunction( functionName, encoding ) {
  10747. const components = getEncodingComponents( encoding );
  10748. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10749. }
  10750. function getToneMappingFunction( functionName, toneMapping ) {
  10751. let toneMappingName;
  10752. switch ( toneMapping ) {
  10753. case LinearToneMapping:
  10754. toneMappingName = 'Linear';
  10755. break;
  10756. case ReinhardToneMapping:
  10757. toneMappingName = 'Reinhard';
  10758. break;
  10759. case CineonToneMapping:
  10760. toneMappingName = 'OptimizedCineon';
  10761. break;
  10762. case ACESFilmicToneMapping:
  10763. toneMappingName = 'ACESFilmic';
  10764. break;
  10765. case CustomToneMapping:
  10766. toneMappingName = 'Custom';
  10767. break;
  10768. default:
  10769. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10770. toneMappingName = 'Linear';
  10771. }
  10772. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10773. }
  10774. function generateExtensions( parameters ) {
  10775. const chunks = [
  10776. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10777. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10778. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10779. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10780. ];
  10781. return chunks.filter( filterEmptyLine ).join( '\n' );
  10782. }
  10783. function generateDefines( defines ) {
  10784. const chunks = [];
  10785. for ( const name in defines ) {
  10786. const value = defines[ name ];
  10787. if ( value === false ) continue;
  10788. chunks.push( '#define ' + name + ' ' + value );
  10789. }
  10790. return chunks.join( '\n' );
  10791. }
  10792. function fetchAttributeLocations( gl, program ) {
  10793. const attributes = {};
  10794. const n = gl.getProgramParameter( program, 35721 );
  10795. for ( let i = 0; i < n; i ++ ) {
  10796. const info = gl.getActiveAttrib( program, i );
  10797. const name = info.name;
  10798. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10799. attributes[ name ] = gl.getAttribLocation( program, name );
  10800. }
  10801. return attributes;
  10802. }
  10803. function filterEmptyLine( string ) {
  10804. return string !== '';
  10805. }
  10806. function replaceLightNums( string, parameters ) {
  10807. return string
  10808. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10809. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10810. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10811. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10812. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10813. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10814. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10815. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10816. }
  10817. function replaceClippingPlaneNums( string, parameters ) {
  10818. return string
  10819. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10820. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10821. }
  10822. // Resolve Includes
  10823. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10824. function resolveIncludes( string ) {
  10825. return string.replace( includePattern, includeReplacer );
  10826. }
  10827. function includeReplacer( match, include ) {
  10828. const string = ShaderChunk[ include ];
  10829. if ( string === undefined ) {
  10830. throw new Error( 'Can not resolve #include <' + include + '>' );
  10831. }
  10832. return resolveIncludes( string );
  10833. }
  10834. // Unroll Loops
  10835. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10836. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  10837. function unrollLoops( string ) {
  10838. return string
  10839. .replace( unrollLoopPattern, loopReplacer )
  10840. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10841. }
  10842. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10843. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10844. return loopReplacer( match, start, end, snippet );
  10845. }
  10846. function loopReplacer( match, start, end, snippet ) {
  10847. let string = '';
  10848. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10849. string += snippet
  10850. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10851. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10852. }
  10853. return string;
  10854. }
  10855. //
  10856. function generatePrecision( parameters ) {
  10857. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10858. if ( parameters.precision === 'highp' ) {
  10859. precisionstring += '\n#define HIGH_PRECISION';
  10860. } else if ( parameters.precision === 'mediump' ) {
  10861. precisionstring += '\n#define MEDIUM_PRECISION';
  10862. } else if ( parameters.precision === 'lowp' ) {
  10863. precisionstring += '\n#define LOW_PRECISION';
  10864. }
  10865. return precisionstring;
  10866. }
  10867. function generateShadowMapTypeDefine( parameters ) {
  10868. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10869. if ( parameters.shadowMapType === PCFShadowMap ) {
  10870. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10871. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10872. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10873. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10874. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10875. }
  10876. return shadowMapTypeDefine;
  10877. }
  10878. function generateEnvMapTypeDefine( parameters ) {
  10879. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10880. if ( parameters.envMap ) {
  10881. switch ( parameters.envMapMode ) {
  10882. case CubeReflectionMapping:
  10883. case CubeRefractionMapping:
  10884. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10885. break;
  10886. case CubeUVReflectionMapping:
  10887. case CubeUVRefractionMapping:
  10888. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10889. break;
  10890. }
  10891. }
  10892. return envMapTypeDefine;
  10893. }
  10894. function generateEnvMapModeDefine( parameters ) {
  10895. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10896. if ( parameters.envMap ) {
  10897. switch ( parameters.envMapMode ) {
  10898. case CubeRefractionMapping:
  10899. case CubeUVRefractionMapping:
  10900. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10901. break;
  10902. }
  10903. }
  10904. return envMapModeDefine;
  10905. }
  10906. function generateEnvMapBlendingDefine( parameters ) {
  10907. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10908. if ( parameters.envMap ) {
  10909. switch ( parameters.combine ) {
  10910. case MultiplyOperation:
  10911. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10912. break;
  10913. case MixOperation:
  10914. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10915. break;
  10916. case AddOperation:
  10917. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10918. break;
  10919. }
  10920. }
  10921. return envMapBlendingDefine;
  10922. }
  10923. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10924. const gl = renderer.getContext();
  10925. const defines = parameters.defines;
  10926. let vertexShader = parameters.vertexShader;
  10927. let fragmentShader = parameters.fragmentShader;
  10928. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10929. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10930. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10931. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10932. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10933. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10934. const customDefines = generateDefines( defines );
  10935. const program = gl.createProgram();
  10936. let prefixVertex, prefixFragment;
  10937. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10938. if ( parameters.isRawShaderMaterial ) {
  10939. prefixVertex = [
  10940. customDefines
  10941. ].filter( filterEmptyLine ).join( '\n' );
  10942. if ( prefixVertex.length > 0 ) {
  10943. prefixVertex += '\n';
  10944. }
  10945. prefixFragment = [
  10946. customExtensions,
  10947. customDefines
  10948. ].filter( filterEmptyLine ).join( '\n' );
  10949. if ( prefixFragment.length > 0 ) {
  10950. prefixFragment += '\n';
  10951. }
  10952. } else {
  10953. prefixVertex = [
  10954. generatePrecision( parameters ),
  10955. '#define SHADER_NAME ' + parameters.shaderName,
  10956. customDefines,
  10957. parameters.instancing ? '#define USE_INSTANCING' : '',
  10958. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10959. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10960. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10961. '#define MAX_BONES ' + parameters.maxBones,
  10962. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10963. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10964. parameters.map ? '#define USE_MAP' : '',
  10965. parameters.envMap ? '#define USE_ENVMAP' : '',
  10966. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10967. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10968. parameters.aoMap ? '#define USE_AOMAP' : '',
  10969. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10970. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10971. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10972. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10973. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10974. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10975. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10976. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10977. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10978. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10979. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10980. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10981. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10982. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10983. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10984. parameters.vertexColors ? '#define USE_COLOR' : '',
  10985. parameters.vertexUvs ? '#define USE_UV' : '',
  10986. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10987. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10988. parameters.skinning ? '#define USE_SKINNING' : '',
  10989. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10990. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10991. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10992. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10993. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10994. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10995. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10996. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10997. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10998. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10999. 'uniform mat4 modelMatrix;',
  11000. 'uniform mat4 modelViewMatrix;',
  11001. 'uniform mat4 projectionMatrix;',
  11002. 'uniform mat4 viewMatrix;',
  11003. 'uniform mat3 normalMatrix;',
  11004. 'uniform vec3 cameraPosition;',
  11005. 'uniform bool isOrthographic;',
  11006. '#ifdef USE_INSTANCING',
  11007. ' attribute mat4 instanceMatrix;',
  11008. '#endif',
  11009. '#ifdef USE_INSTANCING_COLOR',
  11010. ' attribute vec3 instanceColor;',
  11011. '#endif',
  11012. 'attribute vec3 position;',
  11013. 'attribute vec3 normal;',
  11014. 'attribute vec2 uv;',
  11015. '#ifdef USE_TANGENT',
  11016. ' attribute vec4 tangent;',
  11017. '#endif',
  11018. '#ifdef USE_COLOR',
  11019. ' attribute vec3 color;',
  11020. '#endif',
  11021. '#ifdef USE_MORPHTARGETS',
  11022. ' attribute vec3 morphTarget0;',
  11023. ' attribute vec3 morphTarget1;',
  11024. ' attribute vec3 morphTarget2;',
  11025. ' attribute vec3 morphTarget3;',
  11026. ' #ifdef USE_MORPHNORMALS',
  11027. ' attribute vec3 morphNormal0;',
  11028. ' attribute vec3 morphNormal1;',
  11029. ' attribute vec3 morphNormal2;',
  11030. ' attribute vec3 morphNormal3;',
  11031. ' #else',
  11032. ' attribute vec3 morphTarget4;',
  11033. ' attribute vec3 morphTarget5;',
  11034. ' attribute vec3 morphTarget6;',
  11035. ' attribute vec3 morphTarget7;',
  11036. ' #endif',
  11037. '#endif',
  11038. '#ifdef USE_SKINNING',
  11039. ' attribute vec4 skinIndex;',
  11040. ' attribute vec4 skinWeight;',
  11041. '#endif',
  11042. '\n'
  11043. ].filter( filterEmptyLine ).join( '\n' );
  11044. prefixFragment = [
  11045. customExtensions,
  11046. generatePrecision( parameters ),
  11047. '#define SHADER_NAME ' + parameters.shaderName,
  11048. customDefines,
  11049. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  11050. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11051. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11052. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11053. parameters.map ? '#define USE_MAP' : '',
  11054. parameters.matcap ? '#define USE_MATCAP' : '',
  11055. parameters.envMap ? '#define USE_ENVMAP' : '',
  11056. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11057. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11058. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11059. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11060. parameters.aoMap ? '#define USE_AOMAP' : '',
  11061. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11062. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11063. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11064. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11065. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11066. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11067. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11068. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11069. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11070. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11071. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11072. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11073. parameters.sheen ? '#define USE_SHEEN' : '',
  11074. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11075. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11076. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11077. parameters.vertexUvs ? '#define USE_UV' : '',
  11078. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11079. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11080. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11081. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11082. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11083. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11084. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11085. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11086. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11087. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11088. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11089. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11090. 'uniform mat4 viewMatrix;',
  11091. 'uniform vec3 cameraPosition;',
  11092. 'uniform bool isOrthographic;',
  11093. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11094. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11095. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11096. parameters.dithering ? '#define DITHERING' : '',
  11097. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11098. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11099. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11100. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11101. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11102. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11103. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11104. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11105. '\n'
  11106. ].filter( filterEmptyLine ).join( '\n' );
  11107. }
  11108. vertexShader = resolveIncludes( vertexShader );
  11109. vertexShader = replaceLightNums( vertexShader, parameters );
  11110. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11111. fragmentShader = resolveIncludes( fragmentShader );
  11112. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11113. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11114. vertexShader = unrollLoops( vertexShader );
  11115. fragmentShader = unrollLoops( fragmentShader );
  11116. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11117. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11118. versionString = '#version 300 es\n';
  11119. prefixVertex = [
  11120. '#define attribute in',
  11121. '#define varying out',
  11122. '#define texture2D texture'
  11123. ].join( '\n' ) + '\n' + prefixVertex;
  11124. prefixFragment = [
  11125. '#define varying in',
  11126. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11127. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11128. '#define gl_FragDepthEXT gl_FragDepth',
  11129. '#define texture2D texture',
  11130. '#define textureCube texture',
  11131. '#define texture2DProj textureProj',
  11132. '#define texture2DLodEXT textureLod',
  11133. '#define texture2DProjLodEXT textureProjLod',
  11134. '#define textureCubeLodEXT textureLod',
  11135. '#define texture2DGradEXT textureGrad',
  11136. '#define texture2DProjGradEXT textureProjGrad',
  11137. '#define textureCubeGradEXT textureGrad'
  11138. ].join( '\n' ) + '\n' + prefixFragment;
  11139. }
  11140. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11141. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11142. // console.log( '*VERTEX*', vertexGlsl );
  11143. // console.log( '*FRAGMENT*', fragmentGlsl );
  11144. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11145. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11146. gl.attachShader( program, glVertexShader );
  11147. gl.attachShader( program, glFragmentShader );
  11148. // Force a particular attribute to index 0.
  11149. if ( parameters.index0AttributeName !== undefined ) {
  11150. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11151. } else if ( parameters.morphTargets === true ) {
  11152. // programs with morphTargets displace position out of attribute 0
  11153. gl.bindAttribLocation( program, 0, 'position' );
  11154. }
  11155. gl.linkProgram( program );
  11156. // check for link errors
  11157. if ( renderer.debug.checkShaderErrors ) {
  11158. const programLog = gl.getProgramInfoLog( program ).trim();
  11159. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11160. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11161. let runnable = true;
  11162. let haveDiagnostics = true;
  11163. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11164. runnable = false;
  11165. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11166. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11167. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  11168. //add:
  11169. if(fragmentErrors){
  11170. console.log(fragmentGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  11171. }else {
  11172. console.log(vertexGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  11173. }
  11174. } else if ( programLog !== '' ) {
  11175. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  11176. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11177. haveDiagnostics = false;
  11178. }
  11179. if ( haveDiagnostics ) {
  11180. this.diagnostics = {
  11181. runnable: runnable,
  11182. programLog: programLog,
  11183. vertexShader: {
  11184. log: vertexLog,
  11185. prefix: prefixVertex
  11186. },
  11187. fragmentShader: {
  11188. log: fragmentLog,
  11189. prefix: prefixFragment
  11190. }
  11191. };
  11192. }
  11193. }
  11194. // Clean up
  11195. // Crashes in iOS9 and iOS10. #18402
  11196. // gl.detachShader( program, glVertexShader );
  11197. // gl.detachShader( program, glFragmentShader );
  11198. gl.deleteShader( glVertexShader );
  11199. gl.deleteShader( glFragmentShader );
  11200. // set up caching for uniform locations
  11201. let cachedUniforms;
  11202. this.getUniforms = function () {
  11203. if ( cachedUniforms === undefined ) {
  11204. cachedUniforms = new WebGLUniforms( gl, program );
  11205. }
  11206. return cachedUniforms;
  11207. };
  11208. // set up caching for attribute locations
  11209. let cachedAttributes;
  11210. this.getAttributes = function () {
  11211. if ( cachedAttributes === undefined ) {
  11212. cachedAttributes = fetchAttributeLocations( gl, program );
  11213. }
  11214. return cachedAttributes;
  11215. };
  11216. // free resource
  11217. this.destroy = function () {
  11218. bindingStates.releaseStatesOfProgram( this );
  11219. gl.deleteProgram( program );
  11220. this.program = undefined;
  11221. };
  11222. //
  11223. this.name = parameters.shaderName;
  11224. this.id = programIdCount ++;
  11225. this.cacheKey = cacheKey;
  11226. this.usedTimes = 1;
  11227. this.program = program;
  11228. this.vertexShader = glVertexShader;
  11229. this.fragmentShader = glFragmentShader;
  11230. return this;
  11231. }
  11232. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  11233. const programs = [];
  11234. const isWebGL2 = capabilities.isWebGL2;
  11235. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11236. const floatVertexTextures = capabilities.floatVertexTextures;
  11237. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11238. const vertexTextures = capabilities.vertexTextures;
  11239. let precision = capabilities.precision;
  11240. const shaderIDs = {
  11241. MeshDepthMaterial: 'depth',
  11242. MeshDistanceMaterial: 'distanceRGBA',
  11243. MeshNormalMaterial: 'normal',
  11244. MeshBasicMaterial: 'basic',
  11245. MeshLambertMaterial: 'lambert',
  11246. MeshPhongMaterial: 'phong',
  11247. MeshToonMaterial: 'toon',
  11248. MeshStandardMaterial: 'physical',
  11249. MeshPhysicalMaterial: 'physical',
  11250. MeshMatcapMaterial: 'matcap',
  11251. LineBasicMaterial: 'basic',
  11252. LineDashedMaterial: 'dashed',
  11253. PointsMaterial: 'points',
  11254. ShadowMaterial: 'shadow',
  11255. SpriteMaterial: 'sprite'
  11256. };
  11257. const parameterNames = [
  11258. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  11259. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  11260. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  11261. 'roughnessMap', 'metalnessMap', 'gradientMap',
  11262. 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  11263. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  11264. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals',
  11265. 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha',
  11266. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  11267. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  11268. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  11269. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  11270. 'sheen', 'transmissionMap'
  11271. ];
  11272. function getMaxBones( object ) {
  11273. const skeleton = object.skeleton;
  11274. const bones = skeleton.bones;
  11275. if ( floatVertexTextures ) {
  11276. return 1024;
  11277. } else {
  11278. // default for when object is not specified
  11279. // ( for example when prebuilding shader to be used with multiple objects )
  11280. //
  11281. // - leave some extra space for other uniforms
  11282. // - limit here is ANGLE's 254 max uniform vectors
  11283. // (up to 54 should be safe)
  11284. const nVertexUniforms = maxVertexUniforms;
  11285. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11286. const maxBones = Math.min( nVertexMatrices, bones.length );
  11287. if ( maxBones < bones.length ) {
  11288. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11289. return 0;
  11290. }
  11291. return maxBones;
  11292. }
  11293. }
  11294. function getTextureEncodingFromMap( map ) {
  11295. let encoding;
  11296. if ( map && map.isTexture ) {
  11297. encoding = map.encoding;
  11298. } else if ( map && map.isWebGLRenderTarget ) {
  11299. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  11300. encoding = map.texture.encoding;
  11301. } else {
  11302. encoding = LinearEncoding;
  11303. }
  11304. return encoding;
  11305. }
  11306. function getParameters( material, lights, shadows, scene, object ) {
  11307. const fog = scene.fog;
  11308. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11309. const envMap = cubemaps.get( material.envMap || environment );
  11310. const shaderID = shaderIDs[ material.type ];
  11311. // heuristics to create shader parameters according to lights in the scene
  11312. // (not to blow over maxLights budget)
  11313. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11314. if ( material.precision !== null ) {
  11315. precision = capabilities.getMaxPrecision( material.precision );
  11316. if ( precision !== material.precision ) {
  11317. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11318. }
  11319. }
  11320. let vertexShader, fragmentShader;
  11321. if ( shaderID ) {
  11322. const shader = ShaderLib[ shaderID ];
  11323. vertexShader = shader.vertexShader;
  11324. fragmentShader = shader.fragmentShader;
  11325. } else {
  11326. vertexShader = material.vertexShader;
  11327. fragmentShader = material.fragmentShader;
  11328. }
  11329. const currentRenderTarget = renderer.getRenderTarget();
  11330. const parameters = {
  11331. isWebGL2: isWebGL2,
  11332. shaderID: shaderID,
  11333. shaderName: material.type,
  11334. vertexShader: vertexShader,
  11335. fragmentShader: fragmentShader,
  11336. defines: material.defines,
  11337. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11338. glslVersion: material.glslVersion,
  11339. precision: precision,
  11340. instancing: object.isInstancedMesh === true,
  11341. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11342. supportsVertexTextures: vertexTextures,
  11343. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11344. map: !! material.map,
  11345. mapEncoding: getTextureEncodingFromMap( material.map ),
  11346. matcap: !! material.matcap,
  11347. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11348. envMap: !! envMap,
  11349. envMapMode: envMap && envMap.mapping,
  11350. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11351. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11352. lightMap: !! material.lightMap,
  11353. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11354. aoMap: !! material.aoMap,
  11355. emissiveMap: !! material.emissiveMap,
  11356. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11357. bumpMap: !! material.bumpMap,
  11358. normalMap: !! material.normalMap,
  11359. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11360. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11361. clearcoatMap: !! material.clearcoatMap,
  11362. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  11363. clearcoatNormalMap: !! material.clearcoatNormalMap,
  11364. displacementMap: !! material.displacementMap,
  11365. roughnessMap: !! material.roughnessMap,
  11366. metalnessMap: !! material.metalnessMap,
  11367. specularMap: !! material.specularMap,
  11368. alphaMap: !! material.alphaMap,
  11369. gradientMap: !! material.gradientMap,
  11370. sheen: !! material.sheen,
  11371. transmissionMap: !! material.transmissionMap,
  11372. combine: material.combine,
  11373. vertexTangents: ( material.normalMap && material.vertexTangents ),
  11374. vertexColors: material.vertexColors,
  11375. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap,
  11376. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  11377. fog: !! fog,
  11378. useFog: material.fog,
  11379. fogExp2: ( fog && fog.isFogExp2 ),
  11380. flatShading: material.flatShading,
  11381. sizeAttenuation: material.sizeAttenuation,
  11382. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11383. skinning: material.skinning && maxBones > 0,
  11384. maxBones: maxBones,
  11385. useVertexTexture: floatVertexTextures,
  11386. morphTargets: material.morphTargets,
  11387. morphNormals: material.morphNormals,
  11388. maxMorphTargets: renderer.maxMorphTargets,
  11389. maxMorphNormals: renderer.maxMorphNormals,
  11390. numDirLights: lights.directional.length,
  11391. numPointLights: lights.point.length,
  11392. numSpotLights: lights.spot.length,
  11393. numRectAreaLights: lights.rectArea.length,
  11394. numHemiLights: lights.hemi.length,
  11395. numDirLightShadows: lights.directionalShadowMap.length,
  11396. numPointLightShadows: lights.pointShadowMap.length,
  11397. numSpotLightShadows: lights.spotShadowMap.length,
  11398. numClippingPlanes: clipping.numPlanes,
  11399. numClipIntersection: clipping.numIntersection,
  11400. dithering: material.dithering,
  11401. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11402. shadowMapType: renderer.shadowMap.type,
  11403. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11404. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11405. premultipliedAlpha: material.premultipliedAlpha,
  11406. alphaTest: material.alphaTest,
  11407. doubleSided: material.side === DoubleSide,
  11408. flipSided: material.side === BackSide,
  11409. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11410. index0AttributeName: material.index0AttributeName,
  11411. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11412. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11413. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11414. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11415. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11416. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11417. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11418. customProgramCacheKey: material.customProgramCacheKey()
  11419. };
  11420. return parameters;
  11421. }
  11422. function getProgramCacheKey( parameters ) {
  11423. const array = [];
  11424. if ( parameters.shaderID ) {
  11425. array.push( parameters.shaderID );
  11426. } else {
  11427. array.push( parameters.fragmentShader );
  11428. array.push( parameters.vertexShader );
  11429. }
  11430. if ( parameters.defines !== undefined ) {
  11431. for ( const name in parameters.defines ) {
  11432. array.push( name );
  11433. array.push( parameters.defines[ name ] );
  11434. }
  11435. }
  11436. if ( parameters.isRawShaderMaterial === false ) {
  11437. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11438. array.push( parameters[ parameterNames[ i ] ] );
  11439. }
  11440. array.push( renderer.outputEncoding );
  11441. array.push( renderer.gammaFactor );
  11442. }
  11443. array.push( parameters.customProgramCacheKey );
  11444. return array.join();
  11445. }
  11446. function getUniforms( material ) {
  11447. const shaderID = shaderIDs[ material.type ];
  11448. let uniforms;
  11449. if ( shaderID ) {
  11450. const shader = ShaderLib[ shaderID ];
  11451. uniforms = UniformsUtils.clone( shader.uniforms );
  11452. } else {
  11453. uniforms = material.uniforms;
  11454. }
  11455. return uniforms;
  11456. }
  11457. function acquireProgram( parameters, cacheKey ) {
  11458. let program;
  11459. // Check if code has been already compiled
  11460. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11461. const preexistingProgram = programs[ p ];
  11462. if ( preexistingProgram.cacheKey === cacheKey ) {
  11463. program = preexistingProgram;
  11464. ++ program.usedTimes;
  11465. break;
  11466. }
  11467. }
  11468. if ( program === undefined ) {
  11469. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11470. programs.push( program );
  11471. }
  11472. return program;
  11473. }
  11474. function releaseProgram( program ) {
  11475. if ( -- program.usedTimes === 0 ) {
  11476. // Remove from unordered set
  11477. const i = programs.indexOf( program );
  11478. programs[ i ] = programs[ programs.length - 1 ];
  11479. programs.pop();
  11480. // Free WebGL resources
  11481. program.destroy();
  11482. }
  11483. }
  11484. return {
  11485. getParameters: getParameters,
  11486. getProgramCacheKey: getProgramCacheKey,
  11487. getUniforms: getUniforms,
  11488. acquireProgram: acquireProgram,
  11489. releaseProgram: releaseProgram,
  11490. // Exposed for resource monitoring & error feedback via renderer.info:
  11491. programs: programs
  11492. };
  11493. }
  11494. function WebGLProperties() {
  11495. let properties = new WeakMap();
  11496. function get( object ) {
  11497. let map = properties.get( object );
  11498. if ( map === undefined ) {
  11499. map = {};
  11500. properties.set( object, map );
  11501. }
  11502. return map;
  11503. }
  11504. function remove( object ) {
  11505. properties.delete( object );
  11506. }
  11507. function update( object, key, value ) {
  11508. properties.get( object )[ key ] = value;
  11509. }
  11510. function dispose() {
  11511. properties = new WeakMap();
  11512. }
  11513. return {
  11514. get: get,
  11515. remove: remove,
  11516. update: update,
  11517. dispose: dispose
  11518. };
  11519. }
  11520. function painterSortStable( a, b ) {
  11521. if ( a.groupOrder !== b.groupOrder ) {
  11522. return a.groupOrder - b.groupOrder;
  11523. } else if ( a.renderOrder !== b.renderOrder ) {
  11524. return a.renderOrder - b.renderOrder;
  11525. } else if ( a.program !== b.program ) {
  11526. return a.program.id - b.program.id;
  11527. } else if ( a.material.id !== b.material.id ) {
  11528. return a.material.id - b.material.id;
  11529. } else if ( a.z !== b.z ) {
  11530. return a.z - b.z;
  11531. } else {
  11532. return a.id - b.id;
  11533. }
  11534. }
  11535. function reversePainterSortStable( a, b ) {
  11536. if ( a.groupOrder !== b.groupOrder ) {
  11537. return a.groupOrder - b.groupOrder;
  11538. } else if ( a.renderOrder !== b.renderOrder ) {
  11539. return a.renderOrder - b.renderOrder;
  11540. } else if ( a.z !== b.z ) {
  11541. return b.z - a.z;
  11542. } else {
  11543. return a.id - b.id;
  11544. }
  11545. }
  11546. function WebGLRenderList( properties ) {
  11547. const renderItems = [];
  11548. let renderItemsIndex = 0;
  11549. const opaque = [];
  11550. const transparent = [];
  11551. const defaultProgram = { id: - 1 };
  11552. function init() {
  11553. renderItemsIndex = 0;
  11554. opaque.length = 0;
  11555. transparent.length = 0;
  11556. }
  11557. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11558. let renderItem = renderItems[ renderItemsIndex ];
  11559. const materialProperties = properties.get( material );
  11560. if ( renderItem === undefined ) {
  11561. renderItem = {
  11562. id: object.id,
  11563. object: object,
  11564. geometry: geometry,
  11565. material: material,
  11566. program: materialProperties.program || defaultProgram,
  11567. groupOrder: groupOrder,
  11568. renderOrder: object.renderOrder,
  11569. z: z,
  11570. group: group
  11571. };
  11572. renderItems[ renderItemsIndex ] = renderItem;
  11573. } else {
  11574. renderItem.id = object.id;
  11575. renderItem.object = object;
  11576. renderItem.geometry = geometry;
  11577. renderItem.material = material;
  11578. renderItem.program = materialProperties.program || defaultProgram;
  11579. renderItem.groupOrder = groupOrder;
  11580. renderItem.renderOrder = object.renderOrder;
  11581. renderItem.z = z;
  11582. renderItem.group = group;
  11583. }
  11584. renderItemsIndex ++;
  11585. return renderItem;
  11586. }
  11587. function push( object, geometry, material, groupOrder, z, group ) {
  11588. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11589. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  11590. }
  11591. function unshift( object, geometry, material, groupOrder, z, group ) {
  11592. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11593. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  11594. }
  11595. function sort( customOpaqueSort, customTransparentSort ) {
  11596. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11597. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11598. }
  11599. function finish() {
  11600. // Clear references from inactive renderItems in the list
  11601. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11602. const renderItem = renderItems[ i ];
  11603. if ( renderItem.id === null ) break;
  11604. renderItem.id = null;
  11605. renderItem.object = null;
  11606. renderItem.geometry = null;
  11607. renderItem.material = null;
  11608. renderItem.program = null;
  11609. renderItem.group = null;
  11610. }
  11611. }
  11612. return {
  11613. opaque: opaque,
  11614. transparent: transparent,
  11615. init: init,
  11616. push: push,
  11617. unshift: unshift,
  11618. finish: finish,
  11619. sort: sort
  11620. };
  11621. }
  11622. function WebGLRenderLists( properties ) {
  11623. let lists = new WeakMap();
  11624. function get( scene, camera ) {
  11625. const cameras = lists.get( scene );
  11626. let list;
  11627. if ( cameras === undefined ) {
  11628. list = new WebGLRenderList( properties );
  11629. lists.set( scene, new WeakMap() );
  11630. lists.get( scene ).set( camera, list );
  11631. } else {
  11632. list = cameras.get( camera );
  11633. if ( list === undefined ) {
  11634. list = new WebGLRenderList( properties );
  11635. cameras.set( camera, list );
  11636. }
  11637. }
  11638. return list;
  11639. }
  11640. function dispose() {
  11641. lists = new WeakMap();
  11642. }
  11643. return {
  11644. get: get,
  11645. dispose: dispose
  11646. };
  11647. }
  11648. function UniformsCache() {
  11649. const lights = {};
  11650. return {
  11651. get: function ( light ) {
  11652. if ( lights[ light.id ] !== undefined ) {
  11653. return lights[ light.id ];
  11654. }
  11655. let uniforms;
  11656. switch ( light.type ) {
  11657. case 'DirectionalLight':
  11658. uniforms = {
  11659. direction: new Vector3(),
  11660. color: new Color()
  11661. };
  11662. break;
  11663. case 'SpotLight':
  11664. uniforms = {
  11665. position: new Vector3(),
  11666. direction: new Vector3(),
  11667. color: new Color(),
  11668. distance: 0,
  11669. coneCos: 0,
  11670. penumbraCos: 0,
  11671. decay: 0
  11672. };
  11673. break;
  11674. case 'PointLight':
  11675. uniforms = {
  11676. position: new Vector3(),
  11677. color: new Color(),
  11678. distance: 0,
  11679. decay: 0
  11680. };
  11681. break;
  11682. case 'HemisphereLight':
  11683. uniforms = {
  11684. direction: new Vector3(),
  11685. skyColor: new Color(),
  11686. groundColor: new Color()
  11687. };
  11688. break;
  11689. case 'RectAreaLight':
  11690. uniforms = {
  11691. color: new Color(),
  11692. position: new Vector3(),
  11693. halfWidth: new Vector3(),
  11694. halfHeight: new Vector3()
  11695. };
  11696. break;
  11697. }
  11698. lights[ light.id ] = uniforms;
  11699. return uniforms;
  11700. }
  11701. };
  11702. }
  11703. function ShadowUniformsCache() {
  11704. const lights = {};
  11705. return {
  11706. get: function ( light ) {
  11707. if ( lights[ light.id ] !== undefined ) {
  11708. return lights[ light.id ];
  11709. }
  11710. let uniforms;
  11711. switch ( light.type ) {
  11712. case 'DirectionalLight':
  11713. uniforms = {
  11714. shadowBias: 0,
  11715. shadowNormalBias: 0,
  11716. shadowRadius: 1,
  11717. shadowMapSize: new Vector2$1()
  11718. };
  11719. break;
  11720. case 'SpotLight':
  11721. uniforms = {
  11722. shadowBias: 0,
  11723. shadowNormalBias: 0,
  11724. shadowRadius: 1,
  11725. shadowMapSize: new Vector2$1()
  11726. };
  11727. break;
  11728. case 'PointLight':
  11729. uniforms = {
  11730. shadowBias: 0,
  11731. shadowNormalBias: 0,
  11732. shadowRadius: 1,
  11733. shadowMapSize: new Vector2$1(),
  11734. shadowCameraNear: 1,
  11735. shadowCameraFar: 1000
  11736. };
  11737. break;
  11738. // TODO (abelnation): set RectAreaLight shadow uniforms
  11739. }
  11740. lights[ light.id ] = uniforms;
  11741. return uniforms;
  11742. }
  11743. };
  11744. }
  11745. let nextVersion = 0;
  11746. function shadowCastingLightsFirst( lightA, lightB ) {
  11747. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11748. }
  11749. function WebGLLights( extensions, capabilities ) {
  11750. const cache = new UniformsCache();
  11751. const shadowCache = ShadowUniformsCache();
  11752. const state = {
  11753. version: 0,
  11754. hash: {
  11755. directionalLength: - 1,
  11756. pointLength: - 1,
  11757. spotLength: - 1,
  11758. rectAreaLength: - 1,
  11759. hemiLength: - 1,
  11760. numDirectionalShadows: - 1,
  11761. numPointShadows: - 1,
  11762. numSpotShadows: - 1
  11763. },
  11764. ambient: [ 0, 0, 0 ],
  11765. probe: [],
  11766. directional: [],
  11767. directionalShadow: [],
  11768. directionalShadowMap: [],
  11769. directionalShadowMatrix: [],
  11770. spot: [],
  11771. spotShadow: [],
  11772. spotShadowMap: [],
  11773. spotShadowMatrix: [],
  11774. rectArea: [],
  11775. rectAreaLTC1: null,
  11776. rectAreaLTC2: null,
  11777. point: [],
  11778. pointShadow: [],
  11779. pointShadowMap: [],
  11780. pointShadowMatrix: [],
  11781. hemi: []
  11782. };
  11783. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11784. const vector3 = new Vector3();
  11785. const matrix4 = new Matrix4();
  11786. const matrix42 = new Matrix4();
  11787. function setup( lights ) {
  11788. let r = 0, g = 0, b = 0;
  11789. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11790. let directionalLength = 0;
  11791. let pointLength = 0;
  11792. let spotLength = 0;
  11793. let rectAreaLength = 0;
  11794. let hemiLength = 0;
  11795. let numDirectionalShadows = 0;
  11796. let numPointShadows = 0;
  11797. let numSpotShadows = 0;
  11798. lights.sort( shadowCastingLightsFirst );
  11799. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11800. const light = lights[ i ];
  11801. const color = light.color;
  11802. const intensity = light.intensity;
  11803. const distance = light.distance;
  11804. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11805. if ( light.isAmbientLight ) {
  11806. r += color.r * intensity;
  11807. g += color.g * intensity;
  11808. b += color.b * intensity;
  11809. } else if ( light.isLightProbe ) {
  11810. for ( let j = 0; j < 9; j ++ ) {
  11811. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11812. }
  11813. } else if ( light.isDirectionalLight ) {
  11814. const uniforms = cache.get( light );
  11815. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11816. if ( light.castShadow ) {
  11817. const shadow = light.shadow;
  11818. const shadowUniforms = shadowCache.get( light );
  11819. shadowUniforms.shadowBias = shadow.bias;
  11820. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11821. shadowUniforms.shadowRadius = shadow.radius;
  11822. shadowUniforms.shadowMapSize = shadow.mapSize;
  11823. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11824. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11825. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11826. numDirectionalShadows ++;
  11827. }
  11828. state.directional[ directionalLength ] = uniforms;
  11829. directionalLength ++;
  11830. } else if ( light.isSpotLight ) {
  11831. const uniforms = cache.get( light );
  11832. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11833. uniforms.color.copy( color ).multiplyScalar( intensity );
  11834. uniforms.distance = distance;
  11835. uniforms.coneCos = Math.cos( light.angle );
  11836. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11837. uniforms.decay = light.decay;
  11838. if ( light.castShadow ) {
  11839. const shadow = light.shadow;
  11840. const shadowUniforms = shadowCache.get( light );
  11841. shadowUniforms.shadowBias = shadow.bias;
  11842. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11843. shadowUniforms.shadowRadius = shadow.radius;
  11844. shadowUniforms.shadowMapSize = shadow.mapSize;
  11845. state.spotShadow[ spotLength ] = shadowUniforms;
  11846. state.spotShadowMap[ spotLength ] = shadowMap;
  11847. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11848. numSpotShadows ++;
  11849. }
  11850. state.spot[ spotLength ] = uniforms;
  11851. spotLength ++;
  11852. } else if ( light.isRectAreaLight ) {
  11853. const uniforms = cache.get( light );
  11854. // (a) intensity is the total visible light emitted
  11855. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11856. // (b) intensity is the brightness of the light
  11857. uniforms.color.copy( color ).multiplyScalar( intensity );
  11858. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11859. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11860. state.rectArea[ rectAreaLength ] = uniforms;
  11861. rectAreaLength ++;
  11862. } else if ( light.isPointLight ) {
  11863. const uniforms = cache.get( light );
  11864. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11865. uniforms.distance = light.distance;
  11866. uniforms.decay = light.decay;
  11867. if ( light.castShadow ) {
  11868. const shadow = light.shadow;
  11869. const shadowUniforms = shadowCache.get( light );
  11870. shadowUniforms.shadowBias = shadow.bias;
  11871. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11872. shadowUniforms.shadowRadius = shadow.radius;
  11873. shadowUniforms.shadowMapSize = shadow.mapSize;
  11874. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11875. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11876. state.pointShadow[ pointLength ] = shadowUniforms;
  11877. state.pointShadowMap[ pointLength ] = shadowMap;
  11878. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11879. numPointShadows ++;
  11880. }
  11881. state.point[ pointLength ] = uniforms;
  11882. pointLength ++;
  11883. } else if ( light.isHemisphereLight ) {
  11884. const uniforms = cache.get( light );
  11885. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  11886. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  11887. state.hemi[ hemiLength ] = uniforms;
  11888. hemiLength ++;
  11889. }
  11890. }
  11891. if ( rectAreaLength > 0 ) {
  11892. if ( capabilities.isWebGL2 ) {
  11893. // WebGL 2
  11894. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11895. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11896. } else {
  11897. // WebGL 1
  11898. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  11899. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11900. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11901. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  11902. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11903. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11904. } else {
  11905. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  11906. }
  11907. }
  11908. }
  11909. state.ambient[ 0 ] = r;
  11910. state.ambient[ 1 ] = g;
  11911. state.ambient[ 2 ] = b;
  11912. const hash = state.hash;
  11913. if ( hash.directionalLength !== directionalLength ||
  11914. hash.pointLength !== pointLength ||
  11915. hash.spotLength !== spotLength ||
  11916. hash.rectAreaLength !== rectAreaLength ||
  11917. hash.hemiLength !== hemiLength ||
  11918. hash.numDirectionalShadows !== numDirectionalShadows ||
  11919. hash.numPointShadows !== numPointShadows ||
  11920. hash.numSpotShadows !== numSpotShadows ) {
  11921. state.directional.length = directionalLength;
  11922. state.spot.length = spotLength;
  11923. state.rectArea.length = rectAreaLength;
  11924. state.point.length = pointLength;
  11925. state.hemi.length = hemiLength;
  11926. state.directionalShadow.length = numDirectionalShadows;
  11927. state.directionalShadowMap.length = numDirectionalShadows;
  11928. state.pointShadow.length = numPointShadows;
  11929. state.pointShadowMap.length = numPointShadows;
  11930. state.spotShadow.length = numSpotShadows;
  11931. state.spotShadowMap.length = numSpotShadows;
  11932. state.directionalShadowMatrix.length = numDirectionalShadows;
  11933. state.pointShadowMatrix.length = numPointShadows;
  11934. state.spotShadowMatrix.length = numSpotShadows;
  11935. hash.directionalLength = directionalLength;
  11936. hash.pointLength = pointLength;
  11937. hash.spotLength = spotLength;
  11938. hash.rectAreaLength = rectAreaLength;
  11939. hash.hemiLength = hemiLength;
  11940. hash.numDirectionalShadows = numDirectionalShadows;
  11941. hash.numPointShadows = numPointShadows;
  11942. hash.numSpotShadows = numSpotShadows;
  11943. state.version = nextVersion ++;
  11944. }
  11945. }
  11946. function setupView( lights, camera ) {
  11947. let directionalLength = 0;
  11948. let pointLength = 0;
  11949. let spotLength = 0;
  11950. let rectAreaLength = 0;
  11951. let hemiLength = 0;
  11952. const viewMatrix = camera.matrixWorldInverse;
  11953. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11954. const light = lights[ i ];
  11955. if ( light.isDirectionalLight ) {
  11956. const uniforms = state.directional[ directionalLength ];
  11957. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11958. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11959. uniforms.direction.sub( vector3 );
  11960. uniforms.direction.transformDirection( viewMatrix );
  11961. directionalLength ++;
  11962. } else if ( light.isSpotLight ) {
  11963. const uniforms = state.spot[ spotLength ];
  11964. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11965. uniforms.position.applyMatrix4( viewMatrix );
  11966. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11967. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11968. uniforms.direction.sub( vector3 );
  11969. uniforms.direction.transformDirection( viewMatrix );
  11970. spotLength ++;
  11971. } else if ( light.isRectAreaLight ) {
  11972. const uniforms = state.rectArea[ rectAreaLength ];
  11973. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11974. uniforms.position.applyMatrix4( viewMatrix );
  11975. // extract local rotation of light to derive width/height half vectors
  11976. matrix42.identity();
  11977. matrix4.copy( light.matrixWorld );
  11978. matrix4.premultiply( viewMatrix );
  11979. matrix42.extractRotation( matrix4 );
  11980. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11981. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11982. uniforms.halfWidth.applyMatrix4( matrix42 );
  11983. uniforms.halfHeight.applyMatrix4( matrix42 );
  11984. rectAreaLength ++;
  11985. } else if ( light.isPointLight ) {
  11986. const uniforms = state.point[ pointLength ];
  11987. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11988. uniforms.position.applyMatrix4( viewMatrix );
  11989. pointLength ++;
  11990. } else if ( light.isHemisphereLight ) {
  11991. const uniforms = state.hemi[ hemiLength ];
  11992. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11993. uniforms.direction.transformDirection( viewMatrix );
  11994. uniforms.direction.normalize();
  11995. hemiLength ++;
  11996. }
  11997. }
  11998. }
  11999. return {
  12000. setup: setup,
  12001. setupView: setupView,
  12002. state: state
  12003. };
  12004. }
  12005. function WebGLRenderState( extensions, capabilities ) {
  12006. const lights = new WebGLLights( extensions, capabilities );
  12007. const lightsArray = [];
  12008. const shadowsArray = [];
  12009. function init() {
  12010. lightsArray.length = 0;
  12011. shadowsArray.length = 0;
  12012. }
  12013. function pushLight( light ) {
  12014. lightsArray.push( light );
  12015. }
  12016. function pushShadow( shadowLight ) {
  12017. shadowsArray.push( shadowLight );
  12018. }
  12019. function setupLights() {
  12020. lights.setup( lightsArray );
  12021. }
  12022. function setupLightsView( camera ) {
  12023. lights.setupView( lightsArray, camera );
  12024. }
  12025. const state = {
  12026. lightsArray: lightsArray,
  12027. shadowsArray: shadowsArray,
  12028. lights: lights
  12029. };
  12030. return {
  12031. init: init,
  12032. state: state,
  12033. setupLights: setupLights,
  12034. setupLightsView: setupLightsView,
  12035. pushLight: pushLight,
  12036. pushShadow: pushShadow
  12037. };
  12038. }
  12039. function WebGLRenderStates( extensions, capabilities ) {
  12040. let renderStates = new WeakMap();
  12041. function get( scene, renderCallDepth = 0 ) {
  12042. let renderState;
  12043. if ( renderStates.has( scene ) === false ) {
  12044. renderState = new WebGLRenderState( extensions, capabilities );
  12045. renderStates.set( scene, [] );
  12046. renderStates.get( scene ).push( renderState );
  12047. } else {
  12048. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12049. renderState = new WebGLRenderState( extensions, capabilities );
  12050. renderStates.get( scene ).push( renderState );
  12051. } else {
  12052. renderState = renderStates.get( scene )[ renderCallDepth ];
  12053. }
  12054. }
  12055. return renderState;
  12056. }
  12057. function dispose() {
  12058. renderStates = new WeakMap();
  12059. }
  12060. return {
  12061. get: get,
  12062. dispose: dispose
  12063. };
  12064. }
  12065. /**
  12066. * parameters = {
  12067. *
  12068. * opacity: <float>,
  12069. *
  12070. * map: new THREE.Texture( <Image> ),
  12071. *
  12072. * alphaMap: new THREE.Texture( <Image> ),
  12073. *
  12074. * displacementMap: new THREE.Texture( <Image> ),
  12075. * displacementScale: <float>,
  12076. * displacementBias: <float>,
  12077. *
  12078. * wireframe: <boolean>,
  12079. * wireframelineWidth: <float>
  12080. * }
  12081. */
  12082. function MeshDepthMaterial( parameters ) {
  12083. Material.call( this );
  12084. this.type = 'MeshDepthMaterial';
  12085. this.depthPacking = BasicDepthPacking;
  12086. this.skinning = false;
  12087. this.morphTargets = false;
  12088. this.map = null;
  12089. this.alphaMap = null;
  12090. this.displacementMap = null;
  12091. this.displacementScale = 1;
  12092. this.displacementBias = 0;
  12093. this.wireframe = false;
  12094. this.wireframelineWidth = 1;
  12095. this.fog = false;
  12096. this.setValues( parameters );
  12097. }
  12098. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  12099. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12100. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12101. MeshDepthMaterial.prototype.copy = function ( source ) {
  12102. Material.prototype.copy.call( this, source );
  12103. this.depthPacking = source.depthPacking;
  12104. this.skinning = source.skinning;
  12105. this.morphTargets = source.morphTargets;
  12106. this.map = source.map;
  12107. this.alphaMap = source.alphaMap;
  12108. this.displacementMap = source.displacementMap;
  12109. this.displacementScale = source.displacementScale;
  12110. this.displacementBias = source.displacementBias;
  12111. this.wireframe = source.wireframe;
  12112. this.wireframelineWidth = source.wireframelineWidth;
  12113. return this;
  12114. };
  12115. /**
  12116. * parameters = {
  12117. *
  12118. * referencePosition: <float>,
  12119. * nearDistance: <float>,
  12120. * farDistance: <float>,
  12121. *
  12122. * skinning: <bool>,
  12123. * morphTargets: <bool>,
  12124. *
  12125. * map: new THREE.Texture( <Image> ),
  12126. *
  12127. * alphaMap: new THREE.Texture( <Image> ),
  12128. *
  12129. * displacementMap: new THREE.Texture( <Image> ),
  12130. * displacementScale: <float>,
  12131. * displacementBias: <float>
  12132. *
  12133. * }
  12134. */
  12135. function MeshDistanceMaterial( parameters ) {
  12136. Material.call( this );
  12137. this.type = 'MeshDistanceMaterial';
  12138. this.referencePosition = new Vector3();
  12139. this.nearDistance = 1;
  12140. this.farDistance = 1000;
  12141. this.skinning = false;
  12142. this.morphTargets = false;
  12143. this.map = null;
  12144. this.alphaMap = null;
  12145. this.displacementMap = null;
  12146. this.displacementScale = 1;
  12147. this.displacementBias = 0;
  12148. this.fog = false;
  12149. this.setValues( parameters );
  12150. }
  12151. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  12152. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12153. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12154. MeshDistanceMaterial.prototype.copy = function ( source ) {
  12155. Material.prototype.copy.call( this, source );
  12156. this.referencePosition.copy( source.referencePosition );
  12157. this.nearDistance = source.nearDistance;
  12158. this.farDistance = source.farDistance;
  12159. this.skinning = source.skinning;
  12160. this.morphTargets = source.morphTargets;
  12161. this.map = source.map;
  12162. this.alphaMap = source.alphaMap;
  12163. this.displacementMap = source.displacementMap;
  12164. this.displacementScale = source.displacementScale;
  12165. this.displacementBias = source.displacementBias;
  12166. return this;
  12167. };
  12168. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12169. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12170. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  12171. let _frustum = new Frustum();
  12172. const _shadowMapSize = new Vector2$1(),
  12173. _viewportSize = new Vector2$1(),
  12174. _viewport = new Vector4(),
  12175. _depthMaterials = [],
  12176. _distanceMaterials = [],
  12177. _materialCache = {};
  12178. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12179. const shadowMaterialVertical = new ShaderMaterial( {
  12180. defines: {
  12181. SAMPLE_RATE: 2.0 / 8.0,
  12182. HALF_SAMPLE_RATE: 1.0 / 8.0
  12183. },
  12184. uniforms: {
  12185. shadow_pass: { value: null },
  12186. resolution: { value: new Vector2$1() },
  12187. radius: { value: 4.0 }
  12188. },
  12189. vertexShader: vsm_vert,
  12190. fragmentShader: vsm_frag
  12191. } );
  12192. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12193. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12194. const fullScreenTri = new BufferGeometry();
  12195. fullScreenTri.setAttribute(
  12196. 'position',
  12197. new BufferAttribute(
  12198. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12199. 3
  12200. )
  12201. );
  12202. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12203. const scope = this;
  12204. this.enabled = false;
  12205. this.autoUpdate = true;
  12206. this.needsUpdate = false;
  12207. this.type = PCFShadowMap;
  12208. this.render = function ( lights, scene, camera ) {
  12209. if ( scope.enabled === false ) return;
  12210. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12211. if ( lights.length === 0 ) return;
  12212. const currentRenderTarget = _renderer.getRenderTarget();
  12213. const activeCubeFace = _renderer.getActiveCubeFace();
  12214. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12215. const _state = _renderer.state;
  12216. // Set GL state for depth map.
  12217. _state.setBlending( NoBlending );
  12218. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12219. _state.buffers.depth.setTest( true );
  12220. _state.setScissorTest( false );
  12221. // render depth map
  12222. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12223. const light = lights[ i ];
  12224. const shadow = light.shadow;
  12225. if ( shadow === undefined ) {
  12226. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12227. continue;
  12228. }
  12229. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12230. _shadowMapSize.copy( shadow.mapSize );
  12231. const shadowFrameExtents = shadow.getFrameExtents();
  12232. _shadowMapSize.multiply( shadowFrameExtents );
  12233. _viewportSize.copy( shadow.mapSize );
  12234. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  12235. if ( _shadowMapSize.x > maxTextureSize ) {
  12236. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  12237. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12238. shadow.mapSize.x = _viewportSize.x;
  12239. }
  12240. if ( _shadowMapSize.y > maxTextureSize ) {
  12241. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  12242. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12243. shadow.mapSize.y = _viewportSize.y;
  12244. }
  12245. }
  12246. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12247. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12248. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12249. shadow.map.texture.name = light.name + '.shadowMap';
  12250. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12251. shadow.camera.updateProjectionMatrix();
  12252. }
  12253. if ( shadow.map === null ) {
  12254. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12255. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12256. shadow.map.texture.name = light.name + '.shadowMap';
  12257. shadow.camera.updateProjectionMatrix();
  12258. }
  12259. _renderer.setRenderTarget( shadow.map );
  12260. _renderer.clear();
  12261. const viewportCount = shadow.getViewportCount();
  12262. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12263. const viewport = shadow.getViewport( vp );
  12264. _viewport.set(
  12265. _viewportSize.x * viewport.x,
  12266. _viewportSize.y * viewport.y,
  12267. _viewportSize.x * viewport.z,
  12268. _viewportSize.y * viewport.w
  12269. );
  12270. _state.viewport( _viewport );
  12271. shadow.updateMatrices( light, vp );
  12272. _frustum = shadow.getFrustum();
  12273. renderObject( scene, camera, shadow.camera, light, this.type );
  12274. }
  12275. // do blur pass for VSM
  12276. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12277. VSMPass( shadow, camera );
  12278. }
  12279. shadow.needsUpdate = false;
  12280. }
  12281. scope.needsUpdate = false;
  12282. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12283. };
  12284. function VSMPass( shadow, camera ) {
  12285. const geometry = _objects.update( fullScreenMesh );
  12286. // vertical pass
  12287. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12288. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12289. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12290. _renderer.setRenderTarget( shadow.mapPass );
  12291. _renderer.clear();
  12292. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12293. // horizontal pass
  12294. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12295. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12296. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12297. _renderer.setRenderTarget( shadow.map );
  12298. _renderer.clear();
  12299. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12300. }
  12301. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12302. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12303. let material = _depthMaterials[ index ];
  12304. if ( material === undefined ) {
  12305. material = new MeshDepthMaterial( {
  12306. depthPacking: RGBADepthPacking,
  12307. morphTargets: useMorphing,
  12308. skinning: useSkinning
  12309. } );
  12310. _depthMaterials[ index ] = material;
  12311. }
  12312. return material;
  12313. }
  12314. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12315. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12316. let material = _distanceMaterials[ index ];
  12317. if ( material === undefined ) {
  12318. material = new MeshDistanceMaterial( {
  12319. morphTargets: useMorphing,
  12320. skinning: useSkinning
  12321. } );
  12322. _distanceMaterials[ index ] = material;
  12323. }
  12324. return material;
  12325. }
  12326. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12327. let result = null;
  12328. let getMaterialVariant = getDepthMaterialVariant;
  12329. let customMaterial = object.customDepthMaterial;
  12330. if ( light.isPointLight === true ) {
  12331. getMaterialVariant = getDistanceMaterialVariant;
  12332. customMaterial = object.customDistanceMaterial;
  12333. }
  12334. if ( customMaterial === undefined ) {
  12335. let useMorphing = false;
  12336. if ( material.morphTargets === true ) {
  12337. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12338. }
  12339. let useSkinning = false;
  12340. if ( object.isSkinnedMesh === true ) {
  12341. if ( material.skinning === true ) {
  12342. useSkinning = true;
  12343. } else {
  12344. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  12345. }
  12346. }
  12347. const useInstancing = object.isInstancedMesh === true;
  12348. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  12349. } else {
  12350. result = customMaterial;
  12351. }
  12352. if ( _renderer.localClippingEnabled &&
  12353. material.clipShadows === true &&
  12354. material.clippingPlanes.length !== 0 ) {
  12355. // in this case we need a unique material instance reflecting the
  12356. // appropriate state
  12357. const keyA = result.uuid, keyB = material.uuid;
  12358. let materialsForVariant = _materialCache[ keyA ];
  12359. if ( materialsForVariant === undefined ) {
  12360. materialsForVariant = {};
  12361. _materialCache[ keyA ] = materialsForVariant;
  12362. }
  12363. let cachedMaterial = materialsForVariant[ keyB ];
  12364. if ( cachedMaterial === undefined ) {
  12365. cachedMaterial = result.clone();
  12366. materialsForVariant[ keyB ] = cachedMaterial;
  12367. }
  12368. result = cachedMaterial;
  12369. }
  12370. result.visible = material.visible;
  12371. result.wireframe = material.wireframe;
  12372. if ( type === VSMShadowMap ) {
  12373. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12374. } else {
  12375. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12376. }
  12377. result.clipShadows = material.clipShadows;
  12378. result.clippingPlanes = material.clippingPlanes;
  12379. result.clipIntersection = material.clipIntersection;
  12380. result.wireframelineWidth = material.wireframelineWidth;
  12381. result.lineWidth = material.lineWidth;
  12382. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12383. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12384. result.nearDistance = shadowCameraNear;
  12385. result.farDistance = shadowCameraFar;
  12386. }
  12387. return result;
  12388. }
  12389. function renderObject( object, camera, shadowCamera, light, type ) {
  12390. if ( object.visible === false ) return;
  12391. const visible = object.layers.test( camera.layers );
  12392. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12393. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12394. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12395. const geometry = _objects.update( object );
  12396. const material = object.material;
  12397. if ( Array.isArray( material ) ) {
  12398. const groups = geometry.groups;
  12399. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12400. const group = groups[ k ];
  12401. const groupMaterial = material[ group.materialIndex ];
  12402. if ( groupMaterial && groupMaterial.visible ) {
  12403. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12404. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12405. }
  12406. }
  12407. } else if ( material.visible ) {
  12408. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12409. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12410. }
  12411. }
  12412. }
  12413. const children = object.children;
  12414. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12415. renderObject( children[ i ], camera, shadowCamera, light, type );
  12416. }
  12417. }
  12418. }
  12419. function WebGLState( gl, extensions, capabilities ) {
  12420. const isWebGL2 = capabilities.isWebGL2;
  12421. function ColorBuffer() {
  12422. let locked = false;
  12423. const color = new Vector4();
  12424. let currentColorMask = null;
  12425. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12426. return {
  12427. setMask: function ( colorMask ) {
  12428. if ( currentColorMask !== colorMask && ! locked ) {
  12429. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12430. currentColorMask = colorMask;
  12431. }
  12432. },
  12433. setLocked: function ( lock ) {
  12434. locked = lock;
  12435. },
  12436. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12437. if ( premultipliedAlpha === true ) {
  12438. r *= a; g *= a; b *= a;
  12439. }
  12440. color.set( r, g, b, a );
  12441. if ( currentColorClear.equals( color ) === false ) {
  12442. gl.clearColor( r, g, b, a );
  12443. currentColorClear.copy( color );
  12444. }
  12445. },
  12446. reset: function () {
  12447. locked = false;
  12448. currentColorMask = null;
  12449. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12450. }
  12451. };
  12452. }
  12453. function DepthBuffer() {
  12454. let locked = false;
  12455. let currentDepthMask = null;
  12456. let currentDepthFunc = null;
  12457. let currentDepthClear = null;
  12458. return {
  12459. setTest: function ( depthTest ) {
  12460. if ( depthTest ) {
  12461. enable( 2929 );
  12462. } else {
  12463. disable( 2929 );
  12464. }
  12465. },
  12466. setMask: function ( depthMask ) {
  12467. if ( currentDepthMask !== depthMask && ! locked ) {
  12468. gl.depthMask( depthMask );
  12469. currentDepthMask = depthMask;
  12470. }
  12471. },
  12472. setFunc: function ( depthFunc ) {
  12473. if ( currentDepthFunc !== depthFunc ) {
  12474. if ( depthFunc ) {
  12475. switch ( depthFunc ) {
  12476. case NeverDepth:
  12477. gl.depthFunc( 512 );
  12478. break;
  12479. case AlwaysDepth:
  12480. gl.depthFunc( 519 );
  12481. break;
  12482. case LessDepth:
  12483. gl.depthFunc( 513 );
  12484. break;
  12485. case LessEqualDepth:
  12486. gl.depthFunc( 515 );
  12487. break;
  12488. case EqualDepth:
  12489. gl.depthFunc( 514 );
  12490. break;
  12491. case GreaterEqualDepth:
  12492. gl.depthFunc( 518 );
  12493. break;
  12494. case GreaterDepth:
  12495. gl.depthFunc( 516 );
  12496. break;
  12497. case NotEqualDepth:
  12498. gl.depthFunc( 517 );
  12499. break;
  12500. default:
  12501. gl.depthFunc( 515 );
  12502. }
  12503. } else {
  12504. gl.depthFunc( 515 );
  12505. }
  12506. currentDepthFunc = depthFunc;
  12507. }
  12508. },
  12509. setLocked: function ( lock ) {
  12510. locked = lock;
  12511. },
  12512. setClear: function ( depth ) {
  12513. if ( currentDepthClear !== depth ) {
  12514. gl.clearDepth( depth );
  12515. currentDepthClear = depth;
  12516. }
  12517. },
  12518. reset: function () {
  12519. locked = false;
  12520. currentDepthMask = null;
  12521. currentDepthFunc = null;
  12522. currentDepthClear = null;
  12523. }
  12524. };
  12525. }
  12526. function StencilBuffer() {
  12527. let locked = false;
  12528. let currentStencilMask = null;
  12529. let currentStencilFunc = null;
  12530. let currentStencilRef = null;
  12531. let currentStencilFuncMask = null;
  12532. let currentStencilFail = null;
  12533. let currentStencilZFail = null;
  12534. let currentStencilZPass = null;
  12535. let currentStencilClear = null;
  12536. return {
  12537. setTest: function ( stencilTest ) {
  12538. if ( ! locked ) {
  12539. if ( stencilTest ) {
  12540. enable( 2960 );
  12541. } else {
  12542. disable( 2960 );
  12543. }
  12544. }
  12545. },
  12546. setMask: function ( stencilMask ) {
  12547. if ( currentStencilMask !== stencilMask && ! locked ) {
  12548. gl.stencilMask( stencilMask );
  12549. currentStencilMask = stencilMask;
  12550. }
  12551. },
  12552. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12553. if ( currentStencilFunc !== stencilFunc ||
  12554. currentStencilRef !== stencilRef ||
  12555. currentStencilFuncMask !== stencilMask ) {
  12556. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12557. currentStencilFunc = stencilFunc;
  12558. currentStencilRef = stencilRef;
  12559. currentStencilFuncMask = stencilMask;
  12560. }
  12561. },
  12562. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12563. if ( currentStencilFail !== stencilFail ||
  12564. currentStencilZFail !== stencilZFail ||
  12565. currentStencilZPass !== stencilZPass ) {
  12566. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12567. currentStencilFail = stencilFail;
  12568. currentStencilZFail = stencilZFail;
  12569. currentStencilZPass = stencilZPass;
  12570. }
  12571. },
  12572. setLocked: function ( lock ) {
  12573. locked = lock;
  12574. },
  12575. setClear: function ( stencil ) {
  12576. if ( currentStencilClear !== stencil ) {
  12577. gl.clearStencil( stencil );
  12578. currentStencilClear = stencil;
  12579. }
  12580. },
  12581. reset: function () {
  12582. locked = false;
  12583. currentStencilMask = null;
  12584. currentStencilFunc = null;
  12585. currentStencilRef = null;
  12586. currentStencilFuncMask = null;
  12587. currentStencilFail = null;
  12588. currentStencilZFail = null;
  12589. currentStencilZPass = null;
  12590. currentStencilClear = null;
  12591. }
  12592. };
  12593. }
  12594. //
  12595. const colorBuffer = new ColorBuffer();
  12596. const depthBuffer = new DepthBuffer();
  12597. const stencilBuffer = new StencilBuffer();
  12598. let enabledCapabilities = {};
  12599. let currentProgram = null;
  12600. let currentBlendingEnabled = null;
  12601. let currentBlending = null;
  12602. let currentBlendEquation = null;
  12603. let currentBlendSrc = null;
  12604. let currentBlendDst = null;
  12605. let currentBlendEquationAlpha = null;
  12606. let currentBlendSrcAlpha = null;
  12607. let currentBlendDstAlpha = null;
  12608. let currentPremultipledAlpha = false;
  12609. let currentFlipSided = null;
  12610. let currentCullFace = null;
  12611. let currentlineWidth = null;
  12612. let currentPolygonOffsetFactor = null;
  12613. let currentPolygonOffsetUnits = null;
  12614. const maxTextures = gl.getParameter( 35661 );
  12615. let lineWidthAvailable = false;
  12616. let version = 0;
  12617. const glVersion = gl.getParameter( 7938 );
  12618. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12619. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12620. lineWidthAvailable = ( version >= 1.0 );
  12621. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12622. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12623. lineWidthAvailable = ( version >= 2.0 );
  12624. }
  12625. let currentTextureSlot = null;
  12626. let currentBoundTextures = {};
  12627. const currentScissor = new Vector4();
  12628. const currentViewport = new Vector4();
  12629. function createTexture( type, target, count ) {
  12630. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12631. const texture = gl.createTexture();
  12632. gl.bindTexture( type, texture );
  12633. gl.texParameteri( type, 10241, 9728 );
  12634. gl.texParameteri( type, 10240, 9728 );
  12635. for ( let i = 0; i < count; i ++ ) {
  12636. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12637. }
  12638. return texture;
  12639. }
  12640. const emptyTextures = {};
  12641. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12642. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12643. // init
  12644. colorBuffer.setClear( 0, 0, 0, 1 );
  12645. depthBuffer.setClear( 1 );
  12646. stencilBuffer.setClear( 0 );
  12647. enable( 2929 );
  12648. depthBuffer.setFunc( LessEqualDepth );
  12649. setFlipSided( false );
  12650. setCullFace( CullFaceBack );
  12651. enable( 2884 );
  12652. setBlending( NoBlending );
  12653. //
  12654. function enable( id ) {
  12655. if ( enabledCapabilities[ id ] !== true ) {
  12656. gl.enable( id );
  12657. enabledCapabilities[ id ] = true;
  12658. }
  12659. }
  12660. function disable( id ) {
  12661. if ( enabledCapabilities[ id ] !== false ) {
  12662. gl.disable( id );
  12663. enabledCapabilities[ id ] = false;
  12664. }
  12665. }
  12666. function useProgram( program ) {
  12667. if ( currentProgram !== program ) {
  12668. gl.useProgram( program );
  12669. currentProgram = program;
  12670. return true;
  12671. }
  12672. return false;
  12673. }
  12674. const equationToGL = {
  12675. [ AddEquation ]: 32774,
  12676. [ SubtractEquation ]: 32778,
  12677. [ ReverseSubtractEquation ]: 32779
  12678. };
  12679. if ( isWebGL2 ) {
  12680. equationToGL[ MinEquation ] = 32775;
  12681. equationToGL[ MaxEquation ] = 32776;
  12682. } else {
  12683. const extension = extensions.get( 'EXT_blend_minmax' );
  12684. if ( extension !== null ) {
  12685. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12686. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12687. }
  12688. }
  12689. const factorToGL = {
  12690. [ ZeroFactor ]: 0,
  12691. [ OneFactor ]: 1,
  12692. [ SrcColorFactor ]: 768,
  12693. [ SrcAlphaFactor ]: 770,
  12694. [ SrcAlphaSaturateFactor ]: 776,
  12695. [ DstColorFactor ]: 774,
  12696. [ DstAlphaFactor ]: 772,
  12697. [ OneMinusSrcColorFactor ]: 769,
  12698. [ OneMinusSrcAlphaFactor ]: 771,
  12699. [ OneMinusDstColorFactor ]: 775,
  12700. [ OneMinusDstAlphaFactor ]: 773
  12701. };
  12702. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12703. if ( blending === NoBlending ) {
  12704. if ( currentBlendingEnabled ) {
  12705. disable( 3042 );
  12706. currentBlendingEnabled = false;
  12707. }
  12708. return;
  12709. }
  12710. if ( ! currentBlendingEnabled ) {
  12711. enable( 3042 );
  12712. currentBlendingEnabled = true;
  12713. }
  12714. if ( blending !== CustomBlending ) {
  12715. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12716. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12717. gl.blendEquation( 32774 );
  12718. currentBlendEquation = AddEquation;
  12719. currentBlendEquationAlpha = AddEquation;
  12720. }
  12721. if ( premultipliedAlpha ) {
  12722. switch ( blending ) {
  12723. case NormalBlending:
  12724. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12725. break;
  12726. case AdditiveBlending:
  12727. gl.blendFunc( 1, 1 );
  12728. break;
  12729. case SubtractiveBlending:
  12730. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12731. break;
  12732. case MultiplyBlending:
  12733. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12734. break;
  12735. default:
  12736. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12737. break;
  12738. }
  12739. } else {
  12740. switch ( blending ) {
  12741. case NormalBlending:
  12742. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12743. break;
  12744. case AdditiveBlending:
  12745. gl.blendFunc( 770, 1 );
  12746. break;
  12747. case SubtractiveBlending:
  12748. gl.blendFunc( 0, 769 );
  12749. break;
  12750. case MultiplyBlending:
  12751. gl.blendFunc( 0, 768 );
  12752. break;
  12753. default:
  12754. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12755. break;
  12756. }
  12757. }
  12758. currentBlendSrc = null;
  12759. currentBlendDst = null;
  12760. currentBlendSrcAlpha = null;
  12761. currentBlendDstAlpha = null;
  12762. currentBlending = blending;
  12763. currentPremultipledAlpha = premultipliedAlpha;
  12764. }
  12765. return;
  12766. }
  12767. // custom blending
  12768. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12769. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12770. blendDstAlpha = blendDstAlpha || blendDst;
  12771. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12772. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12773. currentBlendEquation = blendEquation;
  12774. currentBlendEquationAlpha = blendEquationAlpha;
  12775. }
  12776. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12777. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12778. currentBlendSrc = blendSrc;
  12779. currentBlendDst = blendDst;
  12780. currentBlendSrcAlpha = blendSrcAlpha;
  12781. currentBlendDstAlpha = blendDstAlpha;
  12782. }
  12783. currentBlending = blending;
  12784. currentPremultipledAlpha = null;
  12785. }
  12786. function setMaterial( material, frontFaceCW ) {
  12787. material.side === DoubleSide
  12788. ? disable( 2884 )
  12789. : enable( 2884 );
  12790. let flipSided = ( material.side === BackSide );
  12791. if ( frontFaceCW ) flipSided = ! flipSided;
  12792. setFlipSided( flipSided );
  12793. ( material.blending === NormalBlending && material.transparent === false )
  12794. ? setBlending( NoBlending )
  12795. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12796. depthBuffer.setFunc( material.depthFunc );
  12797. depthBuffer.setTest( material.depthTest );
  12798. depthBuffer.setMask( material.depthWrite );
  12799. colorBuffer.setMask( material.colorWrite );
  12800. const stencilWrite = material.stencilWrite;
  12801. stencilBuffer.setTest( stencilWrite );
  12802. if ( stencilWrite ) {
  12803. stencilBuffer.setMask( material.stencilWriteMask );
  12804. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12805. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12806. }
  12807. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12808. }
  12809. //
  12810. function setFlipSided( flipSided ) {
  12811. if ( currentFlipSided !== flipSided ) {
  12812. if ( flipSided ) {
  12813. gl.frontFace( 2304 );
  12814. } else {
  12815. gl.frontFace( 2305 );
  12816. }
  12817. currentFlipSided = flipSided;
  12818. }
  12819. }
  12820. function setCullFace( cullFace ) {
  12821. if ( cullFace !== CullFaceNone ) {
  12822. enable( 2884 );
  12823. if ( cullFace !== currentCullFace ) {
  12824. if ( cullFace === CullFaceBack ) {
  12825. gl.cullFace( 1029 );
  12826. } else if ( cullFace === CullFaceFront ) {
  12827. gl.cullFace( 1028 );
  12828. } else {
  12829. gl.cullFace( 1032 );
  12830. }
  12831. }
  12832. } else {
  12833. disable( 2884 );
  12834. }
  12835. currentCullFace = cullFace;
  12836. }
  12837. function setlineWidth( width ) {
  12838. if ( width !== currentlineWidth ) {
  12839. if ( lineWidthAvailable ) gl.lineWidth( width );
  12840. currentlineWidth = width;
  12841. }
  12842. }
  12843. function setPolygonOffset( polygonOffset, factor, units ) {
  12844. if ( polygonOffset ) {
  12845. enable( 32823 );
  12846. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12847. gl.polygonOffset( factor, units );
  12848. currentPolygonOffsetFactor = factor;
  12849. currentPolygonOffsetUnits = units;
  12850. }
  12851. } else {
  12852. disable( 32823 );
  12853. }
  12854. }
  12855. function setScissorTest( scissorTest ) {
  12856. if ( scissorTest ) {
  12857. enable( 3089 );
  12858. } else {
  12859. disable( 3089 );
  12860. }
  12861. }
  12862. // texture
  12863. function activeTexture( webglSlot ) {
  12864. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12865. if ( currentTextureSlot !== webglSlot ) {
  12866. gl.activeTexture( webglSlot );
  12867. currentTextureSlot = webglSlot;
  12868. }
  12869. }
  12870. function bindTexture( webglType, webglTexture ) {
  12871. if ( currentTextureSlot === null ) {
  12872. activeTexture();
  12873. }
  12874. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12875. if ( boundTexture === undefined ) {
  12876. boundTexture = { type: undefined, texture: undefined };
  12877. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12878. }
  12879. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12880. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12881. boundTexture.type = webglType;
  12882. boundTexture.texture = webglTexture;
  12883. }
  12884. }
  12885. function unbindTexture() {
  12886. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12887. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12888. gl.bindTexture( boundTexture.type, null );
  12889. boundTexture.type = undefined;
  12890. boundTexture.texture = undefined;
  12891. }
  12892. }
  12893. function compressedTexImage2D() {
  12894. try {
  12895. gl.compressedTexImage2D.apply( gl, arguments );
  12896. } catch ( error ) {
  12897. console.error( 'THREE.WebGLState:', error );
  12898. }
  12899. }
  12900. function texImage2D() {
  12901. try {
  12902. gl.texImage2D.apply( gl, arguments );
  12903. } catch ( error ) {
  12904. console.error( 'THREE.WebGLState:', error );
  12905. }
  12906. }
  12907. function texImage3D() {
  12908. try {
  12909. gl.texImage3D.apply( gl, arguments );
  12910. } catch ( error ) {
  12911. console.error( 'THREE.WebGLState:', error );
  12912. }
  12913. }
  12914. //
  12915. function scissor( scissor ) {
  12916. if ( currentScissor.equals( scissor ) === false ) {
  12917. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12918. currentScissor.copy( scissor );
  12919. }
  12920. }
  12921. function viewport( viewport ) {
  12922. if ( currentViewport.equals( viewport ) === false ) {
  12923. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12924. currentViewport.copy( viewport );
  12925. }
  12926. }
  12927. //
  12928. function reset() {
  12929. enabledCapabilities = {};
  12930. currentTextureSlot = null;
  12931. currentBoundTextures = {};
  12932. currentProgram = null;
  12933. currentBlendingEnabled = null;
  12934. currentBlending = null;
  12935. currentBlendEquation = null;
  12936. currentBlendSrc = null;
  12937. currentBlendDst = null;
  12938. currentBlendEquationAlpha = null;
  12939. currentBlendSrcAlpha = null;
  12940. currentBlendDstAlpha = null;
  12941. currentPremultipledAlpha = false;
  12942. currentFlipSided = null;
  12943. currentCullFace = null;
  12944. currentlineWidth = null;
  12945. currentPolygonOffsetFactor = null;
  12946. currentPolygonOffsetUnits = null;
  12947. colorBuffer.reset();
  12948. depthBuffer.reset();
  12949. stencilBuffer.reset();
  12950. }
  12951. return {
  12952. buffers: {
  12953. color: colorBuffer,
  12954. depth: depthBuffer,
  12955. stencil: stencilBuffer
  12956. },
  12957. enable: enable,
  12958. disable: disable,
  12959. useProgram: useProgram,
  12960. setBlending: setBlending,
  12961. setMaterial: setMaterial,
  12962. setFlipSided: setFlipSided,
  12963. setCullFace: setCullFace,
  12964. setlineWidth: setlineWidth,
  12965. setPolygonOffset: setPolygonOffset,
  12966. setScissorTest: setScissorTest,
  12967. activeTexture: activeTexture,
  12968. bindTexture: bindTexture,
  12969. unbindTexture: unbindTexture,
  12970. compressedTexImage2D: compressedTexImage2D,
  12971. texImage2D: texImage2D,
  12972. texImage3D: texImage3D,
  12973. scissor: scissor,
  12974. viewport: viewport,
  12975. reset: reset
  12976. };
  12977. }
  12978. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12979. const isWebGL2 = capabilities.isWebGL2;
  12980. const maxTextures = capabilities.maxTextures;
  12981. const maxCubemapSize = capabilities.maxCubemapSize;
  12982. const maxTextureSize = capabilities.maxTextureSize;
  12983. const maxSamples = capabilities.maxSamples;
  12984. const _videoTextures = new WeakMap();
  12985. let _canvas;
  12986. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12987. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12988. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12989. let useOffscreenCanvas = false;
  12990. try {
  12991. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12992. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12993. } catch ( err ) {
  12994. // Ignore any errors
  12995. }
  12996. function createCanvas( width, height ) {
  12997. // Use OffscreenCanvas when available. Specially needed in web workers
  12998. return useOffscreenCanvas ?
  12999. new OffscreenCanvas( width, height ) :
  13000. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13001. }
  13002. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13003. let scale = 1;
  13004. // handle case if texture exceeds max size
  13005. if ( image.width > maxSize || image.height > maxSize ) {
  13006. scale = maxSize / Math.max( image.width, image.height );
  13007. }
  13008. // only perform resize if necessary
  13009. if ( scale < 1 || needsPowerOfTwo === true ) {
  13010. // only perform resize for certain image types
  13011. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13012. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13013. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13014. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  13015. const width = floor( scale * image.width );
  13016. const height = floor( scale * image.height );
  13017. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13018. // cube textures can't reuse the same canvas
  13019. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13020. canvas.width = width;
  13021. canvas.height = height;
  13022. const context = canvas.getContext( '2d' );
  13023. context.drawImage( image, 0, 0, width, height );
  13024. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13025. return canvas;
  13026. } else {
  13027. if ( 'data' in image ) {
  13028. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13029. }
  13030. return image;
  13031. }
  13032. }
  13033. return image;
  13034. }
  13035. function isPowerOfTwo( image ) {
  13036. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  13037. }
  13038. function textureNeedsPowerOfTwo( texture ) {
  13039. if ( isWebGL2 ) return false;
  13040. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13041. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13042. }
  13043. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13044. return texture.generateMipmaps && supportsMips &&
  13045. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13046. }
  13047. function generateMipmap( target, texture, width, height ) {
  13048. _gl.generateMipmap( target );
  13049. const textureProperties = properties.get( texture );
  13050. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13051. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  13052. }
  13053. function getInternalFormat( internalFormatName, glFormat, glType ) {
  13054. if ( isWebGL2 === false ) return glFormat;
  13055. if ( internalFormatName !== null ) {
  13056. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13057. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13058. }
  13059. let internalFormat = glFormat;
  13060. if ( glFormat === 6403 ) {
  13061. if ( glType === 5126 ) internalFormat = 33326;
  13062. if ( glType === 5131 ) internalFormat = 33325;
  13063. if ( glType === 5121 ) internalFormat = 33321;
  13064. }
  13065. if ( glFormat === 6407 ) {
  13066. if ( glType === 5126 ) internalFormat = 34837;
  13067. if ( glType === 5131 ) internalFormat = 34843;
  13068. if ( glType === 5121 ) internalFormat = 32849;
  13069. }
  13070. if ( glFormat === 6408 ) {
  13071. if ( glType === 5126 ) internalFormat = 34836;
  13072. if ( glType === 5131 ) internalFormat = 34842;
  13073. if ( glType === 5121 ) internalFormat = 32856;
  13074. }
  13075. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13076. internalFormat === 34842 || internalFormat === 34836 ) {
  13077. extensions.get( 'EXT_color_buffer_float' );
  13078. }
  13079. return internalFormat;
  13080. }
  13081. // Fallback filters for non-power-of-2 textures
  13082. function filterFallback( f ) {
  13083. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13084. return 9728;
  13085. }
  13086. return 9729;
  13087. }
  13088. //
  13089. function onTextureDispose( event ) {
  13090. const texture = event.target;
  13091. texture.removeEventListener( 'dispose', onTextureDispose );
  13092. deallocateTexture( texture );
  13093. if ( texture.isVideoTexture ) {
  13094. _videoTextures.delete( texture );
  13095. }
  13096. info.memory.textures --;
  13097. }
  13098. function onRenderTargetDispose( event ) {
  13099. const renderTarget = event.target;
  13100. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13101. deallocateRenderTarget( renderTarget );
  13102. info.memory.textures --;
  13103. }
  13104. //
  13105. function deallocateTexture( texture ) {
  13106. const textureProperties = properties.get( texture );
  13107. if ( textureProperties.__webglInit === undefined ) return;
  13108. _gl.deleteTexture( textureProperties.__webglTexture );
  13109. properties.remove( texture );
  13110. }
  13111. function deallocateRenderTarget( renderTarget ) {
  13112. const renderTargetProperties = properties.get( renderTarget );
  13113. const textureProperties = properties.get( renderTarget.texture );
  13114. if ( ! renderTarget ) return;
  13115. if ( textureProperties.__webglTexture !== undefined ) {
  13116. _gl.deleteTexture( textureProperties.__webglTexture );
  13117. }
  13118. if ( renderTarget.depthTexture ) {
  13119. renderTarget.depthTexture.dispose();
  13120. }
  13121. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13122. for ( let i = 0; i < 6; i ++ ) {
  13123. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13124. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13125. }
  13126. } else {
  13127. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13128. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13129. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13130. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13131. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13132. }
  13133. properties.remove( renderTarget.texture );
  13134. properties.remove( renderTarget );
  13135. }
  13136. //
  13137. let textureUnits = 0;
  13138. function resetTextureUnits() {
  13139. textureUnits = 0;
  13140. }
  13141. function allocateTextureUnit() {
  13142. const textureUnit = textureUnits;
  13143. if ( textureUnit >= maxTextures ) {
  13144. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13145. }
  13146. textureUnits += 1;
  13147. return textureUnit;
  13148. }
  13149. //
  13150. function setTexture2D( texture, slot ) {
  13151. const textureProperties = properties.get( texture );
  13152. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13153. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13154. const image = texture.image;
  13155. if ( image === undefined ) {
  13156. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13157. } else if ( image.complete === false ) {
  13158. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13159. } else {
  13160. uploadTexture( textureProperties, texture, slot );
  13161. return;
  13162. }
  13163. }
  13164. state.activeTexture( 33984 + slot );
  13165. state.bindTexture( 3553, textureProperties.__webglTexture );
  13166. }
  13167. function setTexture2DArray( texture, slot ) {
  13168. const textureProperties = properties.get( texture );
  13169. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13170. uploadTexture( textureProperties, texture, slot );
  13171. return;
  13172. }
  13173. state.activeTexture( 33984 + slot );
  13174. state.bindTexture( 35866, textureProperties.__webglTexture );
  13175. }
  13176. function setTexture3D( texture, slot ) {
  13177. const textureProperties = properties.get( texture );
  13178. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13179. uploadTexture( textureProperties, texture, slot );
  13180. return;
  13181. }
  13182. state.activeTexture( 33984 + slot );
  13183. state.bindTexture( 32879, textureProperties.__webglTexture );
  13184. }
  13185. function setTextureCube( texture, slot ) {
  13186. const textureProperties = properties.get( texture );
  13187. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13188. uploadCubeTexture( textureProperties, texture, slot );
  13189. return;
  13190. }
  13191. state.activeTexture( 33984 + slot );
  13192. state.bindTexture( 34067, textureProperties.__webglTexture );
  13193. }
  13194. const wrappingToGL = {
  13195. [ RepeatWrapping ]: 10497,
  13196. [ ClampToEdgeWrapping ]: 33071,
  13197. [ MirroredRepeatWrapping ]: 33648
  13198. };
  13199. const filterToGL = {
  13200. [ NearestFilter ]: 9728,
  13201. [ NearestMipmapNearestFilter ]: 9984,
  13202. [ NearestMipmapLinearFilter ]: 9986,
  13203. [ LinearFilter ]: 9729,
  13204. [ LinearMipmapNearestFilter ]: 9985,
  13205. [ LinearMipmapLinearFilter ]: 9987
  13206. };
  13207. function setTextureParameters( textureType, texture, supportsMips ) {
  13208. if ( supportsMips ) {
  13209. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13210. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13211. if ( textureType === 32879 || textureType === 35866 ) {
  13212. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13213. }
  13214. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13215. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13216. } else {
  13217. _gl.texParameteri( textureType, 10242, 33071 );
  13218. _gl.texParameteri( textureType, 10243, 33071 );
  13219. if ( textureType === 32879 || textureType === 35866 ) {
  13220. _gl.texParameteri( textureType, 32882, 33071 );
  13221. }
  13222. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13223. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13224. }
  13225. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13226. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13227. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13228. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13229. }
  13230. }
  13231. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13232. if ( extension ) {
  13233. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  13234. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  13235. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13236. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13237. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13238. }
  13239. }
  13240. }
  13241. function initTexture( textureProperties, texture ) {
  13242. if ( textureProperties.__webglInit === undefined ) {
  13243. textureProperties.__webglInit = true;
  13244. texture.addEventListener( 'dispose', onTextureDispose );
  13245. textureProperties.__webglTexture = _gl.createTexture();
  13246. info.memory.textures ++;
  13247. }
  13248. }
  13249. function uploadTexture( textureProperties, texture, slot ) {
  13250. let textureType = 3553;
  13251. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13252. if ( texture.isDataTexture3D ) textureType = 32879;
  13253. initTexture( textureProperties, texture );
  13254. state.activeTexture( 33984 + slot );
  13255. state.bindTexture( textureType, textureProperties.__webglTexture );
  13256. _gl.pixelStorei( 37440, texture.flipY );
  13257. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13258. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13259. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  13260. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13261. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13262. glFormat = utils.convert( texture.format );
  13263. let glType = utils.convert( texture.type ),
  13264. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13265. setTextureParameters( textureType, texture, supportsMips );
  13266. let mipmap;
  13267. const mipmaps = texture.mipmaps;
  13268. if ( texture.isDepthTexture ) {
  13269. // populate depth texture with dummy data
  13270. glInternalFormat = 6402;
  13271. if ( isWebGL2 ) {
  13272. if ( texture.type === FloatType ) {
  13273. glInternalFormat = 36012;
  13274. } else if ( texture.type === UnsignedIntType ) {
  13275. glInternalFormat = 33190;
  13276. } else if ( texture.type === UnsignedInt248Type$1 ) {
  13277. glInternalFormat = 35056;
  13278. } else {
  13279. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13280. }
  13281. } else {
  13282. if ( texture.type === FloatType ) {
  13283. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13284. }
  13285. }
  13286. // validation checks for WebGL 1
  13287. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13288. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13289. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13290. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13291. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13292. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13293. texture.type = UnsignedShortType;
  13294. glType = utils.convert( texture.type );
  13295. }
  13296. }
  13297. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13298. // Depth stencil textures need the DEPTH_STENCIL internal format
  13299. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13300. glInternalFormat = 34041;
  13301. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13302. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13303. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13304. if ( texture.type !== UnsignedInt248Type$1 ) {
  13305. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13306. texture.type = UnsignedInt248Type$1;
  13307. glType = utils.convert( texture.type );
  13308. }
  13309. }
  13310. //
  13311. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13312. } else if ( texture.isDataTexture ) {
  13313. // use manually created mipmaps if available
  13314. // if there are no manual mipmaps
  13315. // set 0 level mipmap and then use GL to generate other mipmap levels
  13316. if ( mipmaps.length > 0 && supportsMips ) {
  13317. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13318. mipmap = mipmaps[ i ];
  13319. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13320. }
  13321. texture.generateMipmaps = false;
  13322. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13323. } else {
  13324. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13325. textureProperties.__maxMipLevel = 0;
  13326. }
  13327. } else if ( texture.isCompressedTexture ) {
  13328. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13329. mipmap = mipmaps[ i ];
  13330. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13331. if ( glFormat !== null ) {
  13332. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13333. } else {
  13334. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13335. }
  13336. } else {
  13337. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13338. }
  13339. }
  13340. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13341. } else if ( texture.isDataTexture2DArray ) {
  13342. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13343. textureProperties.__maxMipLevel = 0;
  13344. } else if ( texture.isDataTexture3D ) {
  13345. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13346. textureProperties.__maxMipLevel = 0;
  13347. } else {
  13348. // regular Texture (image, video, canvas)
  13349. // use manually created mipmaps if available
  13350. // if there are no manual mipmaps
  13351. // set 0 level mipmap and then use GL to generate other mipmap levels
  13352. if ( mipmaps.length > 0 && supportsMips ) {
  13353. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13354. mipmap = mipmaps[ i ];
  13355. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13356. }
  13357. texture.generateMipmaps = false;
  13358. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13359. } else {
  13360. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13361. textureProperties.__maxMipLevel = 0;
  13362. }
  13363. }
  13364. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13365. generateMipmap( textureType, texture, image.width, image.height );
  13366. }
  13367. textureProperties.__version = texture.version;
  13368. if ( texture.onUpdate ) texture.onUpdate( texture );
  13369. }
  13370. function uploadCubeTexture( textureProperties, texture, slot ) {
  13371. if ( texture.image.length !== 6 ) return;
  13372. initTexture( textureProperties, texture );
  13373. state.activeTexture( 33984 + slot );
  13374. state.bindTexture( 34067, textureProperties.__webglTexture );
  13375. _gl.pixelStorei( 37440, texture.flipY );
  13376. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13377. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13378. const cubeImage = [];
  13379. for ( let i = 0; i < 6; i ++ ) {
  13380. if ( ! isCompressed && ! isDataTexture ) {
  13381. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13382. } else {
  13383. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13384. }
  13385. }
  13386. const image = cubeImage[ 0 ],
  13387. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13388. glFormat = utils.convert( texture.format ),
  13389. glType = utils.convert( texture.type ),
  13390. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13391. setTextureParameters( 34067, texture, supportsMips );
  13392. let mipmaps;
  13393. if ( isCompressed ) {
  13394. for ( let i = 0; i < 6; i ++ ) {
  13395. mipmaps = cubeImage[ i ].mipmaps;
  13396. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13397. const mipmap = mipmaps[ j ];
  13398. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13399. if ( glFormat !== null ) {
  13400. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13401. } else {
  13402. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13403. }
  13404. } else {
  13405. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13406. }
  13407. }
  13408. }
  13409. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13410. } else {
  13411. mipmaps = texture.mipmaps;
  13412. for ( let i = 0; i < 6; i ++ ) {
  13413. if ( isDataTexture ) {
  13414. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13415. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13416. const mipmap = mipmaps[ j ];
  13417. const mipmapImage = mipmap.image[ i ].image;
  13418. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13419. }
  13420. } else {
  13421. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13422. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13423. const mipmap = mipmaps[ j ];
  13424. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13425. }
  13426. }
  13427. }
  13428. textureProperties.__maxMipLevel = mipmaps.length;
  13429. }
  13430. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13431. // We assume images for cube map have the same size.
  13432. generateMipmap( 34067, texture, image.width, image.height );
  13433. }
  13434. textureProperties.__version = texture.version;
  13435. if ( texture.onUpdate ) texture.onUpdate( texture );
  13436. }
  13437. // Render targets
  13438. // Setup storage for target texture and bind it to correct framebuffer
  13439. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  13440. const glFormat = utils.convert( renderTarget.texture.format );
  13441. const glType = utils.convert( renderTarget.texture.type );
  13442. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13443. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13444. _gl.bindFramebuffer( 36160, framebuffer );
  13445. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  13446. _gl.bindFramebuffer( 36160, null );
  13447. }
  13448. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13449. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13450. _gl.bindRenderbuffer( 36161, renderbuffer );
  13451. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13452. let glInternalFormat = 33189;
  13453. if ( isMultisample ) {
  13454. const depthTexture = renderTarget.depthTexture;
  13455. if ( depthTexture && depthTexture.isDepthTexture ) {
  13456. if ( depthTexture.type === FloatType ) {
  13457. glInternalFormat = 36012;
  13458. } else if ( depthTexture.type === UnsignedIntType ) {
  13459. glInternalFormat = 33190;
  13460. }
  13461. }
  13462. const samples = getRenderTargetSamples( renderTarget );
  13463. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13464. } else {
  13465. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13466. }
  13467. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13468. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13469. if ( isMultisample ) {
  13470. const samples = getRenderTargetSamples( renderTarget );
  13471. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13472. } else {
  13473. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13474. }
  13475. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13476. } else {
  13477. const glFormat = utils.convert( renderTarget.texture.format );
  13478. const glType = utils.convert( renderTarget.texture.type );
  13479. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13480. if ( isMultisample ) {
  13481. const samples = getRenderTargetSamples( renderTarget );
  13482. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13483. } else {
  13484. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13485. }
  13486. }
  13487. _gl.bindRenderbuffer( 36161, null );
  13488. }
  13489. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13490. function setupDepthTexture( framebuffer, renderTarget ) {
  13491. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13492. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13493. _gl.bindFramebuffer( 36160, framebuffer );
  13494. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13495. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13496. }
  13497. // upload an empty depth texture with framebuffer size
  13498. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13499. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13500. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13501. renderTarget.depthTexture.image.width = renderTarget.width;
  13502. renderTarget.depthTexture.image.height = renderTarget.height;
  13503. renderTarget.depthTexture.needsUpdate = true;
  13504. }
  13505. setTexture2D( renderTarget.depthTexture, 0 );
  13506. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13507. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13508. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13509. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13510. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13511. } else {
  13512. throw new Error( 'Unknown depthTexture format' );
  13513. }
  13514. }
  13515. // Setup GL resources for a non-texture depth buffer
  13516. function setupDepthRenderbuffer( renderTarget ) {
  13517. const renderTargetProperties = properties.get( renderTarget );
  13518. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13519. if ( renderTarget.depthTexture ) {
  13520. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13521. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13522. } else {
  13523. if ( isCube ) {
  13524. renderTargetProperties.__webglDepthbuffer = [];
  13525. for ( let i = 0; i < 6; i ++ ) {
  13526. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13527. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13528. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13529. }
  13530. } else {
  13531. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13532. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13533. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13534. }
  13535. }
  13536. _gl.bindFramebuffer( 36160, null );
  13537. }
  13538. // Set up GL resources for the render target
  13539. function setupRenderTarget( renderTarget ) {
  13540. const renderTargetProperties = properties.get( renderTarget );
  13541. const textureProperties = properties.get( renderTarget.texture );
  13542. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13543. textureProperties.__webglTexture = _gl.createTexture();
  13544. info.memory.textures ++;
  13545. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13546. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  13547. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13548. // Handles WebGL2 RGBFormat fallback - #18858
  13549. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  13550. renderTarget.texture.format = RGBAFormat;
  13551. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13552. }
  13553. // Setup framebuffer
  13554. if ( isCube ) {
  13555. renderTargetProperties.__webglFramebuffer = [];
  13556. for ( let i = 0; i < 6; i ++ ) {
  13557. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13558. }
  13559. } else {
  13560. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13561. if ( isMultisample ) {
  13562. if ( isWebGL2 ) {
  13563. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13564. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13565. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13566. const glFormat = utils.convert( renderTarget.texture.format );
  13567. const glType = utils.convert( renderTarget.texture.type );
  13568. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13569. const samples = getRenderTargetSamples( renderTarget );
  13570. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13571. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13572. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13573. _gl.bindRenderbuffer( 36161, null );
  13574. if ( renderTarget.depthBuffer ) {
  13575. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13576. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13577. }
  13578. _gl.bindFramebuffer( 36160, null );
  13579. } else {
  13580. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13581. }
  13582. }
  13583. }
  13584. // Setup color buffer
  13585. if ( isCube ) {
  13586. state.bindTexture( 34067, textureProperties.__webglTexture );
  13587. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  13588. for ( let i = 0; i < 6; i ++ ) {
  13589. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  13590. }
  13591. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13592. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  13593. }
  13594. state.bindTexture( 34067, null );
  13595. } else {
  13596. state.bindTexture( 3553, textureProperties.__webglTexture );
  13597. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  13598. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  13599. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13600. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  13601. }
  13602. state.bindTexture( 3553, null );
  13603. }
  13604. // Setup depth and stencil buffers
  13605. if ( renderTarget.depthBuffer ) {
  13606. setupDepthRenderbuffer( renderTarget );
  13607. }
  13608. }
  13609. function updateRenderTargetMipmap( renderTarget ) {
  13610. const texture = renderTarget.texture;
  13611. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13612. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13613. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13614. const webglTexture = properties.get( texture ).__webglTexture;
  13615. state.bindTexture( target, webglTexture );
  13616. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  13617. state.bindTexture( target, null );
  13618. }
  13619. }
  13620. function updateMultisampleRenderTarget( renderTarget ) {
  13621. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  13622. if ( isWebGL2 ) {
  13623. const renderTargetProperties = properties.get( renderTarget );
  13624. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  13625. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  13626. const width = renderTarget.width;
  13627. const height = renderTarget.height;
  13628. let mask = 16384;
  13629. if ( renderTarget.depthBuffer ) mask |= 256;
  13630. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13631. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  13632. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  13633. } else {
  13634. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13635. }
  13636. }
  13637. }
  13638. function getRenderTargetSamples( renderTarget ) {
  13639. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  13640. Math.min( maxSamples, renderTarget.samples ) : 0;
  13641. }
  13642. function updateVideoTexture( texture ) {
  13643. const frame = info.render.frame;
  13644. // Check the last frame we updated the VideoTexture
  13645. if ( _videoTextures.get( texture ) !== frame ) {
  13646. _videoTextures.set( texture, frame );
  13647. texture.update();
  13648. }
  13649. }
  13650. // backwards compatibility
  13651. let warnedTexture2D = false;
  13652. let warnedTextureCube = false;
  13653. function safeSetTexture2D( texture, slot ) {
  13654. if ( texture && texture.isWebGLRenderTarget ) {
  13655. if ( warnedTexture2D === false ) {
  13656. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  13657. warnedTexture2D = true;
  13658. }
  13659. texture = texture.texture;
  13660. }
  13661. setTexture2D( texture, slot );
  13662. }
  13663. function safeSetTextureCube( texture, slot ) {
  13664. if ( texture && texture.isWebGLCubeRenderTarget ) {
  13665. if ( warnedTextureCube === false ) {
  13666. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  13667. warnedTextureCube = true;
  13668. }
  13669. texture = texture.texture;
  13670. }
  13671. setTextureCube( texture, slot );
  13672. }
  13673. //
  13674. this.allocateTextureUnit = allocateTextureUnit;
  13675. this.resetTextureUnits = resetTextureUnits;
  13676. this.setTexture2D = setTexture2D;
  13677. this.setTexture2DArray = setTexture2DArray;
  13678. this.setTexture3D = setTexture3D;
  13679. this.setTextureCube = setTextureCube;
  13680. this.setupRenderTarget = setupRenderTarget;
  13681. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13682. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13683. this.safeSetTexture2D = safeSetTexture2D;
  13684. this.safeSetTextureCube = safeSetTextureCube;
  13685. }
  13686. function WebGLUtils( gl, extensions, capabilities ) {
  13687. const isWebGL2 = capabilities.isWebGL2;
  13688. function convert( p ) {
  13689. let extension;
  13690. if ( p === UnsignedByteType ) return 5121;
  13691. if ( p === UnsignedShort4444Type ) return 32819;
  13692. if ( p === UnsignedShort5551Type ) return 32820;
  13693. if ( p === UnsignedShort565Type ) return 33635;
  13694. if ( p === ByteType ) return 5120;
  13695. if ( p === ShortType ) return 5122;
  13696. if ( p === UnsignedShortType ) return 5123;
  13697. if ( p === IntType ) return 5124;
  13698. if ( p === UnsignedIntType ) return 5125;
  13699. if ( p === FloatType ) return 5126;
  13700. if ( p === HalfFloatType ) {
  13701. if ( isWebGL2 ) return 5131;
  13702. extension = extensions.get( 'OES_texture_half_float' );
  13703. if ( extension !== null ) {
  13704. return extension.HALF_FLOAT_OES;
  13705. } else {
  13706. return null;
  13707. }
  13708. }
  13709. if ( p === AlphaFormat ) return 6406;
  13710. if ( p === RGBFormat ) return 6407;
  13711. if ( p === RGBAFormat ) return 6408;
  13712. if ( p === LuminanceFormat ) return 6409;
  13713. if ( p === LuminanceAlphaFormat ) return 6410;
  13714. if ( p === DepthFormat ) return 6402;
  13715. if ( p === DepthStencilFormat ) return 34041;
  13716. if ( p === RedFormat ) return 6403;
  13717. // WebGL2 formats.
  13718. if ( p === RedIntegerFormat ) return 36244;
  13719. if ( p === RGFormat ) return 33319;
  13720. if ( p === RGIntegerFormat ) return 33320;
  13721. if ( p === RGBIntegerFormat ) return 36248;
  13722. if ( p === RGBAIntegerFormat ) return 36249;
  13723. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format$1 ||
  13724. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format$1 ) {
  13725. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13726. if ( extension !== null ) {
  13727. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13728. if ( p === RGBA_S3TC_DXT1_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13729. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13730. if ( p === RGBA_S3TC_DXT5_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13731. } else {
  13732. return null;
  13733. }
  13734. }
  13735. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13736. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13737. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13738. if ( extension !== null ) {
  13739. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13740. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13741. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13742. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13743. } else {
  13744. return null;
  13745. }
  13746. }
  13747. if ( p === RGB_ETC1_Format ) {
  13748. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13749. if ( extension !== null ) {
  13750. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13751. } else {
  13752. return null;
  13753. }
  13754. }
  13755. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13756. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13757. if ( extension !== null ) {
  13758. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13759. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13760. }
  13761. }
  13762. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13763. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13764. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13765. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13766. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13767. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13768. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13769. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13770. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13771. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13772. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13773. if ( extension !== null ) {
  13774. // TODO Complete?
  13775. return p;
  13776. } else {
  13777. return null;
  13778. }
  13779. }
  13780. if ( p === RGBA_BPTC_Format ) {
  13781. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13782. if ( extension !== null ) {
  13783. // TODO Complete?
  13784. return p;
  13785. } else {
  13786. return null;
  13787. }
  13788. }
  13789. if ( p === UnsignedInt248Type$1 ) {
  13790. if ( isWebGL2 ) return 34042;
  13791. extension = extensions.get( 'WEBGL_depth_texture' );
  13792. if ( extension !== null ) {
  13793. return extension.UNSIGNED_INT_24_8_WEBGL;
  13794. } else {
  13795. return null;
  13796. }
  13797. }
  13798. }
  13799. return { convert: convert };
  13800. }
  13801. function ArrayCamera( array = [] ) {
  13802. PerspectiveCamera.call( this );
  13803. this.cameras = array;
  13804. }
  13805. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  13806. constructor: ArrayCamera,
  13807. isArrayCamera: true
  13808. } );
  13809. function Group() {
  13810. Object3D.call( this );
  13811. this.type = 'Group';
  13812. }
  13813. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13814. constructor: Group,
  13815. isGroup: true
  13816. } );
  13817. function WebXRController() {
  13818. this._targetRay = null;
  13819. this._grip = null;
  13820. this._hand = null;
  13821. }
  13822. Object.assign( WebXRController.prototype, {
  13823. constructor: WebXRController,
  13824. getHandSpace: function () {
  13825. if ( this._hand === null ) {
  13826. this._hand = new Group();
  13827. this._hand.matrixAutoUpdate = false;
  13828. this._hand.visible = false;
  13829. this._hand.joints = [];
  13830. this._hand.inputState = { pinching: false };
  13831. if ( window.XRHand ) {
  13832. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13833. // The transform of this joint will be updated with the joint pose on each frame
  13834. const joint = new Group();
  13835. joint.matrixAutoUpdate = false;
  13836. joint.visible = false;
  13837. this._hand.joints.push( joint );
  13838. // ??
  13839. this._hand.add( joint );
  13840. }
  13841. }
  13842. }
  13843. return this._hand;
  13844. },
  13845. getTargetRaySpace: function () {
  13846. if ( this._targetRay === null ) {
  13847. this._targetRay = new Group();
  13848. this._targetRay.matrixAutoUpdate = false;
  13849. this._targetRay.visible = false;
  13850. }
  13851. return this._targetRay;
  13852. },
  13853. getGripSpace: function () {
  13854. if ( this._grip === null ) {
  13855. this._grip = new Group();
  13856. this._grip.matrixAutoUpdate = false;
  13857. this._grip.visible = false;
  13858. }
  13859. return this._grip;
  13860. },
  13861. dispatchEvent: function ( event ) {
  13862. if ( this._targetRay !== null ) {
  13863. this._targetRay.dispatchEvent( event );
  13864. }
  13865. if ( this._grip !== null ) {
  13866. this._grip.dispatchEvent( event );
  13867. }
  13868. if ( this._hand !== null ) {
  13869. this._hand.dispatchEvent( event );
  13870. }
  13871. return this;
  13872. },
  13873. disconnect: function ( inputSource ) {
  13874. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13875. if ( this._targetRay !== null ) {
  13876. this._targetRay.visible = false;
  13877. }
  13878. if ( this._grip !== null ) {
  13879. this._grip.visible = false;
  13880. }
  13881. if ( this._hand !== null ) {
  13882. this._hand.visible = false;
  13883. }
  13884. return this;
  13885. },
  13886. update: function ( inputSource, frame, referenceSpace ) {
  13887. let inputPose = null;
  13888. let gripPose = null;
  13889. let handPose = null;
  13890. const targetRay = this._targetRay;
  13891. const grip = this._grip;
  13892. const hand = this._hand;
  13893. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13894. if ( hand && inputSource.hand ) {
  13895. handPose = true;
  13896. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13897. if ( inputSource.hand[ i ] ) {
  13898. // Update the joints groups with the XRJoint poses
  13899. const jointPose = frame.getJointPose( inputSource.hand[ i ], referenceSpace );
  13900. const joint = hand.joints[ i ];
  13901. if ( jointPose !== null ) {
  13902. joint.matrix.fromArray( jointPose.transform.matrix );
  13903. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13904. joint.jointRadius = jointPose.radius;
  13905. }
  13906. joint.visible = jointPose !== null;
  13907. // Custom events
  13908. // Check pinch
  13909. const indexTip = hand.joints[ window.XRHand.INDEX_PHALANX_TIP ];
  13910. const thumbTip = hand.joints[ window.XRHand.THUMB_PHALANX_TIP ];
  13911. const distance = indexTip.position.distanceTo( thumbTip.position );
  13912. const distanceToPinch = 0.02;
  13913. const threshold = 0.005;
  13914. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13915. hand.inputState.pinching = false;
  13916. this.dispatchEvent( {
  13917. type: 'pinchend',
  13918. handedness: inputSource.handedness,
  13919. target: this
  13920. } );
  13921. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13922. hand.inputState.pinching = true;
  13923. this.dispatchEvent( {
  13924. type: 'pinchstart',
  13925. handedness: inputSource.handedness,
  13926. target: this
  13927. } );
  13928. }
  13929. }
  13930. }
  13931. } else {
  13932. if ( targetRay !== null ) {
  13933. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13934. if ( inputPose !== null ) {
  13935. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13936. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13937. }
  13938. }
  13939. if ( grip !== null && inputSource.gripSpace ) {
  13940. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13941. if ( gripPose !== null ) {
  13942. grip.matrix.fromArray( gripPose.transform.matrix );
  13943. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13944. }
  13945. }
  13946. }
  13947. }
  13948. if ( targetRay !== null ) {
  13949. targetRay.visible = ( inputPose !== null );
  13950. }
  13951. if ( grip !== null ) {
  13952. grip.visible = ( gripPose !== null );
  13953. }
  13954. if ( hand !== null ) {
  13955. hand.visible = ( handPose !== null );
  13956. }
  13957. return this;
  13958. }
  13959. } );
  13960. function WebXRManager( renderer, gl ) {
  13961. const scope = this;
  13962. let session = null;
  13963. let framebufferScaleFactor = 1.0;
  13964. let referenceSpace = null;
  13965. let referenceSpaceType = 'local-floor';
  13966. let pose = null;
  13967. const controllers = [];
  13968. const inputSourcesMap = new Map();
  13969. //
  13970. const cameraL = new PerspectiveCamera();
  13971. cameraL.layers.enable( 1 );
  13972. cameraL.viewport = new Vector4();
  13973. const cameraR = new PerspectiveCamera();
  13974. cameraR.layers.enable( 2 );
  13975. cameraR.viewport = new Vector4();
  13976. const cameras = [ cameraL, cameraR ];
  13977. const cameraVR = new ArrayCamera();
  13978. cameraVR.layers.enable( 1 );
  13979. cameraVR.layers.enable( 2 );
  13980. let _currentDepthNear = null;
  13981. let _currentDepthFar = null;
  13982. //
  13983. this.enabled = false;
  13984. this.isPresenting = false;
  13985. this.getController = function ( index ) {
  13986. let controller = controllers[ index ];
  13987. if ( controller === undefined ) {
  13988. controller = new WebXRController();
  13989. controllers[ index ] = controller;
  13990. }
  13991. return controller.getTargetRaySpace();
  13992. };
  13993. this.getControllerGrip = function ( index ) {
  13994. let controller = controllers[ index ];
  13995. if ( controller === undefined ) {
  13996. controller = new WebXRController();
  13997. controllers[ index ] = controller;
  13998. }
  13999. return controller.getGripSpace();
  14000. };
  14001. this.getHand = function ( index ) {
  14002. let controller = controllers[ index ];
  14003. if ( controller === undefined ) {
  14004. controller = new WebXRController();
  14005. controllers[ index ] = controller;
  14006. }
  14007. return controller.getHandSpace();
  14008. };
  14009. //
  14010. function onSessionEvent( event ) {
  14011. const controller = inputSourcesMap.get( event.inputSource );
  14012. if ( controller ) {
  14013. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14014. }
  14015. }
  14016. function onSessionEnd() {
  14017. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14018. controller.disconnect( inputSource );
  14019. } );
  14020. inputSourcesMap.clear();
  14021. //
  14022. renderer.setFramebuffer( null );
  14023. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  14024. animation.stop();
  14025. scope.isPresenting = false;
  14026. scope.dispatchEvent( { type: 'sessionend' } );
  14027. }
  14028. function onRequestReferenceSpace( value ) {
  14029. referenceSpace = value;
  14030. animation.setContext( session );
  14031. animation.start();
  14032. scope.isPresenting = true;
  14033. scope.dispatchEvent( { type: 'sessionstart' } );
  14034. }
  14035. this.setFramebufferScaleFactor = function ( value ) {
  14036. framebufferScaleFactor = value;
  14037. if ( scope.isPresenting === true ) {
  14038. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14039. }
  14040. };
  14041. this.setReferenceSpaceType = function ( value ) {
  14042. referenceSpaceType = value;
  14043. if ( scope.isPresenting === true ) {
  14044. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14045. }
  14046. };
  14047. this.getReferenceSpace = function () {
  14048. return referenceSpace;
  14049. };
  14050. this.getSession = function () {
  14051. return session;
  14052. };
  14053. this.setSession = function ( value ) {
  14054. session = value;
  14055. if ( session !== null ) {
  14056. session.addEventListener( 'select', onSessionEvent );
  14057. session.addEventListener( 'selectstart', onSessionEvent );
  14058. session.addEventListener( 'selectend', onSessionEvent );
  14059. session.addEventListener( 'squeeze', onSessionEvent );
  14060. session.addEventListener( 'squeezestart', onSessionEvent );
  14061. session.addEventListener( 'squeezeend', onSessionEvent );
  14062. session.addEventListener( 'end', onSessionEnd );
  14063. const attributes = gl.getContextAttributes();
  14064. if ( attributes.xrCompatible !== true ) {
  14065. gl.makeXRCompatible();
  14066. }
  14067. const layerInit = {
  14068. antialias: attributes.antialias,
  14069. alpha: attributes.alpha,
  14070. depth: attributes.depth,
  14071. stencil: attributes.stencil,
  14072. framebufferScaleFactor: framebufferScaleFactor
  14073. };
  14074. // eslint-disable-next-line no-undef
  14075. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  14076. session.updateRenderState( { baseLayer: baseLayer } );
  14077. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  14078. //
  14079. session.addEventListener( 'inputsourceschange', updateInputSources );
  14080. }
  14081. };
  14082. function updateInputSources( event ) {
  14083. const inputSources = session.inputSources;
  14084. // Assign inputSources to available controllers
  14085. for ( let i = 0; i < controllers.length; i ++ ) {
  14086. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14087. }
  14088. // Notify disconnected
  14089. for ( let i = 0; i < event.removed.length; i ++ ) {
  14090. const inputSource = event.removed[ i ];
  14091. const controller = inputSourcesMap.get( inputSource );
  14092. if ( controller ) {
  14093. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14094. inputSourcesMap.delete( inputSource );
  14095. }
  14096. }
  14097. // Notify connected
  14098. for ( let i = 0; i < event.added.length; i ++ ) {
  14099. const inputSource = event.added[ i ];
  14100. const controller = inputSourcesMap.get( inputSource );
  14101. if ( controller ) {
  14102. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14103. }
  14104. }
  14105. }
  14106. //
  14107. const cameraLPos = new Vector3();
  14108. const cameraRPos = new Vector3();
  14109. /**
  14110. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14111. * the cameras' projection and world matrices have already been set.
  14112. * And that near and far planes are identical for both cameras.
  14113. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14114. */
  14115. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14116. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14117. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14118. const ipd = cameraLPos.distanceTo( cameraRPos );
  14119. const projL = cameraL.projectionMatrix.elements;
  14120. const projR = cameraR.projectionMatrix.elements;
  14121. // VR systems will have identical far and near planes, and
  14122. // most likely identical top and bottom frustum extents.
  14123. // Use the left camera for these values.
  14124. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14125. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14126. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14127. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14128. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14129. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14130. const left = near * leftFov;
  14131. const right = near * rightFov;
  14132. // Calculate the new camera's position offset from the
  14133. // left camera. xOffset should be roughly half `ipd`.
  14134. const zOffset = ipd / ( - leftFov + rightFov );
  14135. const xOffset = zOffset * - leftFov;
  14136. // TODO: Better way to apply this offset?
  14137. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14138. camera.translateX( xOffset );
  14139. camera.translateZ( zOffset );
  14140. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14141. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14142. // Find the union of the frustum values of the cameras and scale
  14143. // the values so that the near plane's position does not change in world space,
  14144. // although must now be relative to the new union camera.
  14145. const near2 = near + zOffset;
  14146. const far2 = far + zOffset;
  14147. const left2 = left - xOffset;
  14148. const right2 = right + ( ipd - xOffset );
  14149. const top2 = topFov * far / far2 * near2;
  14150. const bottom2 = bottomFov * far / far2 * near2;
  14151. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14152. }
  14153. function updateCamera( camera, parent ) {
  14154. if ( parent === null ) {
  14155. camera.matrixWorld.copy( camera.matrix );
  14156. } else {
  14157. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14158. }
  14159. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14160. }
  14161. this.getCamera = function ( camera ) {
  14162. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14163. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14164. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14165. // Note that the new renderState won't apply until the next frame. See #18320
  14166. session.updateRenderState( {
  14167. depthNear: cameraVR.near,
  14168. depthFar: cameraVR.far
  14169. } );
  14170. _currentDepthNear = cameraVR.near;
  14171. _currentDepthFar = cameraVR.far;
  14172. }
  14173. const parent = camera.parent;
  14174. const cameras = cameraVR.cameras;
  14175. updateCamera( cameraVR, parent );
  14176. for ( let i = 0; i < cameras.length; i ++ ) {
  14177. updateCamera( cameras[ i ], parent );
  14178. }
  14179. // update camera and its children
  14180. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14181. const children = camera.children;
  14182. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14183. children[ i ].updateMatrixWorld( true );
  14184. }
  14185. // update projection matrix for proper view frustum culling
  14186. if ( cameras.length === 2 ) {
  14187. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14188. } else {
  14189. // assume single camera setup (AR)
  14190. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14191. }
  14192. return cameraVR;
  14193. };
  14194. // Animation Loop
  14195. let onAnimationFrameCallback = null;
  14196. function onAnimationFrame( time, frame ) {
  14197. pose = frame.getViewerPose( referenceSpace );
  14198. if ( pose !== null ) {
  14199. const views = pose.views;
  14200. const baseLayer = session.renderState.baseLayer;
  14201. renderer.setFramebuffer( baseLayer.framebuffer );
  14202. let cameraVRNeedsUpdate = false;
  14203. // check if it's necessary to rebuild cameraVR's camera list
  14204. if ( views.length !== cameraVR.cameras.length ) {
  14205. cameraVR.cameras.length = 0;
  14206. cameraVRNeedsUpdate = true;
  14207. }
  14208. for ( let i = 0; i < views.length; i ++ ) {
  14209. const view = views[ i ];
  14210. const viewport = baseLayer.getViewport( view );
  14211. const camera = cameras[ i ];
  14212. camera.matrix.fromArray( view.transform.matrix );
  14213. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14214. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14215. if ( i === 0 ) {
  14216. cameraVR.matrix.copy( camera.matrix );
  14217. }
  14218. if ( cameraVRNeedsUpdate === true ) {
  14219. cameraVR.cameras.push( camera );
  14220. }
  14221. }
  14222. }
  14223. //
  14224. const inputSources = session.inputSources;
  14225. for ( let i = 0; i < controllers.length; i ++ ) {
  14226. const controller = controllers[ i ];
  14227. const inputSource = inputSources[ i ];
  14228. controller.update( inputSource, frame, referenceSpace );
  14229. }
  14230. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14231. }
  14232. const animation = new WebGLAnimation();
  14233. animation.setAnimationLoop( onAnimationFrame );
  14234. this.setAnimationLoop = function ( callback ) {
  14235. onAnimationFrameCallback = callback;
  14236. };
  14237. this.dispose = function () {};
  14238. }
  14239. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  14240. function WebGLMaterials( properties ) {
  14241. function refreshFogUniforms( uniforms, fog ) {
  14242. uniforms.fogColor.value.copy( fog.color );
  14243. if ( fog.isFog ) {
  14244. uniforms.fogNear.value = fog.near;
  14245. uniforms.fogFar.value = fog.far;
  14246. } else if ( fog.isFogExp2 ) {
  14247. uniforms.fogDensity.value = fog.density;
  14248. }
  14249. }
  14250. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  14251. if ( material.isMeshBasicMaterial ) {
  14252. refreshUniformsCommon( uniforms, material );
  14253. } else if ( material.isMeshLambertMaterial ) {
  14254. refreshUniformsCommon( uniforms, material );
  14255. refreshUniformsLambert( uniforms, material );
  14256. } else if ( material.isMeshToonMaterial ) {
  14257. refreshUniformsCommon( uniforms, material );
  14258. refreshUniformsToon( uniforms, material );
  14259. } else if ( material.isMeshPhongMaterial ) {
  14260. refreshUniformsCommon( uniforms, material );
  14261. refreshUniformsPhong( uniforms, material );
  14262. } else if ( material.isMeshStandardMaterial ) {
  14263. refreshUniformsCommon( uniforms, material );
  14264. if ( material.isMeshPhysicalMaterial ) {
  14265. refreshUniformsPhysical( uniforms, material );
  14266. } else {
  14267. refreshUniformsStandard( uniforms, material );
  14268. }
  14269. } else if ( material.isMeshMatcapMaterial ) {
  14270. refreshUniformsCommon( uniforms, material );
  14271. refreshUniformsMatcap( uniforms, material );
  14272. } else if ( material.isMeshDepthMaterial ) {
  14273. refreshUniformsCommon( uniforms, material );
  14274. refreshUniformsDepth( uniforms, material );
  14275. } else if ( material.isMeshDistanceMaterial ) {
  14276. refreshUniformsCommon( uniforms, material );
  14277. refreshUniformsDistance( uniforms, material );
  14278. } else if ( material.isMeshNormalMaterial ) {
  14279. refreshUniformsCommon( uniforms, material );
  14280. refreshUniformsNormal( uniforms, material );
  14281. } else if ( material.isLineBasicMaterial ) {
  14282. refreshUniformsLine( uniforms, material );
  14283. if ( material.isLineDashedMaterial ) {
  14284. refreshUniformsDash( uniforms, material );
  14285. }
  14286. } else if ( material.isPointsMaterial ) {
  14287. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14288. } else if ( material.isSpriteMaterial ) {
  14289. refreshUniformsSprites( uniforms, material );
  14290. } else if ( material.isShadowMaterial ) {
  14291. uniforms.color.value.copy( material.color );
  14292. uniforms.opacity.value = material.opacity;
  14293. } else if ( material.isShaderMaterial ) {
  14294. material.uniformsNeedUpdate = false; // #15581
  14295. }
  14296. }
  14297. function refreshUniformsCommon( uniforms, material ) {
  14298. uniforms.opacity.value = material.opacity;
  14299. if ( material.color ) {
  14300. uniforms.diffuse.value.copy( material.color );
  14301. }
  14302. if ( material.emissive ) {
  14303. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14304. }
  14305. if ( material.map ) {
  14306. uniforms.map.value = material.map;
  14307. }
  14308. if ( material.alphaMap ) {
  14309. uniforms.alphaMap.value = material.alphaMap;
  14310. }
  14311. if ( material.specularMap ) {
  14312. uniforms.specularMap.value = material.specularMap;
  14313. }
  14314. const envMap = properties.get( material ).envMap;
  14315. if ( envMap ) {
  14316. uniforms.envMap.value = envMap;
  14317. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  14318. uniforms.reflectivity.value = material.reflectivity;
  14319. uniforms.refractionRatio.value = material.refractionRatio;
  14320. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  14321. if ( maxMipLevel !== undefined ) {
  14322. uniforms.maxMipLevel.value = maxMipLevel;
  14323. }
  14324. }
  14325. if ( material.lightMap ) {
  14326. uniforms.lightMap.value = material.lightMap;
  14327. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14328. }
  14329. if ( material.aoMap ) {
  14330. uniforms.aoMap.value = material.aoMap;
  14331. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14332. }
  14333. // uv repeat and offset setting priorities
  14334. // 1. color map
  14335. // 2. specular map
  14336. // 3. displacementMap map
  14337. // 4. normal map
  14338. // 5. bump map
  14339. // 6. roughnessMap map
  14340. // 7. metalnessMap map
  14341. // 8. alphaMap map
  14342. // 9. emissiveMap map
  14343. // 10. clearcoat map
  14344. // 11. clearcoat normal map
  14345. // 12. clearcoat roughnessMap map
  14346. let uvScaleMap;
  14347. if ( material.map ) {
  14348. uvScaleMap = material.map;
  14349. } else if ( material.specularMap ) {
  14350. uvScaleMap = material.specularMap;
  14351. } else if ( material.displacementMap ) {
  14352. uvScaleMap = material.displacementMap;
  14353. } else if ( material.normalMap ) {
  14354. uvScaleMap = material.normalMap;
  14355. } else if ( material.bumpMap ) {
  14356. uvScaleMap = material.bumpMap;
  14357. } else if ( material.roughnessMap ) {
  14358. uvScaleMap = material.roughnessMap;
  14359. } else if ( material.metalnessMap ) {
  14360. uvScaleMap = material.metalnessMap;
  14361. } else if ( material.alphaMap ) {
  14362. uvScaleMap = material.alphaMap;
  14363. } else if ( material.emissiveMap ) {
  14364. uvScaleMap = material.emissiveMap;
  14365. } else if ( material.clearcoatMap ) {
  14366. uvScaleMap = material.clearcoatMap;
  14367. } else if ( material.clearcoatNormalMap ) {
  14368. uvScaleMap = material.clearcoatNormalMap;
  14369. } else if ( material.clearcoatRoughnessMap ) {
  14370. uvScaleMap = material.clearcoatRoughnessMap;
  14371. }
  14372. if ( uvScaleMap !== undefined ) {
  14373. // backwards compatibility
  14374. if ( uvScaleMap.isWebGLRenderTarget ) {
  14375. uvScaleMap = uvScaleMap.texture;
  14376. }
  14377. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14378. uvScaleMap.updateMatrix();
  14379. }
  14380. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14381. }
  14382. // uv repeat and offset setting priorities for uv2
  14383. // 1. ao map
  14384. // 2. light map
  14385. let uv2ScaleMap;
  14386. if ( material.aoMap ) {
  14387. uv2ScaleMap = material.aoMap;
  14388. } else if ( material.lightMap ) {
  14389. uv2ScaleMap = material.lightMap;
  14390. }
  14391. if ( uv2ScaleMap !== undefined ) {
  14392. // backwards compatibility
  14393. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14394. uv2ScaleMap = uv2ScaleMap.texture;
  14395. }
  14396. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14397. uv2ScaleMap.updateMatrix();
  14398. }
  14399. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14400. }
  14401. }
  14402. function refreshUniformsLine( uniforms, material ) {
  14403. uniforms.diffuse.value.copy( material.color );
  14404. uniforms.opacity.value = material.opacity;
  14405. }
  14406. function refreshUniformsDash( uniforms, material ) {
  14407. uniforms.dashSize.value = material.dashSize;
  14408. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14409. uniforms.scale.value = material.scale;
  14410. }
  14411. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14412. uniforms.diffuse.value.copy( material.color );
  14413. uniforms.opacity.value = material.opacity;
  14414. uniforms.size.value = material.size * pixelRatio;
  14415. uniforms.scale.value = height * 0.5;
  14416. if ( material.map ) {
  14417. uniforms.map.value = material.map;
  14418. }
  14419. if ( material.alphaMap ) {
  14420. uniforms.alphaMap.value = material.alphaMap;
  14421. }
  14422. // uv repeat and offset setting priorities
  14423. // 1. color map
  14424. // 2. alpha map
  14425. let uvScaleMap;
  14426. if ( material.map ) {
  14427. uvScaleMap = material.map;
  14428. } else if ( material.alphaMap ) {
  14429. uvScaleMap = material.alphaMap;
  14430. }
  14431. if ( uvScaleMap !== undefined ) {
  14432. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14433. uvScaleMap.updateMatrix();
  14434. }
  14435. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14436. }
  14437. }
  14438. function refreshUniformsSprites( uniforms, material ) {
  14439. uniforms.diffuse.value.copy( material.color );
  14440. uniforms.opacity.value = material.opacity;
  14441. uniforms.rotation.value = material.rotation;
  14442. if ( material.map ) {
  14443. uniforms.map.value = material.map;
  14444. }
  14445. if ( material.alphaMap ) {
  14446. uniforms.alphaMap.value = material.alphaMap;
  14447. }
  14448. // uv repeat and offset setting priorities
  14449. // 1. color map
  14450. // 2. alpha map
  14451. let uvScaleMap;
  14452. if ( material.map ) {
  14453. uvScaleMap = material.map;
  14454. } else if ( material.alphaMap ) {
  14455. uvScaleMap = material.alphaMap;
  14456. }
  14457. if ( uvScaleMap !== undefined ) {
  14458. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14459. uvScaleMap.updateMatrix();
  14460. }
  14461. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14462. }
  14463. }
  14464. function refreshUniformsLambert( uniforms, material ) {
  14465. if ( material.emissiveMap ) {
  14466. uniforms.emissiveMap.value = material.emissiveMap;
  14467. }
  14468. }
  14469. function refreshUniformsPhong( uniforms, material ) {
  14470. uniforms.specular.value.copy( material.specular );
  14471. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14472. if ( material.emissiveMap ) {
  14473. uniforms.emissiveMap.value = material.emissiveMap;
  14474. }
  14475. if ( material.bumpMap ) {
  14476. uniforms.bumpMap.value = material.bumpMap;
  14477. uniforms.bumpScale.value = material.bumpScale;
  14478. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14479. }
  14480. if ( material.normalMap ) {
  14481. uniforms.normalMap.value = material.normalMap;
  14482. uniforms.normalScale.value.copy( material.normalScale );
  14483. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14484. }
  14485. if ( material.displacementMap ) {
  14486. uniforms.displacementMap.value = material.displacementMap;
  14487. uniforms.displacementScale.value = material.displacementScale;
  14488. uniforms.displacementBias.value = material.displacementBias;
  14489. }
  14490. }
  14491. function refreshUniformsToon( uniforms, material ) {
  14492. if ( material.gradientMap ) {
  14493. uniforms.gradientMap.value = material.gradientMap;
  14494. }
  14495. if ( material.emissiveMap ) {
  14496. uniforms.emissiveMap.value = material.emissiveMap;
  14497. }
  14498. if ( material.bumpMap ) {
  14499. uniforms.bumpMap.value = material.bumpMap;
  14500. uniforms.bumpScale.value = material.bumpScale;
  14501. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14502. }
  14503. if ( material.normalMap ) {
  14504. uniforms.normalMap.value = material.normalMap;
  14505. uniforms.normalScale.value.copy( material.normalScale );
  14506. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14507. }
  14508. if ( material.displacementMap ) {
  14509. uniforms.displacementMap.value = material.displacementMap;
  14510. uniforms.displacementScale.value = material.displacementScale;
  14511. uniforms.displacementBias.value = material.displacementBias;
  14512. }
  14513. }
  14514. function refreshUniformsStandard( uniforms, material ) {
  14515. uniforms.roughness.value = material.roughness;
  14516. uniforms.metalness.value = material.metalness;
  14517. if ( material.roughnessMap ) {
  14518. uniforms.roughnessMap.value = material.roughnessMap;
  14519. }
  14520. if ( material.metalnessMap ) {
  14521. uniforms.metalnessMap.value = material.metalnessMap;
  14522. }
  14523. if ( material.emissiveMap ) {
  14524. uniforms.emissiveMap.value = material.emissiveMap;
  14525. }
  14526. if ( material.bumpMap ) {
  14527. uniforms.bumpMap.value = material.bumpMap;
  14528. uniforms.bumpScale.value = material.bumpScale;
  14529. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14530. }
  14531. if ( material.normalMap ) {
  14532. uniforms.normalMap.value = material.normalMap;
  14533. uniforms.normalScale.value.copy( material.normalScale );
  14534. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14535. }
  14536. if ( material.displacementMap ) {
  14537. uniforms.displacementMap.value = material.displacementMap;
  14538. uniforms.displacementScale.value = material.displacementScale;
  14539. uniforms.displacementBias.value = material.displacementBias;
  14540. }
  14541. const envMap = properties.get( material ).envMap;
  14542. if ( envMap ) {
  14543. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14544. uniforms.envMapIntensity.value = material.envMapIntensity;
  14545. }
  14546. }
  14547. function refreshUniformsPhysical( uniforms, material ) {
  14548. refreshUniformsStandard( uniforms, material );
  14549. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14550. uniforms.clearcoat.value = material.clearcoat;
  14551. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14552. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  14553. if ( material.clearcoatMap ) {
  14554. uniforms.clearcoatMap.value = material.clearcoatMap;
  14555. }
  14556. if ( material.clearcoatRoughnessMap ) {
  14557. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14558. }
  14559. if ( material.clearcoatNormalMap ) {
  14560. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  14561. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14562. if ( material.side === BackSide ) {
  14563. uniforms.clearcoatNormalScale.value.negate();
  14564. }
  14565. }
  14566. uniforms.transmission.value = material.transmission;
  14567. if ( material.transmissionMap ) {
  14568. uniforms.transmissionMap.value = material.transmissionMap;
  14569. }
  14570. }
  14571. function refreshUniformsMatcap( uniforms, material ) {
  14572. if ( material.matcap ) {
  14573. uniforms.matcap.value = material.matcap;
  14574. }
  14575. if ( material.bumpMap ) {
  14576. uniforms.bumpMap.value = material.bumpMap;
  14577. uniforms.bumpScale.value = material.bumpScale;
  14578. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14579. }
  14580. if ( material.normalMap ) {
  14581. uniforms.normalMap.value = material.normalMap;
  14582. uniforms.normalScale.value.copy( material.normalScale );
  14583. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14584. }
  14585. if ( material.displacementMap ) {
  14586. uniforms.displacementMap.value = material.displacementMap;
  14587. uniforms.displacementScale.value = material.displacementScale;
  14588. uniforms.displacementBias.value = material.displacementBias;
  14589. }
  14590. }
  14591. function refreshUniformsDepth( uniforms, material ) {
  14592. if ( material.displacementMap ) {
  14593. uniforms.displacementMap.value = material.displacementMap;
  14594. uniforms.displacementScale.value = material.displacementScale;
  14595. uniforms.displacementBias.value = material.displacementBias;
  14596. }
  14597. }
  14598. function refreshUniformsDistance( uniforms, material ) {
  14599. if ( material.displacementMap ) {
  14600. uniforms.displacementMap.value = material.displacementMap;
  14601. uniforms.displacementScale.value = material.displacementScale;
  14602. uniforms.displacementBias.value = material.displacementBias;
  14603. }
  14604. uniforms.referencePosition.value.copy( material.referencePosition );
  14605. uniforms.nearDistance.value = material.nearDistance;
  14606. uniforms.farDistance.value = material.farDistance;
  14607. }
  14608. function refreshUniformsNormal( uniforms, material ) {
  14609. if ( material.bumpMap ) {
  14610. uniforms.bumpMap.value = material.bumpMap;
  14611. uniforms.bumpScale.value = material.bumpScale;
  14612. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14613. }
  14614. if ( material.normalMap ) {
  14615. uniforms.normalMap.value = material.normalMap;
  14616. uniforms.normalScale.value.copy( material.normalScale );
  14617. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14618. }
  14619. if ( material.displacementMap ) {
  14620. uniforms.displacementMap.value = material.displacementMap;
  14621. uniforms.displacementScale.value = material.displacementScale;
  14622. uniforms.displacementBias.value = material.displacementBias;
  14623. }
  14624. }
  14625. return {
  14626. refreshFogUniforms: refreshFogUniforms,
  14627. refreshMaterialUniforms: refreshMaterialUniforms
  14628. };
  14629. }
  14630. function createCanvasElement() {
  14631. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14632. canvas.style.display = 'block';
  14633. return canvas;
  14634. }
  14635. function WebGLRenderer( parameters ) {
  14636. parameters = parameters || {};
  14637. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14638. _context = parameters.context !== undefined ? parameters.context : null,
  14639. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14640. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14641. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14642. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14643. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14644. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14645. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14646. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14647. let currentRenderList = null;
  14648. let currentRenderState = null;
  14649. // render() can be called from within a callback triggered by another render.
  14650. // We track this so that the nested render call gets its state isolated from the parent render call.
  14651. const renderStateStack = [];
  14652. // public properties
  14653. this.domElement = _canvas;
  14654. // Debug configuration container
  14655. this.debug = {
  14656. /**
  14657. * Enables error checking and reporting when shader programs are being compiled
  14658. * @type {boolean}
  14659. */
  14660. checkShaderErrors: true
  14661. };
  14662. // clearing
  14663. this.autoClear = true;
  14664. this.autoClearColor = true;
  14665. this.autoClearDepth = true;
  14666. this.autoClearStencil = true;
  14667. // scene graph
  14668. this.sortObjects = true;
  14669. // user-defined clipping
  14670. this.clippingPlanes = [];
  14671. this.localClippingEnabled = false;
  14672. // physically based shading
  14673. this.gammaFactor = 2.0; // for backwards compatibility
  14674. this.outputEncoding = LinearEncoding;
  14675. // physical lights
  14676. this.physicallyCorrectLights = false;
  14677. // tone mapping
  14678. this.toneMapping = NoToneMapping;
  14679. this.toneMappingExposure = 1.0;
  14680. // morphs
  14681. this.maxMorphTargets = 8;
  14682. this.maxMorphNormals = 4;
  14683. // internal properties
  14684. const _this = this;
  14685. let _isContextLost = false;
  14686. // internal state cache
  14687. let _framebuffer = null;
  14688. let _currentActiveCubeFace = 0;
  14689. let _currentActiveMipmapLevel = 0;
  14690. let _currentRenderTarget = null;
  14691. let _currentFramebuffer = null;
  14692. let _currentMaterialId = - 1;
  14693. let _currentCamera = null;
  14694. const _currentViewport = new Vector4();
  14695. const _currentScissor = new Vector4();
  14696. let _currentScissorTest = null;
  14697. //
  14698. let _width = _canvas.width;
  14699. let _height = _canvas.height;
  14700. let _pixelRatio = 1;
  14701. let _opaqueSort = null;
  14702. let _transparentSort = null;
  14703. const _viewport = new Vector4( 0, 0, _width, _height );
  14704. const _scissor = new Vector4( 0, 0, _width, _height );
  14705. let _scissorTest = false;
  14706. // frustum
  14707. const _frustum = new Frustum();
  14708. // clipping
  14709. let _clippingEnabled = false;
  14710. let _localClippingEnabled = false;
  14711. // camera matrices cache
  14712. const _projScreenMatrix = new Matrix4();
  14713. const _vector3 = new Vector3();
  14714. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  14715. function getTargetPixelRatio() {
  14716. return _currentRenderTarget === null ? _pixelRatio : 1;
  14717. }
  14718. // initialize
  14719. let _gl = _context;
  14720. function getContext( contextNames, contextAttributes ) {
  14721. for ( let i = 0; i < contextNames.length; i ++ ) {
  14722. const contextName = contextNames[ i ];
  14723. const context = _canvas.getContext( contextName, contextAttributes );
  14724. if ( context !== null ) return context;
  14725. }
  14726. return null;
  14727. }
  14728. try {
  14729. const contextAttributes = {
  14730. alpha: _alpha,
  14731. depth: _depth,
  14732. stencil: _stencil,
  14733. antialias: _antialias,
  14734. premultipliedAlpha: _premultipliedAlpha,
  14735. preserveDrawingBuffer: _preserveDrawingBuffer,
  14736. powerPreference: _powerPreference,
  14737. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14738. };
  14739. // event listeners must be registered before WebGL context is created, see #12753
  14740. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14741. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14742. if ( _gl === null ) {
  14743. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14744. if ( _this.isWebGL1Renderer === true ) {
  14745. contextNames.shift();
  14746. }
  14747. _gl = getContext( contextNames, contextAttributes );
  14748. if ( _gl === null ) {
  14749. if ( getContext( contextNames ) ) {
  14750. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14751. } else {
  14752. throw new Error( 'Error creating WebGL context.' );
  14753. }
  14754. }
  14755. }
  14756. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14757. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14758. _gl.getShaderPrecisionFormat = function () {
  14759. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14760. };
  14761. }
  14762. } catch ( error ) {
  14763. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14764. throw error;
  14765. }
  14766. let extensions, capabilities, state, info;
  14767. let properties, textures, cubemaps, attributes, geometries, objects;
  14768. let programCache, materials, renderLists, renderStates, clipping;
  14769. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14770. let utils, bindingStates;
  14771. function initGLContext() {
  14772. extensions = new WebGLExtensions( _gl );
  14773. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14774. if ( capabilities.isWebGL2 === false ) {
  14775. extensions.get( 'WEBGL_depth_texture' );
  14776. extensions.get( 'OES_texture_float' );
  14777. extensions.get( 'OES_texture_half_float' );
  14778. extensions.get( 'OES_texture_half_float_linear' );
  14779. extensions.get( 'OES_standard_derivatives' );
  14780. extensions.get( 'OES_element_index_uint' );
  14781. extensions.get( 'OES_vertex_array_object' );
  14782. extensions.get( 'ANGLE_instanced_arrays' );
  14783. }
  14784. extensions.get( 'OES_texture_float_linear' );
  14785. utils = new WebGLUtils( _gl, extensions, capabilities );
  14786. state = new WebGLState( _gl, extensions, capabilities );
  14787. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14788. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14789. info = new WebGLInfo( _gl );
  14790. properties = new WebGLProperties();
  14791. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14792. cubemaps = new WebGLCubeMaps( _this );
  14793. attributes = new WebGLAttributes( _gl, capabilities );
  14794. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14795. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14796. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14797. morphtargets = new WebGLMorphtargets( _gl );
  14798. clipping = new WebGLClipping( properties );
  14799. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14800. materials = new WebGLMaterials( properties );
  14801. renderLists = new WebGLRenderLists( properties );
  14802. renderStates = new WebGLRenderStates( extensions, capabilities );
  14803. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14804. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14805. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14806. info.programs = programCache.programs;
  14807. _this.capabilities = capabilities;
  14808. _this.extensions = extensions;
  14809. _this.properties = properties;
  14810. _this.renderLists = renderLists;
  14811. _this.state = state;
  14812. _this.info = info;
  14813. _this._textures = textures;//add
  14814. }
  14815. initGLContext();
  14816. // xr
  14817. const xr = new WebXRManager( _this, _gl );
  14818. this.xr = xr;
  14819. // shadow map
  14820. const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  14821. this.shadowMap = shadowMap;
  14822. // API
  14823. this.getContext = function () {
  14824. return _gl;
  14825. };
  14826. this.getContextAttributes = function () {
  14827. return _gl.getContextAttributes();
  14828. };
  14829. this.forceContextLoss = function () {
  14830. const extension = extensions.get( 'WEBGL_lose_context' );
  14831. if ( extension ) extension.loseContext();
  14832. };
  14833. this.forceContextRestore = function () {
  14834. const extension = extensions.get( 'WEBGL_lose_context' );
  14835. if ( extension ) extension.restoreContext();
  14836. };
  14837. this.getPixelRatio = function () {
  14838. return _pixelRatio;
  14839. };
  14840. this.setPixelRatio = function ( value ) {
  14841. if ( value === undefined ) return;
  14842. _pixelRatio = value;
  14843. this.setSize( _width, _height, false );
  14844. };
  14845. this.getSize = function ( target ) {
  14846. if ( target === undefined ) {
  14847. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  14848. target = new Vector2$1();
  14849. }
  14850. return target.set( _width, _height );
  14851. };
  14852. this.setSize = function ( width, height, updateStyle, devicePixelRatio ) {//改
  14853. if (devicePixelRatio != void 0) _pixelRatio = devicePixelRatio; //add
  14854. if ( xr.isPresenting ) {
  14855. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14856. return;
  14857. }
  14858. _width = width;
  14859. _height = height;
  14860. //if(!window.unableSetSize){
  14861. _canvas.width = Math.floor( width * _pixelRatio );
  14862. _canvas.height = Math.floor( height * _pixelRatio );
  14863. if ( updateStyle !== false ) {
  14864. _canvas.style.width = width + 'px';
  14865. _canvas.style.height = height + 'px';
  14866. }
  14867. this.setViewport( 0, 0, width, height );
  14868. //}
  14869. };
  14870. this.getDrawingBufferSize = function ( target ) {
  14871. if ( target === undefined ) {
  14872. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  14873. target = new Vector2$1();
  14874. }
  14875. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14876. };
  14877. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14878. _width = width;
  14879. _height = height;
  14880. _pixelRatio = pixelRatio;
  14881. _canvas.width = Math.floor( width * pixelRatio );
  14882. _canvas.height = Math.floor( height * pixelRatio );
  14883. this.setViewport( 0, 0, width, height );
  14884. };
  14885. this.getCurrentViewport = function ( target ) {
  14886. if ( target === undefined ) {
  14887. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14888. target = new Vector4();
  14889. }
  14890. return target.copy( _currentViewport );
  14891. };
  14892. this.getViewport = function ( target ) {
  14893. return target.copy( _viewport );
  14894. };
  14895. this.setViewport = function ( x, y, width, height ) {
  14896. if ( x.isVector4 ) {
  14897. _viewport.set( x.x, x.y, x.z, x.w );
  14898. } else {
  14899. _viewport.set( x, y, width, height );
  14900. }
  14901. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14902. };
  14903. this.getScissor = function ( target ) {
  14904. return target.copy( _scissor );
  14905. };
  14906. this.setScissor = function ( x, y, width, height ) {
  14907. if ( x.isVector4 ) {
  14908. _scissor.set( x.x, x.y, x.z, x.w );
  14909. } else {
  14910. _scissor.set( x, y, width, height );
  14911. }
  14912. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14913. };
  14914. this.getScissorTest = function () {
  14915. return _scissorTest;
  14916. };
  14917. this.setScissorTest = function ( boolean ) {
  14918. state.setScissorTest( _scissorTest = boolean );
  14919. };
  14920. this.setOpaqueSort = function ( method ) {
  14921. _opaqueSort = method;
  14922. };
  14923. this.setTransparentSort = function ( method ) {
  14924. _transparentSort = method;
  14925. };
  14926. // Clearing
  14927. this.getClearColor = function ( target ) {
  14928. if ( target === undefined ) {
  14929. console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
  14930. target = new Color();
  14931. }
  14932. return target.copy( background.getClearColor() );
  14933. };
  14934. this.setClearColor = function () {
  14935. background.setClearColor.apply( background, arguments );
  14936. };
  14937. this.getClearAlpha = function () {
  14938. return background.getClearAlpha();
  14939. };
  14940. this.setClearAlpha = function () {
  14941. background.setClearAlpha.apply( background, arguments );
  14942. };
  14943. this.clear = function ( color, depth, stencil ) {
  14944. let bits = 0;
  14945. if ( color === undefined || color ) bits |= 16384;
  14946. if ( depth === undefined || depth ) bits |= 256;
  14947. if ( stencil === undefined || stencil ) bits |= 1024;
  14948. _gl.clear( bits );
  14949. };
  14950. this.clearColor = function () {
  14951. this.clear( true, false, false );
  14952. };
  14953. this.clearDepth = function () {
  14954. this.clear( false, true, false );
  14955. };
  14956. this.clearStencil = function () {
  14957. this.clear( false, false, true );
  14958. };
  14959. //
  14960. this.dispose = function () {
  14961. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14962. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14963. renderLists.dispose();
  14964. renderStates.dispose();
  14965. properties.dispose();
  14966. cubemaps.dispose();
  14967. objects.dispose();
  14968. bindingStates.dispose();
  14969. xr.dispose();
  14970. animation.stop();
  14971. };
  14972. // Events
  14973. function onContextLost( event ) {
  14974. event.preventDefault();
  14975. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14976. _isContextLost = true;
  14977. }
  14978. function onContextRestore( /* event */ ) {
  14979. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14980. _isContextLost = false;
  14981. initGLContext();
  14982. }
  14983. function onMaterialDispose( event ) {
  14984. const material = event.target;
  14985. material.removeEventListener( 'dispose', onMaterialDispose );
  14986. deallocateMaterial( material );
  14987. }
  14988. // Buffer deallocation
  14989. function deallocateMaterial( material ) {
  14990. releaseMaterialProgramReference( material );
  14991. properties.remove( material );
  14992. }
  14993. function releaseMaterialProgramReference( material ) {
  14994. const programInfo = properties.get( material ).program;
  14995. if ( programInfo !== undefined ) {
  14996. programCache.releaseProgram( programInfo );
  14997. }
  14998. }
  14999. // Buffer rendering
  15000. function renderObjectImmediate( object, program ) {
  15001. object.render( function ( object ) {
  15002. _this.renderBufferImmediate( object, program );
  15003. } );
  15004. }
  15005. this.renderBufferImmediate = function ( object, program ) {
  15006. bindingStates.initAttributes();
  15007. const buffers = properties.get( object );
  15008. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15009. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15010. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15011. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15012. const programAttributes = program.getAttributes();
  15013. if ( object.hasPositions ) {
  15014. _gl.bindBuffer( 34962, buffers.position );
  15015. _gl.bufferData( 34962, object.positionArray, 35048 );
  15016. bindingStates.enableAttribute( programAttributes.position );
  15017. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  15018. }
  15019. if ( object.hasNormals ) {
  15020. _gl.bindBuffer( 34962, buffers.normal );
  15021. _gl.bufferData( 34962, object.normalArray, 35048 );
  15022. bindingStates.enableAttribute( programAttributes.normal );
  15023. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  15024. }
  15025. if ( object.hasUvs ) {
  15026. _gl.bindBuffer( 34962, buffers.uv );
  15027. _gl.bufferData( 34962, object.uvArray, 35048 );
  15028. bindingStates.enableAttribute( programAttributes.uv );
  15029. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  15030. }
  15031. if ( object.hasColors ) {
  15032. _gl.bindBuffer( 34962, buffers.color );
  15033. _gl.bufferData( 34962, object.colorArray, 35048 );
  15034. bindingStates.enableAttribute( programAttributes.color );
  15035. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  15036. }
  15037. bindingStates.disableUnusedAttributes();
  15038. _gl.drawArrays( 4, 0, object.count );
  15039. object.count = 0;
  15040. };
  15041. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15042. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15043. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15044. const program = setProgram( camera, scene, material, object );
  15045. state.setMaterial( material, frontFaceCW );
  15046. //
  15047. let index = geometry.index;
  15048. const position = geometry.attributes.position;
  15049. //
  15050. if ( index === null ) {
  15051. if ( position === undefined || position.count === 0 ) return;
  15052. } else if ( index.count === 0 ) {
  15053. return;
  15054. }
  15055. //
  15056. let rangeFactor = 1;
  15057. if ( material.wireframe === true ) {
  15058. index = geometries.getWireframeAttribute( geometry );
  15059. rangeFactor = 2;
  15060. }
  15061. if ( material.morphTargets || material.morphNormals ) {
  15062. morphtargets.update( object, geometry, material, program );
  15063. }
  15064. bindingStates.setup( object, material, program, geometry, index );
  15065. let attribute;
  15066. let renderer = bufferRenderer;
  15067. if ( index !== null ) {
  15068. attribute = attributes.get( index );
  15069. renderer = indexedBufferRenderer;
  15070. renderer.setIndex( attribute );
  15071. }
  15072. //
  15073. const dataCount = ( index !== null ) ? index.count : position.count;
  15074. const rangeStart = geometry.drawRange.start * rangeFactor;
  15075. const rangeCount = geometry.drawRange.count * rangeFactor;
  15076. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15077. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15078. const drawStart = Math.max( rangeStart, groupStart );
  15079. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15080. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15081. if ( drawCount === 0 ) return;
  15082. //
  15083. if ( object.isMesh ) {
  15084. if ( material.wireframe === true ) {
  15085. state.setlineWidth( material.wireframelineWidth * getTargetPixelRatio() );
  15086. renderer.setMode( 1 );
  15087. } else {
  15088. renderer.setMode( 4 );
  15089. }
  15090. } else if ( object.isLine ) {
  15091. let lineWidth = material.lineWidth;
  15092. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15093. state.setlineWidth( lineWidth * getTargetPixelRatio() );
  15094. if ( object.isLineSegments ) {
  15095. renderer.setMode( 1 );
  15096. } else if ( object.isLineLoop ) {
  15097. renderer.setMode( 2 );
  15098. } else {
  15099. renderer.setMode( 3 );
  15100. }
  15101. } else if ( object.isPoints ) {
  15102. renderer.setMode( 0 );
  15103. } else if ( object.isSprite ) {
  15104. renderer.setMode( 4 );
  15105. }
  15106. if ( object.isInstancedMesh ) {
  15107. renderer.renderInstances( drawStart, drawCount, object.count );
  15108. } else if ( geometry.isInstancedBufferGeometry ) {
  15109. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15110. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15111. } else {
  15112. renderer.render( drawStart, drawCount );
  15113. }
  15114. };
  15115. // Compile
  15116. this.compile = function ( scene, camera ) {
  15117. currentRenderState = renderStates.get( scene );
  15118. currentRenderState.init();
  15119. scene.traverseVisible( function ( object ) {
  15120. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15121. currentRenderState.pushLight( object );
  15122. if ( object.castShadow ) {
  15123. currentRenderState.pushShadow( object );
  15124. }
  15125. }
  15126. } );
  15127. currentRenderState.setupLights();
  15128. const compiled = new WeakMap();
  15129. scene.traverse( function ( object ) {
  15130. const material = object.material;
  15131. if ( material ) {
  15132. if ( Array.isArray( material ) ) {
  15133. for ( let i = 0; i < material.length; i ++ ) {
  15134. const material2 = material[ i ];
  15135. if ( compiled.has( material2 ) === false ) {
  15136. initMaterial( material2, scene, object );
  15137. compiled.set( material2 );
  15138. }
  15139. }
  15140. } else if ( compiled.has( material ) === false ) {
  15141. initMaterial( material, scene, object );
  15142. compiled.set( material );
  15143. }
  15144. }
  15145. } );
  15146. };
  15147. // Animation Loop
  15148. let onAnimationFrameCallback = null;
  15149. function onAnimationFrame( time ) {
  15150. if ( xr.isPresenting ) return;
  15151. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15152. }
  15153. const animation = new WebGLAnimation();
  15154. animation.setAnimationLoop( onAnimationFrame );
  15155. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15156. this.setAnimationLoop = function ( callback ) {
  15157. onAnimationFrameCallback = callback;
  15158. xr.setAnimationLoop( callback );
  15159. ( callback === null ) ? animation.stop() : animation.start();
  15160. };
  15161. // Rendering
  15162. this.render = function ( scene, camera ) {
  15163. let renderTarget, forceClear;
  15164. if ( arguments[ 2 ] !== undefined ) {
  15165. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  15166. renderTarget = arguments[ 2 ];
  15167. }
  15168. if ( arguments[ 3 ] !== undefined ) {
  15169. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  15170. forceClear = arguments[ 3 ];
  15171. }
  15172. if ( camera !== undefined && camera.isCamera !== true ) {
  15173. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15174. return;
  15175. }
  15176. if ( _isContextLost === true ) return;
  15177. // reset caching for this frame
  15178. bindingStates.resetDefaultState();
  15179. _currentMaterialId = - 1;
  15180. _currentCamera = null;
  15181. // update scene graph
  15182. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15183. // update camera matrices and frustum
  15184. if ( camera.parent === null ) camera.updateMatrixWorld();
  15185. if ( xr.enabled === true && xr.isPresenting === true ) {
  15186. camera = xr.getCamera( camera );
  15187. }
  15188. //
  15189. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  15190. currentRenderState = renderStates.get( scene, renderStateStack.length );
  15191. currentRenderState.init();
  15192. renderStateStack.push( currentRenderState );
  15193. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15194. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15195. _localClippingEnabled = this.localClippingEnabled;
  15196. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15197. currentRenderList = renderLists.get( scene, camera );
  15198. currentRenderList.init();
  15199. projectObject( scene, camera, 0, _this.sortObjects );
  15200. currentRenderList.finish();
  15201. if ( _this.sortObjects === true ) {
  15202. currentRenderList.sort( _opaqueSort, _transparentSort );
  15203. }
  15204. //
  15205. if ( _clippingEnabled === true ) clipping.beginShadows();
  15206. const shadowsArray = currentRenderState.state.shadowsArray;
  15207. shadowMap.render( shadowsArray, scene, camera );
  15208. currentRenderState.setupLights();
  15209. currentRenderState.setupLightsView( camera );
  15210. if ( _clippingEnabled === true ) clipping.endShadows();
  15211. //
  15212. if ( this.info.autoReset === true ) this.info.reset();
  15213. if ( renderTarget !== undefined ) {
  15214. this.setRenderTarget( renderTarget );
  15215. }
  15216. //
  15217. background.render( currentRenderList, scene, camera, forceClear );
  15218. // render scene
  15219. const opaqueObjects = currentRenderList.opaque;
  15220. const transparentObjects = currentRenderList.transparent;
  15221. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15222. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15223. //
  15224. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15225. //
  15226. if ( _currentRenderTarget !== null ) {
  15227. // Generate mipmap if we're using any kind of mipmap filtering
  15228. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15229. // resolve multisample renderbuffers to a single-sample texture if necessary
  15230. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15231. }
  15232. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15233. state.buffers.depth.setTest( true );
  15234. state.buffers.depth.setMask( true );
  15235. state.buffers.color.setMask( true );
  15236. state.setPolygonOffset( false );
  15237. // _gl.finish();
  15238. renderStateStack.pop();
  15239. if ( renderStateStack.length > 0 ) {
  15240. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  15241. } else {
  15242. currentRenderState = null;
  15243. }
  15244. currentRenderList = null;
  15245. };
  15246. function projectObject( object, camera, groupOrder, sortObjects ) {
  15247. if ( object.visible === false ) return;
  15248. const visible = object.layers.test( camera.layers );
  15249. if ( visible ) {
  15250. if ( object.isGroup ) {
  15251. groupOrder = object.renderOrder;
  15252. } else if ( object.isLOD ) {
  15253. if ( object.autoUpdate === true ) object.update( camera );
  15254. } else if ( object.isLight ) {
  15255. currentRenderState.pushLight( object );
  15256. if ( object.castShadow ) {
  15257. currentRenderState.pushShadow( object );
  15258. }
  15259. } else if ( object.isSprite ) {
  15260. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15261. if ( sortObjects ) {
  15262. _vector3.setFromMatrixPosition( object.matrixWorld )
  15263. .applyMatrix4( _projScreenMatrix );
  15264. }
  15265. const geometry = objects.update( object );
  15266. const material = object.material;
  15267. if ( material.visible ) {
  15268. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15269. }
  15270. }
  15271. } else if ( object.isImmediateRenderObject ) {
  15272. if ( sortObjects ) {
  15273. _vector3.setFromMatrixPosition( object.matrixWorld )
  15274. .applyMatrix4( _projScreenMatrix );
  15275. }
  15276. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  15277. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15278. if ( object.isSkinnedMesh ) {
  15279. // update skeleton only once in a frame
  15280. if ( object.skeleton.frame !== info.render.frame ) {
  15281. object.skeleton.update();
  15282. object.skeleton.frame = info.render.frame;
  15283. }
  15284. }
  15285. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15286. if ( sortObjects ) {
  15287. _vector3.setFromMatrixPosition( object.matrixWorld )
  15288. .applyMatrix4( _projScreenMatrix );
  15289. }
  15290. const geometry = objects.update( object );
  15291. const material = object.material;
  15292. if ( Array.isArray( material ) ) {
  15293. const groups = geometry.groups;
  15294. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15295. const group = groups[ i ];
  15296. const groupMaterial = material[ group.materialIndex ];
  15297. if ( groupMaterial && groupMaterial.visible ) {
  15298. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15299. }
  15300. }
  15301. } else if ( material.visible ) {
  15302. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15303. }
  15304. }
  15305. }
  15306. }
  15307. const children = object.children;
  15308. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15309. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15310. }
  15311. }
  15312. function renderObjects( renderList, scene, camera ) {
  15313. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15314. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15315. const renderItem = renderList[ i ];
  15316. const object = renderItem.object;
  15317. const geometry = renderItem.geometry;
  15318. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15319. const group = renderItem.group;
  15320. if ( camera.isArrayCamera ) {
  15321. const cameras = camera.cameras;
  15322. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  15323. const camera2 = cameras[ j ];
  15324. if ( object.layers.test( camera2.layers ) ) {
  15325. state.viewport( _currentViewport.copy( camera2.viewport ) );
  15326. currentRenderState.setupLightsView( camera2 );
  15327. renderObject( object, scene, camera2, geometry, material, group );
  15328. }
  15329. }
  15330. } else {
  15331. renderObject( object, scene, camera, geometry, material, group );
  15332. }
  15333. }
  15334. }
  15335. function renderObject( object, scene, camera, geometry, material, group ) {
  15336. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15337. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15338. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15339. if ( object.isImmediateRenderObject ) {
  15340. const program = setProgram( camera, scene, material, object );
  15341. state.setMaterial( material );
  15342. bindingStates.reset();
  15343. renderObjectImmediate( object, program );
  15344. } else {
  15345. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15346. }
  15347. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15348. }
  15349. function initMaterial( material, scene, object ) {
  15350. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15351. const materialProperties = properties.get( material );
  15352. const lights = currentRenderState.state.lights;
  15353. const shadowsArray = currentRenderState.state.shadowsArray;
  15354. const lightsStateVersion = lights.state.version;
  15355. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15356. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15357. let program = materialProperties.program;
  15358. let programChange = true;
  15359. if ( program === undefined ) {
  15360. // new material
  15361. material.addEventListener( 'dispose', onMaterialDispose );
  15362. } else if ( program.cacheKey !== programCacheKey ) {
  15363. // changed glsl or parameters
  15364. releaseMaterialProgramReference( material );
  15365. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  15366. programChange = false;
  15367. } else if ( parameters.shaderID !== undefined ) {
  15368. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15369. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15370. materialProperties.envMap = cubemaps.get( material.envMap || environment );
  15371. return;
  15372. } else {
  15373. // only rebuild uniform list
  15374. programChange = false;
  15375. }
  15376. if ( programChange ) {
  15377. parameters.uniforms = programCache.getUniforms( material );
  15378. material.onBeforeCompile( parameters, _this );
  15379. program = programCache.acquireProgram( parameters, programCacheKey );
  15380. materialProperties.program = program;
  15381. materialProperties.uniforms = parameters.uniforms;
  15382. materialProperties.outputEncoding = parameters.outputEncoding;
  15383. }
  15384. const uniforms = materialProperties.uniforms;
  15385. if ( ! material.isShaderMaterial &&
  15386. ! material.isRawShaderMaterial ||
  15387. material.clipping === true ) {
  15388. materialProperties.numClippingPlanes = clipping.numPlanes;
  15389. materialProperties.numIntersection = clipping.numIntersection;
  15390. uniforms.clippingPlanes = clipping.uniform;
  15391. }
  15392. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15393. materialProperties.fog = scene.fog;
  15394. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  15395. // store the light setup it was created for
  15396. materialProperties.needsLights = materialNeedsLights( material );
  15397. materialProperties.lightsStateVersion = lightsStateVersion;
  15398. if ( materialProperties.needsLights ) {
  15399. // wire up the material to this renderer's lighting state
  15400. uniforms.ambientLightColor.value = lights.state.ambient;
  15401. uniforms.lightProbe.value = lights.state.probe;
  15402. uniforms.directionalLights.value = lights.state.directional;
  15403. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15404. uniforms.spotLights.value = lights.state.spot;
  15405. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15406. uniforms.rectAreaLights.value = lights.state.rectArea;
  15407. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15408. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15409. uniforms.pointLights.value = lights.state.point;
  15410. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15411. uniforms.hemisphereLights.value = lights.state.hemi;
  15412. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15413. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15414. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15415. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15416. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15417. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15418. // TODO (abelnation): add area lights shadow info to uniforms
  15419. }
  15420. const progUniforms = materialProperties.program.getUniforms();
  15421. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15422. materialProperties.uniformsList = uniformsList;
  15423. }
  15424. function setProgram( camera, scene, material, object ) {
  15425. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15426. textures.resetTextureUnits();
  15427. const fog = scene.fog;
  15428. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15429. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15430. const envMap = cubemaps.get( material.envMap || environment );
  15431. const materialProperties = properties.get( material );
  15432. const lights = currentRenderState.state.lights;
  15433. if ( _clippingEnabled === true ) {
  15434. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  15435. const useCache =
  15436. camera === _currentCamera &&
  15437. material.id === _currentMaterialId;
  15438. // we might want to call this function with some ClippingGroup
  15439. // object instead of the material, once it becomes feasible
  15440. // (#8465, #8379)
  15441. clipping.setState( material, camera, useCache );
  15442. }
  15443. }
  15444. if ( material.version === materialProperties.__version ) {
  15445. if ( material.fog && materialProperties.fog !== fog ) {
  15446. initMaterial( material, scene, object );
  15447. } else if ( materialProperties.environment !== environment ) {
  15448. initMaterial( material, scene, object );
  15449. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  15450. initMaterial( material, scene, object );
  15451. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15452. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  15453. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  15454. initMaterial( material, scene, object );
  15455. } else if ( materialProperties.outputEncoding !== encoding ) {
  15456. initMaterial( material, scene, object );
  15457. } else if ( materialProperties.envMap !== envMap ) {
  15458. initMaterial( material, scene, object );
  15459. }
  15460. } else {
  15461. initMaterial( material, scene, object );
  15462. materialProperties.__version = material.version;
  15463. }
  15464. let refreshProgram = false;
  15465. let refreshMaterial = false;
  15466. let refreshLights = false;
  15467. const program = materialProperties.program,
  15468. p_uniforms = program.getUniforms(),
  15469. m_uniforms = materialProperties.uniforms;
  15470. if ( state.useProgram( program.program ) ) {
  15471. refreshProgram = true;
  15472. refreshMaterial = true;
  15473. refreshLights = true;
  15474. }
  15475. if ( material.id !== _currentMaterialId ) {
  15476. _currentMaterialId = material.id;
  15477. refreshMaterial = true;
  15478. }
  15479. if ( refreshProgram || _currentCamera !== camera ) {
  15480. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  15481. if ( capabilities.logarithmicDepthBuffer ) {
  15482. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15483. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15484. }
  15485. if ( _currentCamera !== camera ) {
  15486. _currentCamera = camera;
  15487. // lighting uniforms depend on the camera so enforce an update
  15488. // now, in case this material supports lights - or later, when
  15489. // the next material that does gets activated:
  15490. refreshMaterial = true; // set to true on material change
  15491. refreshLights = true; // remains set until update done
  15492. }
  15493. // load material specific uniforms
  15494. // (shader material also gets them for the sake of genericity)
  15495. if ( material.isShaderMaterial ||
  15496. material.isMeshPhongMaterial ||
  15497. material.isMeshToonMaterial ||
  15498. material.isMeshStandardMaterial ||
  15499. material.envMap ) {
  15500. const uCamPos = p_uniforms.map.cameraPosition;
  15501. if ( uCamPos !== undefined ) {
  15502. uCamPos.setValue( _gl,
  15503. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15504. }
  15505. }
  15506. if ( material.isMeshPhongMaterial ||
  15507. material.isMeshToonMaterial ||
  15508. material.isMeshLambertMaterial ||
  15509. material.isMeshBasicMaterial ||
  15510. material.isMeshStandardMaterial ||
  15511. material.isShaderMaterial ) {
  15512. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  15513. }
  15514. if ( material.isMeshPhongMaterial ||
  15515. material.isMeshToonMaterial ||
  15516. material.isMeshLambertMaterial ||
  15517. material.isMeshBasicMaterial ||
  15518. material.isMeshStandardMaterial ||
  15519. material.isShaderMaterial ||
  15520. material.isShadowMaterial ||
  15521. material.skinning ) {
  15522. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15523. }
  15524. }
  15525. // skinning uniforms must be set even if material didn't change
  15526. // auto-setting of texture unit for bone texture must go before other textures
  15527. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15528. if ( material.skinning ) {
  15529. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15530. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15531. const skeleton = object.skeleton;
  15532. if ( skeleton ) {
  15533. const bones = skeleton.bones;
  15534. if ( capabilities.floatVertexTextures ) {
  15535. if ( skeleton.boneTexture === null ) {
  15536. // layout (1 matrix = 4 pixels)
  15537. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15538. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15539. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15540. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15541. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15542. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  15543. size = MathUtils.ceilPowerOfTwo( size );
  15544. size = Math.max( size, 4 );
  15545. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15546. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  15547. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  15548. skeleton.boneMatrices = boneMatrices;
  15549. skeleton.boneTexture = boneTexture;
  15550. skeleton.boneTextureSize = size;
  15551. }
  15552. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  15553. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  15554. } else {
  15555. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15556. }
  15557. }
  15558. }
  15559. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  15560. materialProperties.receiveShadow = object.receiveShadow;
  15561. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  15562. }
  15563. if ( refreshMaterial ) {
  15564. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  15565. if ( materialProperties.needsLights ) {
  15566. // the current material requires lighting info
  15567. // note: all lighting uniforms are always set correctly
  15568. // they simply reference the renderer's state for their
  15569. // values
  15570. //
  15571. // use the current material's .needsUpdate flags to set
  15572. // the GL state when required
  15573. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15574. }
  15575. // refresh uniforms common to several materials
  15576. if ( fog && material.fog ) {
  15577. materials.refreshFogUniforms( m_uniforms, fog );
  15578. }
  15579. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  15580. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15581. }
  15582. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  15583. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15584. material.uniformsNeedUpdate = false;
  15585. }
  15586. if ( material.isSpriteMaterial ) {
  15587. p_uniforms.setValue( _gl, 'center', object.center );
  15588. }
  15589. // common matrices
  15590. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  15591. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  15592. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15593. return program;
  15594. }
  15595. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15596. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  15597. uniforms.ambientLightColor.needsUpdate = value;
  15598. uniforms.lightProbe.needsUpdate = value;
  15599. uniforms.directionalLights.needsUpdate = value;
  15600. uniforms.directionalLightShadows.needsUpdate = value;
  15601. uniforms.pointLights.needsUpdate = value;
  15602. uniforms.pointLightShadows.needsUpdate = value;
  15603. uniforms.spotLights.needsUpdate = value;
  15604. uniforms.spotLightShadows.needsUpdate = value;
  15605. uniforms.rectAreaLights.needsUpdate = value;
  15606. uniforms.hemisphereLights.needsUpdate = value;
  15607. }
  15608. function materialNeedsLights( material ) {
  15609. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  15610. material.isMeshStandardMaterial || material.isShadowMaterial ||
  15611. ( material.isShaderMaterial && material.lights === true );
  15612. }
  15613. //
  15614. this.setFramebuffer = function ( value ) {
  15615. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );
  15616. _framebuffer = value;
  15617. };
  15618. this.getActiveCubeFace = function () {
  15619. return _currentActiveCubeFace;
  15620. };
  15621. this.getActiveMipmapLevel = function () {
  15622. return _currentActiveMipmapLevel;
  15623. };
  15624. this.getRenderList = function () {
  15625. return currentRenderList;
  15626. };
  15627. this.setRenderList = function ( renderList ) {
  15628. currentRenderList = renderList;
  15629. };
  15630. this.getRenderTarget = function () {
  15631. return _currentRenderTarget;
  15632. };
  15633. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  15634. _currentRenderTarget = renderTarget;
  15635. _currentActiveCubeFace = activeCubeFace;
  15636. _currentActiveMipmapLevel = activeMipmapLevel;
  15637. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  15638. textures.setupRenderTarget( renderTarget );
  15639. }
  15640. let framebuffer = _framebuffer;
  15641. let isCube = false;
  15642. if ( renderTarget ) {
  15643. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15644. if ( renderTarget.isWebGLCubeRenderTarget ) {
  15645. framebuffer = __webglFramebuffer[ activeCubeFace ];
  15646. isCube = true;
  15647. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15648. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  15649. } else {
  15650. framebuffer = __webglFramebuffer;
  15651. }
  15652. _currentViewport.copy( renderTarget.viewport );
  15653. _currentScissor.copy( renderTarget.scissor );
  15654. _currentScissorTest = renderTarget.scissorTest;
  15655. } else {
  15656. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  15657. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  15658. _currentScissorTest = _scissorTest;
  15659. }
  15660. if ( _currentFramebuffer !== framebuffer ) {
  15661. _gl.bindFramebuffer( 36160, framebuffer );
  15662. _currentFramebuffer = framebuffer;
  15663. }
  15664. state.viewport( _currentViewport );
  15665. state.scissor( _currentScissor );
  15666. state.setScissorTest( _currentScissorTest );
  15667. if ( isCube ) {
  15668. const textureProperties = properties.get( renderTarget.texture );
  15669. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  15670. }
  15671. };
  15672. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  15673. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  15674. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  15675. return;
  15676. }
  15677. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15678. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  15679. framebuffer = framebuffer[ activeCubeFaceIndex ];
  15680. }
  15681. if ( framebuffer ) {
  15682. let restore = false;
  15683. if ( framebuffer !== _currentFramebuffer ) {
  15684. _gl.bindFramebuffer( 36160, framebuffer );
  15685. restore = true;
  15686. }
  15687. try {
  15688. const texture = renderTarget.texture;
  15689. const textureFormat = texture.format;
  15690. const textureType = texture.type;
  15691. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  15692. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  15693. return;
  15694. }
  15695. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15696. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  15697. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  15698. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  15699. return;
  15700. }
  15701. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  15702. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15703. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  15704. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  15705. }
  15706. } else {
  15707. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  15708. }
  15709. } finally {
  15710. if ( restore ) {
  15711. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  15712. }
  15713. }
  15714. }
  15715. };
  15716. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  15717. const levelScale = Math.pow( 2, - level );
  15718. const width = Math.floor( texture.image.width * levelScale );
  15719. const height = Math.floor( texture.image.height * levelScale );
  15720. const glFormat = utils.convert( texture.format );
  15721. textures.setTexture2D( texture, 0 );
  15722. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  15723. state.unbindTexture();
  15724. };
  15725. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  15726. const width = srcTexture.image.width;
  15727. const height = srcTexture.image.height;
  15728. const glFormat = utils.convert( dstTexture.format );
  15729. const glType = utils.convert( dstTexture.type );
  15730. textures.setTexture2D( dstTexture, 0 );
  15731. // As another texture upload may have changed pixelStorei
  15732. // parameters, make sure they are correct for the dstTexture
  15733. _gl.pixelStorei( 37440, dstTexture.flipY );
  15734. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15735. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15736. if ( srcTexture.isDataTexture ) {
  15737. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  15738. } else {
  15739. if ( srcTexture.isCompressedTexture ) {
  15740. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  15741. } else {
  15742. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  15743. }
  15744. }
  15745. // Generate mipmaps only when copying level 0
  15746. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15747. state.unbindTexture();
  15748. };
  15749. this.initTexture = function ( texture ) {
  15750. textures.setTexture2D( texture, 0 );
  15751. state.unbindTexture();
  15752. };
  15753. this.resetState = function () {
  15754. state.reset();
  15755. bindingStates.reset();
  15756. };
  15757. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15758. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15759. }
  15760. }
  15761. function WebGL1Renderer( parameters ) {
  15762. WebGLRenderer.call( this, parameters );
  15763. }
  15764. WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {
  15765. constructor: WebGL1Renderer,
  15766. isWebGL1Renderer: true
  15767. } );
  15768. class FogExp2 {
  15769. constructor( color, density ) {
  15770. Object.defineProperty( this, 'isFogExp2', { value: true } );
  15771. this.name = '';
  15772. this.color = new Color( color );
  15773. this.density = ( density !== undefined ) ? density : 0.00025;
  15774. }
  15775. clone() {
  15776. return new FogExp2( this.color, this.density );
  15777. }
  15778. toJSON( /* meta */ ) {
  15779. return {
  15780. type: 'FogExp2',
  15781. color: this.color.getHex(),
  15782. density: this.density
  15783. };
  15784. }
  15785. }
  15786. class Fog {
  15787. constructor( color, near, far ) {
  15788. Object.defineProperty( this, 'isFog', { value: true } );
  15789. this.name = '';
  15790. this.color = new Color( color );
  15791. this.near = ( near !== undefined ) ? near : 1;
  15792. this.far = ( far !== undefined ) ? far : 1000;
  15793. }
  15794. clone() {
  15795. return new Fog( this.color, this.near, this.far );
  15796. }
  15797. toJSON( /* meta */ ) {
  15798. return {
  15799. type: 'Fog',
  15800. color: this.color.getHex(),
  15801. near: this.near,
  15802. far: this.far
  15803. };
  15804. }
  15805. }
  15806. class Scene extends Object3D {
  15807. constructor() {
  15808. super();
  15809. Object.defineProperty( this, 'isScene', { value: true } );
  15810. this.type = 'Scene';
  15811. this.background = null;
  15812. this.environment = null;
  15813. this.fog = null;
  15814. this.overrideMaterial = null;
  15815. this.autoUpdate = true; // checked by the renderer
  15816. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15817. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15818. }
  15819. }
  15820. copy( source, recursive ) {
  15821. super.copy( source, recursive );
  15822. if ( source.background !== null ) this.background = source.background.clone();
  15823. if ( source.environment !== null ) this.environment = source.environment.clone();
  15824. if ( source.fog !== null ) this.fog = source.fog.clone();
  15825. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15826. this.autoUpdate = source.autoUpdate;
  15827. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15828. return this;
  15829. }
  15830. toJSON( meta ) {
  15831. const data = super.toJSON( meta );
  15832. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15833. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15834. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15835. return data;
  15836. }
  15837. }
  15838. function InterleavedBuffer( array, stride ) {
  15839. this.array = array;
  15840. this.stride = stride;
  15841. this.count = array !== undefined ? array.length / stride : 0;
  15842. this.usage = StaticDrawUsage;
  15843. this.updateRange = { offset: 0, count: - 1 };
  15844. this.version = 0;
  15845. this.uuid = MathUtils.generateUUID();
  15846. }
  15847. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  15848. set: function ( value ) {
  15849. if ( value === true ) this.version ++;
  15850. }
  15851. } );
  15852. Object.assign( InterleavedBuffer.prototype, {
  15853. isInterleavedBuffer: true,
  15854. onUploadCallback: function () {},
  15855. setUsage: function ( value ) {
  15856. this.usage = value;
  15857. return this;
  15858. },
  15859. copy: function ( source ) {
  15860. this.array = new source.array.constructor( source.array );
  15861. this.count = source.count;
  15862. this.stride = source.stride;
  15863. this.usage = source.usage;
  15864. return this;
  15865. },
  15866. copyAt: function ( index1, attribute, index2 ) {
  15867. index1 *= this.stride;
  15868. index2 *= attribute.stride;
  15869. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15870. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15871. }
  15872. return this;
  15873. },
  15874. set: function ( value, offset = 0 ) {
  15875. this.array.set( value, offset );
  15876. return this;
  15877. },
  15878. clone: function ( data ) {
  15879. if ( data.arrayBuffers === undefined ) {
  15880. data.arrayBuffers = {};
  15881. }
  15882. if ( this.array.buffer._uuid === undefined ) {
  15883. this.array.buffer._uuid = MathUtils.generateUUID();
  15884. }
  15885. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15886. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15887. }
  15888. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15889. const ib = new InterleavedBuffer( array, this.stride );
  15890. ib.setUsage( this.usage );
  15891. return ib;
  15892. },
  15893. onUpload: function ( callback ) {
  15894. this.onUploadCallback = callback;
  15895. return this;
  15896. },
  15897. toJSON: function ( data ) {
  15898. if ( data.arrayBuffers === undefined ) {
  15899. data.arrayBuffers = {};
  15900. }
  15901. // generate UUID for array buffer if necessary
  15902. if ( this.array.buffer._uuid === undefined ) {
  15903. this.array.buffer._uuid = MathUtils.generateUUID();
  15904. }
  15905. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15906. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15907. }
  15908. //
  15909. return {
  15910. uuid: this.uuid,
  15911. buffer: this.array.buffer._uuid,
  15912. type: this.array.constructor.name,
  15913. stride: this.stride
  15914. };
  15915. }
  15916. } );
  15917. const _vector$6 = new Vector3();
  15918. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  15919. this.name = '';
  15920. this.data = interleavedBuffer;
  15921. this.itemSize = itemSize;
  15922. this.offset = offset;
  15923. this.normalized = normalized === true;
  15924. }
  15925. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  15926. count: {
  15927. get: function () {
  15928. return this.data.count;
  15929. }
  15930. },
  15931. array: {
  15932. get: function () {
  15933. return this.data.array;
  15934. }
  15935. },
  15936. needsUpdate: {
  15937. set: function ( value ) {
  15938. this.data.needsUpdate = value;
  15939. }
  15940. }
  15941. } );
  15942. Object.assign( InterleavedBufferAttribute.prototype, {
  15943. isInterleavedBufferAttribute: true,
  15944. applyMatrix4: function ( m ) {
  15945. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15946. _vector$6.x = this.getX( i );
  15947. _vector$6.y = this.getY( i );
  15948. _vector$6.z = this.getZ( i );
  15949. _vector$6.applyMatrix4( m );
  15950. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15951. }
  15952. return this;
  15953. },
  15954. setX: function ( index, x ) {
  15955. this.data.array[ index * this.data.stride + this.offset ] = x;
  15956. return this;
  15957. },
  15958. setY: function ( index, y ) {
  15959. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15960. return this;
  15961. },
  15962. setZ: function ( index, z ) {
  15963. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15964. return this;
  15965. },
  15966. setW: function ( index, w ) {
  15967. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15968. return this;
  15969. },
  15970. getX: function ( index ) {
  15971. return this.data.array[ index * this.data.stride + this.offset ];
  15972. },
  15973. getY: function ( index ) {
  15974. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15975. },
  15976. getZ: function ( index ) {
  15977. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15978. },
  15979. getW: function ( index ) {
  15980. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15981. },
  15982. setXY: function ( index, x, y ) {
  15983. index = index * this.data.stride + this.offset;
  15984. this.data.array[ index + 0 ] = x;
  15985. this.data.array[ index + 1 ] = y;
  15986. return this;
  15987. },
  15988. setXYZ: function ( index, x, y, z ) {
  15989. index = index * this.data.stride + this.offset;
  15990. this.data.array[ index + 0 ] = x;
  15991. this.data.array[ index + 1 ] = y;
  15992. this.data.array[ index + 2 ] = z;
  15993. return this;
  15994. },
  15995. setXYZW: function ( index, x, y, z, w ) {
  15996. index = index * this.data.stride + this.offset;
  15997. this.data.array[ index + 0 ] = x;
  15998. this.data.array[ index + 1 ] = y;
  15999. this.data.array[ index + 2 ] = z;
  16000. this.data.array[ index + 3 ] = w;
  16001. return this;
  16002. },
  16003. clone: function ( data ) {
  16004. if ( data === undefined ) {
  16005. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16006. const array = [];
  16007. for ( let i = 0; i < this.count; i ++ ) {
  16008. const index = i * this.data.stride + this.offset;
  16009. for ( let j = 0; j < this.itemSize; j ++ ) {
  16010. array.push( this.data.array[ index + j ] );
  16011. }
  16012. }
  16013. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16014. } else {
  16015. if ( data.interleavedBuffers === undefined ) {
  16016. data.interleavedBuffers = {};
  16017. }
  16018. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16019. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16020. }
  16021. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16022. }
  16023. },
  16024. toJSON: function ( data ) {
  16025. if ( data === undefined ) {
  16026. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16027. const array = [];
  16028. for ( let i = 0; i < this.count; i ++ ) {
  16029. const index = i * this.data.stride + this.offset;
  16030. for ( let j = 0; j < this.itemSize; j ++ ) {
  16031. array.push( this.data.array[ index + j ] );
  16032. }
  16033. }
  16034. // deinterleave data and save it as an ordinary buffer attribute for now
  16035. return {
  16036. itemSize: this.itemSize,
  16037. type: this.array.constructor.name,
  16038. array: array,
  16039. normalized: this.normalized
  16040. };
  16041. } else {
  16042. // save as true interlaved attribtue
  16043. if ( data.interleavedBuffers === undefined ) {
  16044. data.interleavedBuffers = {};
  16045. }
  16046. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16047. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16048. }
  16049. return {
  16050. isInterleavedBufferAttribute: true,
  16051. itemSize: this.itemSize,
  16052. data: this.data.uuid,
  16053. offset: this.offset,
  16054. normalized: this.normalized
  16055. };
  16056. }
  16057. }
  16058. } );
  16059. /**
  16060. * parameters = {
  16061. * color: <hex>,
  16062. * map: new THREE.Texture( <Image> ),
  16063. * alphaMap: new THREE.Texture( <Image> ),
  16064. * rotation: <float>,
  16065. * sizeAttenuation: <bool>
  16066. * }
  16067. */
  16068. function SpriteMaterial( parameters ) {
  16069. Material.call( this );
  16070. this.type = 'SpriteMaterial';
  16071. this.color = new Color( 0xffffff );
  16072. this.map = null;
  16073. this.alphaMap = null;
  16074. this.rotation = 0;
  16075. this.sizeAttenuation = true;
  16076. this.transparent = true;
  16077. this.setValues( parameters );
  16078. }
  16079. SpriteMaterial.prototype = Object.create( Material.prototype );
  16080. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16081. SpriteMaterial.prototype.isSpriteMaterial = true;
  16082. SpriteMaterial.prototype.copy = function ( source ) {
  16083. Material.prototype.copy.call( this, source );
  16084. this.color.copy( source.color );
  16085. this.map = source.map;
  16086. this.alphaMap = source.alphaMap;
  16087. this.rotation = source.rotation;
  16088. this.sizeAttenuation = source.sizeAttenuation;
  16089. return this;
  16090. };
  16091. let _geometry;
  16092. const _intersectPoint = new Vector3();
  16093. const _worldScale = new Vector3();
  16094. const _mvPosition = new Vector3();
  16095. const _alignedPosition = new Vector2$1();
  16096. const _rotatedPosition = new Vector2$1();
  16097. const _viewWorldMatrix = new Matrix4();
  16098. const _vA$1 = new Vector3();
  16099. const _vB$1 = new Vector3();
  16100. const _vC$1 = new Vector3();
  16101. const _uvA$1 = new Vector2$1();
  16102. const _uvB$1 = new Vector2$1();
  16103. const _uvC$1 = new Vector2$1();
  16104. function Sprite( material ) {
  16105. Object3D.call( this );
  16106. this.type = 'Sprite';
  16107. if ( _geometry === undefined ) {
  16108. _geometry = new BufferGeometry();
  16109. const float32Array = new Float32Array( [
  16110. - 0.5, - 0.5, 0, 0, 0,
  16111. 0.5, - 0.5, 0, 1, 0,
  16112. 0.5, 0.5, 0, 1, 1,
  16113. - 0.5, 0.5, 0, 0, 1
  16114. ] );
  16115. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16116. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16117. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16118. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16119. }
  16120. this.geometry = _geometry;
  16121. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16122. this.center = new Vector2$1( 0.5, 0.5 );
  16123. }
  16124. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16125. constructor: Sprite,
  16126. isSprite: true,
  16127. raycast: function ( raycaster, intersects ) {
  16128. if ( raycaster.camera === null ) {
  16129. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16130. }
  16131. _worldScale.setFromMatrixScale( this.matrixWorld );
  16132. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16133. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16134. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16135. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16136. _worldScale.multiplyScalar( - _mvPosition.z );
  16137. }
  16138. const rotation = this.material.rotation;
  16139. let sin, cos;
  16140. if ( rotation !== 0 ) {
  16141. cos = Math.cos( rotation );
  16142. sin = Math.sin( rotation );
  16143. }
  16144. const center = this.center;
  16145. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16146. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16147. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16148. _uvA$1.set( 0, 0 );
  16149. _uvB$1.set( 1, 0 );
  16150. _uvC$1.set( 1, 1 );
  16151. // check first triangle
  16152. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16153. if ( intersect === null ) {
  16154. // check second triangle
  16155. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16156. _uvB$1.set( 0, 1 );
  16157. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16158. if ( intersect === null ) {
  16159. return;
  16160. }
  16161. }
  16162. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16163. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16164. intersects.push( {
  16165. distance: distance,
  16166. point: _intersectPoint.clone(),
  16167. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2$1() ),
  16168. face: null,
  16169. object: this
  16170. } );
  16171. },
  16172. copy: function ( source ) {
  16173. Object3D.prototype.copy.call( this, source );
  16174. if ( source.center !== undefined ) this.center.copy( source.center );
  16175. this.material = source.material;
  16176. return this;
  16177. }
  16178. } );
  16179. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16180. // compute position in camera space
  16181. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16182. // to check if rotation is not zero
  16183. if ( sin !== undefined ) {
  16184. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16185. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16186. } else {
  16187. _rotatedPosition.copy( _alignedPosition );
  16188. }
  16189. vertexPosition.copy( mvPosition );
  16190. vertexPosition.x += _rotatedPosition.x;
  16191. vertexPosition.y += _rotatedPosition.y;
  16192. // transform to world space
  16193. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16194. }
  16195. const _v1$4 = new Vector3();
  16196. const _v2$2 = new Vector3();
  16197. function LOD() {
  16198. Object3D.call( this );
  16199. this._currentLevel = 0;
  16200. this.type = 'LOD';
  16201. Object.defineProperties( this, {
  16202. levels: {
  16203. enumerable: true,
  16204. value: []
  16205. }
  16206. } );
  16207. this.autoUpdate = true;
  16208. }
  16209. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16210. constructor: LOD,
  16211. isLOD: true,
  16212. copy: function ( source ) {
  16213. Object3D.prototype.copy.call( this, source, false );
  16214. const levels = source.levels;
  16215. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16216. const level = levels[ i ];
  16217. this.addLevel( level.object.clone(), level.distance );
  16218. }
  16219. this.autoUpdate = source.autoUpdate;
  16220. return this;
  16221. },
  16222. addLevel: function ( object, distance = 0 ) {
  16223. distance = Math.abs( distance );
  16224. const levels = this.levels;
  16225. let l;
  16226. for ( l = 0; l < levels.length; l ++ ) {
  16227. if ( distance < levels[ l ].distance ) {
  16228. break;
  16229. }
  16230. }
  16231. levels.splice( l, 0, { distance: distance, object: object } );
  16232. this.add( object );
  16233. return this;
  16234. },
  16235. getCurrentLevel: function () {
  16236. return this._currentLevel;
  16237. },
  16238. getObjectForDistance: function ( distance ) {
  16239. const levels = this.levels;
  16240. if ( levels.length > 0 ) {
  16241. let i, l;
  16242. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16243. if ( distance < levels[ i ].distance ) {
  16244. break;
  16245. }
  16246. }
  16247. return levels[ i - 1 ].object;
  16248. }
  16249. return null;
  16250. },
  16251. raycast: function ( raycaster, intersects ) {
  16252. const levels = this.levels;
  16253. if ( levels.length > 0 ) {
  16254. _v1$4.setFromMatrixPosition( this.matrixWorld );
  16255. const distance = raycaster.ray.origin.distanceTo( _v1$4 );
  16256. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16257. }
  16258. },
  16259. update: function ( camera ) {
  16260. const levels = this.levels;
  16261. if ( levels.length > 1 ) {
  16262. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  16263. _v2$2.setFromMatrixPosition( this.matrixWorld );
  16264. const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  16265. levels[ 0 ].object.visible = true;
  16266. let i, l;
  16267. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16268. if ( distance >= levels[ i ].distance ) {
  16269. levels[ i - 1 ].object.visible = false;
  16270. levels[ i ].object.visible = true;
  16271. } else {
  16272. break;
  16273. }
  16274. }
  16275. this._currentLevel = i - 1;
  16276. for ( ; i < l; i ++ ) {
  16277. levels[ i ].object.visible = false;
  16278. }
  16279. }
  16280. },
  16281. toJSON: function ( meta ) {
  16282. const data = Object3D.prototype.toJSON.call( this, meta );
  16283. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16284. data.object.levels = [];
  16285. const levels = this.levels;
  16286. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16287. const level = levels[ i ];
  16288. data.object.levels.push( {
  16289. object: level.object.uuid,
  16290. distance: level.distance
  16291. } );
  16292. }
  16293. return data;
  16294. }
  16295. } );
  16296. const _basePosition = new Vector3();
  16297. const _skinIndex = new Vector4();
  16298. const _skinWeight = new Vector4();
  16299. const _vector$7 = new Vector3();
  16300. const _matrix$1 = new Matrix4();
  16301. function SkinnedMesh( geometry, material ) {
  16302. if ( geometry && geometry.isGeometry ) {
  16303. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16304. }
  16305. Mesh.call( this, geometry, material );
  16306. this.type = 'SkinnedMesh';
  16307. this.bindMode = 'attached';
  16308. this.bindMatrix = new Matrix4();
  16309. this.bindMatrixInverse = new Matrix4();
  16310. }
  16311. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16312. constructor: SkinnedMesh,
  16313. isSkinnedMesh: true,
  16314. copy: function ( source ) {
  16315. Mesh.prototype.copy.call( this, source );
  16316. this.bindMode = source.bindMode;
  16317. this.bindMatrix.copy( source.bindMatrix );
  16318. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  16319. this.skeleton = source.skeleton;
  16320. return this;
  16321. },
  16322. bind: function ( skeleton, bindMatrix ) {
  16323. this.skeleton = skeleton;
  16324. if ( bindMatrix === undefined ) {
  16325. this.updateMatrixWorld( true );
  16326. this.skeleton.calculateInverses();
  16327. bindMatrix = this.matrixWorld;
  16328. }
  16329. this.bindMatrix.copy( bindMatrix );
  16330. this.bindMatrixInverse.copy( bindMatrix ).invert();
  16331. },
  16332. pose: function () {
  16333. this.skeleton.pose();
  16334. },
  16335. normalizeSkinWeights: function () {
  16336. const vector = new Vector4();
  16337. const skinWeight = this.geometry.attributes.skinWeight;
  16338. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  16339. vector.x = skinWeight.getX( i );
  16340. vector.y = skinWeight.getY( i );
  16341. vector.z = skinWeight.getZ( i );
  16342. vector.w = skinWeight.getW( i );
  16343. const scale = 1.0 / vector.manhattanLength();
  16344. if ( scale !== Infinity ) {
  16345. vector.multiplyScalar( scale );
  16346. } else {
  16347. vector.set( 1, 0, 0, 0 ); // do something reasonable
  16348. }
  16349. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  16350. }
  16351. },
  16352. updateMatrixWorld: function ( force ) {
  16353. Mesh.prototype.updateMatrixWorld.call( this, force );
  16354. if ( this.bindMode === 'attached' ) {
  16355. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  16356. } else if ( this.bindMode === 'detached' ) {
  16357. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  16358. } else {
  16359. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  16360. }
  16361. },
  16362. boneTransform: function ( index, target ) {
  16363. const skeleton = this.skeleton;
  16364. const geometry = this.geometry;
  16365. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  16366. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  16367. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  16368. target.set( 0, 0, 0 );
  16369. for ( let i = 0; i < 4; i ++ ) {
  16370. const weight = _skinWeight.getComponent( i );
  16371. if ( weight !== 0 ) {
  16372. const boneIndex = _skinIndex.getComponent( i );
  16373. _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  16374. target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight );
  16375. }
  16376. }
  16377. return target.applyMatrix4( this.bindMatrixInverse );
  16378. }
  16379. } );
  16380. function Bone() {
  16381. Object3D.call( this );
  16382. this.type = 'Bone';
  16383. }
  16384. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16385. constructor: Bone,
  16386. isBone: true
  16387. } );
  16388. const _offsetMatrix = new Matrix4();
  16389. const _identityMatrix = new Matrix4();
  16390. function Skeleton( bones = [], boneInverses = [] ) {
  16391. this.uuid = MathUtils.generateUUID();
  16392. this.bones = bones.slice( 0 );
  16393. this.boneInverses = boneInverses;
  16394. this.boneMatrices = null;
  16395. this.boneTexture = null;
  16396. this.boneTextureSize = 0;
  16397. this.frame = - 1;
  16398. this.init();
  16399. }
  16400. Object.assign( Skeleton.prototype, {
  16401. init: function () {
  16402. const bones = this.bones;
  16403. const boneInverses = this.boneInverses;
  16404. this.boneMatrices = new Float32Array( bones.length * 16 );
  16405. // calculate inverse bone matrices if necessary
  16406. if ( boneInverses.length === 0 ) {
  16407. this.calculateInverses();
  16408. } else {
  16409. // handle special case
  16410. if ( bones.length !== boneInverses.length ) {
  16411. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  16412. this.boneInverses = [];
  16413. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16414. this.boneInverses.push( new Matrix4() );
  16415. }
  16416. }
  16417. }
  16418. },
  16419. calculateInverses: function () {
  16420. this.boneInverses.length = 0;
  16421. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16422. const inverse = new Matrix4();
  16423. if ( this.bones[ i ] ) {
  16424. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  16425. }
  16426. this.boneInverses.push( inverse );
  16427. }
  16428. },
  16429. pose: function () {
  16430. // recover the bind-time world matrices
  16431. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16432. const bone = this.bones[ i ];
  16433. if ( bone ) {
  16434. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  16435. }
  16436. }
  16437. // compute the local matrices, positions, rotations and scales
  16438. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16439. const bone = this.bones[ i ];
  16440. if ( bone ) {
  16441. if ( bone.parent && bone.parent.isBone ) {
  16442. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  16443. bone.matrix.multiply( bone.matrixWorld );
  16444. } else {
  16445. bone.matrix.copy( bone.matrixWorld );
  16446. }
  16447. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  16448. }
  16449. }
  16450. },
  16451. update: function () {
  16452. const bones = this.bones;
  16453. const boneInverses = this.boneInverses;
  16454. const boneMatrices = this.boneMatrices;
  16455. const boneTexture = this.boneTexture;
  16456. // flatten bone matrices to array
  16457. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  16458. // compute the offset between the current and the original transform
  16459. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  16460. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  16461. _offsetMatrix.toArray( boneMatrices, i * 16 );
  16462. }
  16463. if ( boneTexture !== null ) {
  16464. boneTexture.needsUpdate = true;
  16465. }
  16466. },
  16467. clone: function () {
  16468. return new Skeleton( this.bones, this.boneInverses );
  16469. },
  16470. getBoneByName: function ( name ) {
  16471. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16472. const bone = this.bones[ i ];
  16473. if ( bone.name === name ) {
  16474. return bone;
  16475. }
  16476. }
  16477. return undefined;
  16478. },
  16479. dispose: function ( ) {
  16480. if ( this.boneTexture !== null ) {
  16481. this.boneTexture.dispose();
  16482. this.boneTexture = null;
  16483. }
  16484. },
  16485. fromJSON: function ( json, bones ) {
  16486. this.uuid = json.uuid;
  16487. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  16488. const uuid = json.bones[ i ];
  16489. let bone = bones[ uuid ];
  16490. if ( bone === undefined ) {
  16491. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  16492. bone = new Bone();
  16493. }
  16494. this.bones.push( bone );
  16495. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  16496. }
  16497. this.init();
  16498. return this;
  16499. },
  16500. toJSON: function () {
  16501. const data = {
  16502. metadata: {
  16503. version: 4.5,
  16504. type: 'Skeleton',
  16505. generator: 'Skeleton.toJSON'
  16506. },
  16507. bones: [],
  16508. boneInverses: []
  16509. };
  16510. data.uuid = this.uuid;
  16511. const bones = this.bones;
  16512. const boneInverses = this.boneInverses;
  16513. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  16514. const bone = bones[ i ];
  16515. data.bones.push( bone.uuid );
  16516. const boneInverse = boneInverses[ i ];
  16517. data.boneInverses.push( boneInverse.toArray() );
  16518. }
  16519. return data;
  16520. }
  16521. } );
  16522. const _instanceLocalMatrix = new Matrix4();
  16523. const _instanceWorldMatrix = new Matrix4();
  16524. const _instanceIntersects = [];
  16525. const _mesh = new Mesh();
  16526. function InstancedMesh( geometry, material, count ) {
  16527. Mesh.call( this, geometry, material );
  16528. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  16529. this.instanceColor = null;
  16530. this.count = count;
  16531. this.frustumCulled = false;
  16532. }
  16533. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16534. constructor: InstancedMesh,
  16535. isInstancedMesh: true,
  16536. copy: function ( source ) {
  16537. Mesh.prototype.copy.call( this, source );
  16538. this.instanceMatrix.copy( source.instanceMatrix );
  16539. this.count = source.count;
  16540. return this;
  16541. },
  16542. getColorAt: function ( index, color ) {
  16543. color.fromArray( this.instanceColor.array, index * 3 );
  16544. },
  16545. getMatrixAt: function ( index, matrix ) {
  16546. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  16547. },
  16548. raycast: function ( raycaster, intersects ) {
  16549. const matrixWorld = this.matrixWorld;
  16550. const raycastTimes = this.count;
  16551. _mesh.geometry = this.geometry;
  16552. _mesh.material = this.material;
  16553. if ( _mesh.material === undefined ) return;
  16554. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  16555. // calculate the world matrix for each instance
  16556. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  16557. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  16558. // the mesh represents this single instance
  16559. _mesh.matrixWorld = _instanceWorldMatrix;
  16560. _mesh.raycast( raycaster, _instanceIntersects );
  16561. // process the result of raycast
  16562. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  16563. const intersect = _instanceIntersects[ i ];
  16564. intersect.instanceId = instanceId;
  16565. intersect.object = this;
  16566. intersects.push( intersect );
  16567. }
  16568. _instanceIntersects.length = 0;
  16569. }
  16570. },
  16571. setColorAt: function ( index, color ) {
  16572. if ( this.instanceColor === null ) {
  16573. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  16574. }
  16575. color.toArray( this.instanceColor.array, index * 3 );
  16576. },
  16577. setMatrixAt: function ( index, matrix ) {
  16578. matrix.toArray( this.instanceMatrix.array, index * 16 );
  16579. },
  16580. updateMorphTargets: function () {
  16581. },
  16582. dispose: function () {
  16583. this.dispatchEvent( { type: 'dispose' } );
  16584. }
  16585. } );
  16586. /**
  16587. * parameters = {
  16588. * color: <hex>,
  16589. * opacity: <float>,
  16590. *
  16591. * lineWidth: <float>,
  16592. * linecap: "round",
  16593. * linejoin: "round"
  16594. * }
  16595. */
  16596. function LineBasicMaterial( parameters ) {
  16597. Material.call( this );
  16598. this.type = 'LineBasicMaterial';
  16599. this.color = new Color( 0xffffff );
  16600. this.lineWidth = 1;
  16601. this.linecap = 'round';
  16602. this.linejoin = 'round';
  16603. this.morphTargets = false;
  16604. this.setValues( parameters );
  16605. }
  16606. LineBasicMaterial.prototype = Object.create( Material.prototype );
  16607. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16608. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16609. LineBasicMaterial.prototype.copy = function ( source ) {
  16610. Material.prototype.copy.call( this, source );
  16611. this.color.copy( source.color );
  16612. this.lineWidth = source.lineWidth;
  16613. this.linecap = source.linecap;
  16614. this.linejoin = source.linejoin;
  16615. this.morphTargets = source.morphTargets;
  16616. return this;
  16617. };
  16618. const _start = new Vector3();
  16619. const _end = new Vector3();
  16620. const _inverseMatrix$1 = new Matrix4();
  16621. const _ray$1 = new Ray();
  16622. const _sphere$2 = new Sphere();
  16623. function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  16624. Object3D.call( this );
  16625. this.type = 'Line';
  16626. this.geometry = geometry;
  16627. this.material = material;
  16628. this.updateMorphTargets();
  16629. }
  16630. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16631. constructor: Line,
  16632. isLine: true,
  16633. copy: function ( source ) {
  16634. Object3D.prototype.copy.call( this, source );
  16635. this.material = source.material;
  16636. this.geometry = source.geometry;
  16637. return this;
  16638. },
  16639. computeLineDistances: function () {
  16640. const geometry = this.geometry;
  16641. if ( geometry.isBufferGeometry ) {
  16642. // we assume non-indexed geometry
  16643. if ( geometry.index === null ) {
  16644. const positionAttribute = geometry.attributes.position;
  16645. const lineDistances = [ 0 ];
  16646. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16647. _start.fromBufferAttribute( positionAttribute, i - 1 );
  16648. _end.fromBufferAttribute( positionAttribute, i );
  16649. lineDistances[ i ] = lineDistances[ i - 1 ];
  16650. lineDistances[ i ] += _start.distanceTo( _end );
  16651. }
  16652. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16653. } else {
  16654. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16655. }
  16656. } else if ( geometry.isGeometry ) {
  16657. const vertices = geometry.vertices;
  16658. const lineDistances = geometry.lineDistances;
  16659. lineDistances[ 0 ] = 0;
  16660. for ( let i = 1, l = vertices.length; i < l; i ++ ) {
  16661. lineDistances[ i ] = lineDistances[ i - 1 ];
  16662. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  16663. }
  16664. }
  16665. return this;
  16666. },
  16667. raycast: function ( raycaster, intersects ) {
  16668. const geometry = this.geometry;
  16669. const matrixWorld = this.matrixWorld;
  16670. const threshold = raycaster.params.Line.threshold;
  16671. // Checking boundingSphere distance to ray
  16672. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16673. _sphere$2.copy( geometry.boundingSphere );
  16674. _sphere$2.applyMatrix4( matrixWorld );
  16675. _sphere$2.radius += threshold;
  16676. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  16677. //
  16678. _inverseMatrix$1.copy( matrixWorld ).invert();
  16679. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16680. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16681. const localThresholdSq = localThreshold * localThreshold;
  16682. const vStart = new Vector3();
  16683. const vEnd = new Vector3();
  16684. const interSegment = new Vector3();
  16685. const interRay = new Vector3();
  16686. const step = this.isLineSegments ? 2 : 1;
  16687. if ( geometry.isBufferGeometry ) {
  16688. const index = geometry.index;
  16689. const attributes = geometry.attributes;
  16690. const positionAttribute = attributes.position;
  16691. if ( index !== null ) {
  16692. const indices = index.array;
  16693. for ( let i = 0, l = indices.length - 1; i < l; i += step ) {
  16694. const a = indices[ i ];
  16695. const b = indices[ i + 1 ];
  16696. vStart.fromBufferAttribute( positionAttribute, a );
  16697. vEnd.fromBufferAttribute( positionAttribute, b );
  16698. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16699. if ( distSq > localThresholdSq ) continue;
  16700. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16701. const distance = raycaster.ray.origin.distanceTo( interRay );
  16702. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16703. intersects.push( {
  16704. distance: distance,
  16705. // What do we want? intersection point on the ray or on the segment??
  16706. // point: raycaster.ray.at( distance ),
  16707. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16708. index: i,
  16709. face: null,
  16710. faceIndex: null,
  16711. object: this
  16712. } );
  16713. }
  16714. } else {
  16715. for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) {
  16716. vStart.fromBufferAttribute( positionAttribute, i );
  16717. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  16718. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16719. if ( distSq > localThresholdSq ) continue;
  16720. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16721. const distance = raycaster.ray.origin.distanceTo( interRay );
  16722. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16723. intersects.push( {
  16724. distance: distance,
  16725. // What do we want? intersection point on the ray or on the segment??
  16726. // point: raycaster.ray.at( distance ),
  16727. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16728. index: i,
  16729. face: null,
  16730. faceIndex: null,
  16731. object: this
  16732. } );
  16733. }
  16734. }
  16735. } else if ( geometry.isGeometry ) {
  16736. const vertices = geometry.vertices;
  16737. const nbVertices = vertices.length;
  16738. for ( let i = 0; i < nbVertices - 1; i += step ) {
  16739. const distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  16740. if ( distSq > localThresholdSq ) continue;
  16741. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16742. const distance = raycaster.ray.origin.distanceTo( interRay );
  16743. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16744. intersects.push( {
  16745. distance: distance,
  16746. // What do we want? intersection point on the ray or on the segment??
  16747. // point: raycaster.ray.at( distance ),
  16748. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16749. index: i,
  16750. face: null,
  16751. faceIndex: null,
  16752. object: this
  16753. } );
  16754. }
  16755. }
  16756. },
  16757. updateMorphTargets: function () {
  16758. const geometry = this.geometry;
  16759. if ( geometry.isBufferGeometry ) {
  16760. const morphAttributes = geometry.morphAttributes;
  16761. const keys = Object.keys( morphAttributes );
  16762. if ( keys.length > 0 ) {
  16763. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16764. if ( morphAttribute !== undefined ) {
  16765. this.morphTargetInfluences = [];
  16766. this.morphTargetDictionary = {};
  16767. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16768. const name = morphAttribute[ m ].name || String( m );
  16769. this.morphTargetInfluences.push( 0 );
  16770. this.morphTargetDictionary[ name ] = m;
  16771. }
  16772. }
  16773. }
  16774. } else {
  16775. const morphTargets = geometry.morphTargets;
  16776. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16777. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16778. }
  16779. }
  16780. }
  16781. } );
  16782. const _start$1 = new Vector3();
  16783. const _end$1 = new Vector3();
  16784. function LineSegments( geometry, material ) {
  16785. Line.call( this, geometry, material );
  16786. this.type = 'LineSegments';
  16787. }
  16788. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  16789. constructor: LineSegments,
  16790. isLineSegments: true,
  16791. computeLineDistances: function () {
  16792. const geometry = this.geometry;
  16793. if ( geometry.isBufferGeometry ) {
  16794. // we assume non-indexed geometry
  16795. if ( geometry.index === null ) {
  16796. const positionAttribute = geometry.attributes.position;
  16797. const lineDistances = [];
  16798. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16799. _start$1.fromBufferAttribute( positionAttribute, i );
  16800. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  16801. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16802. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16803. }
  16804. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16805. } else {
  16806. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16807. }
  16808. } else if ( geometry.isGeometry ) {
  16809. const vertices = geometry.vertices;
  16810. const lineDistances = geometry.lineDistances;
  16811. for ( let i = 0, l = vertices.length; i < l; i += 2 ) {
  16812. _start$1.copy( vertices[ i ] );
  16813. _end$1.copy( vertices[ i + 1 ] );
  16814. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16815. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16816. }
  16817. }
  16818. return this;
  16819. }
  16820. } );
  16821. function LineLoop( geometry, material ) {
  16822. Line.call( this, geometry, material );
  16823. this.type = 'LineLoop';
  16824. }
  16825. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  16826. constructor: LineLoop,
  16827. isLineLoop: true,
  16828. } );
  16829. /**
  16830. * parameters = {
  16831. * color: <hex>,
  16832. * opacity: <float>,
  16833. * map: new THREE.Texture( <Image> ),
  16834. * alphaMap: new THREE.Texture( <Image> ),
  16835. *
  16836. * size: <float>,
  16837. * sizeAttenuation: <bool>
  16838. *
  16839. * morphTargets: <bool>
  16840. * }
  16841. */
  16842. function PointsMaterial( parameters ) {
  16843. Material.call( this );
  16844. this.type = 'PointsMaterial';
  16845. this.color = new Color( 0xffffff );
  16846. this.map = null;
  16847. this.alphaMap = null;
  16848. this.size = 1;
  16849. this.sizeAttenuation = true;
  16850. this.morphTargets = false;
  16851. this.setValues( parameters );
  16852. }
  16853. PointsMaterial.prototype = Object.create( Material.prototype );
  16854. PointsMaterial.prototype.constructor = PointsMaterial;
  16855. PointsMaterial.prototype.isPointsMaterial = true;
  16856. PointsMaterial.prototype.copy = function ( source ) {
  16857. Material.prototype.copy.call( this, source );
  16858. this.color.copy( source.color );
  16859. this.map = source.map;
  16860. this.alphaMap = source.alphaMap;
  16861. this.size = source.size;
  16862. this.sizeAttenuation = source.sizeAttenuation;
  16863. this.morphTargets = source.morphTargets;
  16864. return this;
  16865. };
  16866. const _inverseMatrix$2 = new Matrix4();
  16867. const _ray$2 = new Ray();
  16868. const _sphere$3 = new Sphere();
  16869. const _position$1 = new Vector3();
  16870. function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16871. Object3D.call( this );
  16872. this.type = 'Points';
  16873. this.geometry = geometry;
  16874. this.material = material;
  16875. this.updateMorphTargets();
  16876. }
  16877. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16878. constructor: Points,
  16879. isPoints: true,
  16880. copy: function ( source ) {
  16881. Object3D.prototype.copy.call( this, source );
  16882. this.material = source.material;
  16883. this.geometry = source.geometry;
  16884. return this;
  16885. },
  16886. raycast: function ( raycaster, intersects ) {
  16887. const geometry = this.geometry;
  16888. const matrixWorld = this.matrixWorld;
  16889. const threshold = raycaster.params.Points.threshold;
  16890. // Checking boundingSphere distance to ray
  16891. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16892. _sphere$3.copy( geometry.boundingSphere );
  16893. _sphere$3.applyMatrix4( matrixWorld );
  16894. _sphere$3.radius += threshold;
  16895. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  16896. //
  16897. _inverseMatrix$2.copy( matrixWorld ).invert();
  16898. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  16899. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16900. const localThresholdSq = localThreshold * localThreshold;
  16901. if ( geometry.isBufferGeometry ) {
  16902. const index = geometry.index;
  16903. const attributes = geometry.attributes;
  16904. const positionAttribute = attributes.position;
  16905. if ( index !== null ) {
  16906. const indices = index.array;
  16907. for ( let i = 0, il = indices.length; i < il; i ++ ) {
  16908. const a = indices[ i ];
  16909. _position$1.fromBufferAttribute( positionAttribute, a );
  16910. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16911. }
  16912. } else {
  16913. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  16914. _position$1.fromBufferAttribute( positionAttribute, i );
  16915. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16916. }
  16917. }
  16918. } else {
  16919. const vertices = geometry.vertices;
  16920. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  16921. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16922. }
  16923. }
  16924. },
  16925. updateMorphTargets: function () {
  16926. const geometry = this.geometry;
  16927. if ( geometry.isBufferGeometry ) {
  16928. const morphAttributes = geometry.morphAttributes;
  16929. const keys = Object.keys( morphAttributes );
  16930. if ( keys.length > 0 ) {
  16931. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16932. if ( morphAttribute !== undefined ) {
  16933. this.morphTargetInfluences = [];
  16934. this.morphTargetDictionary = {};
  16935. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16936. const name = morphAttribute[ m ].name || String( m );
  16937. this.morphTargetInfluences.push( 0 );
  16938. this.morphTargetDictionary[ name ] = m;
  16939. }
  16940. }
  16941. }
  16942. } else {
  16943. const morphTargets = geometry.morphTargets;
  16944. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16945. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16946. }
  16947. }
  16948. }
  16949. } );
  16950. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16951. const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  16952. if ( rayPointDistanceSq < localThresholdSq ) {
  16953. const intersectPoint = new Vector3();
  16954. _ray$2.closestPointToPoint( point, intersectPoint );
  16955. intersectPoint.applyMatrix4( matrixWorld );
  16956. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16957. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16958. intersects.push( {
  16959. distance: distance,
  16960. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16961. point: intersectPoint,
  16962. index: index,
  16963. face: null,
  16964. object: object
  16965. } );
  16966. }
  16967. }
  16968. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16969. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16970. this.format = format !== undefined ? format : RGBFormat;
  16971. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16972. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16973. this.generateMipmaps = false;
  16974. const scope = this;
  16975. function updateVideo() {
  16976. scope.needsUpdate = true;
  16977. video.requestVideoFrameCallback( updateVideo );
  16978. }
  16979. if ( 'requestVideoFrameCallback' in video ) {
  16980. video.requestVideoFrameCallback( updateVideo );
  16981. }
  16982. }
  16983. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  16984. constructor: VideoTexture,
  16985. clone: function () {
  16986. return new this.constructor( this.image ).copy( this );
  16987. },
  16988. isVideoTexture: true,
  16989. update: function () {
  16990. const video = this.image;
  16991. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16992. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16993. this.needsUpdate = true;
  16994. }
  16995. }
  16996. } );
  16997. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16998. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16999. this.image = { width: width, height: height };
  17000. this.mipmaps = mipmaps;
  17001. // no flipping for cube textures
  17002. // (also flipping doesn't work for compressed textures )
  17003. this.flipY = false;
  17004. // can't generate mipmaps for compressed textures
  17005. // mips must be embedded in DDS files
  17006. this.generateMipmaps = false;
  17007. }
  17008. CompressedTexture.prototype = Object.create( Texture.prototype );
  17009. CompressedTexture.prototype.constructor = CompressedTexture;
  17010. CompressedTexture.prototype.isCompressedTexture = true;
  17011. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17012. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17013. this.needsUpdate = true;
  17014. }
  17015. CanvasTexture.prototype = Object.create( Texture.prototype );
  17016. CanvasTexture.prototype.constructor = CanvasTexture;
  17017. CanvasTexture.prototype.isCanvasTexture = true;
  17018. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  17019. format = format !== undefined ? format : DepthFormat;
  17020. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17021. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17022. }
  17023. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  17024. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type$1;
  17025. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17026. this.image = { width: width, height: height };
  17027. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17028. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17029. this.flipY = false;
  17030. this.generateMipmaps = false;
  17031. }
  17032. DepthTexture.prototype = Object.create( Texture.prototype );
  17033. DepthTexture.prototype.constructor = DepthTexture;
  17034. DepthTexture.prototype.isDepthTexture = true;
  17035. let _geometryId = 0; // Geometry uses even numbers as Id
  17036. const _m1$3 = new Matrix4();
  17037. const _obj$1 = new Object3D();
  17038. const _offset$1 = new Vector3();
  17039. function Geometry() {
  17040. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  17041. this.uuid = MathUtils.generateUUID();
  17042. this.name = '';
  17043. this.type = 'Geometry';
  17044. this.vertices = [];
  17045. this.colors = [];
  17046. this.faces = [];
  17047. this.faceVertexUvs = [[]];
  17048. this.morphTargets = [];
  17049. this.morphNormals = [];
  17050. this.skinWeights = [];
  17051. this.skinIndices = [];
  17052. this.lineDistances = [];
  17053. this.boundingBox = null;
  17054. this.boundingSphere = null;
  17055. // update flags
  17056. this.elementsNeedUpdate = false;
  17057. this.verticesNeedUpdate = false;
  17058. this.uvsNeedUpdate = false;
  17059. this.normalsNeedUpdate = false;
  17060. this.colorsNeedUpdate = false;
  17061. this.lineDistancesNeedUpdate = false;
  17062. this.groupsNeedUpdate = false;
  17063. }
  17064. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  17065. constructor: Geometry,
  17066. isGeometry: true,
  17067. applyMatrix4: function ( matrix ) {
  17068. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  17069. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  17070. const vertex = this.vertices[ i ];
  17071. vertex.applyMatrix4( matrix );
  17072. }
  17073. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  17074. const face = this.faces[ i ];
  17075. face.normal.applyMatrix3( normalMatrix ).normalize();
  17076. for ( let j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  17077. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  17078. }
  17079. }
  17080. if ( this.boundingBox !== null ) {
  17081. this.computeBoundingBox();
  17082. }
  17083. if ( this.boundingSphere !== null ) {
  17084. this.computeBoundingSphere();
  17085. }
  17086. this.verticesNeedUpdate = true;
  17087. this.normalsNeedUpdate = true;
  17088. return this;
  17089. },
  17090. rotateX: function ( angle ) {
  17091. // rotate geometry around world x-axis
  17092. _m1$3.makeRotationX( angle );
  17093. this.applyMatrix4( _m1$3 );
  17094. return this;
  17095. },
  17096. rotateY: function ( angle ) {
  17097. // rotate geometry around world y-axis
  17098. _m1$3.makeRotationY( angle );
  17099. this.applyMatrix4( _m1$3 );
  17100. return this;
  17101. },
  17102. rotateZ: function ( angle ) {
  17103. // rotate geometry around world z-axis
  17104. _m1$3.makeRotationZ( angle );
  17105. this.applyMatrix4( _m1$3 );
  17106. return this;
  17107. },
  17108. translate: function ( x, y, z ) {
  17109. // translate geometry
  17110. _m1$3.makeTranslation( x, y, z );
  17111. this.applyMatrix4( _m1$3 );
  17112. return this;
  17113. },
  17114. scale: function ( x, y, z ) {
  17115. // scale geometry
  17116. _m1$3.makeScale( x, y, z );
  17117. this.applyMatrix4( _m1$3 );
  17118. return this;
  17119. },
  17120. lookAt: function ( vector ) {
  17121. _obj$1.lookAt( vector );
  17122. _obj$1.updateMatrix();
  17123. this.applyMatrix4( _obj$1.matrix );
  17124. return this;
  17125. },
  17126. fromBufferGeometry: function ( geometry ) {
  17127. const scope = this;
  17128. const index = geometry.index !== null ? geometry.index : undefined;
  17129. const attributes = geometry.attributes;
  17130. if ( attributes.position === undefined ) {
  17131. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  17132. return this;
  17133. }
  17134. const position = attributes.position;
  17135. const normal = attributes.normal;
  17136. const color = attributes.color;
  17137. const uv = attributes.uv;
  17138. const uv2 = attributes.uv2;
  17139. if ( uv2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  17140. for ( let i = 0; i < position.count; i ++ ) {
  17141. scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );
  17142. if ( color !== undefined ) {
  17143. scope.colors.push( new Color().fromBufferAttribute( color, i ) );
  17144. }
  17145. }
  17146. function addFace( a, b, c, materialIndex ) {
  17147. const vertexColors = ( color === undefined ) ? [] : [
  17148. scope.colors[ a ].clone(),
  17149. scope.colors[ b ].clone(),
  17150. scope.colors[ c ].clone()
  17151. ];
  17152. const vertexNormals = ( normal === undefined ) ? [] : [
  17153. new Vector3().fromBufferAttribute( normal, a ),
  17154. new Vector3().fromBufferAttribute( normal, b ),
  17155. new Vector3().fromBufferAttribute( normal, c )
  17156. ];
  17157. const face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  17158. scope.faces.push( face );
  17159. if ( uv !== undefined ) {
  17160. scope.faceVertexUvs[ 0 ].push( [
  17161. new Vector2$1().fromBufferAttribute( uv, a ),
  17162. new Vector2$1().fromBufferAttribute( uv, b ),
  17163. new Vector2$1().fromBufferAttribute( uv, c )
  17164. ] );
  17165. }
  17166. if ( uv2 !== undefined ) {
  17167. scope.faceVertexUvs[ 1 ].push( [
  17168. new Vector2$1().fromBufferAttribute( uv2, a ),
  17169. new Vector2$1().fromBufferAttribute( uv2, b ),
  17170. new Vector2$1().fromBufferAttribute( uv2, c )
  17171. ] );
  17172. }
  17173. }
  17174. const groups = geometry.groups;
  17175. if ( groups.length > 0 ) {
  17176. for ( let i = 0; i < groups.length; i ++ ) {
  17177. const group = groups[ i ];
  17178. const start = group.start;
  17179. const count = group.count;
  17180. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  17181. if ( index !== undefined ) {
  17182. addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );
  17183. } else {
  17184. addFace( j, j + 1, j + 2, group.materialIndex );
  17185. }
  17186. }
  17187. }
  17188. } else {
  17189. if ( index !== undefined ) {
  17190. for ( let i = 0; i < index.count; i += 3 ) {
  17191. addFace( index.getX( i ), index.getX( i + 1 ), index.getX( i + 2 ) );
  17192. }
  17193. } else {
  17194. for ( let i = 0; i < position.count; i += 3 ) {
  17195. addFace( i, i + 1, i + 2 );
  17196. }
  17197. }
  17198. }
  17199. this.computeFaceNormals();
  17200. if ( geometry.boundingBox !== null ) {
  17201. this.boundingBox = geometry.boundingBox.clone();
  17202. }
  17203. if ( geometry.boundingSphere !== null ) {
  17204. this.boundingSphere = geometry.boundingSphere.clone();
  17205. }
  17206. return this;
  17207. },
  17208. center: function () {
  17209. this.computeBoundingBox();
  17210. this.boundingBox.getCenter( _offset$1 ).negate();
  17211. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  17212. return this;
  17213. },
  17214. normalize: function () {
  17215. this.computeBoundingSphere();
  17216. const center = this.boundingSphere.center;
  17217. const radius = this.boundingSphere.radius;
  17218. const s = radius === 0 ? 1 : 1.0 / radius;
  17219. const matrix = new Matrix4();
  17220. matrix.set(
  17221. s, 0, 0, - s * center.x,
  17222. 0, s, 0, - s * center.y,
  17223. 0, 0, s, - s * center.z,
  17224. 0, 0, 0, 1
  17225. );
  17226. this.applyMatrix4( matrix );
  17227. return this;
  17228. },
  17229. computeFaceNormals: function () {
  17230. const cb = new Vector3(), ab = new Vector3();
  17231. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17232. const face = this.faces[ f ];
  17233. const vA = this.vertices[ face.a ];
  17234. const vB = this.vertices[ face.b ];
  17235. const vC = this.vertices[ face.c ];
  17236. cb.subVectors( vC, vB );
  17237. ab.subVectors( vA, vB );
  17238. cb.cross( ab );
  17239. cb.normalize();
  17240. face.normal.copy( cb );
  17241. }
  17242. },
  17243. computeVertexNormals: function ( areaWeighted = true ) {
  17244. const vertices = new Array( this.vertices.length );
  17245. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  17246. vertices[ v ] = new Vector3();
  17247. }
  17248. if ( areaWeighted ) {
  17249. // vertex normals weighted by triangle areas
  17250. // http://www.iquilezles.org/www/articles/normals/normals.htm
  17251. const cb = new Vector3(), ab = new Vector3();
  17252. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17253. const face = this.faces[ f ];
  17254. const vA = this.vertices[ face.a ];
  17255. const vB = this.vertices[ face.b ];
  17256. const vC = this.vertices[ face.c ];
  17257. cb.subVectors( vC, vB );
  17258. ab.subVectors( vA, vB );
  17259. cb.cross( ab );
  17260. vertices[ face.a ].add( cb );
  17261. vertices[ face.b ].add( cb );
  17262. vertices[ face.c ].add( cb );
  17263. }
  17264. } else {
  17265. this.computeFaceNormals();
  17266. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17267. const face = this.faces[ f ];
  17268. vertices[ face.a ].add( face.normal );
  17269. vertices[ face.b ].add( face.normal );
  17270. vertices[ face.c ].add( face.normal );
  17271. }
  17272. }
  17273. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  17274. vertices[ v ].normalize();
  17275. }
  17276. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17277. const face = this.faces[ f ];
  17278. const vertexNormals = face.vertexNormals;
  17279. if ( vertexNormals.length === 3 ) {
  17280. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  17281. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  17282. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  17283. } else {
  17284. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  17285. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  17286. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  17287. }
  17288. }
  17289. if ( this.faces.length > 0 ) {
  17290. this.normalsNeedUpdate = true;
  17291. }
  17292. },
  17293. computeFlatVertexNormals: function () {
  17294. this.computeFaceNormals();
  17295. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17296. const face = this.faces[ f ];
  17297. const vertexNormals = face.vertexNormals;
  17298. if ( vertexNormals.length === 3 ) {
  17299. vertexNormals[ 0 ].copy( face.normal );
  17300. vertexNormals[ 1 ].copy( face.normal );
  17301. vertexNormals[ 2 ].copy( face.normal );
  17302. } else {
  17303. vertexNormals[ 0 ] = face.normal.clone();
  17304. vertexNormals[ 1 ] = face.normal.clone();
  17305. vertexNormals[ 2 ] = face.normal.clone();
  17306. }
  17307. }
  17308. if ( this.faces.length > 0 ) {
  17309. this.normalsNeedUpdate = true;
  17310. }
  17311. },
  17312. computeMorphNormals: function () {
  17313. // save original normals
  17314. // - create temp variables on first access
  17315. // otherwise just copy (for faster repeated calls)
  17316. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17317. const face = this.faces[ f ];
  17318. if ( ! face.__originalFaceNormal ) {
  17319. face.__originalFaceNormal = face.normal.clone();
  17320. } else {
  17321. face.__originalFaceNormal.copy( face.normal );
  17322. }
  17323. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  17324. for ( let i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  17325. if ( ! face.__originalVertexNormals[ i ] ) {
  17326. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  17327. } else {
  17328. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  17329. }
  17330. }
  17331. }
  17332. // use temp geometry to compute face and vertex normals for each morph
  17333. const tmpGeo = new Geometry();
  17334. tmpGeo.faces = this.faces;
  17335. for ( let i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  17336. // create on first access
  17337. if ( ! this.morphNormals[ i ] ) {
  17338. this.morphNormals[ i ] = {};
  17339. this.morphNormals[ i ].faceNormals = [];
  17340. this.morphNormals[ i ].vertexNormals = [];
  17341. const dstNormalsFace = this.morphNormals[ i ].faceNormals;
  17342. const dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  17343. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17344. const faceNormal = new Vector3();
  17345. const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  17346. dstNormalsFace.push( faceNormal );
  17347. dstNormalsVertex.push( vertexNormals );
  17348. }
  17349. }
  17350. const morphNormals = this.morphNormals[ i ];
  17351. // set vertices to morph target
  17352. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  17353. // compute morph normals
  17354. tmpGeo.computeFaceNormals();
  17355. tmpGeo.computeVertexNormals();
  17356. // store morph normals
  17357. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17358. const face = this.faces[ f ];
  17359. const faceNormal = morphNormals.faceNormals[ f ];
  17360. const vertexNormals = morphNormals.vertexNormals[ f ];
  17361. faceNormal.copy( face.normal );
  17362. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  17363. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  17364. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  17365. }
  17366. }
  17367. // restore original normals
  17368. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17369. const face = this.faces[ f ];
  17370. face.normal = face.__originalFaceNormal;
  17371. face.vertexNormals = face.__originalVertexNormals;
  17372. }
  17373. },
  17374. computeBoundingBox: function () {
  17375. if ( this.boundingBox === null ) {
  17376. this.boundingBox = new Box3();
  17377. }
  17378. this.boundingBox.setFromPoints( this.vertices );
  17379. },
  17380. computeBoundingSphere: function () {
  17381. if ( this.boundingSphere === null ) {
  17382. this.boundingSphere = new Sphere();
  17383. }
  17384. this.boundingSphere.setFromPoints( this.vertices );
  17385. },
  17386. merge: function ( geometry, matrix, materialIndexOffset = 0 ) {
  17387. if ( ! ( geometry && geometry.isGeometry ) ) {
  17388. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  17389. return;
  17390. }
  17391. let normalMatrix;
  17392. const vertexOffset = this.vertices.length,
  17393. vertices1 = this.vertices,
  17394. vertices2 = geometry.vertices,
  17395. faces1 = this.faces,
  17396. faces2 = geometry.faces,
  17397. colors1 = this.colors,
  17398. colors2 = geometry.colors;
  17399. if ( matrix !== undefined ) {
  17400. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  17401. }
  17402. // vertices
  17403. for ( let i = 0, il = vertices2.length; i < il; i ++ ) {
  17404. const vertex = vertices2[ i ];
  17405. const vertexCopy = vertex.clone();
  17406. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  17407. vertices1.push( vertexCopy );
  17408. }
  17409. // colors
  17410. for ( let i = 0, il = colors2.length; i < il; i ++ ) {
  17411. colors1.push( colors2[ i ].clone() );
  17412. }
  17413. // faces
  17414. for ( let i = 0, il = faces2.length; i < il; i ++ ) {
  17415. const face = faces2[ i ];
  17416. let normal, color;
  17417. const faceVertexNormals = face.vertexNormals,
  17418. faceVertexColors = face.vertexColors;
  17419. const faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  17420. faceCopy.normal.copy( face.normal );
  17421. if ( normalMatrix !== undefined ) {
  17422. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  17423. }
  17424. for ( let j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  17425. normal = faceVertexNormals[ j ].clone();
  17426. if ( normalMatrix !== undefined ) {
  17427. normal.applyMatrix3( normalMatrix ).normalize();
  17428. }
  17429. faceCopy.vertexNormals.push( normal );
  17430. }
  17431. faceCopy.color.copy( face.color );
  17432. for ( let j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  17433. color = faceVertexColors[ j ];
  17434. faceCopy.vertexColors.push( color.clone() );
  17435. }
  17436. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  17437. faces1.push( faceCopy );
  17438. }
  17439. // uvs
  17440. for ( let i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  17441. const faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  17442. if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];
  17443. for ( let j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  17444. const uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  17445. for ( let k = 0, kl = uvs2.length; k < kl; k ++ ) {
  17446. uvsCopy.push( uvs2[ k ].clone() );
  17447. }
  17448. this.faceVertexUvs[ i ].push( uvsCopy );
  17449. }
  17450. }
  17451. },
  17452. mergeMesh: function ( mesh ) {
  17453. if ( ! ( mesh && mesh.isMesh ) ) {
  17454. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  17455. return;
  17456. }
  17457. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  17458. this.merge( mesh.geometry, mesh.matrix );
  17459. },
  17460. /*
  17461. * Checks for duplicate vertices with hashmap.
  17462. * Duplicated vertices are removed
  17463. * and faces' vertices are updated.
  17464. */
  17465. mergeVertices: function ( precisionPoints = 4 ) {
  17466. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  17467. const unique = [], changes = [];
  17468. const precision = Math.pow( 10, precisionPoints );
  17469. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  17470. const v = this.vertices[ i ];
  17471. const key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  17472. if ( verticesMap[ key ] === undefined ) {
  17473. verticesMap[ key ] = i;
  17474. unique.push( this.vertices[ i ] );
  17475. changes[ i ] = unique.length - 1;
  17476. } else {
  17477. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  17478. changes[ i ] = changes[ verticesMap[ key ] ];
  17479. }
  17480. }
  17481. // if faces are completely degenerate after merging vertices, we
  17482. // have to remove them from the geometry.
  17483. const faceIndicesToRemove = [];
  17484. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  17485. const face = this.faces[ i ];
  17486. face.a = changes[ face.a ];
  17487. face.b = changes[ face.b ];
  17488. face.c = changes[ face.c ];
  17489. const indices = [ face.a, face.b, face.c ];
  17490. // if any duplicate vertices are found in a Face3
  17491. // we have to remove the face as nothing can be saved
  17492. for ( let n = 0; n < 3; n ++ ) {
  17493. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  17494. faceIndicesToRemove.push( i );
  17495. break;
  17496. }
  17497. }
  17498. }
  17499. for ( let i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  17500. const idx = faceIndicesToRemove[ i ];
  17501. this.faces.splice( idx, 1 );
  17502. for ( let j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  17503. this.faceVertexUvs[ j ].splice( idx, 1 );
  17504. }
  17505. }
  17506. // Use unique set of vertices
  17507. const diff = this.vertices.length - unique.length;
  17508. this.vertices = unique;
  17509. return diff;
  17510. },
  17511. setFromPoints: function ( points ) {
  17512. this.vertices = [];
  17513. for ( let i = 0, l = points.length; i < l; i ++ ) {
  17514. const point = points[ i ];
  17515. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  17516. }
  17517. return this;
  17518. },
  17519. sortFacesByMaterialIndex: function () {
  17520. const faces = this.faces;
  17521. const length = faces.length;
  17522. // tag faces
  17523. for ( let i = 0; i < length; i ++ ) {
  17524. faces[ i ]._id = i;
  17525. }
  17526. // sort faces
  17527. function materialIndexSort( a, b ) {
  17528. return a.materialIndex - b.materialIndex;
  17529. }
  17530. faces.sort( materialIndexSort );
  17531. // sort uvs
  17532. const uvs1 = this.faceVertexUvs[ 0 ];
  17533. const uvs2 = this.faceVertexUvs[ 1 ];
  17534. let newUvs1, newUvs2;
  17535. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  17536. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  17537. for ( let i = 0; i < length; i ++ ) {
  17538. const id = faces[ i ]._id;
  17539. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  17540. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  17541. }
  17542. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  17543. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  17544. },
  17545. toJSON: function () {
  17546. const data = {
  17547. metadata: {
  17548. version: 4.5,
  17549. type: 'Geometry',
  17550. generator: 'Geometry.toJSON'
  17551. }
  17552. };
  17553. // standard Geometry serialization
  17554. data.uuid = this.uuid;
  17555. data.type = this.type;
  17556. if ( this.name !== '' ) data.name = this.name;
  17557. if ( this.parameters !== undefined ) {
  17558. const parameters = this.parameters;
  17559. for ( const key in parameters ) {
  17560. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  17561. }
  17562. return data;
  17563. }
  17564. const vertices = [];
  17565. for ( let i = 0; i < this.vertices.length; i ++ ) {
  17566. const vertex = this.vertices[ i ];
  17567. vertices.push( vertex.x, vertex.y, vertex.z );
  17568. }
  17569. const faces = [];
  17570. const normals = [];
  17571. const normalsHash = {};
  17572. const colors = [];
  17573. const colorsHash = {};
  17574. const uvs = [];
  17575. const uvsHash = {};
  17576. for ( let i = 0; i < this.faces.length; i ++ ) {
  17577. const face = this.faces[ i ];
  17578. const hasMaterial = true;
  17579. const hasFaceUv = false; // deprecated
  17580. const hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  17581. const hasFaceNormal = face.normal.length() > 0;
  17582. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  17583. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  17584. const hasFaceVertexColor = face.vertexColors.length > 0;
  17585. let faceType = 0;
  17586. faceType = setBit( faceType, 0, 0 ); // isQuad
  17587. faceType = setBit( faceType, 1, hasMaterial );
  17588. faceType = setBit( faceType, 2, hasFaceUv );
  17589. faceType = setBit( faceType, 3, hasFaceVertexUv );
  17590. faceType = setBit( faceType, 4, hasFaceNormal );
  17591. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  17592. faceType = setBit( faceType, 6, hasFaceColor );
  17593. faceType = setBit( faceType, 7, hasFaceVertexColor );
  17594. faces.push( faceType );
  17595. faces.push( face.a, face.b, face.c );
  17596. faces.push( face.materialIndex );
  17597. if ( hasFaceVertexUv ) {
  17598. const faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  17599. faces.push(
  17600. getUvIndex( faceVertexUvs[ 0 ] ),
  17601. getUvIndex( faceVertexUvs[ 1 ] ),
  17602. getUvIndex( faceVertexUvs[ 2 ] )
  17603. );
  17604. }
  17605. if ( hasFaceNormal ) {
  17606. faces.push( getNormalIndex( face.normal ) );
  17607. }
  17608. if ( hasFaceVertexNormal ) {
  17609. const vertexNormals = face.vertexNormals;
  17610. faces.push(
  17611. getNormalIndex( vertexNormals[ 0 ] ),
  17612. getNormalIndex( vertexNormals[ 1 ] ),
  17613. getNormalIndex( vertexNormals[ 2 ] )
  17614. );
  17615. }
  17616. if ( hasFaceColor ) {
  17617. faces.push( getColorIndex( face.color ) );
  17618. }
  17619. if ( hasFaceVertexColor ) {
  17620. const vertexColors = face.vertexColors;
  17621. faces.push(
  17622. getColorIndex( vertexColors[ 0 ] ),
  17623. getColorIndex( vertexColors[ 1 ] ),
  17624. getColorIndex( vertexColors[ 2 ] )
  17625. );
  17626. }
  17627. }
  17628. function setBit( value, position, enabled ) {
  17629. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  17630. }
  17631. function getNormalIndex( normal ) {
  17632. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  17633. if ( normalsHash[ hash ] !== undefined ) {
  17634. return normalsHash[ hash ];
  17635. }
  17636. normalsHash[ hash ] = normals.length / 3;
  17637. normals.push( normal.x, normal.y, normal.z );
  17638. return normalsHash[ hash ];
  17639. }
  17640. function getColorIndex( color ) {
  17641. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  17642. if ( colorsHash[ hash ] !== undefined ) {
  17643. return colorsHash[ hash ];
  17644. }
  17645. colorsHash[ hash ] = colors.length;
  17646. colors.push( color.getHex() );
  17647. return colorsHash[ hash ];
  17648. }
  17649. function getUvIndex( uv ) {
  17650. const hash = uv.x.toString() + uv.y.toString();
  17651. if ( uvsHash[ hash ] !== undefined ) {
  17652. return uvsHash[ hash ];
  17653. }
  17654. uvsHash[ hash ] = uvs.length / 2;
  17655. uvs.push( uv.x, uv.y );
  17656. return uvsHash[ hash ];
  17657. }
  17658. data.data = {};
  17659. data.data.vertices = vertices;
  17660. data.data.normals = normals;
  17661. if ( colors.length > 0 ) data.data.colors = colors;
  17662. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  17663. data.data.faces = faces;
  17664. return data;
  17665. },
  17666. clone: function () {
  17667. /*
  17668. // Handle primitives
  17669. const parameters = this.parameters;
  17670. if ( parameters !== undefined ) {
  17671. const values = [];
  17672. for ( const key in parameters ) {
  17673. values.push( parameters[ key ] );
  17674. }
  17675. const geometry = Object.create( this.constructor.prototype );
  17676. this.constructor.apply( geometry, values );
  17677. return geometry;
  17678. }
  17679. return new this.constructor().copy( this );
  17680. */
  17681. return new Geometry().copy( this );
  17682. },
  17683. copy: function ( source ) {
  17684. // reset
  17685. this.vertices = [];
  17686. this.colors = [];
  17687. this.faces = [];
  17688. this.faceVertexUvs = [[]];
  17689. this.morphTargets = [];
  17690. this.morphNormals = [];
  17691. this.skinWeights = [];
  17692. this.skinIndices = [];
  17693. this.lineDistances = [];
  17694. this.boundingBox = null;
  17695. this.boundingSphere = null;
  17696. // name
  17697. this.name = source.name;
  17698. // vertices
  17699. const vertices = source.vertices;
  17700. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  17701. this.vertices.push( vertices[ i ].clone() );
  17702. }
  17703. // colors
  17704. const colors = source.colors;
  17705. for ( let i = 0, il = colors.length; i < il; i ++ ) {
  17706. this.colors.push( colors[ i ].clone() );
  17707. }
  17708. // faces
  17709. const faces = source.faces;
  17710. for ( let i = 0, il = faces.length; i < il; i ++ ) {
  17711. this.faces.push( faces[ i ].clone() );
  17712. }
  17713. // face vertex uvs
  17714. for ( let i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  17715. const faceVertexUvs = source.faceVertexUvs[ i ];
  17716. if ( this.faceVertexUvs[ i ] === undefined ) {
  17717. this.faceVertexUvs[ i ] = [];
  17718. }
  17719. for ( let j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  17720. const uvs = faceVertexUvs[ j ], uvsCopy = [];
  17721. for ( let k = 0, kl = uvs.length; k < kl; k ++ ) {
  17722. const uv = uvs[ k ];
  17723. uvsCopy.push( uv.clone() );
  17724. }
  17725. this.faceVertexUvs[ i ].push( uvsCopy );
  17726. }
  17727. }
  17728. // morph targets
  17729. const morphTargets = source.morphTargets;
  17730. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  17731. const morphTarget = {};
  17732. morphTarget.name = morphTargets[ i ].name;
  17733. // vertices
  17734. if ( morphTargets[ i ].vertices !== undefined ) {
  17735. morphTarget.vertices = [];
  17736. for ( let j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  17737. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  17738. }
  17739. }
  17740. // normals
  17741. if ( morphTargets[ i ].normals !== undefined ) {
  17742. morphTarget.normals = [];
  17743. for ( let j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  17744. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  17745. }
  17746. }
  17747. this.morphTargets.push( morphTarget );
  17748. }
  17749. // morph normals
  17750. const morphNormals = source.morphNormals;
  17751. for ( let i = 0, il = morphNormals.length; i < il; i ++ ) {
  17752. const morphNormal = {};
  17753. // vertex normals
  17754. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  17755. morphNormal.vertexNormals = [];
  17756. for ( let j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  17757. const srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  17758. const destVertexNormal = {};
  17759. destVertexNormal.a = srcVertexNormal.a.clone();
  17760. destVertexNormal.b = srcVertexNormal.b.clone();
  17761. destVertexNormal.c = srcVertexNormal.c.clone();
  17762. morphNormal.vertexNormals.push( destVertexNormal );
  17763. }
  17764. }
  17765. // face normals
  17766. if ( morphNormals[ i ].faceNormals !== undefined ) {
  17767. morphNormal.faceNormals = [];
  17768. for ( let j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  17769. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  17770. }
  17771. }
  17772. this.morphNormals.push( morphNormal );
  17773. }
  17774. // skin weights
  17775. const skinWeights = source.skinWeights;
  17776. for ( let i = 0, il = skinWeights.length; i < il; i ++ ) {
  17777. this.skinWeights.push( skinWeights[ i ].clone() );
  17778. }
  17779. // skin indices
  17780. const skinIndices = source.skinIndices;
  17781. for ( let i = 0, il = skinIndices.length; i < il; i ++ ) {
  17782. this.skinIndices.push( skinIndices[ i ].clone() );
  17783. }
  17784. // line distances
  17785. const lineDistances = source.lineDistances;
  17786. for ( let i = 0, il = lineDistances.length; i < il; i ++ ) {
  17787. this.lineDistances.push( lineDistances[ i ] );
  17788. }
  17789. // bounding box
  17790. const boundingBox = source.boundingBox;
  17791. if ( boundingBox !== null ) {
  17792. this.boundingBox = boundingBox.clone();
  17793. }
  17794. // bounding sphere
  17795. const boundingSphere = source.boundingSphere;
  17796. if ( boundingSphere !== null ) {
  17797. this.boundingSphere = boundingSphere.clone();
  17798. }
  17799. // update flags
  17800. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17801. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17802. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17803. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17804. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17805. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17806. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17807. return this;
  17808. },
  17809. dispose: function () {
  17810. this.dispatchEvent( { type: 'dispose' } );
  17811. }
  17812. } );
  17813. class BoxGeometry extends Geometry {
  17814. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17815. super();
  17816. this.type = 'BoxGeometry';
  17817. this.parameters = {
  17818. width: width,
  17819. height: height,
  17820. depth: depth,
  17821. widthSegments: widthSegments,
  17822. heightSegments: heightSegments,
  17823. depthSegments: depthSegments
  17824. };
  17825. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  17826. this.mergeVertices();
  17827. }
  17828. }
  17829. class CircleBufferGeometry extends BufferGeometry {
  17830. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17831. super();
  17832. this.type = 'CircleBufferGeometry';
  17833. this.parameters = {
  17834. radius: radius,
  17835. segments: segments,
  17836. thetaStart: thetaStart,
  17837. thetaLength: thetaLength
  17838. };
  17839. segments = Math.max( 3, segments );
  17840. // buffers
  17841. const indices = [];
  17842. const vertices = [];
  17843. const normals = [];
  17844. const uvs = [];
  17845. // helper variables
  17846. const vertex = new Vector3();
  17847. const uv = new Vector2$1();
  17848. // center point
  17849. vertices.push( 0, 0, 0 );
  17850. normals.push( 0, 0, 1 );
  17851. uvs.push( 0.5, 0.5 );
  17852. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17853. const segment = thetaStart + s / segments * thetaLength;
  17854. // vertex
  17855. vertex.x = radius * Math.cos( segment );
  17856. vertex.y = radius * Math.sin( segment );
  17857. vertices.push( vertex.x, vertex.y, vertex.z );
  17858. // normal
  17859. normals.push( 0, 0, 1 );
  17860. // uvs
  17861. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17862. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17863. uvs.push( uv.x, uv.y );
  17864. }
  17865. // indices
  17866. for ( let i = 1; i <= segments; i ++ ) {
  17867. indices.push( i, i + 1, 0 );
  17868. }
  17869. // build geometry
  17870. this.setIndex( indices );
  17871. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17872. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17873. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17874. }
  17875. }
  17876. class CircleGeometry extends Geometry {
  17877. constructor( radius, segments, thetaStart, thetaLength ) {
  17878. super();
  17879. this.type = 'CircleGeometry';
  17880. this.parameters = {
  17881. radius: radius,
  17882. segments: segments,
  17883. thetaStart: thetaStart,
  17884. thetaLength: thetaLength
  17885. };
  17886. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17887. this.mergeVertices();
  17888. }
  17889. }
  17890. class CylinderBufferGeometry extends BufferGeometry {
  17891. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17892. super();
  17893. this.type = 'CylinderBufferGeometry';
  17894. this.parameters = {
  17895. radiusTop: radiusTop,
  17896. radiusBottom: radiusBottom,
  17897. height: height,
  17898. radialSegments: radialSegments,
  17899. heightSegments: heightSegments,
  17900. openEnded: openEnded,
  17901. thetaStart: thetaStart,
  17902. thetaLength: thetaLength
  17903. };
  17904. const scope = this;
  17905. radialSegments = Math.floor( radialSegments );
  17906. heightSegments = Math.floor( heightSegments );
  17907. // buffers
  17908. const indices = [];
  17909. const vertices = [];
  17910. const normals = [];
  17911. const uvs = [];
  17912. // helper variables
  17913. let index = 0;
  17914. const indexArray = [];
  17915. const halfHeight = height / 2;
  17916. let groupStart = 0;
  17917. // generate geometry
  17918. generateTorso();
  17919. if ( openEnded === false ) {
  17920. if ( radiusTop > 0 ) generateCap( true );
  17921. if ( radiusBottom > 0 ) generateCap( false );
  17922. }
  17923. // build geometry
  17924. this.setIndex( indices );
  17925. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17926. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17927. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17928. function generateTorso() {
  17929. const normal = new Vector3();
  17930. const vertex = new Vector3();
  17931. let groupCount = 0;
  17932. // this will be used to calculate the normal
  17933. const slope = ( radiusBottom - radiusTop ) / height;
  17934. // generate vertices, normals and uvs
  17935. for ( let y = 0; y <= heightSegments; y ++ ) {
  17936. const indexRow = [];
  17937. const v = y / heightSegments;
  17938. // calculate the radius of the current row
  17939. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17940. for ( let x = 0; x <= radialSegments; x ++ ) {
  17941. const u = x / radialSegments;
  17942. const theta = u * thetaLength + thetaStart;
  17943. const sinTheta = Math.sin( theta );
  17944. const cosTheta = Math.cos( theta );
  17945. // vertex
  17946. vertex.x = radius * sinTheta;
  17947. vertex.y = - v * height + halfHeight;
  17948. vertex.z = radius * cosTheta;
  17949. vertices.push( vertex.x, vertex.y, vertex.z );
  17950. // normal
  17951. normal.set( sinTheta, slope, cosTheta ).normalize();
  17952. normals.push( normal.x, normal.y, normal.z );
  17953. // uv
  17954. uvs.push( u, 1 - v );
  17955. // save index of vertex in respective row
  17956. indexRow.push( index ++ );
  17957. }
  17958. // now save vertices of the row in our index array
  17959. indexArray.push( indexRow );
  17960. }
  17961. // generate indices
  17962. for ( let x = 0; x < radialSegments; x ++ ) {
  17963. for ( let y = 0; y < heightSegments; y ++ ) {
  17964. // we use the index array to access the correct indices
  17965. const a = indexArray[ y ][ x ];
  17966. const b = indexArray[ y + 1 ][ x ];
  17967. const c = indexArray[ y + 1 ][ x + 1 ];
  17968. const d = indexArray[ y ][ x + 1 ];
  17969. // faces
  17970. indices.push( a, b, d );
  17971. indices.push( b, c, d );
  17972. // update group counter
  17973. groupCount += 6;
  17974. }
  17975. }
  17976. // add a group to the geometry. this will ensure multi material support
  17977. scope.addGroup( groupStart, groupCount, 0 );
  17978. // calculate new start value for groups
  17979. groupStart += groupCount;
  17980. }
  17981. function generateCap( top ) {
  17982. // save the index of the first center vertex
  17983. const centerIndexStart = index;
  17984. const uv = new Vector2$1();
  17985. const vertex = new Vector3();
  17986. let groupCount = 0;
  17987. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17988. const sign = ( top === true ) ? 1 : - 1;
  17989. // first we generate the center vertex data of the cap.
  17990. // because the geometry needs one set of uvs per face,
  17991. // we must generate a center vertex per face/segment
  17992. for ( let x = 1; x <= radialSegments; x ++ ) {
  17993. // vertex
  17994. vertices.push( 0, halfHeight * sign, 0 );
  17995. // normal
  17996. normals.push( 0, sign, 0 );
  17997. // uv
  17998. uvs.push( 0.5, 0.5 );
  17999. // increase index
  18000. index ++;
  18001. }
  18002. // save the index of the last center vertex
  18003. const centerIndexEnd = index;
  18004. // now we generate the surrounding vertices, normals and uvs
  18005. for ( let x = 0; x <= radialSegments; x ++ ) {
  18006. const u = x / radialSegments;
  18007. const theta = u * thetaLength + thetaStart;
  18008. const cosTheta = Math.cos( theta );
  18009. const sinTheta = Math.sin( theta );
  18010. // vertex
  18011. vertex.x = radius * sinTheta;
  18012. vertex.y = halfHeight * sign;
  18013. vertex.z = radius * cosTheta;
  18014. vertices.push( vertex.x, vertex.y, vertex.z );
  18015. // normal
  18016. normals.push( 0, sign, 0 );
  18017. // uv
  18018. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18019. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18020. uvs.push( uv.x, uv.y );
  18021. // increase index
  18022. index ++;
  18023. }
  18024. // generate indices
  18025. for ( let x = 0; x < radialSegments; x ++ ) {
  18026. const c = centerIndexStart + x;
  18027. const i = centerIndexEnd + x;
  18028. if ( top === true ) {
  18029. // face top
  18030. indices.push( i, i + 1, c );
  18031. } else {
  18032. // face bottom
  18033. indices.push( i + 1, i, c );
  18034. }
  18035. groupCount += 3;
  18036. }
  18037. // add a group to the geometry. this will ensure multi material support
  18038. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18039. // calculate new start value for groups
  18040. groupStart += groupCount;
  18041. }
  18042. }
  18043. }
  18044. class CylinderGeometry extends Geometry {
  18045. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18046. super();
  18047. this.type = 'CylinderGeometry';
  18048. this.parameters = {
  18049. radiusTop: radiusTop,
  18050. radiusBottom: radiusBottom,
  18051. height: height,
  18052. radialSegments: radialSegments,
  18053. heightSegments: heightSegments,
  18054. openEnded: openEnded,
  18055. thetaStart: thetaStart,
  18056. thetaLength: thetaLength
  18057. };
  18058. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  18059. this.mergeVertices();
  18060. }
  18061. }
  18062. class ConeGeometry extends CylinderGeometry {
  18063. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18064. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18065. this.type = 'ConeGeometry';
  18066. this.parameters = {
  18067. radius: radius,
  18068. height: height,
  18069. radialSegments: radialSegments,
  18070. heightSegments: heightSegments,
  18071. openEnded: openEnded,
  18072. thetaStart: thetaStart,
  18073. thetaLength: thetaLength
  18074. };
  18075. }
  18076. }
  18077. class ConeBufferGeometry extends CylinderBufferGeometry {
  18078. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18079. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18080. this.type = 'ConeBufferGeometry';
  18081. this.parameters = {
  18082. radius: radius,
  18083. height: height,
  18084. radialSegments: radialSegments,
  18085. heightSegments: heightSegments,
  18086. openEnded: openEnded,
  18087. thetaStart: thetaStart,
  18088. thetaLength: thetaLength
  18089. };
  18090. }
  18091. }
  18092. class PolyhedronBufferGeometry extends BufferGeometry {
  18093. constructor( vertices, indices, radius = 1, detail = 0 ) {
  18094. super();
  18095. this.type = 'PolyhedronBufferGeometry';
  18096. this.parameters = {
  18097. vertices: vertices,
  18098. indices: indices,
  18099. radius: radius,
  18100. detail: detail
  18101. };
  18102. // default buffer data
  18103. const vertexBuffer = [];
  18104. const uvBuffer = [];
  18105. // the subdivision creates the vertex buffer data
  18106. subdivide( detail );
  18107. // all vertices should lie on a conceptual sphere with a given radius
  18108. applyRadius( radius );
  18109. // finally, create the uv data
  18110. generateUVs();
  18111. // build non-indexed geometry
  18112. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18113. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18114. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18115. if ( detail === 0 ) {
  18116. this.computeVertexNormals(); // flat normals
  18117. } else {
  18118. this.normalizeNormals(); // smooth normals
  18119. }
  18120. // helper functions
  18121. function subdivide( detail ) {
  18122. const a = new Vector3();
  18123. const b = new Vector3();
  18124. const c = new Vector3();
  18125. // iterate over all faces and apply a subdivison with the given detail value
  18126. for ( let i = 0; i < indices.length; i += 3 ) {
  18127. // get the vertices of the face
  18128. getVertexByIndex( indices[ i + 0 ], a );
  18129. getVertexByIndex( indices[ i + 1 ], b );
  18130. getVertexByIndex( indices[ i + 2 ], c );
  18131. // perform subdivision
  18132. subdivideFace( a, b, c, detail );
  18133. }
  18134. }
  18135. function subdivideFace( a, b, c, detail ) {
  18136. const cols = detail + 1;
  18137. // we use this multidimensional array as a data structure for creating the subdivision
  18138. const v = [];
  18139. // construct all of the vertices for this subdivision
  18140. for ( let i = 0; i <= cols; i ++ ) {
  18141. v[ i ] = [];
  18142. const aj = a.clone().lerp( c, i / cols );
  18143. const bj = b.clone().lerp( c, i / cols );
  18144. const rows = cols - i;
  18145. for ( let j = 0; j <= rows; j ++ ) {
  18146. if ( j === 0 && i === cols ) {
  18147. v[ i ][ j ] = aj;
  18148. } else {
  18149. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18150. }
  18151. }
  18152. }
  18153. // construct all of the faces
  18154. for ( let i = 0; i < cols; i ++ ) {
  18155. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18156. const k = Math.floor( j / 2 );
  18157. if ( j % 2 === 0 ) {
  18158. pushVertex( v[ i ][ k + 1 ] );
  18159. pushVertex( v[ i + 1 ][ k ] );
  18160. pushVertex( v[ i ][ k ] );
  18161. } else {
  18162. pushVertex( v[ i ][ k + 1 ] );
  18163. pushVertex( v[ i + 1 ][ k + 1 ] );
  18164. pushVertex( v[ i + 1 ][ k ] );
  18165. }
  18166. }
  18167. }
  18168. }
  18169. function applyRadius( radius ) {
  18170. const vertex = new Vector3();
  18171. // iterate over the entire buffer and apply the radius to each vertex
  18172. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18173. vertex.x = vertexBuffer[ i + 0 ];
  18174. vertex.y = vertexBuffer[ i + 1 ];
  18175. vertex.z = vertexBuffer[ i + 2 ];
  18176. vertex.normalize().multiplyScalar( radius );
  18177. vertexBuffer[ i + 0 ] = vertex.x;
  18178. vertexBuffer[ i + 1 ] = vertex.y;
  18179. vertexBuffer[ i + 2 ] = vertex.z;
  18180. }
  18181. }
  18182. function generateUVs() {
  18183. const vertex = new Vector3();
  18184. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18185. vertex.x = vertexBuffer[ i + 0 ];
  18186. vertex.y = vertexBuffer[ i + 1 ];
  18187. vertex.z = vertexBuffer[ i + 2 ];
  18188. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18189. const v = inclination( vertex ) / Math.PI + 0.5;
  18190. uvBuffer.push( u, 1 - v );
  18191. }
  18192. correctUVs();
  18193. correctSeam();
  18194. }
  18195. function correctSeam() {
  18196. // handle case when face straddles the seam, see #3269
  18197. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18198. // uv data of a single face
  18199. const x0 = uvBuffer[ i + 0 ];
  18200. const x1 = uvBuffer[ i + 2 ];
  18201. const x2 = uvBuffer[ i + 4 ];
  18202. const max = Math.max( x0, x1, x2 );
  18203. const min = Math.min( x0, x1, x2 );
  18204. // 0.9 is somewhat arbitrary
  18205. if ( max > 0.9 && min < 0.1 ) {
  18206. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18207. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18208. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18209. }
  18210. }
  18211. }
  18212. function pushVertex( vertex ) {
  18213. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18214. }
  18215. function getVertexByIndex( index, vertex ) {
  18216. const stride = index * 3;
  18217. vertex.x = vertices[ stride + 0 ];
  18218. vertex.y = vertices[ stride + 1 ];
  18219. vertex.z = vertices[ stride + 2 ];
  18220. }
  18221. function correctUVs() {
  18222. const a = new Vector3();
  18223. const b = new Vector3();
  18224. const c = new Vector3();
  18225. const centroid = new Vector3();
  18226. const uvA = new Vector2$1();
  18227. const uvB = new Vector2$1();
  18228. const uvC = new Vector2$1();
  18229. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18230. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18231. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18232. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18233. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18234. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18235. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18236. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18237. const azi = azimuth( centroid );
  18238. correctUV( uvA, j + 0, a, azi );
  18239. correctUV( uvB, j + 2, b, azi );
  18240. correctUV( uvC, j + 4, c, azi );
  18241. }
  18242. }
  18243. function correctUV( uv, stride, vector, azimuth ) {
  18244. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18245. uvBuffer[ stride ] = uv.x - 1;
  18246. }
  18247. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18248. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18249. }
  18250. }
  18251. // Angle around the Y axis, counter-clockwise when looking from above.
  18252. function azimuth( vector ) {
  18253. return Math.atan2( vector.z, - vector.x );
  18254. }
  18255. // Angle above the XZ plane.
  18256. function inclination( vector ) {
  18257. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18258. }
  18259. }
  18260. }
  18261. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  18262. constructor( radius = 1, detail = 0 ) {
  18263. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18264. const r = 1 / t;
  18265. const vertices = [
  18266. // (±1, ±1, ±1)
  18267. - 1, - 1, - 1, - 1, - 1, 1,
  18268. - 1, 1, - 1, - 1, 1, 1,
  18269. 1, - 1, - 1, 1, - 1, 1,
  18270. 1, 1, - 1, 1, 1, 1,
  18271. // (0, ±1/φ, ±φ)
  18272. 0, - r, - t, 0, - r, t,
  18273. 0, r, - t, 0, r, t,
  18274. // (±1/φ, ±φ, 0)
  18275. - r, - t, 0, - r, t, 0,
  18276. r, - t, 0, r, t, 0,
  18277. // (±φ, 0, ±1/φ)
  18278. - t, 0, - r, t, 0, - r,
  18279. - t, 0, r, t, 0, r
  18280. ];
  18281. const indices = [
  18282. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18283. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18284. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18285. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18286. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18287. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18288. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18289. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18290. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18291. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18292. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18293. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18294. ];
  18295. super( vertices, indices, radius, detail );
  18296. this.type = 'DodecahedronBufferGeometry';
  18297. this.parameters = {
  18298. radius: radius,
  18299. detail: detail
  18300. };
  18301. }
  18302. }
  18303. class DodecahedronGeometry extends Geometry {
  18304. constructor( radius, detail ) {
  18305. super();
  18306. this.type = 'DodecahedronGeometry';
  18307. this.parameters = {
  18308. radius: radius,
  18309. detail: detail
  18310. };
  18311. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  18312. this.mergeVertices();
  18313. }
  18314. }
  18315. const _v0$2 = new Vector3();
  18316. const _v1$5 = new Vector3();
  18317. const _normal$1 = new Vector3();
  18318. const _triangle = new Triangle();
  18319. class EdgesGeometry extends BufferGeometry {
  18320. constructor( geometry, thresholdAngle ) {
  18321. super();
  18322. this.type = 'EdgesGeometry';
  18323. this.parameters = {
  18324. thresholdAngle: thresholdAngle
  18325. };
  18326. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  18327. if ( geometry.isGeometry ) {
  18328. geometry = new BufferGeometry().fromGeometry( geometry );
  18329. }
  18330. const precisionPoints = 4;
  18331. const precision = Math.pow( 10, precisionPoints );
  18332. const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  18333. const indexAttr = geometry.getIndex();
  18334. const positionAttr = geometry.getAttribute( 'position' );
  18335. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18336. const indexArr = [ 0, 0, 0 ];
  18337. const vertKeys = [ 'a', 'b', 'c' ];
  18338. const hashes = new Array( 3 );
  18339. const edgeData = {};
  18340. const vertices = [];
  18341. for ( let i = 0; i < indexCount; i += 3 ) {
  18342. if ( indexAttr ) {
  18343. indexArr[ 0 ] = indexAttr.getX( i );
  18344. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18345. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18346. } else {
  18347. indexArr[ 0 ] = i;
  18348. indexArr[ 1 ] = i + 1;
  18349. indexArr[ 2 ] = i + 2;
  18350. }
  18351. const { a, b, c } = _triangle;
  18352. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18353. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18354. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18355. _triangle.getNormal( _normal$1 );
  18356. // create hashes for the edge from the vertices
  18357. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18358. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18359. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18360. // skip degenerate triangles
  18361. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18362. continue;
  18363. }
  18364. // iterate over every edge
  18365. for ( let j = 0; j < 3; j ++ ) {
  18366. // get the first and next vertex making up the edge
  18367. const jNext = ( j + 1 ) % 3;
  18368. const vecHash0 = hashes[ j ];
  18369. const vecHash1 = hashes[ jNext ];
  18370. const v0 = _triangle[ vertKeys[ j ] ];
  18371. const v1 = _triangle[ vertKeys[ jNext ] ];
  18372. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18373. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18374. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18375. // if we found a sibling edge add it into the vertex array if
  18376. // it meets the angle threshold and delete the edge from the map.
  18377. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18378. vertices.push( v0.x, v0.y, v0.z );
  18379. vertices.push( v1.x, v1.y, v1.z );
  18380. }
  18381. edgeData[ reverseHash ] = null;
  18382. } else if ( ! ( hash in edgeData ) ) {
  18383. // if we've already got an edge here then skip adding a new one
  18384. edgeData[ hash ] = {
  18385. index0: indexArr[ j ],
  18386. index1: indexArr[ jNext ],
  18387. normal: _normal$1.clone(),
  18388. };
  18389. }
  18390. }
  18391. }
  18392. // iterate over all remaining, unmatched edges and add them to the vertex array
  18393. for ( const key in edgeData ) {
  18394. if ( edgeData[ key ] ) {
  18395. const { index0, index1 } = edgeData[ key ];
  18396. _v0$2.fromBufferAttribute( positionAttr, index0 );
  18397. _v1$5.fromBufferAttribute( positionAttr, index1 );
  18398. vertices.push( _v0$2.x, _v0$2.y, _v0$2.z );
  18399. vertices.push( _v1$5.x, _v1$5.y, _v1$5.z );
  18400. }
  18401. }
  18402. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18403. }
  18404. }
  18405. /**
  18406. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18407. */
  18408. const Earcut = {
  18409. triangulate: function ( data, holeIndices, dim ) {
  18410. dim = dim || 2;
  18411. const hasHoles = holeIndices && holeIndices.length;
  18412. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  18413. let outerNode = linkedList( data, 0, outerLen, dim, true );
  18414. const triangles = [];
  18415. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  18416. let minX, minY, maxX, maxY, x, y, invSize;
  18417. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  18418. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18419. if ( data.length > 80 * dim ) {
  18420. minX = maxX = data[ 0 ];
  18421. minY = maxY = data[ 1 ];
  18422. for ( let i = dim; i < outerLen; i += dim ) {
  18423. x = data[ i ];
  18424. y = data[ i + 1 ];
  18425. if ( x < minX ) minX = x;
  18426. if ( y < minY ) minY = y;
  18427. if ( x > maxX ) maxX = x;
  18428. if ( y > maxY ) maxY = y;
  18429. }
  18430. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18431. invSize = Math.max( maxX - minX, maxY - minY );
  18432. invSize = invSize !== 0 ? 1 / invSize : 0;
  18433. }
  18434. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  18435. return triangles;
  18436. }
  18437. };
  18438. // create a circular doubly linked list from polygon points in the specified winding order
  18439. function linkedList( data, start, end, dim, clockwise ) {
  18440. let i, last;
  18441. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  18442. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18443. } else {
  18444. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18445. }
  18446. if ( last && equals( last, last.next ) ) {
  18447. removeNode( last );
  18448. last = last.next;
  18449. }
  18450. return last;
  18451. }
  18452. // eliminate colinear or duplicate points
  18453. function filterPoints( start, end ) {
  18454. if ( ! start ) return start;
  18455. if ( ! end ) end = start;
  18456. let p = start,
  18457. again;
  18458. do {
  18459. again = false;
  18460. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  18461. removeNode( p );
  18462. p = end = p.prev;
  18463. if ( p === p.next ) break;
  18464. again = true;
  18465. } else {
  18466. p = p.next;
  18467. }
  18468. } while ( again || p !== end );
  18469. return end;
  18470. }
  18471. // main ear slicing loop which triangulates a polygon (given as a linked list)
  18472. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  18473. if ( ! ear ) return;
  18474. // interlink polygon nodes in z-order
  18475. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  18476. let stop = ear,
  18477. prev, next;
  18478. // iterate through ears, slicing them one by one
  18479. while ( ear.prev !== ear.next ) {
  18480. prev = ear.prev;
  18481. next = ear.next;
  18482. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  18483. // cut off the triangle
  18484. triangles.push( prev.i / dim );
  18485. triangles.push( ear.i / dim );
  18486. triangles.push( next.i / dim );
  18487. removeNode( ear );
  18488. // skipping the next vertex leads to less sliver triangles
  18489. ear = next.next;
  18490. stop = next.next;
  18491. continue;
  18492. }
  18493. ear = next;
  18494. // if we looped through the whole remaining polygon and can't find any more ears
  18495. if ( ear === stop ) {
  18496. // try filtering points and slicing again
  18497. if ( ! pass ) {
  18498. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  18499. // if this didn't work, try curing all small self-intersections locally
  18500. } else if ( pass === 1 ) {
  18501. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  18502. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  18503. // as a last resort, try splitting the remaining polygon into two
  18504. } else if ( pass === 2 ) {
  18505. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  18506. }
  18507. break;
  18508. }
  18509. }
  18510. }
  18511. // check whether a polygon node forms a valid ear with adjacent nodes
  18512. function isEar( ear ) {
  18513. const a = ear.prev,
  18514. b = ear,
  18515. c = ear.next;
  18516. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18517. // now make sure we don't have other points inside the potential ear
  18518. let p = ear.next.next;
  18519. while ( p !== ear.prev ) {
  18520. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18521. area( p.prev, p, p.next ) >= 0 ) return false;
  18522. p = p.next;
  18523. }
  18524. return true;
  18525. }
  18526. function isEarHashed( ear, minX, minY, invSize ) {
  18527. const a = ear.prev,
  18528. b = ear,
  18529. c = ear.next;
  18530. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18531. // triangle bbox; min & max are calculated like this for speed
  18532. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  18533. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  18534. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  18535. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  18536. // z-order range for the current triangle bbox;
  18537. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  18538. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  18539. let p = ear.prevZ,
  18540. n = ear.nextZ;
  18541. // look for points inside the triangle in both directions
  18542. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  18543. if ( p !== ear.prev && p !== ear.next &&
  18544. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18545. area( p.prev, p, p.next ) >= 0 ) return false;
  18546. p = p.prevZ;
  18547. if ( n !== ear.prev && n !== ear.next &&
  18548. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  18549. area( n.prev, n, n.next ) >= 0 ) return false;
  18550. n = n.nextZ;
  18551. }
  18552. // look for remaining points in decreasing z-order
  18553. while ( p && p.z >= minZ ) {
  18554. if ( p !== ear.prev && p !== ear.next &&
  18555. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18556. area( p.prev, p, p.next ) >= 0 ) return false;
  18557. p = p.prevZ;
  18558. }
  18559. // look for remaining points in increasing z-order
  18560. while ( n && n.z <= maxZ ) {
  18561. if ( n !== ear.prev && n !== ear.next &&
  18562. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  18563. area( n.prev, n, n.next ) >= 0 ) return false;
  18564. n = n.nextZ;
  18565. }
  18566. return true;
  18567. }
  18568. // go through all polygon nodes and cure small local self-intersections
  18569. function cureLocalIntersections( start, triangles, dim ) {
  18570. let p = start;
  18571. do {
  18572. const a = p.prev,
  18573. b = p.next.next;
  18574. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  18575. triangles.push( a.i / dim );
  18576. triangles.push( p.i / dim );
  18577. triangles.push( b.i / dim );
  18578. // remove two nodes involved
  18579. removeNode( p );
  18580. removeNode( p.next );
  18581. p = start = b;
  18582. }
  18583. p = p.next;
  18584. } while ( p !== start );
  18585. return filterPoints( p );
  18586. }
  18587. // try splitting polygon into two and triangulate them independently
  18588. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  18589. // look for a valid diagonal that divides the polygon into two
  18590. let a = start;
  18591. do {
  18592. let b = a.next.next;
  18593. while ( b !== a.prev ) {
  18594. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  18595. // split the polygon in two by the diagonal
  18596. let c = splitPolygon( a, b );
  18597. // filter colinear points around the cuts
  18598. a = filterPoints( a, a.next );
  18599. c = filterPoints( c, c.next );
  18600. // run earcut on each half
  18601. earcutLinked( a, triangles, dim, minX, minY, invSize );
  18602. earcutLinked( c, triangles, dim, minX, minY, invSize );
  18603. return;
  18604. }
  18605. b = b.next;
  18606. }
  18607. a = a.next;
  18608. } while ( a !== start );
  18609. }
  18610. // link every hole into the outer loop, producing a single-ring polygon without holes
  18611. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  18612. const queue = [];
  18613. let i, len, start, end, list;
  18614. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  18615. start = holeIndices[ i ] * dim;
  18616. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  18617. list = linkedList( data, start, end, dim, false );
  18618. if ( list === list.next ) list.steiner = true;
  18619. queue.push( getLeftmost( list ) );
  18620. }
  18621. queue.sort( compareX );
  18622. // process holes from left to right
  18623. for ( i = 0; i < queue.length; i ++ ) {
  18624. eliminateHole( queue[ i ], outerNode );
  18625. outerNode = filterPoints( outerNode, outerNode.next );
  18626. }
  18627. return outerNode;
  18628. }
  18629. function compareX( a, b ) {
  18630. return a.x - b.x;
  18631. }
  18632. // find a bridge between vertices that connects hole with an outer ring and and link it
  18633. function eliminateHole( hole, outerNode ) {
  18634. outerNode = findHoleBridge( hole, outerNode );
  18635. if ( outerNode ) {
  18636. const b = splitPolygon( outerNode, hole );
  18637. // filter collinear points around the cuts
  18638. filterPoints( outerNode, outerNode.next );
  18639. filterPoints( b, b.next );
  18640. }
  18641. }
  18642. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18643. function findHoleBridge( hole, outerNode ) {
  18644. let p = outerNode;
  18645. const hx = hole.x;
  18646. const hy = hole.y;
  18647. let qx = - Infinity, m;
  18648. // find a segment intersected by a ray from the hole's leftmost point to the left;
  18649. // segment's endpoint with lesser x will be potential connection point
  18650. do {
  18651. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  18652. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  18653. if ( x <= hx && x > qx ) {
  18654. qx = x;
  18655. if ( x === hx ) {
  18656. if ( hy === p.y ) return p;
  18657. if ( hy === p.next.y ) return p.next;
  18658. }
  18659. m = p.x < p.next.x ? p : p.next;
  18660. }
  18661. }
  18662. p = p.next;
  18663. } while ( p !== outerNode );
  18664. if ( ! m ) return null;
  18665. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  18666. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18667. // if there are no points found, we have a valid connection;
  18668. // otherwise choose the point of the minimum angle with the ray as connection point
  18669. const stop = m,
  18670. mx = m.x,
  18671. my = m.y;
  18672. let tanMin = Infinity, tan;
  18673. p = m;
  18674. do {
  18675. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  18676. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  18677. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  18678. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  18679. m = p;
  18680. tanMin = tan;
  18681. }
  18682. }
  18683. p = p.next;
  18684. } while ( p !== stop );
  18685. return m;
  18686. }
  18687. // whether sector in vertex m contains sector in vertex p in the same coordinates
  18688. function sectorContainsSector( m, p ) {
  18689. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  18690. }
  18691. // interlink polygon nodes in z-order
  18692. function indexCurve( start, minX, minY, invSize ) {
  18693. let p = start;
  18694. do {
  18695. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  18696. p.prevZ = p.prev;
  18697. p.nextZ = p.next;
  18698. p = p.next;
  18699. } while ( p !== start );
  18700. p.prevZ.nextZ = null;
  18701. p.prevZ = null;
  18702. sortLinked( p );
  18703. }
  18704. // Simon Tatham's linked list merge sort algorithm
  18705. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18706. function sortLinked( list ) {
  18707. let i, p, q, e, tail, numMerges, pSize, qSize,
  18708. inSize = 1;
  18709. do {
  18710. p = list;
  18711. list = null;
  18712. tail = null;
  18713. numMerges = 0;
  18714. while ( p ) {
  18715. numMerges ++;
  18716. q = p;
  18717. pSize = 0;
  18718. for ( i = 0; i < inSize; i ++ ) {
  18719. pSize ++;
  18720. q = q.nextZ;
  18721. if ( ! q ) break;
  18722. }
  18723. qSize = inSize;
  18724. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  18725. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  18726. e = p;
  18727. p = p.nextZ;
  18728. pSize --;
  18729. } else {
  18730. e = q;
  18731. q = q.nextZ;
  18732. qSize --;
  18733. }
  18734. if ( tail ) tail.nextZ = e;
  18735. else list = e;
  18736. e.prevZ = tail;
  18737. tail = e;
  18738. }
  18739. p = q;
  18740. }
  18741. tail.nextZ = null;
  18742. inSize *= 2;
  18743. } while ( numMerges > 1 );
  18744. return list;
  18745. }
  18746. // z-order of a point given coords and inverse of the longer side of data bbox
  18747. function zOrder( x, y, minX, minY, invSize ) {
  18748. // coords are transformed into non-negative 15-bit integer range
  18749. x = 32767 * ( x - minX ) * invSize;
  18750. y = 32767 * ( y - minY ) * invSize;
  18751. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  18752. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  18753. x = ( x | ( x << 2 ) ) & 0x33333333;
  18754. x = ( x | ( x << 1 ) ) & 0x55555555;
  18755. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  18756. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  18757. y = ( y | ( y << 2 ) ) & 0x33333333;
  18758. y = ( y | ( y << 1 ) ) & 0x55555555;
  18759. return x | ( y << 1 );
  18760. }
  18761. // find the leftmost node of a polygon ring
  18762. function getLeftmost( start ) {
  18763. let p = start,
  18764. leftmost = start;
  18765. do {
  18766. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  18767. p = p.next;
  18768. } while ( p !== start );
  18769. return leftmost;
  18770. }
  18771. // check if a point lies within a convex triangle
  18772. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  18773. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  18774. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  18775. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  18776. }
  18777. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18778. function isValidDiagonal( a, b ) {
  18779. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  18780. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  18781. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  18782. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  18783. }
  18784. // signed area of a triangle
  18785. function area( p, q, r ) {
  18786. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  18787. }
  18788. // check if two points are equal
  18789. function equals( p1, p2 ) {
  18790. return p1.x === p2.x && p1.y === p2.y;
  18791. }
  18792. // check if two segments intersect
  18793. function intersects( p1, q1, p2, q2 ) {
  18794. const o1 = sign( area( p1, q1, p2 ) );
  18795. const o2 = sign( area( p1, q1, q2 ) );
  18796. const o3 = sign( area( p2, q2, p1 ) );
  18797. const o4 = sign( area( p2, q2, q1 ) );
  18798. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  18799. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18800. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18801. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18802. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18803. return false;
  18804. }
  18805. // for collinear points p, q, r, check if point q lies on segment pr
  18806. function onSegment( p, q, r ) {
  18807. return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );
  18808. }
  18809. function sign( num ) {
  18810. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  18811. }
  18812. // check if a polygon diagonal intersects any polygon segments
  18813. function intersectsPolygon( a, b ) {
  18814. let p = a;
  18815. do {
  18816. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  18817. intersects( p, p.next, a, b ) ) return true;
  18818. p = p.next;
  18819. } while ( p !== a );
  18820. return false;
  18821. }
  18822. // check if a polygon diagonal is locally inside the polygon
  18823. function locallyInside( a, b ) {
  18824. return area( a.prev, a, a.next ) < 0 ?
  18825. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  18826. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  18827. }
  18828. // check if the middle point of a polygon diagonal is inside the polygon
  18829. function middleInside( a, b ) {
  18830. let p = a,
  18831. inside = false;
  18832. const px = ( a.x + b.x ) / 2,
  18833. py = ( a.y + b.y ) / 2;
  18834. do {
  18835. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  18836. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  18837. inside = ! inside;
  18838. p = p.next;
  18839. } while ( p !== a );
  18840. return inside;
  18841. }
  18842. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18843. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18844. function splitPolygon( a, b ) {
  18845. const a2 = new Node( a.i, a.x, a.y ),
  18846. b2 = new Node( b.i, b.x, b.y ),
  18847. an = a.next,
  18848. bp = b.prev;
  18849. a.next = b;
  18850. b.prev = a;
  18851. a2.next = an;
  18852. an.prev = a2;
  18853. b2.next = a2;
  18854. a2.prev = b2;
  18855. bp.next = b2;
  18856. b2.prev = bp;
  18857. return b2;
  18858. }
  18859. // create a node and optionally link it with previous one (in a circular doubly linked list)
  18860. function insertNode( i, x, y, last ) {
  18861. const p = new Node( i, x, y );
  18862. if ( ! last ) {
  18863. p.prev = p;
  18864. p.next = p;
  18865. } else {
  18866. p.next = last.next;
  18867. p.prev = last;
  18868. last.next.prev = p;
  18869. last.next = p;
  18870. }
  18871. return p;
  18872. }
  18873. function removeNode( p ) {
  18874. p.next.prev = p.prev;
  18875. p.prev.next = p.next;
  18876. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  18877. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  18878. }
  18879. function Node( i, x, y ) {
  18880. // vertex index in coordinates array
  18881. this.i = i;
  18882. // vertex coordinates
  18883. this.x = x;
  18884. this.y = y;
  18885. // previous and next vertex nodes in a polygon ring
  18886. this.prev = null;
  18887. this.next = null;
  18888. // z-order curve value
  18889. this.z = null;
  18890. // previous and next nodes in z-order
  18891. this.prevZ = null;
  18892. this.nextZ = null;
  18893. // indicates whether this is a steiner point
  18894. this.steiner = false;
  18895. }
  18896. function signedArea( data, start, end, dim ) {
  18897. let sum = 0;
  18898. for ( let i = start, j = end - dim; i < end; i += dim ) {
  18899. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  18900. j = i;
  18901. }
  18902. return sum;
  18903. }
  18904. const ShapeUtils = {
  18905. // calculate area of the contour polygon
  18906. area: function ( contour ) {
  18907. const n = contour.length;
  18908. let a = 0.0;
  18909. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  18910. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  18911. }
  18912. return a * 0.5;
  18913. },
  18914. isClockWise: function ( pts ) {
  18915. return ShapeUtils.area( pts ) < 0;
  18916. },
  18917. triangulateShape: function ( contour, holes ) {
  18918. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18919. const holeIndices = []; // array of hole indices
  18920. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18921. removeDupEndPts( contour );
  18922. addContour( vertices, contour );
  18923. //
  18924. let holeIndex = contour.length;
  18925. holes.forEach( removeDupEndPts );
  18926. for ( let i = 0; i < holes.length; i ++ ) {
  18927. holeIndices.push( holeIndex );
  18928. holeIndex += holes[ i ].length;
  18929. addContour( vertices, holes[ i ] );
  18930. }
  18931. //
  18932. const triangles = Earcut.triangulate( vertices, holeIndices );
  18933. //
  18934. for ( let i = 0; i < triangles.length; i += 3 ) {
  18935. faces.push( triangles.slice( i, i + 3 ) );
  18936. }
  18937. return faces;
  18938. }
  18939. };
  18940. function removeDupEndPts( points ) {
  18941. const l = points.length;
  18942. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  18943. points.pop();
  18944. }
  18945. }
  18946. function addContour( vertices, contour ) {
  18947. for ( let i = 0; i < contour.length; i ++ ) {
  18948. vertices.push( contour[ i ].x );
  18949. vertices.push( contour[ i ].y );
  18950. }
  18951. }
  18952. /**
  18953. * Creates extruded geometry from a path shape.
  18954. *
  18955. * parameters = {
  18956. *
  18957. * curveSegments: <int>, // number of points on the curves
  18958. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18959. * depth: <float>, // Depth to extrude the shape
  18960. *
  18961. * bevelEnabled: <bool>, // turn on bevel
  18962. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18963. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18964. * bevelOffset: <float>, // how far from shape outline does bevel start
  18965. * bevelSegments: <int>, // number of bevel layers
  18966. *
  18967. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18968. *
  18969. * UVGenerator: <Object> // object that provides UV generator functions
  18970. *
  18971. * }
  18972. */
  18973. class ExtrudeBufferGeometry extends BufferGeometry {
  18974. constructor( shapes, options ) {
  18975. super();
  18976. this.type = 'ExtrudeBufferGeometry';
  18977. this.parameters = {
  18978. shapes: shapes,
  18979. options: options
  18980. };
  18981. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18982. const scope = this;
  18983. const verticesArray = [];
  18984. const uvArray = [];
  18985. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18986. const shape = shapes[ i ];
  18987. addShape( shape );
  18988. }
  18989. // build geometry
  18990. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  18991. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  18992. this.computeVertexNormals();
  18993. // functions
  18994. function addShape( shape ) {
  18995. const placeholder = [];
  18996. // options
  18997. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18998. const steps = options.steps !== undefined ? options.steps : 1;
  18999. let depth = options.depth !== undefined ? options.depth : 100;
  19000. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19001. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19002. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19003. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19004. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19005. const extrudePath = options.extrudePath;
  19006. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19007. // deprecated options
  19008. if ( options.amount !== undefined ) {
  19009. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  19010. depth = options.amount;
  19011. }
  19012. //
  19013. let extrudePts, extrudeByPath = false;
  19014. let splineTube, binormal, normal, position2;
  19015. if ( extrudePath ) {
  19016. extrudePts = extrudePath.getSpacedPoints( steps );
  19017. extrudeByPath = true;
  19018. bevelEnabled = false; // bevels not supported for path extrusion
  19019. // SETUP TNB variables
  19020. // TODO1 - have a .isClosed in spline?
  19021. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19022. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19023. binormal = new Vector3();
  19024. normal = new Vector3();
  19025. position2 = new Vector3();
  19026. }
  19027. // Safeguards if bevels are not enabled
  19028. if ( ! bevelEnabled ) {
  19029. bevelSegments = 0;
  19030. bevelThickness = 0;
  19031. bevelSize = 0;
  19032. bevelOffset = 0;
  19033. }
  19034. // Variables initialization
  19035. const shapePoints = shape.extractPoints( curveSegments );
  19036. let vertices = shapePoints.shape;
  19037. const holes = shapePoints.holes;
  19038. const reverse = ! ShapeUtils.isClockWise( vertices );
  19039. if ( reverse ) {
  19040. vertices = vertices.reverse();
  19041. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19042. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19043. const ahole = holes[ h ];
  19044. if ( ShapeUtils.isClockWise( ahole ) ) {
  19045. holes[ h ] = ahole.reverse();
  19046. }
  19047. }
  19048. }
  19049. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19050. /* Vertices */
  19051. const contour = vertices; // vertices has all points but contour has only points of circumference
  19052. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19053. const ahole = holes[ h ];
  19054. vertices = vertices.concat( ahole );
  19055. }
  19056. function scalePt2( pt, vec, size ) {
  19057. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19058. return vec.clone().multiplyScalar( size ).add( pt );
  19059. }
  19060. const vlen = vertices.length, flen = faces.length;
  19061. // Find directions for point movement
  19062. function getBevelVec( inPt, inPrev, inNext ) {
  19063. // computes for inPt the corresponding point inPt' on a new contour
  19064. // shifted by 1 unit (length of normalized vector) to the left
  19065. // if we walk along contour clockwise, this new contour is outside the old one
  19066. //
  19067. // inPt' is the intersection of the two lines parallel to the two
  19068. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19069. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19070. // good reading for geometry algorithms (here: line-line intersection)
  19071. // http://geomalgorithms.com/a05-_intersect-1.html
  19072. const v_prev_x = inPt.x - inPrev.x,
  19073. v_prev_y = inPt.y - inPrev.y;
  19074. const v_next_x = inNext.x - inPt.x,
  19075. v_next_y = inNext.y - inPt.y;
  19076. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19077. // check for collinear edges
  19078. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19079. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19080. // not collinear
  19081. // length of vectors for normalizing
  19082. const v_prev_len = Math.sqrt( v_prev_lensq );
  19083. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19084. // shift adjacent points by unit vectors to the left
  19085. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19086. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19087. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19088. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19089. // scaling factor for v_prev to intersection point
  19090. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19091. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19092. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19093. // vector from inPt to intersection point
  19094. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19095. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19096. // Don't normalize!, otherwise sharp corners become ugly
  19097. // but prevent crazy spikes
  19098. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19099. if ( v_trans_lensq <= 2 ) {
  19100. return new Vector2$1( v_trans_x, v_trans_y );
  19101. } else {
  19102. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19103. }
  19104. } else {
  19105. // handle special case of collinear edges
  19106. let direction_eq = false; // assumes: opposite
  19107. if ( v_prev_x > Number.EPSILON ) {
  19108. if ( v_next_x > Number.EPSILON ) {
  19109. direction_eq = true;
  19110. }
  19111. } else {
  19112. if ( v_prev_x < - Number.EPSILON ) {
  19113. if ( v_next_x < - Number.EPSILON ) {
  19114. direction_eq = true;
  19115. }
  19116. } else {
  19117. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19118. direction_eq = true;
  19119. }
  19120. }
  19121. }
  19122. if ( direction_eq ) {
  19123. // console.log("Warning: lines are a straight sequence");
  19124. v_trans_x = - v_prev_y;
  19125. v_trans_y = v_prev_x;
  19126. shrink_by = Math.sqrt( v_prev_lensq );
  19127. } else {
  19128. // console.log("Warning: lines are a straight spike");
  19129. v_trans_x = v_prev_x;
  19130. v_trans_y = v_prev_y;
  19131. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19132. }
  19133. }
  19134. return new Vector2$1( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19135. }
  19136. const contourMovements = [];
  19137. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19138. if ( j === il ) j = 0;
  19139. if ( k === il ) k = 0;
  19140. // (j)---(i)---(k)
  19141. // console.log('i,j,k', i, j , k)
  19142. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19143. }
  19144. const holesMovements = [];
  19145. let oneHoleMovements, verticesMovements = contourMovements.concat();
  19146. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19147. const ahole = holes[ h ];
  19148. oneHoleMovements = [];
  19149. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19150. if ( j === il ) j = 0;
  19151. if ( k === il ) k = 0;
  19152. // (j)---(i)---(k)
  19153. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19154. }
  19155. holesMovements.push( oneHoleMovements );
  19156. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19157. }
  19158. // Loop bevelSegments, 1 for the front, 1 for the back
  19159. for ( let b = 0; b < bevelSegments; b ++ ) {
  19160. //for ( b = bevelSegments; b > 0; b -- ) {
  19161. const t = b / bevelSegments;
  19162. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19163. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19164. // contract shape
  19165. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19166. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19167. v( vert.x, vert.y, - z );
  19168. }
  19169. // expand holes
  19170. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19171. const ahole = holes[ h ];
  19172. oneHoleMovements = holesMovements[ h ];
  19173. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19174. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19175. v( vert.x, vert.y, - z );
  19176. }
  19177. }
  19178. }
  19179. const bs = bevelSize + bevelOffset;
  19180. // Back facing vertices
  19181. for ( let i = 0; i < vlen; i ++ ) {
  19182. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19183. if ( ! extrudeByPath ) {
  19184. v( vert.x, vert.y, 0 );
  19185. } else {
  19186. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19187. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19188. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19189. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19190. v( position2.x, position2.y, position2.z );
  19191. }
  19192. }
  19193. // Add stepped vertices...
  19194. // Including front facing vertices
  19195. for ( let s = 1; s <= steps; s ++ ) {
  19196. for ( let i = 0; i < vlen; i ++ ) {
  19197. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19198. if ( ! extrudeByPath ) {
  19199. v( vert.x, vert.y, depth / steps * s );
  19200. } else {
  19201. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19202. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19203. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19204. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19205. v( position2.x, position2.y, position2.z );
  19206. }
  19207. }
  19208. }
  19209. // Add bevel segments planes
  19210. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19211. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  19212. const t = b / bevelSegments;
  19213. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19214. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19215. // contract shape
  19216. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19217. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19218. v( vert.x, vert.y, depth + z );
  19219. }
  19220. // expand holes
  19221. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19222. const ahole = holes[ h ];
  19223. oneHoleMovements = holesMovements[ h ];
  19224. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19225. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19226. if ( ! extrudeByPath ) {
  19227. v( vert.x, vert.y, depth + z );
  19228. } else {
  19229. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19230. }
  19231. }
  19232. }
  19233. }
  19234. /* Faces */
  19235. // Top and bottom faces
  19236. buildLidFaces();
  19237. // Sides faces
  19238. buildSideFaces();
  19239. ///// Internal functions
  19240. function buildLidFaces() {
  19241. const start = verticesArray.length / 3;
  19242. if ( bevelEnabled ) {
  19243. let layer = 0; // steps + 1
  19244. let offset = vlen * layer;
  19245. // Bottom faces
  19246. for ( let i = 0; i < flen; i ++ ) {
  19247. const face = faces[ i ];
  19248. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19249. }
  19250. layer = steps + bevelSegments * 2;
  19251. offset = vlen * layer;
  19252. // Top faces
  19253. for ( let i = 0; i < flen; i ++ ) {
  19254. const face = faces[ i ];
  19255. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19256. }
  19257. } else {
  19258. // Bottom faces
  19259. for ( let i = 0; i < flen; i ++ ) {
  19260. const face = faces[ i ];
  19261. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19262. }
  19263. // Top faces
  19264. for ( let i = 0; i < flen; i ++ ) {
  19265. const face = faces[ i ];
  19266. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19267. }
  19268. }
  19269. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  19270. }
  19271. // Create faces for the z-sides of the shape
  19272. function buildSideFaces() {
  19273. const start = verticesArray.length / 3;
  19274. let layeroffset = 0;
  19275. sidewalls( contour, layeroffset );
  19276. layeroffset += contour.length;
  19277. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19278. const ahole = holes[ h ];
  19279. sidewalls( ahole, layeroffset );
  19280. //, true
  19281. layeroffset += ahole.length;
  19282. }
  19283. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  19284. }
  19285. function sidewalls( contour, layeroffset ) {
  19286. let i = contour.length;
  19287. while ( -- i >= 0 ) {
  19288. const j = i;
  19289. let k = i - 1;
  19290. if ( k < 0 ) k = contour.length - 1;
  19291. //console.log('b', i,j, i-1, k,vertices.length);
  19292. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  19293. const slen1 = vlen * s;
  19294. const slen2 = vlen * ( s + 1 );
  19295. const a = layeroffset + j + slen1,
  19296. b = layeroffset + k + slen1,
  19297. c = layeroffset + k + slen2,
  19298. d = layeroffset + j + slen2;
  19299. f4( a, b, c, d );
  19300. }
  19301. }
  19302. }
  19303. function v( x, y, z ) {
  19304. placeholder.push( x );
  19305. placeholder.push( y );
  19306. placeholder.push( z );
  19307. }
  19308. function f3( a, b, c ) {
  19309. addVertex( a );
  19310. addVertex( b );
  19311. addVertex( c );
  19312. const nextIndex = verticesArray.length / 3;
  19313. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19314. addUV( uvs[ 0 ] );
  19315. addUV( uvs[ 1 ] );
  19316. addUV( uvs[ 2 ] );
  19317. }
  19318. function f4( a, b, c, d ) {
  19319. addVertex( a );
  19320. addVertex( b );
  19321. addVertex( d );
  19322. addVertex( b );
  19323. addVertex( c );
  19324. addVertex( d );
  19325. const nextIndex = verticesArray.length / 3;
  19326. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19327. addUV( uvs[ 0 ] );
  19328. addUV( uvs[ 1 ] );
  19329. addUV( uvs[ 3 ] );
  19330. addUV( uvs[ 1 ] );
  19331. addUV( uvs[ 2 ] );
  19332. addUV( uvs[ 3 ] );
  19333. }
  19334. function addVertex( index ) {
  19335. verticesArray.push( placeholder[ index * 3 + 0 ] );
  19336. verticesArray.push( placeholder[ index * 3 + 1 ] );
  19337. verticesArray.push( placeholder[ index * 3 + 2 ] );
  19338. }
  19339. function addUV( vector2 ) {
  19340. uvArray.push( vector2.x );
  19341. uvArray.push( vector2.y );
  19342. }
  19343. }
  19344. }
  19345. toJSON() {
  19346. const data = BufferGeometry.prototype.toJSON.call( this );
  19347. const shapes = this.parameters.shapes;
  19348. const options = this.parameters.options;
  19349. return toJSON( shapes, options, data );
  19350. }
  19351. }
  19352. const WorldUVGenerator = {
  19353. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  19354. const a_x = vertices[ indexA * 3 ];
  19355. const a_y = vertices[ indexA * 3 + 1 ];
  19356. const b_x = vertices[ indexB * 3 ];
  19357. const b_y = vertices[ indexB * 3 + 1 ];
  19358. const c_x = vertices[ indexC * 3 ];
  19359. const c_y = vertices[ indexC * 3 + 1 ];
  19360. return [
  19361. new Vector2$1( a_x, a_y ),
  19362. new Vector2$1( b_x, b_y ),
  19363. new Vector2$1( c_x, c_y )
  19364. ];
  19365. },
  19366. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  19367. const a_x = vertices[ indexA * 3 ];
  19368. const a_y = vertices[ indexA * 3 + 1 ];
  19369. const a_z = vertices[ indexA * 3 + 2 ];
  19370. const b_x = vertices[ indexB * 3 ];
  19371. const b_y = vertices[ indexB * 3 + 1 ];
  19372. const b_z = vertices[ indexB * 3 + 2 ];
  19373. const c_x = vertices[ indexC * 3 ];
  19374. const c_y = vertices[ indexC * 3 + 1 ];
  19375. const c_z = vertices[ indexC * 3 + 2 ];
  19376. const d_x = vertices[ indexD * 3 ];
  19377. const d_y = vertices[ indexD * 3 + 1 ];
  19378. const d_z = vertices[ indexD * 3 + 2 ];
  19379. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  19380. return [
  19381. new Vector2$1( a_x, 1 - a_z ),
  19382. new Vector2$1( b_x, 1 - b_z ),
  19383. new Vector2$1( c_x, 1 - c_z ),
  19384. new Vector2$1( d_x, 1 - d_z )
  19385. ];
  19386. } else {
  19387. return [
  19388. new Vector2$1( a_y, 1 - a_z ),
  19389. new Vector2$1( b_y, 1 - b_z ),
  19390. new Vector2$1( c_y, 1 - c_z ),
  19391. new Vector2$1( d_y, 1 - d_z )
  19392. ];
  19393. }
  19394. }
  19395. };
  19396. function toJSON( shapes, options, data ) {
  19397. data.shapes = [];
  19398. if ( Array.isArray( shapes ) ) {
  19399. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19400. const shape = shapes[ i ];
  19401. data.shapes.push( shape.uuid );
  19402. }
  19403. } else {
  19404. data.shapes.push( shapes.uuid );
  19405. }
  19406. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19407. return data;
  19408. }
  19409. /**
  19410. * Creates extruded geometry from a path shape.
  19411. *
  19412. * parameters = {
  19413. *
  19414. * curveSegments: <int>, // number of points on the curves
  19415. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19416. * depth: <float>, // Depth to extrude the shape
  19417. *
  19418. * bevelEnabled: <bool>, // turn on bevel
  19419. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19420. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19421. * bevelOffset: <float>, // how far from shape outline does bevel start
  19422. * bevelSegments: <int>, // number of bevel layers
  19423. *
  19424. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19425. *
  19426. * UVGenerator: <Object> // object that provides UV generator functions
  19427. *
  19428. * }
  19429. */
  19430. class ExtrudeGeometry extends Geometry {
  19431. constructor( shapes, options ) {
  19432. super();
  19433. this.type = 'ExtrudeGeometry';
  19434. this.parameters = {
  19435. shapes: shapes,
  19436. options: options
  19437. };
  19438. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  19439. this.mergeVertices();
  19440. }
  19441. toJSON() {
  19442. const data = super.toJSON();
  19443. const shapes = this.parameters.shapes;
  19444. const options = this.parameters.options;
  19445. return toJSON$1( shapes, options, data );
  19446. }
  19447. }
  19448. function toJSON$1( shapes, options, data ) {
  19449. data.shapes = [];
  19450. if ( Array.isArray( shapes ) ) {
  19451. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19452. const shape = shapes[ i ];
  19453. data.shapes.push( shape.uuid );
  19454. }
  19455. } else {
  19456. data.shapes.push( shapes.uuid );
  19457. }
  19458. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19459. return data;
  19460. }
  19461. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  19462. constructor( radius = 1, detail = 0 ) {
  19463. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19464. const vertices = [
  19465. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19466. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19467. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19468. ];
  19469. const indices = [
  19470. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19471. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19472. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19473. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19474. ];
  19475. super( vertices, indices, radius, detail );
  19476. this.type = 'IcosahedronBufferGeometry';
  19477. this.parameters = {
  19478. radius: radius,
  19479. detail: detail
  19480. };
  19481. }
  19482. }
  19483. class IcosahedronGeometry extends Geometry {
  19484. constructor( radius, detail ) {
  19485. super();
  19486. this.type = 'IcosahedronGeometry';
  19487. this.parameters = {
  19488. radius: radius,
  19489. detail: detail
  19490. };
  19491. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19492. this.mergeVertices();
  19493. }
  19494. }
  19495. class LatheBufferGeometry extends BufferGeometry {
  19496. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  19497. super();
  19498. this.type = 'LatheBufferGeometry';
  19499. this.parameters = {
  19500. points: points,
  19501. segments: segments,
  19502. phiStart: phiStart,
  19503. phiLength: phiLength
  19504. };
  19505. segments = Math.floor( segments );
  19506. // clamp phiLength so it's in range of [ 0, 2PI ]
  19507. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  19508. // buffers
  19509. const indices = [];
  19510. const vertices = [];
  19511. const uvs = [];
  19512. // helper variables
  19513. const inverseSegments = 1.0 / segments;
  19514. const vertex = new Vector3();
  19515. const uv = new Vector2$1();
  19516. // generate vertices and uvs
  19517. for ( let i = 0; i <= segments; i ++ ) {
  19518. const phi = phiStart + i * inverseSegments * phiLength;
  19519. const sin = Math.sin( phi );
  19520. const cos = Math.cos( phi );
  19521. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19522. // vertex
  19523. vertex.x = points[ j ].x * sin;
  19524. vertex.y = points[ j ].y;
  19525. vertex.z = points[ j ].x * cos;
  19526. vertices.push( vertex.x, vertex.y, vertex.z );
  19527. // uv
  19528. uv.x = i / segments;
  19529. uv.y = j / ( points.length - 1 );
  19530. uvs.push( uv.x, uv.y );
  19531. }
  19532. }
  19533. // indices
  19534. for ( let i = 0; i < segments; i ++ ) {
  19535. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19536. const base = j + i * points.length;
  19537. const a = base;
  19538. const b = base + points.length;
  19539. const c = base + points.length + 1;
  19540. const d = base + 1;
  19541. // faces
  19542. indices.push( a, b, d );
  19543. indices.push( b, c, d );
  19544. }
  19545. }
  19546. // build geometry
  19547. this.setIndex( indices );
  19548. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19549. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19550. // generate normals
  19551. this.computeVertexNormals();
  19552. // if the geometry is closed, we need to average the normals along the seam.
  19553. // because the corresponding vertices are identical (but still have different UVs).
  19554. if ( phiLength === Math.PI * 2 ) {
  19555. const normals = this.attributes.normal.array;
  19556. const n1 = new Vector3();
  19557. const n2 = new Vector3();
  19558. const n = new Vector3();
  19559. // this is the buffer offset for the last line of vertices
  19560. const base = segments * points.length * 3;
  19561. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  19562. // select the normal of the vertex in the first line
  19563. n1.x = normals[ j + 0 ];
  19564. n1.y = normals[ j + 1 ];
  19565. n1.z = normals[ j + 2 ];
  19566. // select the normal of the vertex in the last line
  19567. n2.x = normals[ base + j + 0 ];
  19568. n2.y = normals[ base + j + 1 ];
  19569. n2.z = normals[ base + j + 2 ];
  19570. // average normals
  19571. n.addVectors( n1, n2 ).normalize();
  19572. // assign the new values to both normals
  19573. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  19574. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  19575. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  19576. }
  19577. }
  19578. }
  19579. }
  19580. class LatheGeometry extends Geometry {
  19581. constructor( points, segments, phiStart, phiLength ) {
  19582. super();
  19583. this.type = 'LatheGeometry';
  19584. this.parameters = {
  19585. points: points,
  19586. segments: segments,
  19587. phiStart: phiStart,
  19588. phiLength: phiLength
  19589. };
  19590. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  19591. this.mergeVertices();
  19592. }
  19593. }
  19594. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  19595. constructor( radius = 1, detail = 0 ) {
  19596. const vertices = [
  19597. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  19598. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19599. ];
  19600. const indices = [
  19601. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  19602. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  19603. 1, 3, 4, 1, 4, 2
  19604. ];
  19605. super( vertices, indices, radius, detail );
  19606. this.type = 'OctahedronBufferGeometry';
  19607. this.parameters = {
  19608. radius: radius,
  19609. detail: detail
  19610. };
  19611. }
  19612. }
  19613. class OctahedronGeometry extends Geometry {
  19614. constructor( radius, detail ) {
  19615. super();
  19616. this.type = 'OctahedronGeometry';
  19617. this.parameters = {
  19618. radius: radius,
  19619. detail: detail
  19620. };
  19621. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19622. this.mergeVertices();
  19623. }
  19624. }
  19625. /**
  19626. * Parametric Surfaces Geometry
  19627. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19628. */
  19629. function ParametricBufferGeometry( func, slices, stacks ) {
  19630. BufferGeometry.call( this );
  19631. this.type = 'ParametricBufferGeometry';
  19632. this.parameters = {
  19633. func: func,
  19634. slices: slices,
  19635. stacks: stacks
  19636. };
  19637. // buffers
  19638. const indices = [];
  19639. const vertices = [];
  19640. const normals = [];
  19641. const uvs = [];
  19642. const EPS = 0.00001;
  19643. const normal = new Vector3();
  19644. const p0 = new Vector3(), p1 = new Vector3();
  19645. const pu = new Vector3(), pv = new Vector3();
  19646. if ( func.length < 3 ) {
  19647. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  19648. }
  19649. // generate vertices, normals and uvs
  19650. const sliceCount = slices + 1;
  19651. for ( let i = 0; i <= stacks; i ++ ) {
  19652. const v = i / stacks;
  19653. for ( let j = 0; j <= slices; j ++ ) {
  19654. const u = j / slices;
  19655. // vertex
  19656. func( u, v, p0 );
  19657. vertices.push( p0.x, p0.y, p0.z );
  19658. // normal
  19659. // approximate tangent vectors via finite differences
  19660. if ( u - EPS >= 0 ) {
  19661. func( u - EPS, v, p1 );
  19662. pu.subVectors( p0, p1 );
  19663. } else {
  19664. func( u + EPS, v, p1 );
  19665. pu.subVectors( p1, p0 );
  19666. }
  19667. if ( v - EPS >= 0 ) {
  19668. func( u, v - EPS, p1 );
  19669. pv.subVectors( p0, p1 );
  19670. } else {
  19671. func( u, v + EPS, p1 );
  19672. pv.subVectors( p1, p0 );
  19673. }
  19674. // cross product of tangent vectors returns surface normal
  19675. normal.crossVectors( pu, pv ).normalize();
  19676. normals.push( normal.x, normal.y, normal.z );
  19677. // uv
  19678. uvs.push( u, v );
  19679. }
  19680. }
  19681. // generate indices
  19682. for ( let i = 0; i < stacks; i ++ ) {
  19683. for ( let j = 0; j < slices; j ++ ) {
  19684. const a = i * sliceCount + j;
  19685. const b = i * sliceCount + j + 1;
  19686. const c = ( i + 1 ) * sliceCount + j + 1;
  19687. const d = ( i + 1 ) * sliceCount + j;
  19688. // faces one and two
  19689. indices.push( a, b, d );
  19690. indices.push( b, c, d );
  19691. }
  19692. }
  19693. // build geometry
  19694. this.setIndex( indices );
  19695. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19696. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19697. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19698. }
  19699. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19700. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19701. /**
  19702. * Parametric Surfaces Geometry
  19703. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19704. */
  19705. function ParametricGeometry( func, slices, stacks ) {
  19706. Geometry.call( this );
  19707. this.type = 'ParametricGeometry';
  19708. this.parameters = {
  19709. func: func,
  19710. slices: slices,
  19711. stacks: stacks
  19712. };
  19713. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19714. this.mergeVertices();
  19715. }
  19716. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19717. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19718. class PlaneGeometry extends Geometry {
  19719. constructor( width, height, widthSegments, heightSegments ) {
  19720. super();
  19721. this.type = 'PlaneGeometry';
  19722. this.parameters = {
  19723. width: width,
  19724. height: height,
  19725. widthSegments: widthSegments,
  19726. heightSegments: heightSegments
  19727. };
  19728. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19729. this.mergeVertices();
  19730. }
  19731. }
  19732. class PolyhedronGeometry extends Geometry {
  19733. constructor( vertices, indices, radius, detail ) {
  19734. super();
  19735. this.type = 'PolyhedronGeometry';
  19736. this.parameters = {
  19737. vertices: vertices,
  19738. indices: indices,
  19739. radius: radius,
  19740. detail: detail
  19741. };
  19742. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19743. this.mergeVertices();
  19744. }
  19745. }
  19746. class RingBufferGeometry extends BufferGeometry {
  19747. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19748. super();
  19749. this.type = 'RingBufferGeometry';
  19750. this.parameters = {
  19751. innerRadius: innerRadius,
  19752. outerRadius: outerRadius,
  19753. thetaSegments: thetaSegments,
  19754. phiSegments: phiSegments,
  19755. thetaStart: thetaStart,
  19756. thetaLength: thetaLength
  19757. };
  19758. thetaSegments = Math.max( 3, thetaSegments );
  19759. phiSegments = Math.max( 1, phiSegments );
  19760. // buffers
  19761. const indices = [];
  19762. const vertices = [];
  19763. const normals = [];
  19764. const uvs = [];
  19765. // some helper variables
  19766. let radius = innerRadius;
  19767. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19768. const vertex = new Vector3();
  19769. const uv = new Vector2$1();
  19770. // generate vertices, normals and uvs
  19771. for ( let j = 0; j <= phiSegments; j ++ ) {
  19772. for ( let i = 0; i <= thetaSegments; i ++ ) {
  19773. // values are generate from the inside of the ring to the outside
  19774. const segment = thetaStart + i / thetaSegments * thetaLength;
  19775. // vertex
  19776. vertex.x = radius * Math.cos( segment );
  19777. vertex.y = radius * Math.sin( segment );
  19778. vertices.push( vertex.x, vertex.y, vertex.z );
  19779. // normal
  19780. normals.push( 0, 0, 1 );
  19781. // uv
  19782. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  19783. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  19784. uvs.push( uv.x, uv.y );
  19785. }
  19786. // increase the radius for next row of vertices
  19787. radius += radiusStep;
  19788. }
  19789. // indices
  19790. for ( let j = 0; j < phiSegments; j ++ ) {
  19791. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  19792. for ( let i = 0; i < thetaSegments; i ++ ) {
  19793. const segment = i + thetaSegmentLevel;
  19794. const a = segment;
  19795. const b = segment + thetaSegments + 1;
  19796. const c = segment + thetaSegments + 2;
  19797. const d = segment + 1;
  19798. // faces
  19799. indices.push( a, b, d );
  19800. indices.push( b, c, d );
  19801. }
  19802. }
  19803. // build geometry
  19804. this.setIndex( indices );
  19805. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19806. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19807. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19808. }
  19809. }
  19810. class RingGeometry extends Geometry {
  19811. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19812. super();
  19813. this.type = 'RingGeometry';
  19814. this.parameters = {
  19815. innerRadius: innerRadius,
  19816. outerRadius: outerRadius,
  19817. thetaSegments: thetaSegments,
  19818. phiSegments: phiSegments,
  19819. thetaStart: thetaStart,
  19820. thetaLength: thetaLength
  19821. };
  19822. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  19823. this.mergeVertices();
  19824. }
  19825. }
  19826. class ShapeBufferGeometry extends BufferGeometry {
  19827. constructor( shapes, curveSegments = 12 ) {
  19828. super();
  19829. this.type = 'ShapeBufferGeometry';
  19830. this.parameters = {
  19831. shapes: shapes,
  19832. curveSegments: curveSegments
  19833. };
  19834. // buffers
  19835. const indices = [];
  19836. const vertices = [];
  19837. const normals = [];
  19838. const uvs = [];
  19839. // helper variables
  19840. let groupStart = 0;
  19841. let groupCount = 0;
  19842. // allow single and array values for "shapes" parameter
  19843. if ( Array.isArray( shapes ) === false ) {
  19844. addShape( shapes );
  19845. } else {
  19846. for ( let i = 0; i < shapes.length; i ++ ) {
  19847. addShape( shapes[ i ] );
  19848. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  19849. groupStart += groupCount;
  19850. groupCount = 0;
  19851. }
  19852. }
  19853. // build geometry
  19854. this.setIndex( indices );
  19855. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19856. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19857. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19858. // helper functions
  19859. function addShape( shape ) {
  19860. const indexOffset = vertices.length / 3;
  19861. const points = shape.extractPoints( curveSegments );
  19862. let shapeVertices = points.shape;
  19863. const shapeHoles = points.holes;
  19864. // check direction of vertices
  19865. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  19866. shapeVertices = shapeVertices.reverse();
  19867. }
  19868. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19869. const shapeHole = shapeHoles[ i ];
  19870. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  19871. shapeHoles[ i ] = shapeHole.reverse();
  19872. }
  19873. }
  19874. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  19875. // join vertices of inner and outer paths to a single array
  19876. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19877. const shapeHole = shapeHoles[ i ];
  19878. shapeVertices = shapeVertices.concat( shapeHole );
  19879. }
  19880. // vertices, normals, uvs
  19881. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  19882. const vertex = shapeVertices[ i ];
  19883. vertices.push( vertex.x, vertex.y, 0 );
  19884. normals.push( 0, 0, 1 );
  19885. uvs.push( vertex.x, vertex.y ); // world uvs
  19886. }
  19887. // incides
  19888. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  19889. const face = faces[ i ];
  19890. const a = face[ 0 ] + indexOffset;
  19891. const b = face[ 1 ] + indexOffset;
  19892. const c = face[ 2 ] + indexOffset;
  19893. indices.push( a, b, c );
  19894. groupCount += 3;
  19895. }
  19896. }
  19897. }
  19898. toJSON() {
  19899. const data = BufferGeometry.prototype.toJSON.call( this );
  19900. const shapes = this.parameters.shapes;
  19901. return toJSON$2( shapes, data );
  19902. }
  19903. }
  19904. function toJSON$2( shapes, data ) {
  19905. data.shapes = [];
  19906. if ( Array.isArray( shapes ) ) {
  19907. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19908. const shape = shapes[ i ];
  19909. data.shapes.push( shape.uuid );
  19910. }
  19911. } else {
  19912. data.shapes.push( shapes.uuid );
  19913. }
  19914. return data;
  19915. }
  19916. class ShapeGeometry extends Geometry {
  19917. constructor( shapes, curveSegments ) {
  19918. super();
  19919. this.type = 'ShapeGeometry';
  19920. if ( typeof curveSegments === 'object' ) {
  19921. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  19922. curveSegments = curveSegments.curveSegments;
  19923. }
  19924. this.parameters = {
  19925. shapes: shapes,
  19926. curveSegments: curveSegments
  19927. };
  19928. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  19929. this.mergeVertices();
  19930. }
  19931. toJSON() {
  19932. const data = Geometry.prototype.toJSON.call( this );
  19933. const shapes = this.parameters.shapes;
  19934. return toJSON$3( shapes, data );
  19935. }
  19936. }
  19937. function toJSON$3( shapes, data ) {
  19938. data.shapes = [];
  19939. if ( Array.isArray( shapes ) ) {
  19940. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19941. const shape = shapes[ i ];
  19942. data.shapes.push( shape.uuid );
  19943. }
  19944. } else {
  19945. data.shapes.push( shapes.uuid );
  19946. }
  19947. return data;
  19948. }
  19949. class SphereBufferGeometry extends BufferGeometry {
  19950. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  19951. super();
  19952. this.type = 'SphereBufferGeometry';
  19953. this.parameters = {
  19954. radius: radius,
  19955. widthSegments: widthSegments,
  19956. heightSegments: heightSegments,
  19957. phiStart: phiStart,
  19958. phiLength: phiLength,
  19959. thetaStart: thetaStart,
  19960. thetaLength: thetaLength
  19961. };
  19962. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  19963. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  19964. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  19965. let index = 0;
  19966. const grid = [];
  19967. const vertex = new Vector3();
  19968. const normal = new Vector3();
  19969. // buffers
  19970. const indices = [];
  19971. const vertices = [];
  19972. const normals = [];
  19973. const uvs = [];
  19974. // generate vertices, normals and uvs
  19975. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  19976. const verticesRow = [];
  19977. const v = iy / heightSegments;
  19978. // special case for the poles
  19979. let uOffset = 0;
  19980. if ( iy == 0 && thetaStart == 0 ) {
  19981. uOffset = 0.5 / widthSegments;
  19982. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  19983. uOffset = - 0.5 / widthSegments;
  19984. }
  19985. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  19986. const u = ix / widthSegments;
  19987. // vertex
  19988. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19989. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19990. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19991. vertices.push( vertex.x, vertex.y, vertex.z );
  19992. // normal
  19993. normal.copy( vertex ).normalize();
  19994. normals.push( normal.x, normal.y, normal.z );
  19995. // uv
  19996. uvs.push( u + uOffset, 1 - v );
  19997. verticesRow.push( index ++ );
  19998. }
  19999. grid.push( verticesRow );
  20000. }
  20001. // indices
  20002. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20003. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20004. const a = grid[ iy ][ ix + 1 ];
  20005. const b = grid[ iy ][ ix ];
  20006. const c = grid[ iy + 1 ][ ix ];
  20007. const d = grid[ iy + 1 ][ ix + 1 ];
  20008. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20009. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20010. }
  20011. }
  20012. // build geometry
  20013. this.setIndex( indices );
  20014. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20015. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20016. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20017. }
  20018. }
  20019. class SphereGeometry extends Geometry {
  20020. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20021. super();
  20022. this.type = 'SphereGeometry';
  20023. this.parameters = {
  20024. radius: radius,
  20025. widthSegments: widthSegments,
  20026. heightSegments: heightSegments,
  20027. phiStart: phiStart,
  20028. phiLength: phiLength,
  20029. thetaStart: thetaStart,
  20030. thetaLength: thetaLength
  20031. };
  20032. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  20033. this.mergeVertices();
  20034. }
  20035. }
  20036. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  20037. constructor( radius = 1, detail = 0 ) {
  20038. const vertices = [
  20039. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20040. ];
  20041. const indices = [
  20042. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20043. ];
  20044. super( vertices, indices, radius, detail );
  20045. this.type = 'TetrahedronBufferGeometry';
  20046. this.parameters = {
  20047. radius: radius,
  20048. detail: detail
  20049. };
  20050. }
  20051. }
  20052. class TetrahedronGeometry extends Geometry {
  20053. constructor( radius, detail ) {
  20054. super();
  20055. this.type = 'TetrahedronGeometry';
  20056. this.parameters = {
  20057. radius: radius,
  20058. detail: detail
  20059. };
  20060. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  20061. this.mergeVertices();
  20062. }
  20063. }
  20064. /**
  20065. * Text = 3D Text
  20066. *
  20067. * parameters = {
  20068. * font: <THREE.Font>, // font
  20069. *
  20070. * size: <float>, // size of the text
  20071. * height: <float>, // thickness to extrude text
  20072. * curveSegments: <int>, // number of points on the curves
  20073. *
  20074. * bevelEnabled: <bool>, // turn on bevel
  20075. * bevelThickness: <float>, // how deep into text bevel goes
  20076. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20077. * bevelOffset: <float> // how far from text outline does bevel start
  20078. * }
  20079. */
  20080. class TextBufferGeometry extends ExtrudeBufferGeometry {
  20081. constructor( text, parameters = {} ) {
  20082. const font = parameters.font;
  20083. if ( ! ( font && font.isFont ) ) {
  20084. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20085. return new BufferGeometry();
  20086. }
  20087. const shapes = font.generateShapes( text, parameters.size );
  20088. // translate parameters to ExtrudeGeometry API
  20089. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  20090. // defaults
  20091. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20092. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20093. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20094. super( shapes, parameters );
  20095. this.type = 'TextBufferGeometry';
  20096. }
  20097. }
  20098. /**
  20099. * Text = 3D Text
  20100. *
  20101. * parameters = {
  20102. * font: <THREE.Font>, // font
  20103. *
  20104. * size: <float>, // size of the text
  20105. * height: <float>, // thickness to extrude text
  20106. * curveSegments: <int>, // number of points on the curves
  20107. *
  20108. * bevelEnabled: <bool>, // turn on bevel
  20109. * bevelThickness: <float>, // how deep into text bevel goes
  20110. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20111. * bevelOffset: <float> // how far from text outline does bevel start
  20112. * }
  20113. */
  20114. class TextGeometry extends Geometry {
  20115. constructor( text, parameters ) {
  20116. super();
  20117. this.type = 'TextGeometry';
  20118. this.parameters = {
  20119. text: text,
  20120. parameters: parameters
  20121. };
  20122. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  20123. this.mergeVertices();
  20124. }
  20125. }
  20126. class TorusBufferGeometry extends BufferGeometry {
  20127. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  20128. super();
  20129. this.type = 'TorusBufferGeometry';
  20130. this.parameters = {
  20131. radius: radius,
  20132. tube: tube,
  20133. radialSegments: radialSegments,
  20134. tubularSegments: tubularSegments,
  20135. arc: arc
  20136. };
  20137. radialSegments = Math.floor( radialSegments );
  20138. tubularSegments = Math.floor( tubularSegments );
  20139. // buffers
  20140. const indices = [];
  20141. const vertices = [];
  20142. const normals = [];
  20143. const uvs = [];
  20144. // helper variables
  20145. const center = new Vector3();
  20146. const vertex = new Vector3();
  20147. const normal = new Vector3();
  20148. // generate vertices, normals and uvs
  20149. for ( let j = 0; j <= radialSegments; j ++ ) {
  20150. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20151. const u = i / tubularSegments * arc;
  20152. const v = j / radialSegments * Math.PI * 2;
  20153. // vertex
  20154. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20155. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20156. vertex.z = tube * Math.sin( v );
  20157. vertices.push( vertex.x, vertex.y, vertex.z );
  20158. // normal
  20159. center.x = radius * Math.cos( u );
  20160. center.y = radius * Math.sin( u );
  20161. normal.subVectors( vertex, center ).normalize();
  20162. normals.push( normal.x, normal.y, normal.z );
  20163. // uv
  20164. uvs.push( i / tubularSegments );
  20165. uvs.push( j / radialSegments );
  20166. }
  20167. }
  20168. // generate indices
  20169. for ( let j = 1; j <= radialSegments; j ++ ) {
  20170. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20171. // indices
  20172. const a = ( tubularSegments + 1 ) * j + i - 1;
  20173. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20174. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20175. const d = ( tubularSegments + 1 ) * j + i;
  20176. // faces
  20177. indices.push( a, b, d );
  20178. indices.push( b, c, d );
  20179. }
  20180. }
  20181. // build geometry
  20182. this.setIndex( indices );
  20183. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20184. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20185. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20186. }
  20187. }
  20188. class TorusGeometry extends Geometry {
  20189. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  20190. super();
  20191. this.type = 'TorusGeometry';
  20192. this.parameters = {
  20193. radius: radius,
  20194. tube: tube,
  20195. radialSegments: radialSegments,
  20196. tubularSegments: tubularSegments,
  20197. arc: arc
  20198. };
  20199. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20200. this.mergeVertices();
  20201. }
  20202. }
  20203. class TorusKnotBufferGeometry extends BufferGeometry {
  20204. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20205. super();
  20206. this.type = 'TorusKnotBufferGeometry';
  20207. this.parameters = {
  20208. radius: radius,
  20209. tube: tube,
  20210. tubularSegments: tubularSegments,
  20211. radialSegments: radialSegments,
  20212. p: p,
  20213. q: q
  20214. };
  20215. tubularSegments = Math.floor( tubularSegments );
  20216. radialSegments = Math.floor( radialSegments );
  20217. // buffers
  20218. const indices = [];
  20219. const vertices = [];
  20220. const normals = [];
  20221. const uvs = [];
  20222. // helper variables
  20223. const vertex = new Vector3();
  20224. const normal = new Vector3();
  20225. const P1 = new Vector3();
  20226. const P2 = new Vector3();
  20227. const B = new Vector3();
  20228. const T = new Vector3();
  20229. const N = new Vector3();
  20230. // generate vertices, normals and uvs
  20231. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20232. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20233. const u = i / tubularSegments * p * Math.PI * 2;
  20234. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20235. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20236. calculatePositionOnCurve( u, p, q, radius, P1 );
  20237. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20238. // calculate orthonormal basis
  20239. T.subVectors( P2, P1 );
  20240. N.addVectors( P2, P1 );
  20241. B.crossVectors( T, N );
  20242. N.crossVectors( B, T );
  20243. // normalize B, N. T can be ignored, we don't use it
  20244. B.normalize();
  20245. N.normalize();
  20246. for ( let j = 0; j <= radialSegments; ++ j ) {
  20247. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20248. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20249. const v = j / radialSegments * Math.PI * 2;
  20250. const cx = - tube * Math.cos( v );
  20251. const cy = tube * Math.sin( v );
  20252. // now calculate the final vertex position.
  20253. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20254. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20255. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20256. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20257. vertices.push( vertex.x, vertex.y, vertex.z );
  20258. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20259. normal.subVectors( vertex, P1 ).normalize();
  20260. normals.push( normal.x, normal.y, normal.z );
  20261. // uv
  20262. uvs.push( i / tubularSegments );
  20263. uvs.push( j / radialSegments );
  20264. }
  20265. }
  20266. // generate indices
  20267. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20268. for ( let i = 1; i <= radialSegments; i ++ ) {
  20269. // indices
  20270. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20271. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20272. const c = ( radialSegments + 1 ) * j + i;
  20273. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20274. // faces
  20275. indices.push( a, b, d );
  20276. indices.push( b, c, d );
  20277. }
  20278. }
  20279. // build geometry
  20280. this.setIndex( indices );
  20281. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20282. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20283. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20284. // this function calculates the current position on the torus curve
  20285. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20286. const cu = Math.cos( u );
  20287. const su = Math.sin( u );
  20288. const quOverP = q / p * u;
  20289. const cs = Math.cos( quOverP );
  20290. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20291. position.y = radius * ( 2 + cs ) * su * 0.5;
  20292. position.z = radius * Math.sin( quOverP ) * 0.5;
  20293. }
  20294. }
  20295. }
  20296. class TorusKnotGeometry extends Geometry {
  20297. constructor( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20298. super();
  20299. this.type = 'TorusKnotGeometry';
  20300. this.parameters = {
  20301. radius: radius,
  20302. tube: tube,
  20303. tubularSegments: tubularSegments,
  20304. radialSegments: radialSegments,
  20305. p: p,
  20306. q: q
  20307. };
  20308. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20309. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20310. this.mergeVertices();
  20311. }
  20312. }
  20313. class TubeBufferGeometry extends BufferGeometry {
  20314. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  20315. super();
  20316. this.type = 'TubeBufferGeometry';
  20317. this.parameters = {
  20318. path: path,
  20319. tubularSegments: tubularSegments,
  20320. radius: radius,
  20321. radialSegments: radialSegments,
  20322. closed: closed
  20323. };
  20324. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20325. // expose internals
  20326. this.tangents = frames.tangents;
  20327. this.normals = frames.normals;
  20328. this.binormals = frames.binormals;
  20329. // helper variables
  20330. const vertex = new Vector3();
  20331. const normal = new Vector3();
  20332. const uv = new Vector2$1();
  20333. let P = new Vector3();
  20334. // buffer
  20335. const vertices = [];
  20336. const normals = [];
  20337. const uvs = [];
  20338. const indices = [];
  20339. // create buffer data
  20340. generateBufferData();
  20341. // build geometry
  20342. this.setIndex( indices );
  20343. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20344. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20345. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20346. // functions
  20347. function generateBufferData() {
  20348. for ( let i = 0; i < tubularSegments; i ++ ) {
  20349. generateSegment( i );
  20350. }
  20351. // if the geometry is not closed, generate the last row of vertices and normals
  20352. // at the regular position on the given path
  20353. //
  20354. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20355. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20356. // uvs are generated in a separate function.
  20357. // this makes it easy compute correct values for closed geometries
  20358. generateUVs();
  20359. // finally create faces
  20360. generateIndices();
  20361. }
  20362. function generateSegment( i ) {
  20363. // we use getPointAt to sample evenly distributed points from the given path
  20364. P = path.getPointAt( i / tubularSegments, P );
  20365. // retrieve corresponding normal and binormal
  20366. const N = frames.normals[ i ];
  20367. const B = frames.binormals[ i ];
  20368. // generate normals and vertices for the current segment
  20369. for ( let j = 0; j <= radialSegments; j ++ ) {
  20370. const v = j / radialSegments * Math.PI * 2;
  20371. const sin = Math.sin( v );
  20372. const cos = - Math.cos( v );
  20373. // normal
  20374. normal.x = ( cos * N.x + sin * B.x );
  20375. normal.y = ( cos * N.y + sin * B.y );
  20376. normal.z = ( cos * N.z + sin * B.z );
  20377. normal.normalize();
  20378. normals.push( normal.x, normal.y, normal.z );
  20379. // vertex
  20380. vertex.x = P.x + radius * normal.x;
  20381. vertex.y = P.y + radius * normal.y;
  20382. vertex.z = P.z + radius * normal.z;
  20383. vertices.push( vertex.x, vertex.y, vertex.z );
  20384. }
  20385. }
  20386. function generateIndices() {
  20387. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20388. for ( let i = 1; i <= radialSegments; i ++ ) {
  20389. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20390. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20391. const c = ( radialSegments + 1 ) * j + i;
  20392. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20393. // faces
  20394. indices.push( a, b, d );
  20395. indices.push( b, c, d );
  20396. }
  20397. }
  20398. }
  20399. function generateUVs() {
  20400. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20401. for ( let j = 0; j <= radialSegments; j ++ ) {
  20402. uv.x = i / tubularSegments;
  20403. uv.y = j / radialSegments;
  20404. uvs.push( uv.x, uv.y );
  20405. }
  20406. }
  20407. }
  20408. }
  20409. toJSON() {
  20410. const data = BufferGeometry.prototype.toJSON.call( this );
  20411. data.path = this.parameters.path.toJSON();
  20412. return data;
  20413. }
  20414. }
  20415. class TubeGeometry extends Geometry {
  20416. constructor( path, tubularSegments, radius, radialSegments, closed, taper ) {
  20417. super();
  20418. this.type = 'TubeGeometry';
  20419. this.parameters = {
  20420. path: path,
  20421. tubularSegments: tubularSegments,
  20422. radius: radius,
  20423. radialSegments: radialSegments,
  20424. closed: closed
  20425. };
  20426. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  20427. const bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  20428. // expose internals
  20429. this.tangents = bufferGeometry.tangents;
  20430. this.normals = bufferGeometry.normals;
  20431. this.binormals = bufferGeometry.binormals;
  20432. // create geometry
  20433. this.fromBufferGeometry( bufferGeometry );
  20434. this.mergeVertices();
  20435. }
  20436. }
  20437. class WireframeGeometry extends BufferGeometry {
  20438. constructor( geometry ) {
  20439. super();
  20440. this.type = 'WireframeGeometry';
  20441. // buffer
  20442. const vertices = [];
  20443. // helper variables
  20444. const edge = [ 0, 0 ], edges = {};
  20445. const keys = [ 'a', 'b', 'c' ];
  20446. // different logic for Geometry and BufferGeometry
  20447. if ( geometry && geometry.isGeometry ) {
  20448. // create a data structure that contains all edges without duplicates
  20449. const faces = geometry.faces;
  20450. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20451. const face = faces[ i ];
  20452. for ( let j = 0; j < 3; j ++ ) {
  20453. const edge1 = face[ keys[ j ] ];
  20454. const edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  20455. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20456. edge[ 1 ] = Math.max( edge1, edge2 );
  20457. const key = edge[ 0 ] + ',' + edge[ 1 ];
  20458. if ( edges[ key ] === undefined ) {
  20459. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20460. }
  20461. }
  20462. }
  20463. // generate vertices
  20464. for ( const key in edges ) {
  20465. const e = edges[ key ];
  20466. let vertex = geometry.vertices[ e.index1 ];
  20467. vertices.push( vertex.x, vertex.y, vertex.z );
  20468. vertex = geometry.vertices[ e.index2 ];
  20469. vertices.push( vertex.x, vertex.y, vertex.z );
  20470. }
  20471. } else if ( geometry && geometry.isBufferGeometry ) {
  20472. const vertex = new Vector3();
  20473. if ( geometry.index !== null ) {
  20474. // indexed BufferGeometry
  20475. const position = geometry.attributes.position;
  20476. const indices = geometry.index;
  20477. let groups = geometry.groups;
  20478. if ( groups.length === 0 ) {
  20479. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20480. }
  20481. // create a data structure that contains all eges without duplicates
  20482. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  20483. const group = groups[ o ];
  20484. const start = group.start;
  20485. const count = group.count;
  20486. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  20487. for ( let j = 0; j < 3; j ++ ) {
  20488. const edge1 = indices.getX( i + j );
  20489. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  20490. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20491. edge[ 1 ] = Math.max( edge1, edge2 );
  20492. const key = edge[ 0 ] + ',' + edge[ 1 ];
  20493. if ( edges[ key ] === undefined ) {
  20494. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20495. }
  20496. }
  20497. }
  20498. }
  20499. // generate vertices
  20500. for ( const key in edges ) {
  20501. const e = edges[ key ];
  20502. vertex.fromBufferAttribute( position, e.index1 );
  20503. vertices.push( vertex.x, vertex.y, vertex.z );
  20504. vertex.fromBufferAttribute( position, e.index2 );
  20505. vertices.push( vertex.x, vertex.y, vertex.z );
  20506. }
  20507. } else {
  20508. // non-indexed BufferGeometry
  20509. const position = geometry.attributes.position;
  20510. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20511. for ( let j = 0; j < 3; j ++ ) {
  20512. // three edges per triangle, an edge is represented as (index1, index2)
  20513. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20514. const index1 = 3 * i + j;
  20515. vertex.fromBufferAttribute( position, index1 );
  20516. vertices.push( vertex.x, vertex.y, vertex.z );
  20517. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  20518. vertex.fromBufferAttribute( position, index2 );
  20519. vertices.push( vertex.x, vertex.y, vertex.z );
  20520. }
  20521. }
  20522. }
  20523. }
  20524. // build geometry
  20525. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20526. }
  20527. }
  20528. var Geometries = /*#__PURE__*/Object.freeze({
  20529. __proto__: null,
  20530. BoxGeometry: BoxGeometry,
  20531. BoxBufferGeometry: BoxBufferGeometry,
  20532. CircleGeometry: CircleGeometry,
  20533. CircleBufferGeometry: CircleBufferGeometry,
  20534. ConeGeometry: ConeGeometry,
  20535. ConeBufferGeometry: ConeBufferGeometry,
  20536. CylinderGeometry: CylinderGeometry,
  20537. CylinderBufferGeometry: CylinderBufferGeometry,
  20538. DodecahedronGeometry: DodecahedronGeometry,
  20539. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20540. EdgesGeometry: EdgesGeometry,
  20541. ExtrudeGeometry: ExtrudeGeometry,
  20542. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20543. IcosahedronGeometry: IcosahedronGeometry,
  20544. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20545. LatheGeometry: LatheGeometry,
  20546. LatheBufferGeometry: LatheBufferGeometry,
  20547. OctahedronGeometry: OctahedronGeometry,
  20548. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20549. ParametricGeometry: ParametricGeometry,
  20550. ParametricBufferGeometry: ParametricBufferGeometry,
  20551. PlaneGeometry: PlaneGeometry,
  20552. PlaneBufferGeometry: PlaneBufferGeometry,
  20553. PolyhedronGeometry: PolyhedronGeometry,
  20554. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20555. RingGeometry: RingGeometry,
  20556. RingBufferGeometry: RingBufferGeometry,
  20557. ShapeGeometry: ShapeGeometry,
  20558. ShapeBufferGeometry: ShapeBufferGeometry,
  20559. SphereGeometry: SphereGeometry,
  20560. SphereBufferGeometry: SphereBufferGeometry,
  20561. TetrahedronGeometry: TetrahedronGeometry,
  20562. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20563. TextGeometry: TextGeometry,
  20564. TextBufferGeometry: TextBufferGeometry,
  20565. TorusGeometry: TorusGeometry,
  20566. TorusBufferGeometry: TorusBufferGeometry,
  20567. TorusKnotGeometry: TorusKnotGeometry,
  20568. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20569. TubeGeometry: TubeGeometry,
  20570. TubeBufferGeometry: TubeBufferGeometry,
  20571. WireframeGeometry: WireframeGeometry
  20572. });
  20573. /**
  20574. * parameters = {
  20575. * color: <THREE.Color>
  20576. * }
  20577. */
  20578. function ShadowMaterial( parameters ) {
  20579. Material.call( this );
  20580. this.type = 'ShadowMaterial';
  20581. this.color = new Color( 0x000000 );
  20582. this.transparent = true;
  20583. this.setValues( parameters );
  20584. }
  20585. ShadowMaterial.prototype = Object.create( Material.prototype );
  20586. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20587. ShadowMaterial.prototype.isShadowMaterial = true;
  20588. ShadowMaterial.prototype.copy = function ( source ) {
  20589. Material.prototype.copy.call( this, source );
  20590. this.color.copy( source.color );
  20591. return this;
  20592. };
  20593. function RawShaderMaterial( parameters ) {
  20594. ShaderMaterial.call( this, parameters );
  20595. this.type = 'RawShaderMaterial';
  20596. }
  20597. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  20598. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20599. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20600. /**
  20601. * parameters = {
  20602. * color: <hex>,
  20603. * roughness: <float>,
  20604. * metalness: <float>,
  20605. * opacity: <float>,
  20606. *
  20607. * map: new THREE.Texture( <Image> ),
  20608. *
  20609. * lightMap: new THREE.Texture( <Image> ),
  20610. * lightMapIntensity: <float>
  20611. *
  20612. * aoMap: new THREE.Texture( <Image> ),
  20613. * aoMapIntensity: <float>
  20614. *
  20615. * emissive: <hex>,
  20616. * emissiveIntensity: <float>
  20617. * emissiveMap: new THREE.Texture( <Image> ),
  20618. *
  20619. * bumpMap: new THREE.Texture( <Image> ),
  20620. * bumpScale: <float>,
  20621. *
  20622. * normalMap: new THREE.Texture( <Image> ),
  20623. * normalMapType: THREE.TangentSpaceNormalMap,
  20624. * normalScale: <Vector2>,
  20625. *
  20626. * displacementMap: new THREE.Texture( <Image> ),
  20627. * displacementScale: <float>,
  20628. * displacementBias: <float>,
  20629. *
  20630. * roughnessMap: new THREE.Texture( <Image> ),
  20631. *
  20632. * metalnessMap: new THREE.Texture( <Image> ),
  20633. *
  20634. * alphaMap: new THREE.Texture( <Image> ),
  20635. *
  20636. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20637. * envMapIntensity: <float>
  20638. *
  20639. * refractionRatio: <float>,
  20640. *
  20641. * wireframe: <boolean>,
  20642. * wireframelineWidth: <float>,
  20643. *
  20644. * skinning: <bool>,
  20645. * morphTargets: <bool>,
  20646. * morphNormals: <bool>
  20647. * }
  20648. */
  20649. function MeshStandardMaterial( parameters ) {
  20650. Material.call( this );
  20651. this.defines = { 'STANDARD': '' };
  20652. this.type = 'MeshStandardMaterial';
  20653. this.color = new Color( 0xffffff ); // diffuse
  20654. this.roughness = 1.0;
  20655. this.metalness = 0.0;
  20656. this.map = null;
  20657. this.lightMap = null;
  20658. this.lightMapIntensity = 1.0;
  20659. this.aoMap = null;
  20660. this.aoMapIntensity = 1.0;
  20661. this.emissive = new Color( 0x000000 );
  20662. this.emissiveIntensity = 1.0;
  20663. this.emissiveMap = null;
  20664. this.bumpMap = null;
  20665. this.bumpScale = 1;
  20666. this.normalMap = null;
  20667. this.normalMapType = TangentSpaceNormalMap;
  20668. this.normalScale = new Vector2$1( 1, 1 );
  20669. this.displacementMap = null;
  20670. this.displacementScale = 1;
  20671. this.displacementBias = 0;
  20672. this.roughnessMap = null;
  20673. this.metalnessMap = null;
  20674. this.alphaMap = null;
  20675. this.envMap = null;
  20676. this.envMapIntensity = 1.0;
  20677. this.refractionRatio = 0.98;
  20678. this.wireframe = false;
  20679. this.wireframelineWidth = 1;
  20680. this.wireframeLinecap = 'round';
  20681. this.wireframeLinejoin = 'round';
  20682. this.skinning = false;
  20683. this.morphTargets = false;
  20684. this.morphNormals = false;
  20685. this.vertexTangents = false;
  20686. this.setValues( parameters );
  20687. }
  20688. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  20689. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20690. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20691. MeshStandardMaterial.prototype.copy = function ( source ) {
  20692. Material.prototype.copy.call( this, source );
  20693. this.defines = { 'STANDARD': '' };
  20694. this.color.copy( source.color );
  20695. this.roughness = source.roughness;
  20696. this.metalness = source.metalness;
  20697. this.map = source.map;
  20698. this.lightMap = source.lightMap;
  20699. this.lightMapIntensity = source.lightMapIntensity;
  20700. this.aoMap = source.aoMap;
  20701. this.aoMapIntensity = source.aoMapIntensity;
  20702. this.emissive.copy( source.emissive );
  20703. this.emissiveMap = source.emissiveMap;
  20704. this.emissiveIntensity = source.emissiveIntensity;
  20705. this.bumpMap = source.bumpMap;
  20706. this.bumpScale = source.bumpScale;
  20707. this.normalMap = source.normalMap;
  20708. this.normalMapType = source.normalMapType;
  20709. this.normalScale.copy( source.normalScale );
  20710. this.displacementMap = source.displacementMap;
  20711. this.displacementScale = source.displacementScale;
  20712. this.displacementBias = source.displacementBias;
  20713. this.roughnessMap = source.roughnessMap;
  20714. this.metalnessMap = source.metalnessMap;
  20715. this.alphaMap = source.alphaMap;
  20716. this.envMap = source.envMap;
  20717. this.envMapIntensity = source.envMapIntensity;
  20718. this.refractionRatio = source.refractionRatio;
  20719. this.wireframe = source.wireframe;
  20720. this.wireframelineWidth = source.wireframelineWidth;
  20721. this.wireframeLinecap = source.wireframeLinecap;
  20722. this.wireframeLinejoin = source.wireframeLinejoin;
  20723. this.skinning = source.skinning;
  20724. this.morphTargets = source.morphTargets;
  20725. this.morphNormals = source.morphNormals;
  20726. this.vertexTangents = source.vertexTangents;
  20727. return this;
  20728. };
  20729. /**
  20730. * parameters = {
  20731. * clearcoat: <float>,
  20732. * clearcoatMap: new THREE.Texture( <Image> ),
  20733. * clearcoatRoughness: <float>,
  20734. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20735. * clearcoatNormalScale: <Vector2>,
  20736. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20737. *
  20738. * reflectivity: <float>,
  20739. * ior: <float>,
  20740. *
  20741. * sheen: <Color>,
  20742. *
  20743. * transmission: <float>,
  20744. * transmissionMap: new THREE.Texture( <Image> )
  20745. * }
  20746. */
  20747. function MeshPhysicalMaterial( parameters ) {
  20748. MeshStandardMaterial.call( this );
  20749. this.defines = {
  20750. 'STANDARD': '',
  20751. 'PHYSICAL': ''
  20752. };
  20753. this.type = 'MeshPhysicalMaterial';
  20754. this.clearcoat = 0.0;
  20755. this.clearcoatMap = null;
  20756. this.clearcoatRoughness = 0.0;
  20757. this.clearcoatRoughnessMap = null;
  20758. this.clearcoatNormalScale = new Vector2$1( 1, 1 );
  20759. this.clearcoatNormalMap = null;
  20760. this.reflectivity = 0.5; // maps to F0 = 0.04
  20761. Object.defineProperty( this, 'ior', {
  20762. get: function () {
  20763. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  20764. },
  20765. set: function ( ior ) {
  20766. this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  20767. }
  20768. } );
  20769. this.sheen = null; // null will disable sheen bsdf
  20770. this.transmission = 0.0;
  20771. this.transmissionMap = null;
  20772. this.setValues( parameters );
  20773. }
  20774. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  20775. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20776. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20777. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  20778. MeshStandardMaterial.prototype.copy.call( this, source );
  20779. this.defines = {
  20780. 'STANDARD': '',
  20781. 'PHYSICAL': ''
  20782. };
  20783. this.clearcoat = source.clearcoat;
  20784. this.clearcoatMap = source.clearcoatMap;
  20785. this.clearcoatRoughness = source.clearcoatRoughness;
  20786. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20787. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20788. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  20789. this.reflectivity = source.reflectivity;
  20790. if ( source.sheen ) {
  20791. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  20792. } else {
  20793. this.sheen = null;
  20794. }
  20795. this.transmission = source.transmission;
  20796. this.transmissionMap = source.transmissionMap;
  20797. return this;
  20798. };
  20799. /**
  20800. * parameters = {
  20801. * color: <hex>,
  20802. * specular: <hex>,
  20803. * shininess: <float>,
  20804. * opacity: <float>,
  20805. *
  20806. * map: new THREE.Texture( <Image> ),
  20807. *
  20808. * lightMap: new THREE.Texture( <Image> ),
  20809. * lightMapIntensity: <float>
  20810. *
  20811. * aoMap: new THREE.Texture( <Image> ),
  20812. * aoMapIntensity: <float>
  20813. *
  20814. * emissive: <hex>,
  20815. * emissiveIntensity: <float>
  20816. * emissiveMap: new THREE.Texture( <Image> ),
  20817. *
  20818. * bumpMap: new THREE.Texture( <Image> ),
  20819. * bumpScale: <float>,
  20820. *
  20821. * normalMap: new THREE.Texture( <Image> ),
  20822. * normalMapType: THREE.TangentSpaceNormalMap,
  20823. * normalScale: <Vector2>,
  20824. *
  20825. * displacementMap: new THREE.Texture( <Image> ),
  20826. * displacementScale: <float>,
  20827. * displacementBias: <float>,
  20828. *
  20829. * specularMap: new THREE.Texture( <Image> ),
  20830. *
  20831. * alphaMap: new THREE.Texture( <Image> ),
  20832. *
  20833. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20834. * combine: THREE.MultiplyOperation,
  20835. * reflectivity: <float>,
  20836. * refractionRatio: <float>,
  20837. *
  20838. * wireframe: <boolean>,
  20839. * wireframelineWidth: <float>,
  20840. *
  20841. * skinning: <bool>,
  20842. * morphTargets: <bool>,
  20843. * morphNormals: <bool>
  20844. * }
  20845. */
  20846. function MeshPhongMaterial( parameters ) {
  20847. Material.call( this );
  20848. this.type = 'MeshPhongMaterial';
  20849. this.color = new Color( 0xffffff ); // diffuse
  20850. this.specular = new Color( 0x111111 );
  20851. this.shininess = 30;
  20852. this.map = null;
  20853. this.lightMap = null;
  20854. this.lightMapIntensity = 1.0;
  20855. this.aoMap = null;
  20856. this.aoMapIntensity = 1.0;
  20857. this.emissive = new Color( 0x000000 );
  20858. this.emissiveIntensity = 1.0;
  20859. this.emissiveMap = null;
  20860. this.bumpMap = null;
  20861. this.bumpScale = 1;
  20862. this.normalMap = null;
  20863. this.normalMapType = TangentSpaceNormalMap;
  20864. this.normalScale = new Vector2$1( 1, 1 );
  20865. this.displacementMap = null;
  20866. this.displacementScale = 1;
  20867. this.displacementBias = 0;
  20868. this.specularMap = null;
  20869. this.alphaMap = null;
  20870. this.envMap = null;
  20871. this.combine = MultiplyOperation;
  20872. this.reflectivity = 1;
  20873. this.refractionRatio = 0.98;
  20874. this.wireframe = false;
  20875. this.wireframelineWidth = 1;
  20876. this.wireframeLinecap = 'round';
  20877. this.wireframeLinejoin = 'round';
  20878. this.skinning = false;
  20879. this.morphTargets = false;
  20880. this.morphNormals = false;
  20881. this.setValues( parameters );
  20882. }
  20883. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  20884. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20885. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20886. MeshPhongMaterial.prototype.copy = function ( source ) {
  20887. Material.prototype.copy.call( this, source );
  20888. this.color.copy( source.color );
  20889. this.specular.copy( source.specular );
  20890. this.shininess = source.shininess;
  20891. this.map = source.map;
  20892. this.lightMap = source.lightMap;
  20893. this.lightMapIntensity = source.lightMapIntensity;
  20894. this.aoMap = source.aoMap;
  20895. this.aoMapIntensity = source.aoMapIntensity;
  20896. this.emissive.copy( source.emissive );
  20897. this.emissiveMap = source.emissiveMap;
  20898. this.emissiveIntensity = source.emissiveIntensity;
  20899. this.bumpMap = source.bumpMap;
  20900. this.bumpScale = source.bumpScale;
  20901. this.normalMap = source.normalMap;
  20902. this.normalMapType = source.normalMapType;
  20903. this.normalScale.copy( source.normalScale );
  20904. this.displacementMap = source.displacementMap;
  20905. this.displacementScale = source.displacementScale;
  20906. this.displacementBias = source.displacementBias;
  20907. this.specularMap = source.specularMap;
  20908. this.alphaMap = source.alphaMap;
  20909. this.envMap = source.envMap;
  20910. this.combine = source.combine;
  20911. this.reflectivity = source.reflectivity;
  20912. this.refractionRatio = source.refractionRatio;
  20913. this.wireframe = source.wireframe;
  20914. this.wireframelineWidth = source.wireframelineWidth;
  20915. this.wireframeLinecap = source.wireframeLinecap;
  20916. this.wireframeLinejoin = source.wireframeLinejoin;
  20917. this.skinning = source.skinning;
  20918. this.morphTargets = source.morphTargets;
  20919. this.morphNormals = source.morphNormals;
  20920. return this;
  20921. };
  20922. /**
  20923. * parameters = {
  20924. * color: <hex>,
  20925. *
  20926. * map: new THREE.Texture( <Image> ),
  20927. * gradientMap: new THREE.Texture( <Image> ),
  20928. *
  20929. * lightMap: new THREE.Texture( <Image> ),
  20930. * lightMapIntensity: <float>
  20931. *
  20932. * aoMap: new THREE.Texture( <Image> ),
  20933. * aoMapIntensity: <float>
  20934. *
  20935. * emissive: <hex>,
  20936. * emissiveIntensity: <float>
  20937. * emissiveMap: new THREE.Texture( <Image> ),
  20938. *
  20939. * bumpMap: new THREE.Texture( <Image> ),
  20940. * bumpScale: <float>,
  20941. *
  20942. * normalMap: new THREE.Texture( <Image> ),
  20943. * normalMapType: THREE.TangentSpaceNormalMap,
  20944. * normalScale: <Vector2>,
  20945. *
  20946. * displacementMap: new THREE.Texture( <Image> ),
  20947. * displacementScale: <float>,
  20948. * displacementBias: <float>,
  20949. *
  20950. * alphaMap: new THREE.Texture( <Image> ),
  20951. *
  20952. * wireframe: <boolean>,
  20953. * wireframelineWidth: <float>,
  20954. *
  20955. * skinning: <bool>,
  20956. * morphTargets: <bool>,
  20957. * morphNormals: <bool>
  20958. * }
  20959. */
  20960. function MeshToonMaterial( parameters ) {
  20961. Material.call( this );
  20962. this.defines = { 'TOON': '' };
  20963. this.type = 'MeshToonMaterial';
  20964. this.color = new Color( 0xffffff );
  20965. this.map = null;
  20966. this.gradientMap = null;
  20967. this.lightMap = null;
  20968. this.lightMapIntensity = 1.0;
  20969. this.aoMap = null;
  20970. this.aoMapIntensity = 1.0;
  20971. this.emissive = new Color( 0x000000 );
  20972. this.emissiveIntensity = 1.0;
  20973. this.emissiveMap = null;
  20974. this.bumpMap = null;
  20975. this.bumpScale = 1;
  20976. this.normalMap = null;
  20977. this.normalMapType = TangentSpaceNormalMap;
  20978. this.normalScale = new Vector2$1( 1, 1 );
  20979. this.displacementMap = null;
  20980. this.displacementScale = 1;
  20981. this.displacementBias = 0;
  20982. this.alphaMap = null;
  20983. this.wireframe = false;
  20984. this.wireframelineWidth = 1;
  20985. this.wireframeLinecap = 'round';
  20986. this.wireframeLinejoin = 'round';
  20987. this.skinning = false;
  20988. this.morphTargets = false;
  20989. this.morphNormals = false;
  20990. this.setValues( parameters );
  20991. }
  20992. MeshToonMaterial.prototype = Object.create( Material.prototype );
  20993. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20994. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20995. MeshToonMaterial.prototype.copy = function ( source ) {
  20996. Material.prototype.copy.call( this, source );
  20997. this.color.copy( source.color );
  20998. this.map = source.map;
  20999. this.gradientMap = source.gradientMap;
  21000. this.lightMap = source.lightMap;
  21001. this.lightMapIntensity = source.lightMapIntensity;
  21002. this.aoMap = source.aoMap;
  21003. this.aoMapIntensity = source.aoMapIntensity;
  21004. this.emissive.copy( source.emissive );
  21005. this.emissiveMap = source.emissiveMap;
  21006. this.emissiveIntensity = source.emissiveIntensity;
  21007. this.bumpMap = source.bumpMap;
  21008. this.bumpScale = source.bumpScale;
  21009. this.normalMap = source.normalMap;
  21010. this.normalMapType = source.normalMapType;
  21011. this.normalScale.copy( source.normalScale );
  21012. this.displacementMap = source.displacementMap;
  21013. this.displacementScale = source.displacementScale;
  21014. this.displacementBias = source.displacementBias;
  21015. this.alphaMap = source.alphaMap;
  21016. this.wireframe = source.wireframe;
  21017. this.wireframelineWidth = source.wireframelineWidth;
  21018. this.wireframeLinecap = source.wireframeLinecap;
  21019. this.wireframeLinejoin = source.wireframeLinejoin;
  21020. this.skinning = source.skinning;
  21021. this.morphTargets = source.morphTargets;
  21022. this.morphNormals = source.morphNormals;
  21023. return this;
  21024. };
  21025. /**
  21026. * parameters = {
  21027. * opacity: <float>,
  21028. *
  21029. * bumpMap: new THREE.Texture( <Image> ),
  21030. * bumpScale: <float>,
  21031. *
  21032. * normalMap: new THREE.Texture( <Image> ),
  21033. * normalMapType: THREE.TangentSpaceNormalMap,
  21034. * normalScale: <Vector2>,
  21035. *
  21036. * displacementMap: new THREE.Texture( <Image> ),
  21037. * displacementScale: <float>,
  21038. * displacementBias: <float>,
  21039. *
  21040. * wireframe: <boolean>,
  21041. * wireframelineWidth: <float>
  21042. *
  21043. * skinning: <bool>,
  21044. * morphTargets: <bool>,
  21045. * morphNormals: <bool>
  21046. * }
  21047. */
  21048. function MeshNormalMaterial( parameters ) {
  21049. Material.call( this );
  21050. this.type = 'MeshNormalMaterial';
  21051. this.bumpMap = null;
  21052. this.bumpScale = 1;
  21053. this.normalMap = null;
  21054. this.normalMapType = TangentSpaceNormalMap;
  21055. this.normalScale = new Vector2$1( 1, 1 );
  21056. this.displacementMap = null;
  21057. this.displacementScale = 1;
  21058. this.displacementBias = 0;
  21059. this.wireframe = false;
  21060. this.wireframelineWidth = 1;
  21061. this.fog = false;
  21062. this.skinning = false;
  21063. this.morphTargets = false;
  21064. this.morphNormals = false;
  21065. this.setValues( parameters );
  21066. }
  21067. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  21068. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  21069. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21070. MeshNormalMaterial.prototype.copy = function ( source ) {
  21071. Material.prototype.copy.call( this, source );
  21072. this.bumpMap = source.bumpMap;
  21073. this.bumpScale = source.bumpScale;
  21074. this.normalMap = source.normalMap;
  21075. this.normalMapType = source.normalMapType;
  21076. this.normalScale.copy( source.normalScale );
  21077. this.displacementMap = source.displacementMap;
  21078. this.displacementScale = source.displacementScale;
  21079. this.displacementBias = source.displacementBias;
  21080. this.wireframe = source.wireframe;
  21081. this.wireframelineWidth = source.wireframelineWidth;
  21082. this.skinning = source.skinning;
  21083. this.morphTargets = source.morphTargets;
  21084. this.morphNormals = source.morphNormals;
  21085. return this;
  21086. };
  21087. /**
  21088. * parameters = {
  21089. * color: <hex>,
  21090. * opacity: <float>,
  21091. *
  21092. * map: new THREE.Texture( <Image> ),
  21093. *
  21094. * lightMap: new THREE.Texture( <Image> ),
  21095. * lightMapIntensity: <float>
  21096. *
  21097. * aoMap: new THREE.Texture( <Image> ),
  21098. * aoMapIntensity: <float>
  21099. *
  21100. * emissive: <hex>,
  21101. * emissiveIntensity: <float>
  21102. * emissiveMap: new THREE.Texture( <Image> ),
  21103. *
  21104. * specularMap: new THREE.Texture( <Image> ),
  21105. *
  21106. * alphaMap: new THREE.Texture( <Image> ),
  21107. *
  21108. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21109. * combine: THREE.Multiply,
  21110. * reflectivity: <float>,
  21111. * refractionRatio: <float>,
  21112. *
  21113. * wireframe: <boolean>,
  21114. * wireframelineWidth: <float>,
  21115. *
  21116. * skinning: <bool>,
  21117. * morphTargets: <bool>,
  21118. * morphNormals: <bool>
  21119. * }
  21120. */
  21121. function MeshLambertMaterial( parameters ) {
  21122. Material.call( this );
  21123. this.type = 'MeshLambertMaterial';
  21124. this.color = new Color( 0xffffff ); // diffuse
  21125. this.map = null;
  21126. this.lightMap = null;
  21127. this.lightMapIntensity = 1.0;
  21128. this.aoMap = null;
  21129. this.aoMapIntensity = 1.0;
  21130. this.emissive = new Color( 0x000000 );
  21131. this.emissiveIntensity = 1.0;
  21132. this.emissiveMap = null;
  21133. this.specularMap = null;
  21134. this.alphaMap = null;
  21135. this.envMap = null;
  21136. this.combine = MultiplyOperation;
  21137. this.reflectivity = 1;
  21138. this.refractionRatio = 0.98;
  21139. this.wireframe = false;
  21140. this.wireframelineWidth = 1;
  21141. this.wireframeLinecap = 'round';
  21142. this.wireframeLinejoin = 'round';
  21143. this.skinning = false;
  21144. this.morphTargets = false;
  21145. this.morphNormals = false;
  21146. this.setValues( parameters );
  21147. }
  21148. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  21149. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21150. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21151. MeshLambertMaterial.prototype.copy = function ( source ) {
  21152. Material.prototype.copy.call( this, source );
  21153. this.color.copy( source.color );
  21154. this.map = source.map;
  21155. this.lightMap = source.lightMap;
  21156. this.lightMapIntensity = source.lightMapIntensity;
  21157. this.aoMap = source.aoMap;
  21158. this.aoMapIntensity = source.aoMapIntensity;
  21159. this.emissive.copy( source.emissive );
  21160. this.emissiveMap = source.emissiveMap;
  21161. this.emissiveIntensity = source.emissiveIntensity;
  21162. this.specularMap = source.specularMap;
  21163. this.alphaMap = source.alphaMap;
  21164. this.envMap = source.envMap;
  21165. this.combine = source.combine;
  21166. this.reflectivity = source.reflectivity;
  21167. this.refractionRatio = source.refractionRatio;
  21168. this.wireframe = source.wireframe;
  21169. this.wireframelineWidth = source.wireframelineWidth;
  21170. this.wireframeLinecap = source.wireframeLinecap;
  21171. this.wireframeLinejoin = source.wireframeLinejoin;
  21172. this.skinning = source.skinning;
  21173. this.morphTargets = source.morphTargets;
  21174. this.morphNormals = source.morphNormals;
  21175. return this;
  21176. };
  21177. /**
  21178. * parameters = {
  21179. * color: <hex>,
  21180. * opacity: <float>,
  21181. *
  21182. * matcap: new THREE.Texture( <Image> ),
  21183. *
  21184. * map: new THREE.Texture( <Image> ),
  21185. *
  21186. * bumpMap: new THREE.Texture( <Image> ),
  21187. * bumpScale: <float>,
  21188. *
  21189. * normalMap: new THREE.Texture( <Image> ),
  21190. * normalMapType: THREE.TangentSpaceNormalMap,
  21191. * normalScale: <Vector2>,
  21192. *
  21193. * displacementMap: new THREE.Texture( <Image> ),
  21194. * displacementScale: <float>,
  21195. * displacementBias: <float>,
  21196. *
  21197. * alphaMap: new THREE.Texture( <Image> ),
  21198. *
  21199. * skinning: <bool>,
  21200. * morphTargets: <bool>,
  21201. * morphNormals: <bool>
  21202. * }
  21203. */
  21204. function MeshMatcapMaterial( parameters ) {
  21205. Material.call( this );
  21206. this.defines = { 'MATCAP': '' };
  21207. this.type = 'MeshMatcapMaterial';
  21208. this.color = new Color( 0xffffff ); // diffuse
  21209. this.matcap = null;
  21210. this.map = null;
  21211. this.bumpMap = null;
  21212. this.bumpScale = 1;
  21213. this.normalMap = null;
  21214. this.normalMapType = TangentSpaceNormalMap;
  21215. this.normalScale = new Vector2$1( 1, 1 );
  21216. this.displacementMap = null;
  21217. this.displacementScale = 1;
  21218. this.displacementBias = 0;
  21219. this.alphaMap = null;
  21220. this.skinning = false;
  21221. this.morphTargets = false;
  21222. this.morphNormals = false;
  21223. this.setValues( parameters );
  21224. }
  21225. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  21226. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21227. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21228. MeshMatcapMaterial.prototype.copy = function ( source ) {
  21229. Material.prototype.copy.call( this, source );
  21230. this.defines = { 'MATCAP': '' };
  21231. this.color.copy( source.color );
  21232. this.matcap = source.matcap;
  21233. this.map = source.map;
  21234. this.bumpMap = source.bumpMap;
  21235. this.bumpScale = source.bumpScale;
  21236. this.normalMap = source.normalMap;
  21237. this.normalMapType = source.normalMapType;
  21238. this.normalScale.copy( source.normalScale );
  21239. this.displacementMap = source.displacementMap;
  21240. this.displacementScale = source.displacementScale;
  21241. this.displacementBias = source.displacementBias;
  21242. this.alphaMap = source.alphaMap;
  21243. this.skinning = source.skinning;
  21244. this.morphTargets = source.morphTargets;
  21245. this.morphNormals = source.morphNormals;
  21246. return this;
  21247. };
  21248. /**
  21249. * parameters = {
  21250. * color: <hex>,
  21251. * opacity: <float>,
  21252. *
  21253. * lineWidth: <float>,
  21254. *
  21255. * scale: <float>,
  21256. * dashSize: <float>,
  21257. * gapSize: <float>
  21258. * }
  21259. */
  21260. function LineDashedMaterial( parameters ) {
  21261. LineBasicMaterial.call( this );
  21262. this.type = 'LineDashedMaterial';
  21263. this.scale = 1;
  21264. this.dashSize = 3;
  21265. this.gapSize = 1;
  21266. this.setValues( parameters );
  21267. }
  21268. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  21269. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21270. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21271. LineDashedMaterial.prototype.copy = function ( source ) {
  21272. LineBasicMaterial.prototype.copy.call( this, source );
  21273. this.scale = source.scale;
  21274. this.dashSize = source.dashSize;
  21275. this.gapSize = source.gapSize;
  21276. return this;
  21277. };
  21278. var Materials = /*#__PURE__*/Object.freeze({
  21279. __proto__: null,
  21280. ShadowMaterial: ShadowMaterial,
  21281. SpriteMaterial: SpriteMaterial,
  21282. RawShaderMaterial: RawShaderMaterial,
  21283. ShaderMaterial: ShaderMaterial,
  21284. PointsMaterial: PointsMaterial,
  21285. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21286. MeshStandardMaterial: MeshStandardMaterial,
  21287. MeshPhongMaterial: MeshPhongMaterial,
  21288. MeshToonMaterial: MeshToonMaterial,
  21289. MeshNormalMaterial: MeshNormalMaterial,
  21290. MeshLambertMaterial: MeshLambertMaterial,
  21291. MeshDepthMaterial: MeshDepthMaterial,
  21292. MeshDistanceMaterial: MeshDistanceMaterial,
  21293. MeshBasicMaterial: MeshBasicMaterial,
  21294. MeshMatcapMaterial: MeshMatcapMaterial,
  21295. LineDashedMaterial: LineDashedMaterial,
  21296. LineBasicMaterial: LineBasicMaterial,
  21297. Material: Material
  21298. });
  21299. const AnimationUtils = {
  21300. // same as Array.prototype.slice, but also works on typed arrays
  21301. arraySlice: function ( array, from, to ) {
  21302. if ( AnimationUtils.isTypedArray( array ) ) {
  21303. // in ios9 array.subarray(from, undefined) will return empty array
  21304. // but array.subarray(from) or array.subarray(from, len) is correct
  21305. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  21306. }
  21307. return array.slice( from, to );
  21308. },
  21309. // converts an array to a specific type
  21310. convertArray: function ( array, type, forceClone ) {
  21311. if ( ! array || // let 'undefined' and 'null' pass
  21312. ! forceClone && array.constructor === type ) return array;
  21313. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21314. return new type( array ); // create typed array
  21315. }
  21316. return Array.prototype.slice.call( array ); // create Array
  21317. },
  21318. isTypedArray: function ( object ) {
  21319. return ArrayBuffer.isView( object ) &&
  21320. ! ( object instanceof DataView );
  21321. },
  21322. // returns an array by which times and values can be sorted
  21323. getKeyframeOrder: function ( times ) {
  21324. function compareTime( i, j ) {
  21325. return times[ i ] - times[ j ];
  21326. }
  21327. const n = times.length;
  21328. const result = new Array( n );
  21329. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21330. result.sort( compareTime );
  21331. return result;
  21332. },
  21333. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21334. sortedArray: function ( values, stride, order ) {
  21335. const nValues = values.length;
  21336. const result = new values.constructor( nValues );
  21337. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21338. const srcOffset = order[ i ] * stride;
  21339. for ( let j = 0; j !== stride; ++ j ) {
  21340. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21341. }
  21342. }
  21343. return result;
  21344. },
  21345. // function for parsing AOS keyframe formats
  21346. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  21347. let i = 1, key = jsonKeys[ 0 ];
  21348. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21349. key = jsonKeys[ i ++ ];
  21350. }
  21351. if ( key === undefined ) return; // no data
  21352. let value = key[ valuePropertyName ];
  21353. if ( value === undefined ) return; // no data
  21354. if ( Array.isArray( value ) ) {
  21355. do {
  21356. value = key[ valuePropertyName ];
  21357. if ( value !== undefined ) {
  21358. times.push( key.time );
  21359. values.push.apply( values, value ); // push all elements
  21360. }
  21361. key = jsonKeys[ i ++ ];
  21362. } while ( key !== undefined );
  21363. } else if ( value.toArray !== undefined ) {
  21364. // ...assume THREE.Math-ish
  21365. do {
  21366. value = key[ valuePropertyName ];
  21367. if ( value !== undefined ) {
  21368. times.push( key.time );
  21369. value.toArray( values, values.length );
  21370. }
  21371. key = jsonKeys[ i ++ ];
  21372. } while ( key !== undefined );
  21373. } else {
  21374. // otherwise push as-is
  21375. do {
  21376. value = key[ valuePropertyName ];
  21377. if ( value !== undefined ) {
  21378. times.push( key.time );
  21379. values.push( value );
  21380. }
  21381. key = jsonKeys[ i ++ ];
  21382. } while ( key !== undefined );
  21383. }
  21384. },
  21385. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21386. const clip = sourceClip.clone();
  21387. clip.name = name;
  21388. const tracks = [];
  21389. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21390. const track = clip.tracks[ i ];
  21391. const valueSize = track.getValueSize();
  21392. const times = [];
  21393. const values = [];
  21394. for ( let j = 0; j < track.times.length; ++ j ) {
  21395. const frame = track.times[ j ] * fps;
  21396. if ( frame < startFrame || frame >= endFrame ) continue;
  21397. times.push( track.times[ j ] );
  21398. for ( let k = 0; k < valueSize; ++ k ) {
  21399. values.push( track.values[ j * valueSize + k ] );
  21400. }
  21401. }
  21402. if ( times.length === 0 ) continue;
  21403. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  21404. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  21405. tracks.push( track );
  21406. }
  21407. clip.tracks = tracks;
  21408. // find minimum .times value across all tracks in the trimmed clip
  21409. let minStartTime = Infinity;
  21410. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21411. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21412. minStartTime = clip.tracks[ i ].times[ 0 ];
  21413. }
  21414. }
  21415. // shift all tracks such that clip begins at t=0
  21416. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21417. clip.tracks[ i ].shift( - 1 * minStartTime );
  21418. }
  21419. clip.resetDuration();
  21420. return clip;
  21421. },
  21422. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21423. if ( fps <= 0 ) fps = 30;
  21424. const numTracks = referenceClip.tracks.length;
  21425. const referenceTime = referenceFrame / fps;
  21426. // Make each track's values relative to the values at the reference frame
  21427. for ( let i = 0; i < numTracks; ++ i ) {
  21428. const referenceTrack = referenceClip.tracks[ i ];
  21429. const referenceTrackType = referenceTrack.ValueTypeName;
  21430. // Skip this track if it's non-numeric
  21431. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21432. // Find the track in the target clip whose name and type matches the reference track
  21433. const targetTrack = targetClip.tracks.find( function ( track ) {
  21434. return track.name === referenceTrack.name
  21435. && track.ValueTypeName === referenceTrackType;
  21436. } );
  21437. if ( targetTrack === undefined ) continue;
  21438. let referenceOffset = 0;
  21439. const referenceValueSize = referenceTrack.getValueSize();
  21440. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21441. referenceOffset = referenceValueSize / 3;
  21442. }
  21443. let targetOffset = 0;
  21444. const targetValueSize = targetTrack.getValueSize();
  21445. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21446. targetOffset = targetValueSize / 3;
  21447. }
  21448. const lastIndex = referenceTrack.times.length - 1;
  21449. let referenceValue;
  21450. // Find the value to subtract out of the track
  21451. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21452. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21453. const startIndex = referenceOffset;
  21454. const endIndex = referenceValueSize - referenceOffset;
  21455. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21456. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21457. // Reference frame is after the last keyframe, so just use the last keyframe
  21458. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21459. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21460. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21461. } else {
  21462. // Interpolate to the reference value
  21463. const interpolant = referenceTrack.createInterpolant();
  21464. const startIndex = referenceOffset;
  21465. const endIndex = referenceValueSize - referenceOffset;
  21466. interpolant.evaluate( referenceTime );
  21467. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  21468. }
  21469. // Conjugate the quaternion
  21470. if ( referenceTrackType === 'quaternion' ) {
  21471. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21472. referenceQuat.toArray( referenceValue );
  21473. }
  21474. // Subtract the reference value from all of the track values
  21475. const numTimes = targetTrack.times.length;
  21476. for ( let j = 0; j < numTimes; ++ j ) {
  21477. const valueStart = j * targetValueSize + targetOffset;
  21478. if ( referenceTrackType === 'quaternion' ) {
  21479. // Multiply the conjugate for quaternion track types
  21480. Quaternion.multiplyQuaternionsFlat(
  21481. targetTrack.values,
  21482. valueStart,
  21483. referenceValue,
  21484. 0,
  21485. targetTrack.values,
  21486. valueStart
  21487. );
  21488. } else {
  21489. const valueEnd = targetValueSize - targetOffset * 2;
  21490. // Subtract each value for all other numeric track types
  21491. for ( let k = 0; k < valueEnd; ++ k ) {
  21492. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  21493. }
  21494. }
  21495. }
  21496. }
  21497. targetClip.blendMode = AdditiveAnimationBlendMode;
  21498. return targetClip;
  21499. }
  21500. };
  21501. /**
  21502. * Abstract base class of interpolants over parametric samples.
  21503. *
  21504. * The parameter domain is one dimensional, typically the time or a path
  21505. * along a curve defined by the data.
  21506. *
  21507. * The sample values can have any dimensionality and derived classes may
  21508. * apply special interpretations to the data.
  21509. *
  21510. * This class provides the interval seek in a Template Method, deferring
  21511. * the actual interpolation to derived classes.
  21512. *
  21513. * Time complexity is O(1) for linear access crossing at most two points
  21514. * and O(log N) for random access, where N is the number of positions.
  21515. *
  21516. * References:
  21517. *
  21518. * http://www.oodesign.com/template-method-pattern.html
  21519. *
  21520. */
  21521. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21522. this.parameterPositions = parameterPositions;
  21523. this._cachedIndex = 0;
  21524. this.resultBuffer = resultBuffer !== undefined ?
  21525. resultBuffer : new sampleValues.constructor( sampleSize );
  21526. this.sampleValues = sampleValues;
  21527. this.valueSize = sampleSize;
  21528. }
  21529. Object.assign( Interpolant.prototype, {
  21530. evaluate: function ( t ) {
  21531. const pp = this.parameterPositions;
  21532. let i1 = this._cachedIndex,
  21533. t1 = pp[ i1 ],
  21534. t0 = pp[ i1 - 1 ];
  21535. validate_interval: {
  21536. seek: {
  21537. let right;
  21538. linear_scan: {
  21539. //- See http://jsperf.com/comparison-to-undefined/3
  21540. //- slower code:
  21541. //-
  21542. //- if ( t >= t1 || t1 === undefined ) {
  21543. forward_scan: if ( ! ( t < t1 ) ) {
  21544. for ( let giveUpAt = i1 + 2; ; ) {
  21545. if ( t1 === undefined ) {
  21546. if ( t < t0 ) break forward_scan;
  21547. // after end
  21548. i1 = pp.length;
  21549. this._cachedIndex = i1;
  21550. return this.afterEnd_( i1 - 1, t, t0 );
  21551. }
  21552. if ( i1 === giveUpAt ) break; // this loop
  21553. t0 = t1;
  21554. t1 = pp[ ++ i1 ];
  21555. if ( t < t1 ) {
  21556. // we have arrived at the sought interval
  21557. break seek;
  21558. }
  21559. }
  21560. // prepare binary search on the right side of the index
  21561. right = pp.length;
  21562. break linear_scan;
  21563. }
  21564. //- slower code:
  21565. //- if ( t < t0 || t0 === undefined ) {
  21566. if ( ! ( t >= t0 ) ) {
  21567. // looping?
  21568. const t1global = pp[ 1 ];
  21569. if ( t < t1global ) {
  21570. i1 = 2; // + 1, using the scan for the details
  21571. t0 = t1global;
  21572. }
  21573. // linear reverse scan
  21574. for ( let giveUpAt = i1 - 2; ; ) {
  21575. if ( t0 === undefined ) {
  21576. // before start
  21577. this._cachedIndex = 0;
  21578. return this.beforeStart_( 0, t, t1 );
  21579. }
  21580. if ( i1 === giveUpAt ) break; // this loop
  21581. t1 = t0;
  21582. t0 = pp[ -- i1 - 1 ];
  21583. if ( t >= t0 ) {
  21584. // we have arrived at the sought interval
  21585. break seek;
  21586. }
  21587. }
  21588. // prepare binary search on the left side of the index
  21589. right = i1;
  21590. i1 = 0;
  21591. break linear_scan;
  21592. }
  21593. // the interval is valid
  21594. break validate_interval;
  21595. } // linear scan
  21596. // binary search
  21597. while ( i1 < right ) {
  21598. const mid = ( i1 + right ) >>> 1;
  21599. if ( t < pp[ mid ] ) {
  21600. right = mid;
  21601. } else {
  21602. i1 = mid + 1;
  21603. }
  21604. }
  21605. t1 = pp[ i1 ];
  21606. t0 = pp[ i1 - 1 ];
  21607. // check boundary cases, again
  21608. if ( t0 === undefined ) {
  21609. this._cachedIndex = 0;
  21610. return this.beforeStart_( 0, t, t1 );
  21611. }
  21612. if ( t1 === undefined ) {
  21613. i1 = pp.length;
  21614. this._cachedIndex = i1;
  21615. return this.afterEnd_( i1 - 1, t0, t );
  21616. }
  21617. } // seek
  21618. this._cachedIndex = i1;
  21619. this.intervalChanged_( i1, t0, t1 );
  21620. } // validate_interval
  21621. return this.interpolate_( i1, t0, t, t1 );
  21622. },
  21623. settings: null, // optional, subclass-specific settings structure
  21624. // Note: The indirection allows central control of many interpolants.
  21625. // --- Protected interface
  21626. DefaultSettings_: {},
  21627. getSettings_: function () {
  21628. return this.settings || this.DefaultSettings_;
  21629. },
  21630. copySampleValue_: function ( index ) {
  21631. // copies a sample value to the result buffer
  21632. const result = this.resultBuffer,
  21633. values = this.sampleValues,
  21634. stride = this.valueSize,
  21635. offset = index * stride;
  21636. for ( let i = 0; i !== stride; ++ i ) {
  21637. result[ i ] = values[ offset + i ];
  21638. }
  21639. return result;
  21640. },
  21641. // Template methods for derived classes:
  21642. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  21643. throw new Error( 'call to abstract method' );
  21644. // implementations shall return this.resultBuffer
  21645. },
  21646. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  21647. // empty
  21648. }
  21649. } );
  21650. // DECLARE ALIAS AFTER assign prototype
  21651. Object.assign( Interpolant.prototype, {
  21652. //( 0, t, t0 ), returns this.resultBuffer
  21653. beforeStart_: Interpolant.prototype.copySampleValue_,
  21654. //( N-1, tN-1, t ), returns this.resultBuffer
  21655. afterEnd_: Interpolant.prototype.copySampleValue_,
  21656. } );
  21657. /**
  21658. * Fast and simple cubic spline interpolant.
  21659. *
  21660. * It was derived from a Hermitian construction setting the first derivative
  21661. * at each sample position to the linear slope between neighboring positions
  21662. * over their parameter interval.
  21663. */
  21664. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21665. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21666. this._weightPrev = - 0;
  21667. this._offsetPrev = - 0;
  21668. this._weightNext = - 0;
  21669. this._offsetNext = - 0;
  21670. }
  21671. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21672. constructor: CubicInterpolant,
  21673. DefaultSettings_: {
  21674. endingStart: ZeroCurvatureEnding,
  21675. endingEnd: ZeroCurvatureEnding
  21676. },
  21677. intervalChanged_: function ( i1, t0, t1 ) {
  21678. const pp = this.parameterPositions;
  21679. let iPrev = i1 - 2,
  21680. iNext = i1 + 1,
  21681. tPrev = pp[ iPrev ],
  21682. tNext = pp[ iNext ];
  21683. if ( tPrev === undefined ) {
  21684. switch ( this.getSettings_().endingStart ) {
  21685. case ZeroSlopeEnding:
  21686. // f'(t0) = 0
  21687. iPrev = i1;
  21688. tPrev = 2 * t0 - t1;
  21689. break;
  21690. case WrapAroundEnding:
  21691. // use the other end of the curve
  21692. iPrev = pp.length - 2;
  21693. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  21694. break;
  21695. default: // ZeroCurvatureEnding
  21696. // f''(t0) = 0 a.k.a. Natural Spline
  21697. iPrev = i1;
  21698. tPrev = t1;
  21699. }
  21700. }
  21701. if ( tNext === undefined ) {
  21702. switch ( this.getSettings_().endingEnd ) {
  21703. case ZeroSlopeEnding:
  21704. // f'(tN) = 0
  21705. iNext = i1;
  21706. tNext = 2 * t1 - t0;
  21707. break;
  21708. case WrapAroundEnding:
  21709. // use the other end of the curve
  21710. iNext = 1;
  21711. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  21712. break;
  21713. default: // ZeroCurvatureEnding
  21714. // f''(tN) = 0, a.k.a. Natural Spline
  21715. iNext = i1 - 1;
  21716. tNext = t0;
  21717. }
  21718. }
  21719. const halfDt = ( t1 - t0 ) * 0.5,
  21720. stride = this.valueSize;
  21721. this._weightPrev = halfDt / ( t0 - tPrev );
  21722. this._weightNext = halfDt / ( tNext - t1 );
  21723. this._offsetPrev = iPrev * stride;
  21724. this._offsetNext = iNext * stride;
  21725. },
  21726. interpolate_: function ( i1, t0, t, t1 ) {
  21727. const result = this.resultBuffer,
  21728. values = this.sampleValues,
  21729. stride = this.valueSize,
  21730. o1 = i1 * stride, o0 = o1 - stride,
  21731. oP = this._offsetPrev, oN = this._offsetNext,
  21732. wP = this._weightPrev, wN = this._weightNext,
  21733. p = ( t - t0 ) / ( t1 - t0 ),
  21734. pp = p * p,
  21735. ppp = pp * p;
  21736. // evaluate polynomials
  21737. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  21738. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  21739. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  21740. const sN = wN * ppp - wN * pp;
  21741. // combine data linearly
  21742. for ( let i = 0; i !== stride; ++ i ) {
  21743. result[ i ] =
  21744. sP * values[ oP + i ] +
  21745. s0 * values[ o0 + i ] +
  21746. s1 * values[ o1 + i ] +
  21747. sN * values[ oN + i ];
  21748. }
  21749. return result;
  21750. }
  21751. } );
  21752. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21753. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21754. }
  21755. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21756. constructor: LinearInterpolant,
  21757. interpolate_: function ( i1, t0, t, t1 ) {
  21758. const result = this.resultBuffer,
  21759. values = this.sampleValues,
  21760. stride = this.valueSize,
  21761. offset1 = i1 * stride,
  21762. offset0 = offset1 - stride,
  21763. weight1 = ( t - t0 ) / ( t1 - t0 ),
  21764. weight0 = 1 - weight1;
  21765. for ( let i = 0; i !== stride; ++ i ) {
  21766. result[ i ] =
  21767. values[ offset0 + i ] * weight0 +
  21768. values[ offset1 + i ] * weight1;
  21769. }
  21770. return result;
  21771. }
  21772. } );
  21773. /**
  21774. *
  21775. * Interpolant that evaluates to the sample value at the position preceeding
  21776. * the parameter.
  21777. */
  21778. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21779. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21780. }
  21781. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21782. constructor: DiscreteInterpolant,
  21783. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  21784. return this.copySampleValue_( i1 - 1 );
  21785. }
  21786. } );
  21787. function KeyframeTrack( name, times, values, interpolation ) {
  21788. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  21789. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  21790. this.name = name;
  21791. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  21792. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  21793. this.setInterpolation( interpolation || this.DefaultInterpolation );
  21794. }
  21795. // Static methods
  21796. Object.assign( KeyframeTrack, {
  21797. // Serialization (in static context, because of constructor invocation
  21798. // and automatic invocation of .toJSON):
  21799. toJSON: function ( track ) {
  21800. const trackType = track.constructor;
  21801. let json;
  21802. // derived classes can define a static toJSON method
  21803. if ( trackType.toJSON !== undefined ) {
  21804. json = trackType.toJSON( track );
  21805. } else {
  21806. // by default, we assume the data can be serialized as-is
  21807. json = {
  21808. 'name': track.name,
  21809. 'times': AnimationUtils.convertArray( track.times, Array ),
  21810. 'values': AnimationUtils.convertArray( track.values, Array )
  21811. };
  21812. const interpolation = track.getInterpolation();
  21813. if ( interpolation !== track.DefaultInterpolation ) {
  21814. json.interpolation = interpolation;
  21815. }
  21816. }
  21817. json.type = track.ValueTypeName; // mandatory
  21818. return json;
  21819. }
  21820. } );
  21821. Object.assign( KeyframeTrack.prototype, {
  21822. constructor: KeyframeTrack,
  21823. TimeBufferType: Float32Array,
  21824. ValueBufferType: Float32Array,
  21825. DefaultInterpolation: InterpolateLinear,
  21826. InterpolantFactoryMethodDiscrete: function ( result ) {
  21827. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  21828. },
  21829. InterpolantFactoryMethodLinear: function ( result ) {
  21830. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  21831. },
  21832. InterpolantFactoryMethodSmooth: function ( result ) {
  21833. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  21834. },
  21835. setInterpolation: function ( interpolation ) {
  21836. let factoryMethod;
  21837. switch ( interpolation ) {
  21838. case InterpolateDiscrete:
  21839. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21840. break;
  21841. case InterpolateLinear:
  21842. factoryMethod = this.InterpolantFactoryMethodLinear;
  21843. break;
  21844. case InterpolateSmooth:
  21845. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21846. break;
  21847. }
  21848. if ( factoryMethod === undefined ) {
  21849. const message = 'unsupported interpolation for ' +
  21850. this.ValueTypeName + ' keyframe track named ' + this.name;
  21851. if ( this.createInterpolant === undefined ) {
  21852. // fall back to default, unless the default itself is messed up
  21853. if ( interpolation !== this.DefaultInterpolation ) {
  21854. this.setInterpolation( this.DefaultInterpolation );
  21855. } else {
  21856. throw new Error( message ); // fatal, in this case
  21857. }
  21858. }
  21859. console.warn( 'THREE.KeyframeTrack:', message );
  21860. return this;
  21861. }
  21862. this.createInterpolant = factoryMethod;
  21863. return this;
  21864. },
  21865. getInterpolation: function () {
  21866. switch ( this.createInterpolant ) {
  21867. case this.InterpolantFactoryMethodDiscrete:
  21868. return InterpolateDiscrete;
  21869. case this.InterpolantFactoryMethodLinear:
  21870. return InterpolateLinear;
  21871. case this.InterpolantFactoryMethodSmooth:
  21872. return InterpolateSmooth;
  21873. }
  21874. },
  21875. getValueSize: function () {
  21876. return this.values.length / this.times.length;
  21877. },
  21878. // move all keyframes either forwards or backwards in time
  21879. shift: function ( timeOffset ) {
  21880. if ( timeOffset !== 0.0 ) {
  21881. const times = this.times;
  21882. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21883. times[ i ] += timeOffset;
  21884. }
  21885. }
  21886. return this;
  21887. },
  21888. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21889. scale: function ( timeScale ) {
  21890. if ( timeScale !== 1.0 ) {
  21891. const times = this.times;
  21892. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21893. times[ i ] *= timeScale;
  21894. }
  21895. }
  21896. return this;
  21897. },
  21898. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21899. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21900. trim: function ( startTime, endTime ) {
  21901. const times = this.times,
  21902. nKeys = times.length;
  21903. let from = 0,
  21904. to = nKeys - 1;
  21905. while ( from !== nKeys && times[ from ] < startTime ) {
  21906. ++ from;
  21907. }
  21908. while ( to !== - 1 && times[ to ] > endTime ) {
  21909. -- to;
  21910. }
  21911. ++ to; // inclusive -> exclusive bound
  21912. if ( from !== 0 || to !== nKeys ) {
  21913. // empty tracks are forbidden, so keep at least one keyframe
  21914. if ( from >= to ) {
  21915. to = Math.max( to, 1 );
  21916. from = to - 1;
  21917. }
  21918. const stride = this.getValueSize();
  21919. this.times = AnimationUtils.arraySlice( times, from, to );
  21920. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  21921. }
  21922. return this;
  21923. },
  21924. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21925. validate: function () {
  21926. let valid = true;
  21927. const valueSize = this.getValueSize();
  21928. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  21929. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  21930. valid = false;
  21931. }
  21932. const times = this.times,
  21933. values = this.values,
  21934. nKeys = times.length;
  21935. if ( nKeys === 0 ) {
  21936. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  21937. valid = false;
  21938. }
  21939. let prevTime = null;
  21940. for ( let i = 0; i !== nKeys; i ++ ) {
  21941. const currTime = times[ i ];
  21942. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  21943. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  21944. valid = false;
  21945. break;
  21946. }
  21947. if ( prevTime !== null && prevTime > currTime ) {
  21948. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  21949. valid = false;
  21950. break;
  21951. }
  21952. prevTime = currTime;
  21953. }
  21954. if ( values !== undefined ) {
  21955. if ( AnimationUtils.isTypedArray( values ) ) {
  21956. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  21957. const value = values[ i ];
  21958. if ( isNaN( value ) ) {
  21959. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  21960. valid = false;
  21961. break;
  21962. }
  21963. }
  21964. }
  21965. }
  21966. return valid;
  21967. },
  21968. // removes equivalent sequential keys as common in morph target sequences
  21969. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21970. optimize: function () {
  21971. // times or values may be shared with other tracks, so overwriting is unsafe
  21972. const times = AnimationUtils.arraySlice( this.times ),
  21973. values = AnimationUtils.arraySlice( this.values ),
  21974. stride = this.getValueSize(),
  21975. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21976. lastIndex = times.length - 1;
  21977. let writeIndex = 1;
  21978. for ( let i = 1; i < lastIndex; ++ i ) {
  21979. let keep = false;
  21980. const time = times[ i ];
  21981. const timeNext = times[ i + 1 ];
  21982. // remove adjacent keyframes scheduled at the same time
  21983. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  21984. if ( ! smoothInterpolation ) {
  21985. // remove unnecessary keyframes same as their neighbors
  21986. const offset = i * stride,
  21987. offsetP = offset - stride,
  21988. offsetN = offset + stride;
  21989. for ( let j = 0; j !== stride; ++ j ) {
  21990. const value = values[ offset + j ];
  21991. if ( value !== values[ offsetP + j ] ||
  21992. value !== values[ offsetN + j ] ) {
  21993. keep = true;
  21994. break;
  21995. }
  21996. }
  21997. } else {
  21998. keep = true;
  21999. }
  22000. }
  22001. // in-place compaction
  22002. if ( keep ) {
  22003. if ( i !== writeIndex ) {
  22004. times[ writeIndex ] = times[ i ];
  22005. const readOffset = i * stride,
  22006. writeOffset = writeIndex * stride;
  22007. for ( let j = 0; j !== stride; ++ j ) {
  22008. values[ writeOffset + j ] = values[ readOffset + j ];
  22009. }
  22010. }
  22011. ++ writeIndex;
  22012. }
  22013. }
  22014. // flush last keyframe (compaction looks ahead)
  22015. if ( lastIndex > 0 ) {
  22016. times[ writeIndex ] = times[ lastIndex ];
  22017. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22018. values[ writeOffset + j ] = values[ readOffset + j ];
  22019. }
  22020. ++ writeIndex;
  22021. }
  22022. if ( writeIndex !== times.length ) {
  22023. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22024. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22025. } else {
  22026. this.times = times;
  22027. this.values = values;
  22028. }
  22029. return this;
  22030. },
  22031. clone: function () {
  22032. const times = AnimationUtils.arraySlice( this.times, 0 );
  22033. const values = AnimationUtils.arraySlice( this.values, 0 );
  22034. const TypedKeyframeTrack = this.constructor;
  22035. const track = new TypedKeyframeTrack( this.name, times, values );
  22036. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22037. track.createInterpolant = this.createInterpolant;
  22038. return track;
  22039. }
  22040. } );
  22041. /**
  22042. * A Track of Boolean keyframe values.
  22043. */
  22044. function BooleanKeyframeTrack( name, times, values ) {
  22045. KeyframeTrack.call( this, name, times, values );
  22046. }
  22047. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22048. constructor: BooleanKeyframeTrack,
  22049. ValueTypeName: 'bool',
  22050. ValueBufferType: Array,
  22051. DefaultInterpolation: InterpolateDiscrete,
  22052. InterpolantFactoryMethodLinear: undefined,
  22053. InterpolantFactoryMethodSmooth: undefined
  22054. // Note: Actually this track could have a optimized / compressed
  22055. // representation of a single value and a custom interpolant that
  22056. // computes "firstValue ^ isOdd( index )".
  22057. } );
  22058. /**
  22059. * A Track of keyframe values that represent color.
  22060. */
  22061. function ColorKeyframeTrack( name, times, values, interpolation ) {
  22062. KeyframeTrack.call( this, name, times, values, interpolation );
  22063. }
  22064. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22065. constructor: ColorKeyframeTrack,
  22066. ValueTypeName: 'color'
  22067. // ValueBufferType is inherited
  22068. // DefaultInterpolation is inherited
  22069. // Note: Very basic implementation and nothing special yet.
  22070. // However, this is the place for color space parameterization.
  22071. } );
  22072. /**
  22073. * A Track of numeric keyframe values.
  22074. */
  22075. function NumberKeyframeTrack( name, times, values, interpolation ) {
  22076. KeyframeTrack.call( this, name, times, values, interpolation );
  22077. }
  22078. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22079. constructor: NumberKeyframeTrack,
  22080. ValueTypeName: 'number'
  22081. // ValueBufferType is inherited
  22082. // DefaultInterpolation is inherited
  22083. } );
  22084. /**
  22085. * Spherical linear unit quaternion interpolant.
  22086. */
  22087. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22088. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22089. }
  22090. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  22091. constructor: QuaternionLinearInterpolant,
  22092. interpolate_: function ( i1, t0, t, t1 ) {
  22093. const result = this.resultBuffer,
  22094. values = this.sampleValues,
  22095. stride = this.valueSize,
  22096. alpha = ( t - t0 ) / ( t1 - t0 );
  22097. let offset = i1 * stride;
  22098. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22099. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22100. }
  22101. return result;
  22102. }
  22103. } );
  22104. /**
  22105. * A Track of quaternion keyframe values.
  22106. */
  22107. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  22108. KeyframeTrack.call( this, name, times, values, interpolation );
  22109. }
  22110. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22111. constructor: QuaternionKeyframeTrack,
  22112. ValueTypeName: 'quaternion',
  22113. // ValueBufferType is inherited
  22114. DefaultInterpolation: InterpolateLinear,
  22115. InterpolantFactoryMethodLinear: function ( result ) {
  22116. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22117. },
  22118. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  22119. } );
  22120. /**
  22121. * A Track that interpolates Strings
  22122. */
  22123. function StringKeyframeTrack( name, times, values, interpolation ) {
  22124. KeyframeTrack.call( this, name, times, values, interpolation );
  22125. }
  22126. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22127. constructor: StringKeyframeTrack,
  22128. ValueTypeName: 'string',
  22129. ValueBufferType: Array,
  22130. DefaultInterpolation: InterpolateDiscrete,
  22131. InterpolantFactoryMethodLinear: undefined,
  22132. InterpolantFactoryMethodSmooth: undefined
  22133. } );
  22134. /**
  22135. * A Track of vectored keyframe values.
  22136. */
  22137. function VectorKeyframeTrack( name, times, values, interpolation ) {
  22138. KeyframeTrack.call( this, name, times, values, interpolation );
  22139. }
  22140. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22141. constructor: VectorKeyframeTrack,
  22142. ValueTypeName: 'vector'
  22143. // ValueBufferType is inherited
  22144. // DefaultInterpolation is inherited
  22145. } );
  22146. function AnimationClip( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22147. this.name = name;
  22148. this.tracks = tracks;
  22149. this.duration = duration;
  22150. this.blendMode = blendMode;
  22151. this.uuid = MathUtils.generateUUID();
  22152. // this means it should figure out its duration by scanning the tracks
  22153. if ( this.duration < 0 ) {
  22154. this.resetDuration();
  22155. }
  22156. }
  22157. function getTrackTypeForValueTypeName( typeName ) {
  22158. switch ( typeName.toLowerCase() ) {
  22159. case 'scalar':
  22160. case 'double':
  22161. case 'float':
  22162. case 'number':
  22163. case 'integer':
  22164. return NumberKeyframeTrack;
  22165. case 'vector':
  22166. case 'vector2':
  22167. case 'vector3':
  22168. case 'vector4':
  22169. return VectorKeyframeTrack;
  22170. case 'color':
  22171. return ColorKeyframeTrack;
  22172. case 'quaternion':
  22173. return QuaternionKeyframeTrack;
  22174. case 'bool':
  22175. case 'boolean':
  22176. return BooleanKeyframeTrack;
  22177. case 'string':
  22178. return StringKeyframeTrack;
  22179. }
  22180. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22181. }
  22182. function parseKeyframeTrack( json ) {
  22183. if ( json.type === undefined ) {
  22184. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22185. }
  22186. const trackType = getTrackTypeForValueTypeName( json.type );
  22187. if ( json.times === undefined ) {
  22188. const times = [], values = [];
  22189. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  22190. json.times = times;
  22191. json.values = values;
  22192. }
  22193. // derived classes can define a static parse method
  22194. if ( trackType.parse !== undefined ) {
  22195. return trackType.parse( json );
  22196. } else {
  22197. // by default, we assume a constructor compatible with the base
  22198. return new trackType( json.name, json.times, json.values, json.interpolation );
  22199. }
  22200. }
  22201. Object.assign( AnimationClip, {
  22202. parse: function ( json ) {
  22203. const tracks = [],
  22204. jsonTracks = json.tracks,
  22205. frameTime = 1.0 / ( json.fps || 1.0 );
  22206. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22207. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22208. }
  22209. const clip = new AnimationClip( json.name, json.duration, tracks, json.blendMode );
  22210. clip.uuid = json.uuid;
  22211. return clip;
  22212. },
  22213. toJSON: function ( clip ) {
  22214. const tracks = [],
  22215. clipTracks = clip.tracks;
  22216. const json = {
  22217. 'name': clip.name,
  22218. 'duration': clip.duration,
  22219. 'tracks': tracks,
  22220. 'uuid': clip.uuid,
  22221. 'blendMode': clip.blendMode
  22222. };
  22223. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22224. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22225. }
  22226. return json;
  22227. },
  22228. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  22229. const numMorphTargets = morphTargetSequence.length;
  22230. const tracks = [];
  22231. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22232. let times = [];
  22233. let values = [];
  22234. times.push(
  22235. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22236. i,
  22237. ( i + 1 ) % numMorphTargets );
  22238. values.push( 0, 1, 0 );
  22239. const order = AnimationUtils.getKeyframeOrder( times );
  22240. times = AnimationUtils.sortedArray( times, 1, order );
  22241. values = AnimationUtils.sortedArray( values, 1, order );
  22242. // if there is a key at the first frame, duplicate it as the
  22243. // last frame as well for perfect loop.
  22244. if ( ! noLoop && times[ 0 ] === 0 ) {
  22245. times.push( numMorphTargets );
  22246. values.push( values[ 0 ] );
  22247. }
  22248. tracks.push(
  22249. new NumberKeyframeTrack(
  22250. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22251. times, values
  22252. ).scale( 1.0 / fps ) );
  22253. }
  22254. return new AnimationClip( name, - 1, tracks );
  22255. },
  22256. findByName: function ( objectOrClipArray, name ) {
  22257. let clipArray = objectOrClipArray;
  22258. if ( ! Array.isArray( objectOrClipArray ) ) {
  22259. const o = objectOrClipArray;
  22260. clipArray = o.geometry && o.geometry.animations || o.animations;
  22261. }
  22262. for ( let i = 0; i < clipArray.length; i ++ ) {
  22263. if ( clipArray[ i ].name === name ) {
  22264. return clipArray[ i ];
  22265. }
  22266. }
  22267. return null;
  22268. },
  22269. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  22270. const animationToMorphTargets = {};
  22271. // tested with https://regex101.com/ on trick sequences
  22272. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22273. const pattern = /^([\w-]*?)([\d]+)$/;
  22274. // sort morph target names into animation groups based
  22275. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22276. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22277. const morphTarget = morphTargets[ i ];
  22278. const parts = morphTarget.name.match( pattern );
  22279. if ( parts && parts.length > 1 ) {
  22280. const name = parts[ 1 ];
  22281. let animationMorphTargets = animationToMorphTargets[ name ];
  22282. if ( ! animationMorphTargets ) {
  22283. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22284. }
  22285. animationMorphTargets.push( morphTarget );
  22286. }
  22287. }
  22288. const clips = [];
  22289. for ( const name in animationToMorphTargets ) {
  22290. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22291. }
  22292. return clips;
  22293. },
  22294. // parse the animation.hierarchy format
  22295. parseAnimation: function ( animation, bones ) {
  22296. if ( ! animation ) {
  22297. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22298. return null;
  22299. }
  22300. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22301. // only return track if there are actually keys.
  22302. if ( animationKeys.length !== 0 ) {
  22303. const times = [];
  22304. const values = [];
  22305. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22306. // empty keys are filtered out, so check again
  22307. if ( times.length !== 0 ) {
  22308. destTracks.push( new trackType( trackName, times, values ) );
  22309. }
  22310. }
  22311. };
  22312. const tracks = [];
  22313. const clipName = animation.name || 'default';
  22314. const fps = animation.fps || 30;
  22315. const blendMode = animation.blendMode;
  22316. // automatic length determination in AnimationClip.
  22317. let duration = animation.length || - 1;
  22318. const hierarchyTracks = animation.hierarchy || [];
  22319. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22320. const animationKeys = hierarchyTracks[ h ].keys;
  22321. // skip empty tracks
  22322. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22323. // process morph targets
  22324. if ( animationKeys[ 0 ].morphTargets ) {
  22325. // figure out all morph targets used in this track
  22326. const morphTargetNames = {};
  22327. let k;
  22328. for ( k = 0; k < animationKeys.length; k ++ ) {
  22329. if ( animationKeys[ k ].morphTargets ) {
  22330. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22331. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  22332. }
  22333. }
  22334. }
  22335. // create a track for each morph target with all zero
  22336. // morphTargetInfluences except for the keys in which
  22337. // the morphTarget is named.
  22338. for ( const morphTargetName in morphTargetNames ) {
  22339. const times = [];
  22340. const values = [];
  22341. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22342. const animationKey = animationKeys[ k ];
  22343. times.push( animationKey.time );
  22344. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22345. }
  22346. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22347. }
  22348. duration = morphTargetNames.length * ( fps || 1.0 );
  22349. } else {
  22350. // ...assume skeletal animation
  22351. const boneName = '.bones[' + bones[ h ].name + ']';
  22352. addNonemptyTrack(
  22353. VectorKeyframeTrack, boneName + '.position',
  22354. animationKeys, 'pos', tracks );
  22355. addNonemptyTrack(
  22356. QuaternionKeyframeTrack, boneName + '.quaternion',
  22357. animationKeys, 'rot', tracks );
  22358. addNonemptyTrack(
  22359. VectorKeyframeTrack, boneName + '.scale',
  22360. animationKeys, 'scl', tracks );
  22361. }
  22362. }
  22363. if ( tracks.length === 0 ) {
  22364. return null;
  22365. }
  22366. const clip = new AnimationClip( clipName, duration, tracks, blendMode );
  22367. return clip;
  22368. }
  22369. } );
  22370. Object.assign( AnimationClip.prototype, {
  22371. resetDuration: function () {
  22372. const tracks = this.tracks;
  22373. let duration = 0;
  22374. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22375. const track = this.tracks[ i ];
  22376. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22377. }
  22378. this.duration = duration;
  22379. return this;
  22380. },
  22381. trim: function () {
  22382. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22383. this.tracks[ i ].trim( 0, this.duration );
  22384. }
  22385. return this;
  22386. },
  22387. validate: function () {
  22388. let valid = true;
  22389. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22390. valid = valid && this.tracks[ i ].validate();
  22391. }
  22392. return valid;
  22393. },
  22394. optimize: function () {
  22395. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22396. this.tracks[ i ].optimize();
  22397. }
  22398. return this;
  22399. },
  22400. clone: function () {
  22401. const tracks = [];
  22402. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22403. tracks.push( this.tracks[ i ].clone() );
  22404. }
  22405. return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
  22406. },
  22407. toJSON: function () {
  22408. return AnimationClip.toJSON( this );
  22409. }
  22410. } );
  22411. const Cache = {
  22412. enabled: false,
  22413. files: {},
  22414. add: function ( key, file ) {
  22415. if ( this.enabled === false ) return;
  22416. // console.log( 'THREE.Cache', 'Adding key:', key );
  22417. this.files[ key ] = file;
  22418. },
  22419. get: function ( key ) {
  22420. if ( this.enabled === false ) return;
  22421. // console.log( 'THREE.Cache', 'Checking key:', key );
  22422. return this.files[ key ];
  22423. },
  22424. remove: function ( key ) {
  22425. delete this.files[ key ];
  22426. },
  22427. clear: function () {
  22428. this.files = {};
  22429. }
  22430. };
  22431. function LoadingManager( onLoad, onProgress, onError ) {
  22432. const scope = this;
  22433. let isLoading = false;
  22434. let itemsLoaded = 0;
  22435. let itemsTotal = 0;
  22436. let urlModifier = undefined;
  22437. const handlers = [];
  22438. // Refer to #5689 for the reason why we don't set .onStart
  22439. // in the constructor
  22440. this.onStart = undefined;
  22441. this.onLoad = onLoad;
  22442. this.onProgress = onProgress;
  22443. this.onError = onError;
  22444. this.itemStart = function ( url ) {
  22445. itemsTotal ++;
  22446. if ( isLoading === false ) {
  22447. if ( scope.onStart !== undefined ) {
  22448. scope.onStart( url, itemsLoaded, itemsTotal );
  22449. }
  22450. }
  22451. isLoading = true;
  22452. };
  22453. this.itemEnd = function ( url ) {
  22454. itemsLoaded ++;
  22455. if ( scope.onProgress !== undefined ) {
  22456. scope.onProgress( url, itemsLoaded, itemsTotal );
  22457. }
  22458. if ( itemsLoaded === itemsTotal ) {
  22459. isLoading = false;
  22460. if ( scope.onLoad !== undefined ) {
  22461. scope.onLoad();
  22462. }
  22463. }
  22464. };
  22465. this.itemError = function ( url ) {
  22466. if ( scope.onError !== undefined ) {
  22467. scope.onError( url );
  22468. }
  22469. };
  22470. this.resolveURL = function ( url ) {
  22471. if ( urlModifier ) {
  22472. return urlModifier( url );
  22473. }
  22474. return url;
  22475. };
  22476. this.setURLModifier = function ( transform ) {
  22477. urlModifier = transform;
  22478. return this;
  22479. };
  22480. this.addHandler = function ( regex, loader ) {
  22481. handlers.push( regex, loader );
  22482. return this;
  22483. };
  22484. this.removeHandler = function ( regex ) {
  22485. const index = handlers.indexOf( regex );
  22486. if ( index !== - 1 ) {
  22487. handlers.splice( index, 2 );
  22488. }
  22489. return this;
  22490. };
  22491. this.getHandler = function ( file ) {
  22492. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22493. const regex = handlers[ i ];
  22494. const loader = handlers[ i + 1 ];
  22495. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22496. if ( regex.test( file ) ) {
  22497. return loader;
  22498. }
  22499. }
  22500. return null;
  22501. };
  22502. }
  22503. const DefaultLoadingManager = new LoadingManager();
  22504. function Loader( manager ) {
  22505. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22506. this.crossOrigin = 'anonymous';
  22507. this.withCredentials = false;
  22508. this.path = '';
  22509. this.resourcePath = '';
  22510. this.requestHeader = {};
  22511. }
  22512. Object.assign( Loader.prototype, {
  22513. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  22514. loadAsync: function ( url, onProgress ) {
  22515. const scope = this;
  22516. return new Promise( function ( resolve, reject ) {
  22517. scope.load( url, resolve, onProgress, reject );
  22518. } );
  22519. },
  22520. parse: function ( /* data */ ) {},
  22521. setCrossOrigin: function ( crossOrigin ) {
  22522. this.crossOrigin = crossOrigin;
  22523. return this;
  22524. },
  22525. setWithCredentials: function ( value ) {
  22526. this.withCredentials = value;
  22527. return this;
  22528. },
  22529. setPath: function ( path ) {
  22530. this.path = path;
  22531. return this;
  22532. },
  22533. setResourcePath: function ( resourcePath ) {
  22534. this.resourcePath = resourcePath;
  22535. return this;
  22536. },
  22537. setRequestHeader: function ( requestHeader ) {
  22538. this.requestHeader = requestHeader;
  22539. return this;
  22540. }
  22541. } );
  22542. const loading = {};
  22543. function FileLoader( manager ) {
  22544. Loader.call( this, manager );
  22545. }
  22546. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22547. constructor: FileLoader,
  22548. load: function ( url, onLoad, onProgress, onError ) {
  22549. if ( url === undefined ) url = '';
  22550. if ( this.path !== undefined ) url = this.path + url;
  22551. url = this.manager.resolveURL( url );
  22552. const scope = this;
  22553. const cached = Cache.get( url );
  22554. if ( cached !== undefined ) {
  22555. scope.manager.itemStart( url );
  22556. setTimeout( function () {
  22557. if ( onLoad ) onLoad( cached );
  22558. scope.manager.itemEnd( url );
  22559. }, 0 );
  22560. return cached;
  22561. }
  22562. // Check if request is duplicate
  22563. if ( loading[ url ] !== undefined ) {
  22564. loading[ url ].push( {
  22565. onLoad: onLoad,
  22566. onProgress: onProgress,
  22567. onError: onError
  22568. } );
  22569. return;
  22570. }
  22571. // Check for data: URI
  22572. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22573. const dataUriRegexResult = url.match( dataUriRegex );
  22574. let request;
  22575. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22576. if ( dataUriRegexResult ) {
  22577. const mimeType = dataUriRegexResult[ 1 ];
  22578. const isBase64 = !! dataUriRegexResult[ 2 ];
  22579. let data = dataUriRegexResult[ 3 ];
  22580. data = decodeURIComponent( data );
  22581. if ( isBase64 ) data = atob( data );
  22582. try {
  22583. let response;
  22584. const responseType = ( this.responseType || '' ).toLowerCase();
  22585. switch ( responseType ) {
  22586. case 'arraybuffer':
  22587. case 'blob':
  22588. const view = new Uint8Array( data.length );
  22589. for ( let i = 0; i < data.length; i ++ ) {
  22590. view[ i ] = data.charCodeAt( i );
  22591. }
  22592. if ( responseType === 'blob' ) {
  22593. response = new Blob( [ view.buffer ], { type: mimeType } );
  22594. } else {
  22595. response = view.buffer;
  22596. }
  22597. break;
  22598. case 'document':
  22599. const parser = new DOMParser();
  22600. response = parser.parseFromString( data, mimeType );
  22601. break;
  22602. case 'json':
  22603. response = JSON.parse( data );
  22604. break;
  22605. default: // 'text' or other
  22606. response = data;
  22607. break;
  22608. }
  22609. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22610. setTimeout( function () {
  22611. if ( onLoad ) onLoad( response );
  22612. scope.manager.itemEnd( url );
  22613. }, 0 );
  22614. } catch ( error ) {
  22615. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22616. setTimeout( function () {
  22617. if ( onError ) onError( error );
  22618. scope.manager.itemError( url );
  22619. scope.manager.itemEnd( url );
  22620. }, 0 );
  22621. }
  22622. } else {
  22623. // Initialise array for duplicate requests
  22624. loading[ url ] = [];
  22625. loading[ url ].push( {
  22626. onLoad: onLoad,
  22627. onProgress: onProgress,
  22628. onError: onError
  22629. } );
  22630. request = new XMLHttpRequest();
  22631. request.open( 'GET', url, true );
  22632. request.addEventListener( 'load', function ( event ) {
  22633. const response = this.response;
  22634. const callbacks = loading[ url ];
  22635. delete loading[ url ];
  22636. if ( this.status === 200 || this.status === 0 ) {
  22637. // Some browsers return HTTP Status 0 when using non-http protocol
  22638. // e.g. 'file://' or 'data://'. Handle as success.
  22639. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22640. // Add to cache only on HTTP success, so that we do not cache
  22641. // error response bodies as proper responses to requests.
  22642. Cache.add( url, response );
  22643. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22644. const callback = callbacks[ i ];
  22645. if ( callback.onLoad ) callback.onLoad( response, event.total); //xzw add event.total
  22646. }
  22647. scope.manager.itemEnd( url );
  22648. } else {
  22649. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22650. const callback = callbacks[ i ];
  22651. if ( callback.onError ) callback.onError( event );
  22652. }
  22653. scope.manager.itemError( url );
  22654. scope.manager.itemEnd( url );
  22655. }
  22656. }, false );
  22657. request.addEventListener( 'progress', function ( event ) {
  22658. const callbacks = loading[ url ];
  22659. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22660. const callback = callbacks[ i ];
  22661. if ( callback.onProgress ) callback.onProgress( event );
  22662. }
  22663. }, false );
  22664. request.addEventListener( 'error', function ( event ) {
  22665. const callbacks = loading[ url ];
  22666. delete loading[ url ];
  22667. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22668. const callback = callbacks[ i ];
  22669. if ( callback.onError ) callback.onError( event );
  22670. }
  22671. scope.manager.itemError( url );
  22672. scope.manager.itemEnd( url );
  22673. }, false );
  22674. request.addEventListener( 'abort', function ( event ) {
  22675. const callbacks = loading[ url ];
  22676. delete loading[ url ];
  22677. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22678. const callback = callbacks[ i ];
  22679. if ( callback.onError ) callback.onError( event );
  22680. }
  22681. scope.manager.itemError( url );
  22682. scope.manager.itemEnd( url );
  22683. }, false );
  22684. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22685. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22686. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22687. for ( const header in this.requestHeader ) {
  22688. request.setRequestHeader( header, this.requestHeader[ header ] );
  22689. }
  22690. request.send( null );
  22691. }
  22692. scope.manager.itemStart( url );
  22693. return request;
  22694. },
  22695. setResponseType: function ( value ) {
  22696. this.responseType = value;
  22697. return this;
  22698. },
  22699. setMimeType: function ( value ) {
  22700. this.mimeType = value;
  22701. return this;
  22702. }
  22703. } );
  22704. function AnimationLoader( manager ) {
  22705. Loader.call( this, manager );
  22706. }
  22707. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22708. constructor: AnimationLoader,
  22709. load: function ( url, onLoad, onProgress, onError ) {
  22710. const scope = this;
  22711. const loader = new FileLoader( scope.manager );
  22712. loader.setPath( scope.path );
  22713. loader.setRequestHeader( scope.requestHeader );
  22714. loader.setWithCredentials( scope.withCredentials );
  22715. loader.load( url, function ( text ) {
  22716. try {
  22717. onLoad( scope.parse( JSON.parse( text ) ) );
  22718. } catch ( e ) {
  22719. if ( onError ) {
  22720. onError( e );
  22721. } else {
  22722. console.error( e );
  22723. }
  22724. scope.manager.itemError( url );
  22725. }
  22726. }, onProgress, onError );
  22727. },
  22728. parse: function ( json ) {
  22729. const animations = [];
  22730. for ( let i = 0; i < json.length; i ++ ) {
  22731. const clip = AnimationClip.parse( json[ i ] );
  22732. animations.push( clip );
  22733. }
  22734. return animations;
  22735. }
  22736. } );
  22737. /**
  22738. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22739. *
  22740. * Sub classes have to implement the parse() method which will be used in load().
  22741. */
  22742. function CompressedTextureLoader( manager ) {
  22743. Loader.call( this, manager );
  22744. }
  22745. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22746. constructor: CompressedTextureLoader,
  22747. load: function ( url, onLoad, onProgress, onError ) {
  22748. const scope = this;
  22749. const images = [];
  22750. const texture = new CompressedTexture();
  22751. const loader = new FileLoader( this.manager );
  22752. loader.setPath( this.path );
  22753. loader.setResponseType( 'arraybuffer' );
  22754. loader.setRequestHeader( this.requestHeader );
  22755. loader.setWithCredentials( scope.withCredentials );
  22756. let loaded = 0;
  22757. function loadTexture( i ) {
  22758. loader.load( url[ i ], function ( buffer ) {
  22759. const texDatas = scope.parse( buffer, true );
  22760. images[ i ] = {
  22761. width: texDatas.width,
  22762. height: texDatas.height,
  22763. format: texDatas.format,
  22764. mipmaps: texDatas.mipmaps
  22765. };
  22766. loaded += 1;
  22767. if ( loaded === 6 ) {
  22768. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  22769. texture.image = images;
  22770. texture.format = texDatas.format;
  22771. texture.needsUpdate = true;
  22772. if ( onLoad ) onLoad( texture );
  22773. }
  22774. }, onProgress, onError );
  22775. }
  22776. if ( Array.isArray( url ) ) {
  22777. for ( let i = 0, il = url.length; i < il; ++ i ) {
  22778. loadTexture( i );
  22779. }
  22780. } else {
  22781. // compressed cubemap texture stored in a single DDS file
  22782. loader.load( url, function ( buffer ) {
  22783. const texDatas = scope.parse( buffer, true );
  22784. if ( texDatas.isCubemap ) {
  22785. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22786. for ( let f = 0; f < faces; f ++ ) {
  22787. images[ f ] = { mipmaps: [] };
  22788. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  22789. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22790. images[ f ].format = texDatas.format;
  22791. images[ f ].width = texDatas.width;
  22792. images[ f ].height = texDatas.height;
  22793. }
  22794. }
  22795. texture.image = images;
  22796. } else {
  22797. texture.image.width = texDatas.width;
  22798. texture.image.height = texDatas.height;
  22799. texture.mipmaps = texDatas.mipmaps;
  22800. }
  22801. if ( texDatas.mipmapCount === 1 ) {
  22802. texture.minFilter = LinearFilter;
  22803. }
  22804. texture.format = texDatas.format;
  22805. texture.needsUpdate = true;
  22806. if ( onLoad ) onLoad( texture );
  22807. }, onProgress, onError );
  22808. }
  22809. return texture;
  22810. }
  22811. } );
  22812. function ImageLoader( manager ) {
  22813. Loader.call( this, manager );
  22814. }
  22815. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22816. constructor: ImageLoader,
  22817. load: function ( url, onLoad, onProgress, onError ) {
  22818. if ( this.path !== undefined ) url = this.path + url;
  22819. url = this.manager.resolveURL( url );
  22820. const scope = this;
  22821. const cached = Cache.get( url );
  22822. if ( cached !== undefined ) {
  22823. scope.manager.itemStart( url );
  22824. setTimeout( function () {
  22825. if ( onLoad ) onLoad( cached );
  22826. scope.manager.itemEnd( url );
  22827. }, 0 );
  22828. return cached;
  22829. }
  22830. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22831. function onImageLoad() {
  22832. image.removeEventListener( 'load', onImageLoad, false );
  22833. image.removeEventListener( 'error', onImageError, false );
  22834. Cache.add( url, this );
  22835. if ( onLoad ) onLoad( this );
  22836. scope.manager.itemEnd( url );
  22837. }
  22838. function onImageError( event ) {
  22839. image.removeEventListener( 'load', onImageLoad, false );
  22840. image.removeEventListener( 'error', onImageError, false );
  22841. if ( onError ) onError( event );
  22842. scope.manager.itemError( url );
  22843. scope.manager.itemEnd( url );
  22844. }
  22845. image.addEventListener( 'load', onImageLoad, false );
  22846. image.addEventListener( 'error', onImageError, false );
  22847. if ( url.substr( 0, 5 ) !== 'data:' ) {
  22848. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  22849. }
  22850. scope.manager.itemStart( url );
  22851. image.src = url;
  22852. return image;
  22853. }
  22854. } );
  22855. function CubeTextureLoader( manager ) {
  22856. Loader.call( this, manager );
  22857. }
  22858. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22859. constructor: CubeTextureLoader,
  22860. load: function ( urls, onLoad, onProgress, onError ) {
  22861. const texture = new CubeTexture();
  22862. const loader = new ImageLoader( this.manager );
  22863. loader.setCrossOrigin( this.crossOrigin );
  22864. loader.setPath( this.path );
  22865. let loaded = 0;
  22866. function loadTexture( i ) {
  22867. loader.load( urls[ i ], function ( image ) {
  22868. texture.images[ i ] = image;
  22869. loaded ++;
  22870. if ( loaded === 6 ) {
  22871. texture.needsUpdate = true;
  22872. if ( onLoad ) onLoad( texture );
  22873. }
  22874. }, undefined, onError );
  22875. }
  22876. for ( let i = 0; i < urls.length; ++ i ) {
  22877. loadTexture( i );
  22878. }
  22879. return texture;
  22880. }
  22881. } );
  22882. /**
  22883. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22884. *
  22885. * Sub classes have to implement the parse() method which will be used in load().
  22886. */
  22887. function DataTextureLoader( manager ) {
  22888. Loader.call( this, manager );
  22889. }
  22890. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22891. constructor: DataTextureLoader,
  22892. load: function ( url, onLoad, onProgress, onError ) {
  22893. const scope = this;
  22894. const texture = new DataTexture();
  22895. const loader = new FileLoader( this.manager );
  22896. loader.setResponseType( 'arraybuffer' );
  22897. loader.setRequestHeader( this.requestHeader );
  22898. loader.setPath( this.path );
  22899. loader.setWithCredentials( scope.withCredentials );
  22900. loader.load( url, function ( buffer ) {
  22901. const texData = scope.parse( buffer );
  22902. if ( ! texData ) return;
  22903. if ( texData.image !== undefined ) {
  22904. texture.image = texData.image;
  22905. } else if ( texData.data !== undefined ) {
  22906. texture.image.width = texData.width;
  22907. texture.image.height = texData.height;
  22908. texture.image.data = texData.data;
  22909. }
  22910. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22911. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22912. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22913. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22914. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22915. if ( texData.format !== undefined ) {
  22916. texture.format = texData.format;
  22917. }
  22918. if ( texData.type !== undefined ) {
  22919. texture.type = texData.type;
  22920. }
  22921. if ( texData.mipmaps !== undefined ) {
  22922. texture.mipmaps = texData.mipmaps;
  22923. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22924. }
  22925. if ( texData.mipmapCount === 1 ) {
  22926. texture.minFilter = LinearFilter;
  22927. }
  22928. texture.needsUpdate = true;
  22929. if ( onLoad ) onLoad( texture, texData );
  22930. }, onProgress, onError );
  22931. return texture;
  22932. }
  22933. } );
  22934. function TextureLoader( manager ) {
  22935. Loader.call( this, manager );
  22936. }
  22937. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22938. constructor: TextureLoader,
  22939. load: function ( url, onLoad, onProgress, onError ) {
  22940. const texture = new Texture();
  22941. const loader = new ImageLoader( this.manager );
  22942. loader.setCrossOrigin( this.crossOrigin );
  22943. loader.setPath( this.path );
  22944. loader.load( url, function ( image ) {
  22945. texture.image = image;
  22946. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22947. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22948. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22949. texture.needsUpdate = true;
  22950. if ( onLoad !== undefined ) {
  22951. onLoad( texture );
  22952. }
  22953. }, onProgress, onError );
  22954. return texture;
  22955. }
  22956. } );
  22957. /**
  22958. * Extensible curve object.
  22959. *
  22960. * Some common of curve methods:
  22961. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22962. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22963. * .getPoints(), .getSpacedPoints()
  22964. * .getLength()
  22965. * .updateArcLengths()
  22966. *
  22967. * This following curves inherit from THREE.Curve:
  22968. *
  22969. * -- 2D curves --
  22970. * THREE.ArcCurve
  22971. * THREE.CubicBezierCurve
  22972. * THREE.EllipseCurve
  22973. * THREE.LineCurve
  22974. * THREE.QuadraticBezierCurve
  22975. * THREE.SplineCurve
  22976. *
  22977. * -- 3D curves --
  22978. * THREE.CatmullRomCurve3
  22979. * THREE.CubicBezierCurve3
  22980. * THREE.LineCurve3
  22981. * THREE.QuadraticBezierCurve3
  22982. *
  22983. * A series of curves can be represented as a THREE.CurvePath.
  22984. *
  22985. **/
  22986. function Curve() {
  22987. this.type = 'Curve';
  22988. this.arcLengthDivisions = 200;
  22989. }
  22990. Object.assign( Curve.prototype, {
  22991. // Virtual base class method to overwrite and implement in subclasses
  22992. // - t [0 .. 1]
  22993. getPoint: function ( /* t, optionalTarget */ ) {
  22994. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  22995. return null;
  22996. },
  22997. // Get point at relative position in curve according to arc length
  22998. // - u [0 .. 1]
  22999. getPointAt: function ( u, optionalTarget ) {
  23000. const t = this.getUtoTmapping( u );
  23001. return this.getPoint( t, optionalTarget );
  23002. },
  23003. // Get sequence of points using getPoint( t )
  23004. getPoints: function ( divisions = 5 ) {
  23005. const points = [];
  23006. for ( let d = 0; d <= divisions; d ++ ) {
  23007. points.push( this.getPoint( d / divisions ) );
  23008. }
  23009. return points;
  23010. },
  23011. // Get sequence of points using getPointAt( u )
  23012. getSpacedPoints: function ( divisions = 5 ) {
  23013. const points = [];
  23014. for ( let d = 0; d <= divisions; d ++ ) {
  23015. points.push( this.getPointAt( d / divisions ) );
  23016. }
  23017. return points;
  23018. },
  23019. // Get total curve arc length
  23020. getLength: function () {
  23021. const lengths = this.getLengths();
  23022. return lengths[ lengths.length - 1 ];
  23023. },
  23024. // Get list of cumulative segment lengths
  23025. getLengths: function ( divisions ) {
  23026. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  23027. if ( this.cacheArcLengths &&
  23028. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23029. ! this.needsUpdate ) {
  23030. return this.cacheArcLengths;
  23031. }
  23032. this.needsUpdate = false;
  23033. const cache = [];
  23034. let current, last = this.getPoint( 0 );
  23035. let sum = 0;
  23036. cache.push( 0 );
  23037. for ( let p = 1; p <= divisions; p ++ ) {
  23038. current = this.getPoint( p / divisions );
  23039. sum += current.distanceTo( last );
  23040. cache.push( sum );
  23041. last = current;
  23042. }
  23043. this.cacheArcLengths = cache;
  23044. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23045. },
  23046. updateArcLengths: function () {
  23047. this.needsUpdate = true;
  23048. this.getLengths();
  23049. },
  23050. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  23051. getUtoTmapping: function ( u, distance ) {
  23052. const arcLengths = this.getLengths();
  23053. let i = 0;
  23054. const il = arcLengths.length;
  23055. let targetArcLength; // The targeted u distance value to get
  23056. if ( distance ) {
  23057. targetArcLength = distance;
  23058. } else {
  23059. targetArcLength = u * arcLengths[ il - 1 ];
  23060. }
  23061. // binary search for the index with largest value smaller than target u distance
  23062. let low = 0, high = il - 1, comparison;
  23063. while ( low <= high ) {
  23064. 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
  23065. comparison = arcLengths[ i ] - targetArcLength;
  23066. if ( comparison < 0 ) {
  23067. low = i + 1;
  23068. } else if ( comparison > 0 ) {
  23069. high = i - 1;
  23070. } else {
  23071. high = i;
  23072. break;
  23073. // DONE
  23074. }
  23075. }
  23076. i = high;
  23077. if ( arcLengths[ i ] === targetArcLength ) {
  23078. return i / ( il - 1 );
  23079. }
  23080. // we could get finer grain at lengths, or use simple interpolation between two points
  23081. const lengthBefore = arcLengths[ i ];
  23082. const lengthAfter = arcLengths[ i + 1 ];
  23083. const segmentLength = lengthAfter - lengthBefore;
  23084. // determine where we are between the 'before' and 'after' points
  23085. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23086. // add that fractional amount to t
  23087. const t = ( i + segmentFraction ) / ( il - 1 );
  23088. return t;
  23089. },
  23090. // Returns a unit vector tangent at t
  23091. // In case any sub curve does not implement its tangent derivation,
  23092. // 2 points a small delta apart will be used to find its gradient
  23093. // which seems to give a reasonable approximation
  23094. getTangent: function ( t, optionalTarget ) {
  23095. const delta = 0.0001;
  23096. let t1 = t - delta;
  23097. let t2 = t + delta;
  23098. // Capping in case of danger
  23099. if ( t1 < 0 ) t1 = 0;
  23100. if ( t2 > 1 ) t2 = 1;
  23101. const pt1 = this.getPoint( t1 );
  23102. const pt2 = this.getPoint( t2 );
  23103. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2$1() : new Vector3() );
  23104. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23105. return tangent;
  23106. },
  23107. getTangentAt: function ( u, optionalTarget ) {
  23108. const t = this.getUtoTmapping( u );
  23109. return this.getTangent( t, optionalTarget );
  23110. },
  23111. computeFrenetFrames: function ( segments, closed ) {
  23112. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23113. const normal = new Vector3();
  23114. const tangents = [];
  23115. const normals = [];
  23116. const binormals = [];
  23117. const vec = new Vector3();
  23118. const mat = new Matrix4();
  23119. // compute the tangent vectors for each segment on the curve
  23120. for ( let i = 0; i <= segments; i ++ ) {
  23121. const u = i / segments;
  23122. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23123. tangents[ i ].normalize();
  23124. }
  23125. // select an initial normal vector perpendicular to the first tangent vector,
  23126. // and in the direction of the minimum tangent xyz component
  23127. normals[ 0 ] = new Vector3();
  23128. binormals[ 0 ] = new Vector3();
  23129. let min = Number.MAX_VALUE;
  23130. const tx = Math.abs( tangents[ 0 ].x );
  23131. const ty = Math.abs( tangents[ 0 ].y );
  23132. const tz = Math.abs( tangents[ 0 ].z );
  23133. if ( tx <= min ) {
  23134. min = tx;
  23135. normal.set( 1, 0, 0 );
  23136. }
  23137. if ( ty <= min ) {
  23138. min = ty;
  23139. normal.set( 0, 1, 0 );
  23140. }
  23141. if ( tz <= min ) {
  23142. normal.set( 0, 0, 1 );
  23143. }
  23144. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23145. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23146. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23147. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23148. for ( let i = 1; i <= segments; i ++ ) {
  23149. normals[ i ] = normals[ i - 1 ].clone();
  23150. binormals[ i ] = binormals[ i - 1 ].clone();
  23151. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23152. if ( vec.length() > Number.EPSILON ) {
  23153. vec.normalize();
  23154. const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23155. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23156. }
  23157. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23158. }
  23159. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23160. if ( closed === true ) {
  23161. let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  23162. theta /= segments;
  23163. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23164. theta = - theta;
  23165. }
  23166. for ( let i = 1; i <= segments; i ++ ) {
  23167. // twist a little...
  23168. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23169. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23170. }
  23171. }
  23172. return {
  23173. tangents: tangents,
  23174. normals: normals,
  23175. binormals: binormals
  23176. };
  23177. },
  23178. clone: function () {
  23179. return new this.constructor().copy( this );
  23180. },
  23181. copy: function ( source ) {
  23182. this.arcLengthDivisions = source.arcLengthDivisions;
  23183. return this;
  23184. },
  23185. toJSON: function () {
  23186. const data = {
  23187. metadata: {
  23188. version: 4.5,
  23189. type: 'Curve',
  23190. generator: 'Curve.toJSON'
  23191. }
  23192. };
  23193. data.arcLengthDivisions = this.arcLengthDivisions;
  23194. data.type = this.type;
  23195. return data;
  23196. },
  23197. fromJSON: function ( json ) {
  23198. this.arcLengthDivisions = json.arcLengthDivisions;
  23199. return this;
  23200. }
  23201. } );
  23202. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23203. Curve.call( this );
  23204. this.type = 'EllipseCurve';
  23205. this.aX = aX || 0;
  23206. this.aY = aY || 0;
  23207. this.xRadius = xRadius || 1;
  23208. this.yRadius = yRadius || 1;
  23209. this.aStartAngle = aStartAngle || 0;
  23210. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23211. this.aClockwise = aClockwise || false;
  23212. this.aRotation = aRotation || 0;
  23213. }
  23214. EllipseCurve.prototype = Object.create( Curve.prototype );
  23215. EllipseCurve.prototype.constructor = EllipseCurve;
  23216. EllipseCurve.prototype.isEllipseCurve = true;
  23217. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23218. const point = optionalTarget || new Vector2$1();
  23219. const twoPi = Math.PI * 2;
  23220. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23221. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23222. // ensures that deltaAngle is 0 .. 2 PI
  23223. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23224. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23225. if ( deltaAngle < Number.EPSILON ) {
  23226. if ( samePoints ) {
  23227. deltaAngle = 0;
  23228. } else {
  23229. deltaAngle = twoPi;
  23230. }
  23231. }
  23232. if ( this.aClockwise === true && ! samePoints ) {
  23233. if ( deltaAngle === twoPi ) {
  23234. deltaAngle = - twoPi;
  23235. } else {
  23236. deltaAngle = deltaAngle - twoPi;
  23237. }
  23238. }
  23239. const angle = this.aStartAngle + t * deltaAngle;
  23240. let x = this.aX + this.xRadius * Math.cos( angle );
  23241. let y = this.aY + this.yRadius * Math.sin( angle );
  23242. if ( this.aRotation !== 0 ) {
  23243. const cos = Math.cos( this.aRotation );
  23244. const sin = Math.sin( this.aRotation );
  23245. const tx = x - this.aX;
  23246. const ty = y - this.aY;
  23247. // Rotate the point about the center of the ellipse.
  23248. x = tx * cos - ty * sin + this.aX;
  23249. y = tx * sin + ty * cos + this.aY;
  23250. }
  23251. return point.set( x, y );
  23252. };
  23253. EllipseCurve.prototype.copy = function ( source ) {
  23254. Curve.prototype.copy.call( this, source );
  23255. this.aX = source.aX;
  23256. this.aY = source.aY;
  23257. this.xRadius = source.xRadius;
  23258. this.yRadius = source.yRadius;
  23259. this.aStartAngle = source.aStartAngle;
  23260. this.aEndAngle = source.aEndAngle;
  23261. this.aClockwise = source.aClockwise;
  23262. this.aRotation = source.aRotation;
  23263. return this;
  23264. };
  23265. EllipseCurve.prototype.toJSON = function () {
  23266. const data = Curve.prototype.toJSON.call( this );
  23267. data.aX = this.aX;
  23268. data.aY = this.aY;
  23269. data.xRadius = this.xRadius;
  23270. data.yRadius = this.yRadius;
  23271. data.aStartAngle = this.aStartAngle;
  23272. data.aEndAngle = this.aEndAngle;
  23273. data.aClockwise = this.aClockwise;
  23274. data.aRotation = this.aRotation;
  23275. return data;
  23276. };
  23277. EllipseCurve.prototype.fromJSON = function ( json ) {
  23278. Curve.prototype.fromJSON.call( this, json );
  23279. this.aX = json.aX;
  23280. this.aY = json.aY;
  23281. this.xRadius = json.xRadius;
  23282. this.yRadius = json.yRadius;
  23283. this.aStartAngle = json.aStartAngle;
  23284. this.aEndAngle = json.aEndAngle;
  23285. this.aClockwise = json.aClockwise;
  23286. this.aRotation = json.aRotation;
  23287. return this;
  23288. };
  23289. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23290. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23291. this.type = 'ArcCurve';
  23292. }
  23293. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  23294. ArcCurve.prototype.constructor = ArcCurve;
  23295. ArcCurve.prototype.isArcCurve = true;
  23296. /**
  23297. * Centripetal CatmullRom Curve - which is useful for avoiding
  23298. * cusps and self-intersections in non-uniform catmull rom curves.
  23299. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23300. *
  23301. * curve.type accepts centripetal(default), chordal and catmullrom
  23302. * curve.tension is used for catmullrom which defaults to 0.5
  23303. */
  23304. /*
  23305. Based on an optimized c++ solution in
  23306. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23307. - http://ideone.com/NoEbVM
  23308. This CubicPoly class could be used for reusing some variables and calculations,
  23309. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23310. which can be placed in CurveUtils.
  23311. */
  23312. function CubicPoly() {
  23313. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23314. /*
  23315. * Compute coefficients for a cubic polynomial
  23316. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23317. * such that
  23318. * p(0) = x0, p(1) = x1
  23319. * and
  23320. * p'(0) = t0, p'(1) = t1.
  23321. */
  23322. function init( x0, x1, t0, t1 ) {
  23323. c0 = x0;
  23324. c1 = t0;
  23325. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  23326. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23327. }
  23328. return {
  23329. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23330. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23331. },
  23332. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23333. // compute tangents when parameterized in [t1,t2]
  23334. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23335. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23336. // rescale tangents for parametrization in [0,1]
  23337. t1 *= dt1;
  23338. t2 *= dt1;
  23339. init( x1, x2, t1, t2 );
  23340. },
  23341. calc: function ( t ) {
  23342. const t2 = t * t;
  23343. const t3 = t2 * t;
  23344. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23345. }
  23346. };
  23347. }
  23348. //
  23349. const tmp = new Vector3();
  23350. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  23351. function CatmullRomCurve3( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23352. Curve.call( this );
  23353. this.type = 'CatmullRomCurve3';
  23354. this.points = points;
  23355. this.closed = closed;
  23356. this.curveType = curveType;
  23357. this.tension = tension;
  23358. }
  23359. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  23360. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23361. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23362. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23363. const point = optionalTarget;
  23364. const points = this.points;
  23365. const l = points.length;
  23366. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23367. let intPoint = Math.floor( p );
  23368. let weight = p - intPoint;
  23369. if ( this.closed ) {
  23370. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23371. } else if ( weight === 0 && intPoint === l - 1 ) {
  23372. intPoint = l - 2;
  23373. weight = 1;
  23374. }
  23375. let p0, p3; // 4 points (p1 & p2 defined below)
  23376. if ( this.closed || intPoint > 0 ) {
  23377. p0 = points[ ( intPoint - 1 ) % l ];
  23378. } else {
  23379. // extrapolate first point
  23380. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23381. p0 = tmp;
  23382. }
  23383. const p1 = points[ intPoint % l ];
  23384. const p2 = points[ ( intPoint + 1 ) % l ];
  23385. if ( this.closed || intPoint + 2 < l ) {
  23386. p3 = points[ ( intPoint + 2 ) % l ];
  23387. } else {
  23388. // extrapolate last point
  23389. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23390. p3 = tmp;
  23391. }
  23392. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23393. // init Centripetal / Chordal Catmull-Rom
  23394. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23395. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23396. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23397. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23398. // safety check for repeated points
  23399. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23400. if ( dt0 < 1e-4 ) dt0 = dt1;
  23401. if ( dt2 < 1e-4 ) dt2 = dt1;
  23402. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23403. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23404. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23405. } else if ( this.curveType === 'catmullrom' ) {
  23406. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23407. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23408. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23409. }
  23410. point.set(
  23411. px.calc( weight ),
  23412. py.calc( weight ),
  23413. pz.calc( weight )
  23414. );
  23415. return point;
  23416. };
  23417. CatmullRomCurve3.prototype.copy = function ( source ) {
  23418. Curve.prototype.copy.call( this, source );
  23419. this.points = [];
  23420. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23421. const point = source.points[ i ];
  23422. this.points.push( point.clone() );
  23423. }
  23424. this.closed = source.closed;
  23425. this.curveType = source.curveType;
  23426. this.tension = source.tension;
  23427. return this;
  23428. };
  23429. CatmullRomCurve3.prototype.toJSON = function () {
  23430. const data = Curve.prototype.toJSON.call( this );
  23431. data.points = [];
  23432. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23433. const point = this.points[ i ];
  23434. data.points.push( point.toArray() );
  23435. }
  23436. data.closed = this.closed;
  23437. data.curveType = this.curveType;
  23438. data.tension = this.tension;
  23439. return data;
  23440. };
  23441. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  23442. Curve.prototype.fromJSON.call( this, json );
  23443. this.points = [];
  23444. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23445. const point = json.points[ i ];
  23446. this.points.push( new Vector3().fromArray( point ) );
  23447. }
  23448. this.closed = json.closed;
  23449. this.curveType = json.curveType;
  23450. this.tension = json.tension;
  23451. return this;
  23452. };
  23453. /**
  23454. * Bezier Curves formulas obtained from
  23455. * http://en.wikipedia.org/wiki/Bézier_curve
  23456. */
  23457. function CatmullRom( t, p0, p1, p2, p3 ) {
  23458. const v0 = ( p2 - p0 ) * 0.5;
  23459. const v1 = ( p3 - p1 ) * 0.5;
  23460. const t2 = t * t;
  23461. const t3 = t * t2;
  23462. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23463. }
  23464. //
  23465. function QuadraticBezierP0( t, p ) {
  23466. const k = 1 - t;
  23467. return k * k * p;
  23468. }
  23469. function QuadraticBezierP1( t, p ) {
  23470. return 2 * ( 1 - t ) * t * p;
  23471. }
  23472. function QuadraticBezierP2( t, p ) {
  23473. return t * t * p;
  23474. }
  23475. function QuadraticBezier( t, p0, p1, p2 ) {
  23476. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23477. QuadraticBezierP2( t, p2 );
  23478. }
  23479. //
  23480. function CubicBezierP0( t, p ) {
  23481. const k = 1 - t;
  23482. return k * k * k * p;
  23483. }
  23484. function CubicBezierP1( t, p ) {
  23485. const k = 1 - t;
  23486. return 3 * k * k * t * p;
  23487. }
  23488. function CubicBezierP2( t, p ) {
  23489. return 3 * ( 1 - t ) * t * t * p;
  23490. }
  23491. function CubicBezierP3( t, p ) {
  23492. return t * t * t * p;
  23493. }
  23494. function CubicBezier( t, p0, p1, p2, p3 ) {
  23495. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23496. CubicBezierP3( t, p3 );
  23497. }
  23498. function CubicBezierCurve( v0 = new Vector2$1(), v1 = new Vector2$1(), v2 = new Vector2$1(), v3 = new Vector2$1() ) {
  23499. Curve.call( this );
  23500. this.type = 'CubicBezierCurve';
  23501. this.v0 = v0;
  23502. this.v1 = v1;
  23503. this.v2 = v2;
  23504. this.v3 = v3;
  23505. }
  23506. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  23507. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23508. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23509. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23510. const point = optionalTarget;
  23511. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23512. point.set(
  23513. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23514. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23515. );
  23516. return point;
  23517. };
  23518. CubicBezierCurve.prototype.copy = function ( source ) {
  23519. Curve.prototype.copy.call( this, source );
  23520. this.v0.copy( source.v0 );
  23521. this.v1.copy( source.v1 );
  23522. this.v2.copy( source.v2 );
  23523. this.v3.copy( source.v3 );
  23524. return this;
  23525. };
  23526. CubicBezierCurve.prototype.toJSON = function () {
  23527. const data = Curve.prototype.toJSON.call( this );
  23528. data.v0 = this.v0.toArray();
  23529. data.v1 = this.v1.toArray();
  23530. data.v2 = this.v2.toArray();
  23531. data.v3 = this.v3.toArray();
  23532. return data;
  23533. };
  23534. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  23535. Curve.prototype.fromJSON.call( this, json );
  23536. this.v0.fromArray( json.v0 );
  23537. this.v1.fromArray( json.v1 );
  23538. this.v2.fromArray( json.v2 );
  23539. this.v3.fromArray( json.v3 );
  23540. return this;
  23541. };
  23542. function CubicBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23543. Curve.call( this );
  23544. this.type = 'CubicBezierCurve3';
  23545. this.v0 = v0;
  23546. this.v1 = v1;
  23547. this.v2 = v2;
  23548. this.v3 = v3;
  23549. }
  23550. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  23551. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23552. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23553. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23554. const point = optionalTarget;
  23555. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23556. point.set(
  23557. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23558. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23559. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23560. );
  23561. return point;
  23562. };
  23563. CubicBezierCurve3.prototype.copy = function ( source ) {
  23564. Curve.prototype.copy.call( this, source );
  23565. this.v0.copy( source.v0 );
  23566. this.v1.copy( source.v1 );
  23567. this.v2.copy( source.v2 );
  23568. this.v3.copy( source.v3 );
  23569. return this;
  23570. };
  23571. CubicBezierCurve3.prototype.toJSON = function () {
  23572. const data = Curve.prototype.toJSON.call( this );
  23573. data.v0 = this.v0.toArray();
  23574. data.v1 = this.v1.toArray();
  23575. data.v2 = this.v2.toArray();
  23576. data.v3 = this.v3.toArray();
  23577. return data;
  23578. };
  23579. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  23580. Curve.prototype.fromJSON.call( this, json );
  23581. this.v0.fromArray( json.v0 );
  23582. this.v1.fromArray( json.v1 );
  23583. this.v2.fromArray( json.v2 );
  23584. this.v3.fromArray( json.v3 );
  23585. return this;
  23586. };
  23587. function LineCurve( v1 = new Vector2$1(), v2 = new Vector2$1() ) {
  23588. Curve.call( this );
  23589. this.type = 'LineCurve';
  23590. this.v1 = v1;
  23591. this.v2 = v2;
  23592. }
  23593. LineCurve.prototype = Object.create( Curve.prototype );
  23594. LineCurve.prototype.constructor = LineCurve;
  23595. LineCurve.prototype.isLineCurve = true;
  23596. LineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23597. const point = optionalTarget;
  23598. if ( t === 1 ) {
  23599. point.copy( this.v2 );
  23600. } else {
  23601. point.copy( this.v2 ).sub( this.v1 );
  23602. point.multiplyScalar( t ).add( this.v1 );
  23603. }
  23604. return point;
  23605. };
  23606. // Line curve is linear, so we can overwrite default getPointAt
  23607. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  23608. return this.getPoint( u, optionalTarget );
  23609. };
  23610. LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
  23611. const tangent = optionalTarget || new Vector2$1();
  23612. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  23613. return tangent;
  23614. };
  23615. LineCurve.prototype.copy = function ( source ) {
  23616. Curve.prototype.copy.call( this, source );
  23617. this.v1.copy( source.v1 );
  23618. this.v2.copy( source.v2 );
  23619. return this;
  23620. };
  23621. LineCurve.prototype.toJSON = function () {
  23622. const data = Curve.prototype.toJSON.call( this );
  23623. data.v1 = this.v1.toArray();
  23624. data.v2 = this.v2.toArray();
  23625. return data;
  23626. };
  23627. LineCurve.prototype.fromJSON = function ( json ) {
  23628. Curve.prototype.fromJSON.call( this, json );
  23629. this.v1.fromArray( json.v1 );
  23630. this.v2.fromArray( json.v2 );
  23631. return this;
  23632. };
  23633. function LineCurve3( v1 = new Vector3(), v2 = new Vector3() ) {
  23634. Curve.call( this );
  23635. this.type = 'LineCurve3';
  23636. this.v1 = v1;
  23637. this.v2 = v2;
  23638. }
  23639. LineCurve3.prototype = Object.create( Curve.prototype );
  23640. LineCurve3.prototype.constructor = LineCurve3;
  23641. LineCurve3.prototype.isLineCurve3 = true;
  23642. LineCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23643. const point = optionalTarget;
  23644. if ( t === 1 ) {
  23645. point.copy( this.v2 );
  23646. } else {
  23647. point.copy( this.v2 ).sub( this.v1 );
  23648. point.multiplyScalar( t ).add( this.v1 );
  23649. }
  23650. return point;
  23651. };
  23652. // Line curve is linear, so we can overwrite default getPointAt
  23653. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  23654. return this.getPoint( u, optionalTarget );
  23655. };
  23656. LineCurve3.prototype.copy = function ( source ) {
  23657. Curve.prototype.copy.call( this, source );
  23658. this.v1.copy( source.v1 );
  23659. this.v2.copy( source.v2 );
  23660. return this;
  23661. };
  23662. LineCurve3.prototype.toJSON = function () {
  23663. const data = Curve.prototype.toJSON.call( this );
  23664. data.v1 = this.v1.toArray();
  23665. data.v2 = this.v2.toArray();
  23666. return data;
  23667. };
  23668. LineCurve3.prototype.fromJSON = function ( json ) {
  23669. Curve.prototype.fromJSON.call( this, json );
  23670. this.v1.fromArray( json.v1 );
  23671. this.v2.fromArray( json.v2 );
  23672. return this;
  23673. };
  23674. function QuadraticBezierCurve( v0 = new Vector2$1(), v1 = new Vector2$1(), v2 = new Vector2$1() ) {
  23675. Curve.call( this );
  23676. this.type = 'QuadraticBezierCurve';
  23677. this.v0 = v0;
  23678. this.v1 = v1;
  23679. this.v2 = v2;
  23680. }
  23681. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  23682. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23683. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23684. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23685. const point = optionalTarget;
  23686. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23687. point.set(
  23688. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23689. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23690. );
  23691. return point;
  23692. };
  23693. QuadraticBezierCurve.prototype.copy = function ( source ) {
  23694. Curve.prototype.copy.call( this, source );
  23695. this.v0.copy( source.v0 );
  23696. this.v1.copy( source.v1 );
  23697. this.v2.copy( source.v2 );
  23698. return this;
  23699. };
  23700. QuadraticBezierCurve.prototype.toJSON = function () {
  23701. const data = Curve.prototype.toJSON.call( this );
  23702. data.v0 = this.v0.toArray();
  23703. data.v1 = this.v1.toArray();
  23704. data.v2 = this.v2.toArray();
  23705. return data;
  23706. };
  23707. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  23708. Curve.prototype.fromJSON.call( this, json );
  23709. this.v0.fromArray( json.v0 );
  23710. this.v1.fromArray( json.v1 );
  23711. this.v2.fromArray( json.v2 );
  23712. return this;
  23713. };
  23714. function QuadraticBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23715. Curve.call( this );
  23716. this.type = 'QuadraticBezierCurve3';
  23717. this.v0 = v0;
  23718. this.v1 = v1;
  23719. this.v2 = v2;
  23720. }
  23721. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  23722. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23723. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23724. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23725. const point = optionalTarget;
  23726. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23727. point.set(
  23728. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23729. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23730. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23731. );
  23732. return point;
  23733. };
  23734. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  23735. Curve.prototype.copy.call( this, source );
  23736. this.v0.copy( source.v0 );
  23737. this.v1.copy( source.v1 );
  23738. this.v2.copy( source.v2 );
  23739. return this;
  23740. };
  23741. QuadraticBezierCurve3.prototype.toJSON = function () {
  23742. const data = Curve.prototype.toJSON.call( this );
  23743. data.v0 = this.v0.toArray();
  23744. data.v1 = this.v1.toArray();
  23745. data.v2 = this.v2.toArray();
  23746. return data;
  23747. };
  23748. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  23749. Curve.prototype.fromJSON.call( this, json );
  23750. this.v0.fromArray( json.v0 );
  23751. this.v1.fromArray( json.v1 );
  23752. this.v2.fromArray( json.v2 );
  23753. return this;
  23754. };
  23755. function SplineCurve( points = [] ) {
  23756. Curve.call( this );
  23757. this.type = 'SplineCurve';
  23758. this.points = points;
  23759. }
  23760. SplineCurve.prototype = Object.create( Curve.prototype );
  23761. SplineCurve.prototype.constructor = SplineCurve;
  23762. SplineCurve.prototype.isSplineCurve = true;
  23763. SplineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23764. const point = optionalTarget;
  23765. const points = this.points;
  23766. const p = ( points.length - 1 ) * t;
  23767. const intPoint = Math.floor( p );
  23768. const weight = p - intPoint;
  23769. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23770. const p1 = points[ intPoint ];
  23771. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23772. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23773. point.set(
  23774. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23775. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23776. );
  23777. return point;
  23778. };
  23779. SplineCurve.prototype.copy = function ( source ) {
  23780. Curve.prototype.copy.call( this, source );
  23781. this.points = [];
  23782. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23783. const point = source.points[ i ];
  23784. this.points.push( point.clone() );
  23785. }
  23786. return this;
  23787. };
  23788. SplineCurve.prototype.toJSON = function () {
  23789. const data = Curve.prototype.toJSON.call( this );
  23790. data.points = [];
  23791. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23792. const point = this.points[ i ];
  23793. data.points.push( point.toArray() );
  23794. }
  23795. return data;
  23796. };
  23797. SplineCurve.prototype.fromJSON = function ( json ) {
  23798. Curve.prototype.fromJSON.call( this, json );
  23799. this.points = [];
  23800. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23801. const point = json.points[ i ];
  23802. this.points.push( new Vector2$1().fromArray( point ) );
  23803. }
  23804. return this;
  23805. };
  23806. var Curves = /*#__PURE__*/Object.freeze({
  23807. __proto__: null,
  23808. ArcCurve: ArcCurve,
  23809. CatmullRomCurve3: CatmullRomCurve3,
  23810. CubicBezierCurve: CubicBezierCurve,
  23811. CubicBezierCurve3: CubicBezierCurve3,
  23812. EllipseCurve: EllipseCurve,
  23813. LineCurve: LineCurve,
  23814. LineCurve3: LineCurve3,
  23815. QuadraticBezierCurve: QuadraticBezierCurve,
  23816. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23817. SplineCurve: SplineCurve
  23818. });
  23819. /**************************************************************
  23820. * Curved Path - a curve path is simply a array of connected
  23821. * curves, but retains the api of a curve
  23822. **************************************************************/
  23823. function CurvePath() {
  23824. Curve.call( this );
  23825. this.type = 'CurvePath';
  23826. this.curves = [];
  23827. this.autoClose = false; // Automatically closes the path
  23828. }
  23829. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  23830. constructor: CurvePath,
  23831. add: function ( curve ) {
  23832. this.curves.push( curve );
  23833. },
  23834. closePath: function () {
  23835. // Add a line curve if start and end of lines are not connected
  23836. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23837. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23838. if ( ! startPoint.equals( endPoint ) ) {
  23839. this.curves.push( new LineCurve( endPoint, startPoint ) );
  23840. }
  23841. },
  23842. // To get accurate point with reference to
  23843. // entire path distance at time t,
  23844. // following has to be done:
  23845. // 1. Length of each sub path have to be known
  23846. // 2. Locate and identify type of curve
  23847. // 3. Get t for the curve
  23848. // 4. Return curve.getPointAt(t')
  23849. getPoint: function ( t ) {
  23850. const d = t * this.getLength();
  23851. const curveLengths = this.getCurveLengths();
  23852. let i = 0;
  23853. // To think about boundaries points.
  23854. while ( i < curveLengths.length ) {
  23855. if ( curveLengths[ i ] >= d ) {
  23856. const diff = curveLengths[ i ] - d;
  23857. const curve = this.curves[ i ];
  23858. const segmentLength = curve.getLength();
  23859. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23860. return curve.getPointAt( u );
  23861. }
  23862. i ++;
  23863. }
  23864. return null;
  23865. // loop where sum != 0, sum > d , sum+1 <d
  23866. },
  23867. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23868. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23869. // getPoint() depends on getLength
  23870. getLength: function () {
  23871. const lens = this.getCurveLengths();
  23872. return lens[ lens.length - 1 ];
  23873. },
  23874. // cacheLengths must be recalculated.
  23875. updateArcLengths: function () {
  23876. this.needsUpdate = true;
  23877. this.cacheLengths = null;
  23878. this.getCurveLengths();
  23879. },
  23880. // Compute lengths and cache them
  23881. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23882. getCurveLengths: function () {
  23883. // We use cache values if curves and cache array are same length
  23884. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23885. return this.cacheLengths;
  23886. }
  23887. // Get length of sub-curve
  23888. // Push sums into cached array
  23889. const lengths = [];
  23890. let sums = 0;
  23891. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23892. sums += this.curves[ i ].getLength();
  23893. lengths.push( sums );
  23894. }
  23895. this.cacheLengths = lengths;
  23896. return lengths;
  23897. },
  23898. getSpacedPoints: function ( divisions = 40 ) {
  23899. const points = [];
  23900. for ( let i = 0; i <= divisions; i ++ ) {
  23901. points.push( this.getPoint( i / divisions ) );
  23902. }
  23903. if ( this.autoClose ) {
  23904. points.push( points[ 0 ] );
  23905. }
  23906. return points;
  23907. },
  23908. getPoints: function ( divisions = 12 ) {
  23909. const points = [];
  23910. let last;
  23911. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23912. const curve = curves[ i ];
  23913. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  23914. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  23915. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  23916. : divisions;
  23917. const pts = curve.getPoints( resolution );
  23918. for ( let j = 0; j < pts.length; j ++ ) {
  23919. const point = pts[ j ];
  23920. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23921. points.push( point );
  23922. last = point;
  23923. }
  23924. }
  23925. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23926. points.push( points[ 0 ] );
  23927. }
  23928. return points;
  23929. },
  23930. copy: function ( source ) {
  23931. Curve.prototype.copy.call( this, source );
  23932. this.curves = [];
  23933. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23934. const curve = source.curves[ i ];
  23935. this.curves.push( curve.clone() );
  23936. }
  23937. this.autoClose = source.autoClose;
  23938. return this;
  23939. },
  23940. toJSON: function () {
  23941. const data = Curve.prototype.toJSON.call( this );
  23942. data.autoClose = this.autoClose;
  23943. data.curves = [];
  23944. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23945. const curve = this.curves[ i ];
  23946. data.curves.push( curve.toJSON() );
  23947. }
  23948. return data;
  23949. },
  23950. fromJSON: function ( json ) {
  23951. Curve.prototype.fromJSON.call( this, json );
  23952. this.autoClose = json.autoClose;
  23953. this.curves = [];
  23954. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23955. const curve = json.curves[ i ];
  23956. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23957. }
  23958. return this;
  23959. }
  23960. } );
  23961. function Path( points ) {
  23962. CurvePath.call( this );
  23963. this.type = 'Path';
  23964. this.currentPoint = new Vector2$1();
  23965. if ( points ) {
  23966. this.setFromPoints( points );
  23967. }
  23968. }
  23969. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  23970. constructor: Path,
  23971. setFromPoints: function ( points ) {
  23972. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23973. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23974. this.lineTo( points[ i ].x, points[ i ].y );
  23975. }
  23976. return this;
  23977. },
  23978. moveTo: function ( x, y ) {
  23979. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23980. return this;
  23981. },
  23982. lineTo: function ( x, y ) {
  23983. const curve = new LineCurve( this.currentPoint.clone(), new Vector2$1( x, y ) );
  23984. this.curves.push( curve );
  23985. this.currentPoint.set( x, y );
  23986. return this;
  23987. },
  23988. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  23989. const curve = new QuadraticBezierCurve(
  23990. this.currentPoint.clone(),
  23991. new Vector2$1( aCPx, aCPy ),
  23992. new Vector2$1( aX, aY )
  23993. );
  23994. this.curves.push( curve );
  23995. this.currentPoint.set( aX, aY );
  23996. return this;
  23997. },
  23998. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23999. const curve = new CubicBezierCurve(
  24000. this.currentPoint.clone(),
  24001. new Vector2$1( aCP1x, aCP1y ),
  24002. new Vector2$1( aCP2x, aCP2y ),
  24003. new Vector2$1( aX, aY )
  24004. );
  24005. this.curves.push( curve );
  24006. this.currentPoint.set( aX, aY );
  24007. return this;
  24008. },
  24009. splineThru: function ( pts /*Array of Vector*/ ) {
  24010. const npts = [ this.currentPoint.clone() ].concat( pts );
  24011. const curve = new SplineCurve( npts );
  24012. this.curves.push( curve );
  24013. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24014. return this;
  24015. },
  24016. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24017. const x0 = this.currentPoint.x;
  24018. const y0 = this.currentPoint.y;
  24019. this.absarc( aX + x0, aY + y0, aRadius,
  24020. aStartAngle, aEndAngle, aClockwise );
  24021. return this;
  24022. },
  24023. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24024. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24025. return this;
  24026. },
  24027. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24028. const x0 = this.currentPoint.x;
  24029. const y0 = this.currentPoint.y;
  24030. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24031. return this;
  24032. },
  24033. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24034. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24035. if ( this.curves.length > 0 ) {
  24036. // if a previous curve is present, attempt to join
  24037. const firstPoint = curve.getPoint( 0 );
  24038. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24039. this.lineTo( firstPoint.x, firstPoint.y );
  24040. }
  24041. }
  24042. this.curves.push( curve );
  24043. const lastPoint = curve.getPoint( 1 );
  24044. this.currentPoint.copy( lastPoint );
  24045. return this;
  24046. },
  24047. copy: function ( source ) {
  24048. CurvePath.prototype.copy.call( this, source );
  24049. this.currentPoint.copy( source.currentPoint );
  24050. return this;
  24051. },
  24052. toJSON: function () {
  24053. const data = CurvePath.prototype.toJSON.call( this );
  24054. data.currentPoint = this.currentPoint.toArray();
  24055. return data;
  24056. },
  24057. fromJSON: function ( json ) {
  24058. CurvePath.prototype.fromJSON.call( this, json );
  24059. this.currentPoint.fromArray( json.currentPoint );
  24060. return this;
  24061. }
  24062. } );
  24063. function Shape( points ) {
  24064. Path.call( this, points );
  24065. this.uuid = MathUtils.generateUUID();
  24066. this.type = 'Shape';
  24067. this.holes = [];
  24068. }
  24069. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  24070. constructor: Shape,
  24071. getPointsHoles: function ( divisions ) {
  24072. const holesPts = [];
  24073. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24074. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24075. }
  24076. return holesPts;
  24077. },
  24078. // get points of shape and holes (keypoints based on segments parameter)
  24079. extractPoints: function ( divisions ) {
  24080. return {
  24081. shape: this.getPoints( divisions ),
  24082. holes: this.getPointsHoles( divisions )
  24083. };
  24084. },
  24085. copy: function ( source ) {
  24086. Path.prototype.copy.call( this, source );
  24087. this.holes = [];
  24088. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24089. const hole = source.holes[ i ];
  24090. this.holes.push( hole.clone() );
  24091. }
  24092. return this;
  24093. },
  24094. toJSON: function () {
  24095. const data = Path.prototype.toJSON.call( this );
  24096. data.uuid = this.uuid;
  24097. data.holes = [];
  24098. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24099. const hole = this.holes[ i ];
  24100. data.holes.push( hole.toJSON() );
  24101. }
  24102. return data;
  24103. },
  24104. fromJSON: function ( json ) {
  24105. Path.prototype.fromJSON.call( this, json );
  24106. this.uuid = json.uuid;
  24107. this.holes = [];
  24108. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24109. const hole = json.holes[ i ];
  24110. this.holes.push( new Path().fromJSON( hole ) );
  24111. }
  24112. return this;
  24113. }
  24114. } );
  24115. function Light( color, intensity = 1 ) {
  24116. Object3D.call( this );
  24117. this.type = 'Light';
  24118. this.color = new Color( color );
  24119. this.intensity = intensity;
  24120. }
  24121. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24122. constructor: Light,
  24123. isLight: true,
  24124. copy: function ( source ) {
  24125. Object3D.prototype.copy.call( this, source );
  24126. this.color.copy( source.color );
  24127. this.intensity = source.intensity;
  24128. return this;
  24129. },
  24130. toJSON: function ( meta ) {
  24131. const data = Object3D.prototype.toJSON.call( this, meta );
  24132. data.object.color = this.color.getHex();
  24133. data.object.intensity = this.intensity;
  24134. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24135. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24136. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24137. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24138. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24139. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24140. return data;
  24141. }
  24142. } );
  24143. function HemisphereLight( skyColor, groundColor, intensity ) {
  24144. Light.call( this, skyColor, intensity );
  24145. this.type = 'HemisphereLight';
  24146. this.position.copy( Object3D.DefaultUp );
  24147. this.updateMatrix();
  24148. this.groundColor = new Color( groundColor );
  24149. }
  24150. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24151. constructor: HemisphereLight,
  24152. isHemisphereLight: true,
  24153. copy: function ( source ) {
  24154. Light.prototype.copy.call( this, source );
  24155. this.groundColor.copy( source.groundColor );
  24156. return this;
  24157. }
  24158. } );
  24159. function LightShadow( camera ) {
  24160. this.camera = camera;
  24161. this.bias = 0;
  24162. this.normalBias = 0;
  24163. this.radius = 1;
  24164. this.mapSize = new Vector2$1( 512, 512 );
  24165. this.map = null;
  24166. this.mapPass = null;
  24167. this.matrix = new Matrix4();
  24168. this.autoUpdate = true;
  24169. this.needsUpdate = false;
  24170. this._frustum = new Frustum();
  24171. this._frameExtents = new Vector2$1( 1, 1 );
  24172. this._viewportCount = 1;
  24173. this._viewports = [
  24174. new Vector4( 0, 0, 1, 1 )
  24175. ];
  24176. }
  24177. Object.assign( LightShadow.prototype, {
  24178. _projScreenMatrix: new Matrix4(),
  24179. _lightPositionWorld: new Vector3(),
  24180. _lookTarget: new Vector3(),
  24181. getViewportCount: function () {
  24182. return this._viewportCount;
  24183. },
  24184. getFrustum: function () {
  24185. return this._frustum;
  24186. },
  24187. updateMatrices: function ( light ) {
  24188. const shadowCamera = this.camera,
  24189. shadowMatrix = this.matrix,
  24190. projScreenMatrix = this._projScreenMatrix,
  24191. lookTarget = this._lookTarget,
  24192. lightPositionWorld = this._lightPositionWorld;
  24193. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24194. shadowCamera.position.copy( lightPositionWorld );
  24195. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  24196. shadowCamera.lookAt( lookTarget );
  24197. shadowCamera.updateMatrixWorld();
  24198. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24199. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  24200. shadowMatrix.set(
  24201. 0.5, 0.0, 0.0, 0.5,
  24202. 0.0, 0.5, 0.0, 0.5,
  24203. 0.0, 0.0, 0.5, 0.5,
  24204. 0.0, 0.0, 0.0, 1.0
  24205. );
  24206. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24207. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24208. },
  24209. getViewport: function ( viewportIndex ) {
  24210. return this._viewports[ viewportIndex ];
  24211. },
  24212. getFrameExtents: function () {
  24213. return this._frameExtents;
  24214. },
  24215. copy: function ( source ) {
  24216. this.camera = source.camera.clone();
  24217. this.bias = source.bias;
  24218. this.radius = source.radius;
  24219. this.mapSize.copy( source.mapSize );
  24220. return this;
  24221. },
  24222. clone: function () {
  24223. return new this.constructor().copy( this );
  24224. },
  24225. toJSON: function () {
  24226. const object = {};
  24227. if ( this.bias !== 0 ) object.bias = this.bias;
  24228. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24229. if ( this.radius !== 1 ) object.radius = this.radius;
  24230. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24231. object.camera = this.camera.toJSON( false ).object;
  24232. delete object.camera.matrix;
  24233. return object;
  24234. }
  24235. } );
  24236. function SpotLightShadow() {
  24237. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24238. this.focus = 1;
  24239. }
  24240. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24241. constructor: SpotLightShadow,
  24242. isSpotLightShadow: true,
  24243. updateMatrices: function ( light ) {
  24244. const camera = this.camera;
  24245. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  24246. const aspect = this.mapSize.width / this.mapSize.height;
  24247. const far = light.distance || camera.far;
  24248. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24249. camera.fov = fov;
  24250. camera.aspect = aspect;
  24251. camera.far = far;
  24252. camera.updateProjectionMatrix();
  24253. }
  24254. LightShadow.prototype.updateMatrices.call( this, light );
  24255. }
  24256. } );
  24257. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  24258. Light.call( this, color, intensity );
  24259. this.type = 'SpotLight';
  24260. this.position.copy( Object3D.DefaultUp );
  24261. this.updateMatrix();
  24262. this.target = new Object3D();
  24263. Object.defineProperty( this, 'power', {
  24264. get: function () {
  24265. // intensity = power per solid angle.
  24266. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24267. return this.intensity * Math.PI;
  24268. },
  24269. set: function ( power ) {
  24270. // intensity = power per solid angle.
  24271. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24272. this.intensity = power / Math.PI;
  24273. }
  24274. } );
  24275. this.distance = ( distance !== undefined ) ? distance : 0;
  24276. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  24277. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  24278. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24279. this.shadow = new SpotLightShadow();
  24280. }
  24281. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24282. constructor: SpotLight,
  24283. isSpotLight: true,
  24284. copy: function ( source ) {
  24285. Light.prototype.copy.call( this, source );
  24286. this.distance = source.distance;
  24287. this.angle = source.angle;
  24288. this.penumbra = source.penumbra;
  24289. this.decay = source.decay;
  24290. this.target = source.target.clone();
  24291. this.shadow = source.shadow.clone();
  24292. return this;
  24293. }
  24294. } );
  24295. function PointLightShadow() {
  24296. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24297. this._frameExtents = new Vector2$1( 4, 2 );
  24298. this._viewportCount = 6;
  24299. this._viewports = [
  24300. // These viewports map a cube-map onto a 2D texture with the
  24301. // following orientation:
  24302. //
  24303. // xzXZ
  24304. // y Y
  24305. //
  24306. // X - Positive x direction
  24307. // x - Negative x direction
  24308. // Y - Positive y direction
  24309. // y - Negative y direction
  24310. // Z - Positive z direction
  24311. // z - Negative z direction
  24312. // positive X
  24313. new Vector4( 2, 1, 1, 1 ),
  24314. // negative X
  24315. new Vector4( 0, 1, 1, 1 ),
  24316. // positive Z
  24317. new Vector4( 3, 1, 1, 1 ),
  24318. // negative Z
  24319. new Vector4( 1, 1, 1, 1 ),
  24320. // positive Y
  24321. new Vector4( 3, 0, 1, 1 ),
  24322. // negative Y
  24323. new Vector4( 1, 0, 1, 1 )
  24324. ];
  24325. this._cubeDirections = [
  24326. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24327. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24328. ];
  24329. this._cubeUps = [
  24330. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24331. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24332. ];
  24333. }
  24334. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24335. constructor: PointLightShadow,
  24336. isPointLightShadow: true,
  24337. updateMatrices: function ( light, viewportIndex = 0 ) {
  24338. const camera = this.camera,
  24339. shadowMatrix = this.matrix,
  24340. lightPositionWorld = this._lightPositionWorld,
  24341. lookTarget = this._lookTarget,
  24342. projScreenMatrix = this._projScreenMatrix;
  24343. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24344. camera.position.copy( lightPositionWorld );
  24345. lookTarget.copy( camera.position );
  24346. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24347. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24348. camera.lookAt( lookTarget );
  24349. camera.updateMatrixWorld();
  24350. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  24351. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24352. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  24353. }
  24354. } );
  24355. function PointLight( color, intensity, distance, decay ) {
  24356. Light.call( this, color, intensity );
  24357. this.type = 'PointLight';
  24358. Object.defineProperty( this, 'power', {
  24359. get: function () {
  24360. // intensity = power per solid angle.
  24361. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24362. return this.intensity * 4 * Math.PI;
  24363. },
  24364. set: function ( power ) {
  24365. // intensity = power per solid angle.
  24366. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24367. this.intensity = power / ( 4 * Math.PI );
  24368. }
  24369. } );
  24370. this.distance = ( distance !== undefined ) ? distance : 0;
  24371. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24372. this.shadow = new PointLightShadow();
  24373. }
  24374. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24375. constructor: PointLight,
  24376. isPointLight: true,
  24377. copy: function ( source ) {
  24378. Light.prototype.copy.call( this, source );
  24379. this.distance = source.distance;
  24380. this.decay = source.decay;
  24381. this.shadow = source.shadow.clone();
  24382. return this;
  24383. }
  24384. } );
  24385. function OrthographicCamera( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  24386. Camera.call( this );
  24387. this.type = 'OrthographicCamera';
  24388. this.zoom = 1;
  24389. this.view = null;
  24390. this.left = left;
  24391. this.right = right;
  24392. this.top = top;
  24393. this.bottom = bottom;
  24394. this.near = near;
  24395. this.far = far;
  24396. this.updateProjectionMatrix();
  24397. }
  24398. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  24399. constructor: OrthographicCamera,
  24400. isOrthographicCamera: true,
  24401. copy: function ( source, recursive ) {
  24402. Camera.prototype.copy.call( this, source, recursive );
  24403. this.left = source.left;
  24404. this.right = source.right;
  24405. this.top = source.top;
  24406. this.bottom = source.bottom;
  24407. this.near = source.near;
  24408. this.far = source.far;
  24409. this.zoom = source.zoom;
  24410. this.view = source.view === null ? null : Object.assign( {}, source.view );
  24411. return this;
  24412. },
  24413. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  24414. if ( this.view === null ) {
  24415. this.view = {
  24416. enabled: true,
  24417. fullWidth: 1,
  24418. fullHeight: 1,
  24419. offsetX: 0,
  24420. offsetY: 0,
  24421. width: 1,
  24422. height: 1
  24423. };
  24424. }
  24425. this.view.enabled = true;
  24426. this.view.fullWidth = fullWidth;
  24427. this.view.fullHeight = fullHeight;
  24428. this.view.offsetX = x;
  24429. this.view.offsetY = y;
  24430. this.view.width = width;
  24431. this.view.height = height;
  24432. this.updateProjectionMatrix();
  24433. },
  24434. clearViewOffset: function () {
  24435. if ( this.view !== null ) {
  24436. this.view.enabled = false;
  24437. }
  24438. this.updateProjectionMatrix();
  24439. },
  24440. updateProjectionMatrix: function () {
  24441. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  24442. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  24443. const cx = ( this.right + this.left ) / 2;
  24444. const cy = ( this.top + this.bottom ) / 2;
  24445. let left = cx - dx;
  24446. let right = cx + dx;
  24447. let top = cy + dy;
  24448. let bottom = cy - dy;
  24449. if ( this.view !== null && this.view.enabled ) {
  24450. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  24451. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  24452. left += scaleW * this.view.offsetX;
  24453. right = left + scaleW * this.view.width;
  24454. top -= scaleH * this.view.offsetY;
  24455. bottom = top - scaleH * this.view.height;
  24456. }
  24457. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  24458. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  24459. },
  24460. toJSON: function ( meta ) {
  24461. const data = Object3D.prototype.toJSON.call( this, meta );
  24462. data.object.zoom = this.zoom;
  24463. data.object.left = this.left;
  24464. data.object.right = this.right;
  24465. data.object.top = this.top;
  24466. data.object.bottom = this.bottom;
  24467. data.object.near = this.near;
  24468. data.object.far = this.far;
  24469. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  24470. return data;
  24471. }
  24472. } );
  24473. function DirectionalLightShadow() {
  24474. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24475. }
  24476. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24477. constructor: DirectionalLightShadow,
  24478. isDirectionalLightShadow: true,
  24479. updateMatrices: function ( light ) {
  24480. LightShadow.prototype.updateMatrices.call( this, light );
  24481. }
  24482. } );
  24483. function DirectionalLight( color, intensity ) {
  24484. Light.call( this, color, intensity );
  24485. this.type = 'DirectionalLight';
  24486. this.position.copy( Object3D.DefaultUp );
  24487. this.updateMatrix();
  24488. this.target = new Object3D();
  24489. this.shadow = new DirectionalLightShadow();
  24490. }
  24491. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24492. constructor: DirectionalLight,
  24493. isDirectionalLight: true,
  24494. copy: function ( source ) {
  24495. Light.prototype.copy.call( this, source );
  24496. this.target = source.target.clone();
  24497. this.shadow = source.shadow.clone();
  24498. return this;
  24499. }
  24500. } );
  24501. function AmbientLight( color, intensity ) {
  24502. Light.call( this, color, intensity );
  24503. this.type = 'AmbientLight';
  24504. }
  24505. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24506. constructor: AmbientLight,
  24507. isAmbientLight: true
  24508. } );
  24509. function RectAreaLight( color, intensity, width, height ) {
  24510. Light.call( this, color, intensity );
  24511. this.type = 'RectAreaLight';
  24512. this.width = ( width !== undefined ) ? width : 10;
  24513. this.height = ( height !== undefined ) ? height : 10;
  24514. }
  24515. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24516. constructor: RectAreaLight,
  24517. isRectAreaLight: true,
  24518. copy: function ( source ) {
  24519. Light.prototype.copy.call( this, source );
  24520. this.width = source.width;
  24521. this.height = source.height;
  24522. return this;
  24523. },
  24524. toJSON: function ( meta ) {
  24525. const data = Light.prototype.toJSON.call( this, meta );
  24526. data.object.width = this.width;
  24527. data.object.height = this.height;
  24528. return data;
  24529. }
  24530. } );
  24531. /**
  24532. * Primary reference:
  24533. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24534. *
  24535. * Secondary reference:
  24536. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24537. */
  24538. // 3-band SH defined by 9 coefficients
  24539. class SphericalHarmonics3 {
  24540. constructor() {
  24541. Object.defineProperty( this, 'isSphericalHarmonics3', { value: true } );
  24542. this.coefficients = [];
  24543. for ( let i = 0; i < 9; i ++ ) {
  24544. this.coefficients.push( new Vector3() );
  24545. }
  24546. }
  24547. set( coefficients ) {
  24548. for ( let i = 0; i < 9; i ++ ) {
  24549. this.coefficients[ i ].copy( coefficients[ i ] );
  24550. }
  24551. return this;
  24552. }
  24553. zero() {
  24554. for ( let i = 0; i < 9; i ++ ) {
  24555. this.coefficients[ i ].set( 0, 0, 0 );
  24556. }
  24557. return this;
  24558. }
  24559. // get the radiance in the direction of the normal
  24560. // target is a Vector3
  24561. getAt( normal, target ) {
  24562. // normal is assumed to be unit length
  24563. const x = normal.x, y = normal.y, z = normal.z;
  24564. const coeff = this.coefficients;
  24565. // band 0
  24566. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24567. // band 1
  24568. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24569. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24570. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24571. // band 2
  24572. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24573. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24574. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24575. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24576. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24577. return target;
  24578. }
  24579. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24580. // target is a Vector3
  24581. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24582. getIrradianceAt( normal, target ) {
  24583. // normal is assumed to be unit length
  24584. const x = normal.x, y = normal.y, z = normal.z;
  24585. const coeff = this.coefficients;
  24586. // band 0
  24587. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24588. // band 1
  24589. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24590. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24591. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24592. // band 2
  24593. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24594. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24595. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24596. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24597. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24598. return target;
  24599. }
  24600. add( sh ) {
  24601. for ( let i = 0; i < 9; i ++ ) {
  24602. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24603. }
  24604. return this;
  24605. }
  24606. addScaledSH( sh, s ) {
  24607. for ( let i = 0; i < 9; i ++ ) {
  24608. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24609. }
  24610. return this;
  24611. }
  24612. scale( s ) {
  24613. for ( let i = 0; i < 9; i ++ ) {
  24614. this.coefficients[ i ].multiplyScalar( s );
  24615. }
  24616. return this;
  24617. }
  24618. lerp( sh, alpha ) {
  24619. for ( let i = 0; i < 9; i ++ ) {
  24620. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24621. }
  24622. return this;
  24623. }
  24624. equals( sh ) {
  24625. for ( let i = 0; i < 9; i ++ ) {
  24626. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24627. return false;
  24628. }
  24629. }
  24630. return true;
  24631. }
  24632. copy( sh ) {
  24633. return this.set( sh.coefficients );
  24634. }
  24635. clone() {
  24636. return new this.constructor().copy( this );
  24637. }
  24638. fromArray( array, offset = 0 ) {
  24639. const coefficients = this.coefficients;
  24640. for ( let i = 0; i < 9; i ++ ) {
  24641. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24642. }
  24643. return this;
  24644. }
  24645. toArray( array = [], offset = 0 ) {
  24646. const coefficients = this.coefficients;
  24647. for ( let i = 0; i < 9; i ++ ) {
  24648. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24649. }
  24650. return array;
  24651. }
  24652. // evaluate the basis functions
  24653. // shBasis is an Array[ 9 ]
  24654. static getBasisAt( normal, shBasis ) {
  24655. // normal is assumed to be unit length
  24656. const x = normal.x, y = normal.y, z = normal.z;
  24657. // band 0
  24658. shBasis[ 0 ] = 0.282095;
  24659. // band 1
  24660. shBasis[ 1 ] = 0.488603 * y;
  24661. shBasis[ 2 ] = 0.488603 * z;
  24662. shBasis[ 3 ] = 0.488603 * x;
  24663. // band 2
  24664. shBasis[ 4 ] = 1.092548 * x * y;
  24665. shBasis[ 5 ] = 1.092548 * y * z;
  24666. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24667. shBasis[ 7 ] = 1.092548 * x * z;
  24668. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24669. }
  24670. }
  24671. function LightProbe( sh, intensity ) {
  24672. Light.call( this, undefined, intensity );
  24673. this.type = 'LightProbe';
  24674. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  24675. }
  24676. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  24677. constructor: LightProbe,
  24678. isLightProbe: true,
  24679. copy: function ( source ) {
  24680. Light.prototype.copy.call( this, source );
  24681. this.sh.copy( source.sh );
  24682. return this;
  24683. },
  24684. fromJSON: function ( json ) {
  24685. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24686. this.sh.fromArray( json.sh );
  24687. return this;
  24688. },
  24689. toJSON: function ( meta ) {
  24690. const data = Light.prototype.toJSON.call( this, meta );
  24691. data.object.sh = this.sh.toArray();
  24692. return data;
  24693. }
  24694. } );
  24695. function MaterialLoader( manager ) {
  24696. Loader.call( this, manager );
  24697. this.textures = {};
  24698. }
  24699. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24700. constructor: MaterialLoader,
  24701. load: function ( url, onLoad, onProgress, onError ) {
  24702. const scope = this;
  24703. const loader = new FileLoader( scope.manager );
  24704. loader.setPath( scope.path );
  24705. loader.setRequestHeader( scope.requestHeader );
  24706. loader.setWithCredentials( scope.withCredentials );
  24707. loader.load( url, function ( text ) {
  24708. try {
  24709. onLoad( scope.parse( JSON.parse( text ) ) );
  24710. } catch ( e ) {
  24711. if ( onError ) {
  24712. onError( e );
  24713. } else {
  24714. console.error( e );
  24715. }
  24716. scope.manager.itemError( url );
  24717. }
  24718. }, onProgress, onError );
  24719. },
  24720. parse: function ( json ) {
  24721. const textures = this.textures;
  24722. function getTexture( name ) {
  24723. if ( textures[ name ] === undefined ) {
  24724. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24725. }
  24726. return textures[ name ];
  24727. }
  24728. const material = new Materials[ json.type ]();
  24729. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24730. if ( json.name !== undefined ) material.name = json.name;
  24731. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24732. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24733. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24734. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  24735. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24736. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24737. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24738. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24739. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24740. if ( json.fog !== undefined ) material.fog = json.fog;
  24741. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24742. if ( json.blending !== undefined ) material.blending = json.blending;
  24743. if ( json.combine !== undefined ) material.combine = json.combine;
  24744. if ( json.side !== undefined ) material.side = json.side;
  24745. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24746. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24747. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24748. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24749. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24750. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24751. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24752. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24753. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24754. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24755. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24756. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24757. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24758. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24759. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24760. if ( json.wireframelineWidth !== undefined ) material.wireframelineWidth = json.wireframelineWidth;
  24761. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24762. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24763. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24764. if ( json.lineWidth !== 1 ) material.lineWidth = json.lineWidth;
  24765. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24766. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24767. if ( json.scale !== undefined ) material.scale = json.scale;
  24768. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24769. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24770. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24771. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  24772. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  24773. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  24774. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24775. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  24776. if ( json.visible !== undefined ) material.visible = json.visible;
  24777. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24778. if ( json.userData !== undefined ) material.userData = json.userData;
  24779. if ( json.vertexColors !== undefined ) {
  24780. if ( typeof json.vertexColors === 'number' ) {
  24781. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24782. } else {
  24783. material.vertexColors = json.vertexColors;
  24784. }
  24785. }
  24786. // Shader Material
  24787. if ( json.uniforms !== undefined ) {
  24788. for ( const name in json.uniforms ) {
  24789. const uniform = json.uniforms[ name ];
  24790. material.uniforms[ name ] = {};
  24791. switch ( uniform.type ) {
  24792. case 't':
  24793. material.uniforms[ name ].value = getTexture( uniform.value );
  24794. break;
  24795. case 'c':
  24796. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24797. break;
  24798. case 'v2':
  24799. material.uniforms[ name ].value = new Vector2$1().fromArray( uniform.value );
  24800. break;
  24801. case 'v3':
  24802. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24803. break;
  24804. case 'v4':
  24805. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24806. break;
  24807. case 'm3':
  24808. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24809. break;
  24810. case 'm4':
  24811. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24812. break;
  24813. default:
  24814. material.uniforms[ name ].value = uniform.value;
  24815. }
  24816. }
  24817. }
  24818. if ( json.defines !== undefined ) material.defines = json.defines;
  24819. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24820. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24821. if ( json.extensions !== undefined ) {
  24822. for ( const key in json.extensions ) {
  24823. material.extensions[ key ] = json.extensions[ key ];
  24824. }
  24825. }
  24826. // Deprecated
  24827. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24828. // for PointsMaterial
  24829. if ( json.size !== undefined ) material.size = json.size;
  24830. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24831. // maps
  24832. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24833. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24834. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24835. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24836. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24837. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24838. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24839. if ( json.normalScale !== undefined ) {
  24840. let normalScale = json.normalScale;
  24841. if ( Array.isArray( normalScale ) === false ) {
  24842. // Blender exporter used to export a scalar. See #7459
  24843. normalScale = [ normalScale, normalScale ];
  24844. }
  24845. material.normalScale = new Vector2$1().fromArray( normalScale );
  24846. }
  24847. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24848. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24849. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24850. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24851. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24852. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24853. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24854. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24855. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24856. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24857. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24858. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24859. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24860. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24861. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24862. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24863. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24864. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24865. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24866. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24867. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2$1().fromArray( json.clearcoatNormalScale );
  24868. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24869. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24870. return material;
  24871. },
  24872. setTextures: function ( value ) {
  24873. this.textures = value;
  24874. return this;
  24875. }
  24876. } );
  24877. const LoaderUtils = {
  24878. decodeText: function ( array ) {
  24879. if ( typeof TextDecoder !== 'undefined' ) {
  24880. return new TextDecoder().decode( array );
  24881. }
  24882. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24883. // throws a "maximum call stack size exceeded" error for large arrays.
  24884. let s = '';
  24885. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24886. // Implicitly assumes little-endian.
  24887. s += String.fromCharCode( array[ i ] );
  24888. }
  24889. try {
  24890. // merges multi-byte utf-8 characters.
  24891. return decodeURIComponent( escape( s ) );
  24892. } catch ( e ) { // see #16358
  24893. return s;
  24894. }
  24895. },
  24896. extractUrlBase: function ( url ) {
  24897. const index = url.lastIndexOf( '/' );
  24898. if ( index === - 1 ) return './';
  24899. return url.substr( 0, index + 1 );
  24900. }
  24901. };
  24902. function InstancedBufferGeometry() {
  24903. BufferGeometry.call( this );
  24904. this.type = 'InstancedBufferGeometry';
  24905. this.instanceCount = Infinity;
  24906. }
  24907. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  24908. constructor: InstancedBufferGeometry,
  24909. isInstancedBufferGeometry: true,
  24910. copy: function ( source ) {
  24911. BufferGeometry.prototype.copy.call( this, source );
  24912. this.instanceCount = source.instanceCount;
  24913. return this;
  24914. },
  24915. clone: function () {
  24916. return new this.constructor().copy( this );
  24917. },
  24918. toJSON: function () {
  24919. const data = BufferGeometry.prototype.toJSON.call( this );
  24920. data.instanceCount = this.instanceCount;
  24921. data.isInstancedBufferGeometry = true;
  24922. return data;
  24923. }
  24924. } );
  24925. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  24926. if ( typeof ( normalized ) === 'number' ) {
  24927. meshPerAttribute = normalized;
  24928. normalized = false;
  24929. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  24930. }
  24931. BufferAttribute.call( this, array, itemSize, normalized );
  24932. this.meshPerAttribute = meshPerAttribute || 1;
  24933. }
  24934. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24935. constructor: InstancedBufferAttribute,
  24936. isInstancedBufferAttribute: true,
  24937. copy: function ( source ) {
  24938. BufferAttribute.prototype.copy.call( this, source );
  24939. this.meshPerAttribute = source.meshPerAttribute;
  24940. return this;
  24941. },
  24942. toJSON: function () {
  24943. const data = BufferAttribute.prototype.toJSON.call( this );
  24944. data.meshPerAttribute = this.meshPerAttribute;
  24945. data.isInstancedBufferAttribute = true;
  24946. return data;
  24947. }
  24948. } );
  24949. function BufferGeometryLoader( manager ) {
  24950. Loader.call( this, manager );
  24951. }
  24952. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24953. constructor: BufferGeometryLoader,
  24954. load: function ( url, onLoad, onProgress, onError ) {
  24955. const scope = this;
  24956. const loader = new FileLoader( scope.manager );
  24957. loader.setPath( scope.path );
  24958. loader.setRequestHeader( scope.requestHeader );
  24959. loader.setWithCredentials( scope.withCredentials );
  24960. loader.load( url, function ( text ) {
  24961. try {
  24962. onLoad( scope.parse( JSON.parse( text ) ) );
  24963. } catch ( e ) {
  24964. if ( onError ) {
  24965. onError( e );
  24966. } else {
  24967. console.error( e );
  24968. }
  24969. scope.manager.itemError( url );
  24970. }
  24971. }, onProgress, onError );
  24972. },
  24973. parse: function ( json ) {
  24974. const interleavedBufferMap = {};
  24975. const arrayBufferMap = {};
  24976. function getInterleavedBuffer( json, uuid ) {
  24977. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24978. const interleavedBuffers = json.interleavedBuffers;
  24979. const interleavedBuffer = interleavedBuffers[ uuid ];
  24980. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24981. const array = getTypedArray( interleavedBuffer.type, buffer );
  24982. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24983. ib.uuid = interleavedBuffer.uuid;
  24984. interleavedBufferMap[ uuid ] = ib;
  24985. return ib;
  24986. }
  24987. function getArrayBuffer( json, uuid ) {
  24988. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24989. const arrayBuffers = json.arrayBuffers;
  24990. const arrayBuffer = arrayBuffers[ uuid ];
  24991. const ab = new Uint32Array( arrayBuffer ).buffer;
  24992. arrayBufferMap[ uuid ] = ab;
  24993. return ab;
  24994. }
  24995. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24996. const index = json.data.index;
  24997. if ( index !== undefined ) {
  24998. const typedArray = getTypedArray( index.type, index.array );
  24999. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25000. }
  25001. const attributes = json.data.attributes;
  25002. for ( const key in attributes ) {
  25003. const attribute = attributes[ key ];
  25004. let bufferAttribute;
  25005. if ( attribute.isInterleavedBufferAttribute ) {
  25006. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25007. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25008. } else {
  25009. const typedArray = getTypedArray( attribute.type, attribute.array );
  25010. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25011. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25012. }
  25013. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25014. geometry.setAttribute( key, bufferAttribute );
  25015. }
  25016. const morphAttributes = json.data.morphAttributes;
  25017. if ( morphAttributes ) {
  25018. for ( const key in morphAttributes ) {
  25019. const attributeArray = morphAttributes[ key ];
  25020. const array = [];
  25021. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25022. const attribute = attributeArray[ i ];
  25023. let bufferAttribute;
  25024. if ( attribute.isInterleavedBufferAttribute ) {
  25025. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25026. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25027. } else {
  25028. const typedArray = getTypedArray( attribute.type, attribute.array );
  25029. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25030. }
  25031. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25032. array.push( bufferAttribute );
  25033. }
  25034. geometry.morphAttributes[ key ] = array;
  25035. }
  25036. }
  25037. const morphTargetsRelative = json.data.morphTargetsRelative;
  25038. if ( morphTargetsRelative ) {
  25039. geometry.morphTargetsRelative = true;
  25040. }
  25041. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25042. if ( groups !== undefined ) {
  25043. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25044. const group = groups[ i ];
  25045. geometry.addGroup( group.start, group.count, group.materialIndex );
  25046. }
  25047. }
  25048. const boundingSphere = json.data.boundingSphere;
  25049. if ( boundingSphere !== undefined ) {
  25050. const center = new Vector3();
  25051. if ( boundingSphere.center !== undefined ) {
  25052. center.fromArray( boundingSphere.center );
  25053. }
  25054. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25055. }
  25056. if ( json.name ) geometry.name = json.name;
  25057. if ( json.userData ) geometry.userData = json.userData;
  25058. return geometry;
  25059. }
  25060. } );
  25061. class ObjectLoader extends Loader {
  25062. constructor( manager ) {
  25063. super( manager );
  25064. }
  25065. load( url, onLoad, onProgress, onError ) {
  25066. const scope = this;
  25067. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25068. this.resourcePath = this.resourcePath || path;
  25069. const loader = new FileLoader( this.manager );
  25070. loader.setPath( this.path );
  25071. loader.setRequestHeader( this.requestHeader );
  25072. loader.setWithCredentials( this.withCredentials );
  25073. loader.load( url, function ( text ) {
  25074. let json = null;
  25075. try {
  25076. json = JSON.parse( text );
  25077. } catch ( error ) {
  25078. if ( onError !== undefined ) onError( error );
  25079. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25080. return;
  25081. }
  25082. const metadata = json.metadata;
  25083. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25084. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25085. return;
  25086. }
  25087. scope.parse( json, onLoad );
  25088. }, onProgress, onError );
  25089. }
  25090. parse( json, onLoad ) {
  25091. const animations = this.parseAnimations( json.animations );
  25092. const shapes = this.parseShapes( json.shapes );
  25093. const geometries = this.parseGeometries( json.geometries, shapes );
  25094. const images = this.parseImages( json.images, function () {
  25095. if ( onLoad !== undefined ) onLoad( object );
  25096. } );
  25097. const textures = this.parseTextures( json.textures, images );
  25098. const materials = this.parseMaterials( json.materials, textures );
  25099. const object = this.parseObject( json.object, geometries, materials, animations );
  25100. const skeletons = this.parseSkeletons( json.skeletons, object );
  25101. this.bindSkeletons( object, skeletons );
  25102. //
  25103. if ( onLoad !== undefined ) {
  25104. let hasImages = false;
  25105. for ( const uuid in images ) {
  25106. if ( images[ uuid ] instanceof HTMLImageElement ) {
  25107. hasImages = true;
  25108. break;
  25109. }
  25110. }
  25111. if ( hasImages === false ) onLoad( object );
  25112. }
  25113. return object;
  25114. }
  25115. parseShapes( json ) {
  25116. const shapes = {};
  25117. if ( json !== undefined ) {
  25118. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25119. const shape = new Shape().fromJSON( json[ i ] );
  25120. shapes[ shape.uuid ] = shape;
  25121. }
  25122. }
  25123. return shapes;
  25124. }
  25125. parseSkeletons( json, object ) {
  25126. const skeletons = {};
  25127. const bones = {};
  25128. // generate bone lookup table
  25129. object.traverse( function ( child ) {
  25130. if ( child.isBone ) bones[ child.uuid ] = child;
  25131. } );
  25132. // create skeletons
  25133. if ( json !== undefined ) {
  25134. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25135. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25136. skeletons[ skeleton.uuid ] = skeleton;
  25137. }
  25138. }
  25139. return skeletons;
  25140. }
  25141. parseGeometries( json, shapes ) {
  25142. const geometries = {};
  25143. let geometryShapes;
  25144. if ( json !== undefined ) {
  25145. const bufferGeometryLoader = new BufferGeometryLoader();
  25146. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25147. let geometry;
  25148. const data = json[ i ];
  25149. switch ( data.type ) {
  25150. case 'PlaneGeometry':
  25151. case 'PlaneBufferGeometry':
  25152. geometry = new Geometries[ data.type ](
  25153. data.width,
  25154. data.height,
  25155. data.widthSegments,
  25156. data.heightSegments
  25157. );
  25158. break;
  25159. case 'BoxGeometry':
  25160. case 'BoxBufferGeometry':
  25161. case 'CubeGeometry': // backwards compatible
  25162. geometry = new Geometries[ data.type ](
  25163. data.width,
  25164. data.height,
  25165. data.depth,
  25166. data.widthSegments,
  25167. data.heightSegments,
  25168. data.depthSegments
  25169. );
  25170. break;
  25171. case 'CircleGeometry':
  25172. case 'CircleBufferGeometry':
  25173. geometry = new Geometries[ data.type ](
  25174. data.radius,
  25175. data.segments,
  25176. data.thetaStart,
  25177. data.thetaLength
  25178. );
  25179. break;
  25180. case 'CylinderGeometry':
  25181. case 'CylinderBufferGeometry':
  25182. geometry = new Geometries[ data.type ](
  25183. data.radiusTop,
  25184. data.radiusBottom,
  25185. data.height,
  25186. data.radialSegments,
  25187. data.heightSegments,
  25188. data.openEnded,
  25189. data.thetaStart,
  25190. data.thetaLength
  25191. );
  25192. break;
  25193. case 'ConeGeometry':
  25194. case 'ConeBufferGeometry':
  25195. geometry = new Geometries[ data.type ](
  25196. data.radius,
  25197. data.height,
  25198. data.radialSegments,
  25199. data.heightSegments,
  25200. data.openEnded,
  25201. data.thetaStart,
  25202. data.thetaLength
  25203. );
  25204. break;
  25205. case 'SphereGeometry':
  25206. case 'SphereBufferGeometry':
  25207. geometry = new Geometries[ data.type ](
  25208. data.radius,
  25209. data.widthSegments,
  25210. data.heightSegments,
  25211. data.phiStart,
  25212. data.phiLength,
  25213. data.thetaStart,
  25214. data.thetaLength
  25215. );
  25216. break;
  25217. case 'DodecahedronGeometry':
  25218. case 'DodecahedronBufferGeometry':
  25219. case 'IcosahedronGeometry':
  25220. case 'IcosahedronBufferGeometry':
  25221. case 'OctahedronGeometry':
  25222. case 'OctahedronBufferGeometry':
  25223. case 'TetrahedronGeometry':
  25224. case 'TetrahedronBufferGeometry':
  25225. geometry = new Geometries[ data.type ](
  25226. data.radius,
  25227. data.detail
  25228. );
  25229. break;
  25230. case 'RingGeometry':
  25231. case 'RingBufferGeometry':
  25232. geometry = new Geometries[ data.type ](
  25233. data.innerRadius,
  25234. data.outerRadius,
  25235. data.thetaSegments,
  25236. data.phiSegments,
  25237. data.thetaStart,
  25238. data.thetaLength
  25239. );
  25240. break;
  25241. case 'TorusGeometry':
  25242. case 'TorusBufferGeometry':
  25243. geometry = new Geometries[ data.type ](
  25244. data.radius,
  25245. data.tube,
  25246. data.radialSegments,
  25247. data.tubularSegments,
  25248. data.arc
  25249. );
  25250. break;
  25251. case 'TorusKnotGeometry':
  25252. case 'TorusKnotBufferGeometry':
  25253. geometry = new Geometries[ data.type ](
  25254. data.radius,
  25255. data.tube,
  25256. data.tubularSegments,
  25257. data.radialSegments,
  25258. data.p,
  25259. data.q
  25260. );
  25261. break;
  25262. case 'TubeGeometry':
  25263. case 'TubeBufferGeometry':
  25264. // This only works for built-in curves (e.g. CatmullRomCurve3).
  25265. // User defined curves or instances of CurvePath will not be deserialized.
  25266. geometry = new Geometries[ data.type ](
  25267. new Curves[ data.path.type ]().fromJSON( data.path ),
  25268. data.tubularSegments,
  25269. data.radius,
  25270. data.radialSegments,
  25271. data.closed
  25272. );
  25273. break;
  25274. case 'LatheGeometry':
  25275. case 'LatheBufferGeometry':
  25276. geometry = new Geometries[ data.type ](
  25277. data.points,
  25278. data.segments,
  25279. data.phiStart,
  25280. data.phiLength
  25281. );
  25282. break;
  25283. case 'PolyhedronGeometry':
  25284. case 'PolyhedronBufferGeometry':
  25285. geometry = new Geometries[ data.type ](
  25286. data.vertices,
  25287. data.indices,
  25288. data.radius,
  25289. data.details
  25290. );
  25291. break;
  25292. case 'ShapeGeometry':
  25293. case 'ShapeBufferGeometry':
  25294. geometryShapes = [];
  25295. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25296. const shape = shapes[ data.shapes[ j ] ];
  25297. geometryShapes.push( shape );
  25298. }
  25299. geometry = new Geometries[ data.type ](
  25300. geometryShapes,
  25301. data.curveSegments
  25302. );
  25303. break;
  25304. case 'ExtrudeGeometry':
  25305. case 'ExtrudeBufferGeometry':
  25306. geometryShapes = [];
  25307. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25308. const shape = shapes[ data.shapes[ j ] ];
  25309. geometryShapes.push( shape );
  25310. }
  25311. const extrudePath = data.options.extrudePath;
  25312. if ( extrudePath !== undefined ) {
  25313. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25314. }
  25315. geometry = new Geometries[ data.type ](
  25316. geometryShapes,
  25317. data.options
  25318. );
  25319. break;
  25320. case 'BufferGeometry':
  25321. case 'InstancedBufferGeometry':
  25322. geometry = bufferGeometryLoader.parse( data );
  25323. break;
  25324. case 'Geometry':
  25325. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  25326. break;
  25327. default:
  25328. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  25329. continue;
  25330. }
  25331. geometry.uuid = data.uuid;
  25332. if ( data.name !== undefined ) geometry.name = data.name;
  25333. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25334. geometries[ data.uuid ] = geometry;
  25335. }
  25336. }
  25337. return geometries;
  25338. }
  25339. parseMaterials( json, textures ) {
  25340. const cache = {}; // MultiMaterial
  25341. const materials = {};
  25342. if ( json !== undefined ) {
  25343. const loader = new MaterialLoader();
  25344. loader.setTextures( textures );
  25345. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25346. const data = json[ i ];
  25347. if ( data.type === 'MultiMaterial' ) {
  25348. // Deprecated
  25349. const array = [];
  25350. for ( let j = 0; j < data.materials.length; j ++ ) {
  25351. const material = data.materials[ j ];
  25352. if ( cache[ material.uuid ] === undefined ) {
  25353. cache[ material.uuid ] = loader.parse( material );
  25354. }
  25355. array.push( cache[ material.uuid ] );
  25356. }
  25357. materials[ data.uuid ] = array;
  25358. } else {
  25359. if ( cache[ data.uuid ] === undefined ) {
  25360. cache[ data.uuid ] = loader.parse( data );
  25361. }
  25362. materials[ data.uuid ] = cache[ data.uuid ];
  25363. }
  25364. }
  25365. }
  25366. return materials;
  25367. }
  25368. parseAnimations( json ) {
  25369. const animations = {};
  25370. if ( json !== undefined ) {
  25371. for ( let i = 0; i < json.length; i ++ ) {
  25372. const data = json[ i ];
  25373. const clip = AnimationClip.parse( data );
  25374. animations[ clip.uuid ] = clip;
  25375. }
  25376. }
  25377. return animations;
  25378. }
  25379. parseImages( json, onLoad ) {
  25380. const scope = this;
  25381. const images = {};
  25382. let loader;
  25383. function loadImage( url ) {
  25384. scope.manager.itemStart( url );
  25385. return loader.load( url, function () {
  25386. scope.manager.itemEnd( url );
  25387. }, undefined, function () {
  25388. scope.manager.itemError( url );
  25389. scope.manager.itemEnd( url );
  25390. } );
  25391. }
  25392. function deserializeImage( image ) {
  25393. if ( typeof image === 'string' ) {
  25394. const url = image;
  25395. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25396. return loadImage( path );
  25397. } else {
  25398. if ( image.data ) {
  25399. return {
  25400. data: getTypedArray( image.type, image.data ),
  25401. width: image.width,
  25402. height: image.height
  25403. };
  25404. } else {
  25405. return null;
  25406. }
  25407. }
  25408. }
  25409. if ( json !== undefined && json.length > 0 ) {
  25410. const manager = new LoadingManager( onLoad );
  25411. loader = new ImageLoader( manager );
  25412. loader.setCrossOrigin( this.crossOrigin );
  25413. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25414. const image = json[ i ];
  25415. const url = image.url;
  25416. if ( Array.isArray( url ) ) {
  25417. // load array of images e.g CubeTexture
  25418. images[ image.uuid ] = [];
  25419. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25420. const currentUrl = url[ j ];
  25421. const deserializedImage = deserializeImage( currentUrl );
  25422. if ( deserializedImage !== null ) {
  25423. if ( deserializedImage instanceof HTMLImageElement ) {
  25424. images[ image.uuid ].push( deserializedImage );
  25425. } else {
  25426. // special case: handle array of data textures for cube textures
  25427. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25428. }
  25429. }
  25430. }
  25431. } else {
  25432. // load single image
  25433. const deserializedImage = deserializeImage( image.url );
  25434. if ( deserializedImage !== null ) {
  25435. images[ image.uuid ] = deserializedImage;
  25436. }
  25437. }
  25438. }
  25439. }
  25440. return images;
  25441. }
  25442. parseTextures( json, images ) {
  25443. function parseConstant( value, type ) {
  25444. if ( typeof value === 'number' ) return value;
  25445. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25446. return type[ value ];
  25447. }
  25448. const textures = {};
  25449. if ( json !== undefined ) {
  25450. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25451. const data = json[ i ];
  25452. if ( data.image === undefined ) {
  25453. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25454. }
  25455. if ( images[ data.image ] === undefined ) {
  25456. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25457. }
  25458. let texture;
  25459. const image = images[ data.image ];
  25460. if ( Array.isArray( image ) ) {
  25461. texture = new CubeTexture( image );
  25462. if ( image.length === 6 ) texture.needsUpdate = true;
  25463. } else {
  25464. if ( image && image.data ) {
  25465. texture = new DataTexture( image.data, image.width, image.height );
  25466. } else {
  25467. texture = new Texture( image );
  25468. }
  25469. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25470. }
  25471. texture.uuid = data.uuid;
  25472. if ( data.name !== undefined ) texture.name = data.name;
  25473. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25474. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25475. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25476. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25477. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25478. if ( data.wrap !== undefined ) {
  25479. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25480. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25481. }
  25482. if ( data.format !== undefined ) texture.format = data.format;
  25483. if ( data.type !== undefined ) texture.type = data.type;
  25484. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25485. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25486. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25487. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25488. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25489. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25490. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25491. textures[ data.uuid ] = texture;
  25492. }
  25493. }
  25494. return textures;
  25495. }
  25496. parseObject( data, geometries, materials, animations ) {
  25497. let object;
  25498. function getGeometry( name ) {
  25499. if ( geometries[ name ] === undefined ) {
  25500. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25501. }
  25502. return geometries[ name ];
  25503. }
  25504. function getMaterial( name ) {
  25505. if ( name === undefined ) return undefined;
  25506. if ( Array.isArray( name ) ) {
  25507. const array = [];
  25508. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25509. const uuid = name[ i ];
  25510. if ( materials[ uuid ] === undefined ) {
  25511. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25512. }
  25513. array.push( materials[ uuid ] );
  25514. }
  25515. return array;
  25516. }
  25517. if ( materials[ name ] === undefined ) {
  25518. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25519. }
  25520. return materials[ name ];
  25521. }
  25522. let geometry, material;
  25523. switch ( data.type ) {
  25524. case 'Scene':
  25525. object = new Scene();
  25526. if ( data.background !== undefined ) {
  25527. if ( Number.isInteger( data.background ) ) {
  25528. object.background = new Color( data.background );
  25529. }
  25530. }
  25531. if ( data.fog !== undefined ) {
  25532. if ( data.fog.type === 'Fog' ) {
  25533. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25534. } else if ( data.fog.type === 'FogExp2' ) {
  25535. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25536. }
  25537. }
  25538. break;
  25539. case 'PerspectiveCamera':
  25540. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25541. if ( data.focus !== undefined ) object.focus = data.focus;
  25542. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25543. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25544. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25545. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25546. break;
  25547. case 'OrthographicCamera':
  25548. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25549. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25550. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25551. break;
  25552. case 'AmbientLight':
  25553. object = new AmbientLight( data.color, data.intensity );
  25554. break;
  25555. case 'DirectionalLight':
  25556. object = new DirectionalLight( data.color, data.intensity );
  25557. break;
  25558. case 'PointLight':
  25559. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25560. break;
  25561. case 'RectAreaLight':
  25562. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25563. break;
  25564. case 'SpotLight':
  25565. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25566. break;
  25567. case 'HemisphereLight':
  25568. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25569. break;
  25570. case 'LightProbe':
  25571. object = new LightProbe().fromJSON( data );
  25572. break;
  25573. case 'SkinnedMesh':
  25574. geometry = getGeometry( data.geometry );
  25575. material = getMaterial( data.material );
  25576. object = new SkinnedMesh( geometry, material );
  25577. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25578. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25579. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25580. break;
  25581. case 'Mesh':
  25582. geometry = getGeometry( data.geometry );
  25583. material = getMaterial( data.material );
  25584. object = new Mesh( geometry, material );
  25585. break;
  25586. case 'InstancedMesh':
  25587. geometry = getGeometry( data.geometry );
  25588. material = getMaterial( data.material );
  25589. const count = data.count;
  25590. const instanceMatrix = data.instanceMatrix;
  25591. object = new InstancedMesh( geometry, material, count );
  25592. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25593. break;
  25594. case 'LOD':
  25595. object = new LOD();
  25596. break;
  25597. case 'Line':
  25598. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25599. break;
  25600. case 'LineLoop':
  25601. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25602. break;
  25603. case 'LineSegments':
  25604. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25605. break;
  25606. case 'PointCloud':
  25607. case 'Points':
  25608. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25609. break;
  25610. case 'Sprite':
  25611. object = new Sprite( getMaterial( data.material ) );
  25612. break;
  25613. case 'Group':
  25614. object = new Group();
  25615. break;
  25616. case 'Bone':
  25617. object = new Bone();
  25618. break;
  25619. default:
  25620. object = new Object3D();
  25621. }
  25622. object.uuid = data.uuid;
  25623. if ( data.name !== undefined ) object.name = data.name;
  25624. if ( data.matrix !== undefined ) {
  25625. object.matrix.fromArray( data.matrix );
  25626. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25627. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25628. } else {
  25629. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25630. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25631. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25632. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25633. }
  25634. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25635. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25636. if ( data.shadow ) {
  25637. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25638. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25639. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25640. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25641. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25642. }
  25643. if ( data.visible !== undefined ) object.visible = data.visible;
  25644. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25645. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25646. if ( data.userData !== undefined ) object.userData = data.userData;
  25647. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25648. if ( data.children !== undefined ) {
  25649. const children = data.children;
  25650. for ( let i = 0; i < children.length; i ++ ) {
  25651. object.add( this.parseObject( children[ i ], geometries, materials, animations ) );
  25652. }
  25653. }
  25654. if ( data.animations !== undefined ) {
  25655. const objectAnimations = data.animations;
  25656. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25657. const uuid = objectAnimations[ i ];
  25658. object.animations.push( animations[ uuid ] );
  25659. }
  25660. }
  25661. if ( data.type === 'LOD' ) {
  25662. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25663. const levels = data.levels;
  25664. for ( let l = 0; l < levels.length; l ++ ) {
  25665. const level = levels[ l ];
  25666. const child = object.getObjectByProperty( 'uuid', level.object );
  25667. if ( child !== undefined ) {
  25668. object.addLevel( child, level.distance );
  25669. }
  25670. }
  25671. }
  25672. return object;
  25673. }
  25674. bindSkeletons( object, skeletons ) {
  25675. if ( Object.keys( skeletons ).length === 0 ) return;
  25676. object.traverse( function ( child ) {
  25677. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25678. const skeleton = skeletons[ child.skeleton ];
  25679. if ( skeleton === undefined ) {
  25680. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25681. } else {
  25682. child.bind( skeleton, child.bindMatrix );
  25683. }
  25684. }
  25685. } );
  25686. }
  25687. /* DEPRECATED */
  25688. setTexturePath( value ) {
  25689. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  25690. return this.setResourcePath( value );
  25691. }
  25692. }
  25693. const TEXTURE_MAPPING = {
  25694. UVMapping: UVMapping,
  25695. CubeReflectionMapping: CubeReflectionMapping,
  25696. CubeRefractionMapping: CubeRefractionMapping,
  25697. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25698. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25699. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25700. CubeUVRefractionMapping: CubeUVRefractionMapping
  25701. };
  25702. const TEXTURE_WRAPPING = {
  25703. RepeatWrapping: RepeatWrapping,
  25704. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25705. MirroredRepeatWrapping: MirroredRepeatWrapping
  25706. };
  25707. const TEXTURE_FILTER = {
  25708. NearestFilter: NearestFilter,
  25709. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25710. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25711. LinearFilter: LinearFilter,
  25712. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25713. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25714. };
  25715. function ImageBitmapLoader( manager ) {
  25716. if ( typeof createImageBitmap === 'undefined' ) {
  25717. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25718. }
  25719. if ( typeof fetch === 'undefined' ) {
  25720. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25721. }
  25722. Loader.call( this, manager );
  25723. this.options = { premultiplyAlpha: 'none' };
  25724. }
  25725. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25726. constructor: ImageBitmapLoader,
  25727. isImageBitmapLoader: true,
  25728. setOptions: function setOptions( options ) {
  25729. this.options = options;
  25730. return this;
  25731. },
  25732. load: function ( url, onLoad, onProgress, onError ) {
  25733. if ( url === undefined ) url = '';
  25734. if ( this.path !== undefined ) url = this.path + url;
  25735. url = this.manager.resolveURL( url );
  25736. const scope = this;
  25737. const cached = Cache.get( url );
  25738. if ( cached !== undefined ) {
  25739. scope.manager.itemStart( url );
  25740. setTimeout( function () {
  25741. if ( onLoad ) onLoad( cached );
  25742. scope.manager.itemEnd( url );
  25743. }, 0 );
  25744. return cached;
  25745. }
  25746. const fetchOptions = {};
  25747. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25748. fetch( url, fetchOptions ).then( function ( res ) {
  25749. return res.blob();
  25750. } ).then( function ( blob ) {
  25751. //console.log('getBlob', url )
  25752. return createImageBitmap( blob, scope.options );
  25753. } ).then( function ( imageBitmap ) {
  25754. Cache.add( url, imageBitmap );
  25755. if ( onLoad ) onLoad( imageBitmap );
  25756. scope.manager.itemEnd( url );
  25757. } ).catch( function ( e ) {
  25758. //console.log('error', url, e)
  25759. if ( onError ) onError( e, url );
  25760. scope.manager.itemError( url );
  25761. scope.manager.itemEnd( url );
  25762. } );
  25763. scope.manager.itemStart( url );
  25764. }
  25765. } );
  25766. function ShapePath() {
  25767. this.type = 'ShapePath';
  25768. this.color = new Color();
  25769. this.subPaths = [];
  25770. this.currentPath = null;
  25771. }
  25772. Object.assign( ShapePath.prototype, {
  25773. moveTo: function ( x, y ) {
  25774. this.currentPath = new Path();
  25775. this.subPaths.push( this.currentPath );
  25776. this.currentPath.moveTo( x, y );
  25777. return this;
  25778. },
  25779. lineTo: function ( x, y ) {
  25780. this.currentPath.lineTo( x, y );
  25781. return this;
  25782. },
  25783. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25784. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25785. return this;
  25786. },
  25787. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25788. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25789. return this;
  25790. },
  25791. splineThru: function ( pts ) {
  25792. this.currentPath.splineThru( pts );
  25793. return this;
  25794. },
  25795. toShapes: function ( isCCW, noHoles ) {
  25796. function toShapesNoHoles( inSubpaths ) {
  25797. const shapes = [];
  25798. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25799. const tmpPath = inSubpaths[ i ];
  25800. const tmpShape = new Shape();
  25801. tmpShape.curves = tmpPath.curves;
  25802. shapes.push( tmpShape );
  25803. }
  25804. return shapes;
  25805. }
  25806. function isPointInsidePolygon( inPt, inPolygon ) {
  25807. const polyLen = inPolygon.length;
  25808. // inPt on polygon contour => immediate success or
  25809. // toggling of inside/outside at every single! intersection point of an edge
  25810. // with the horizontal line through inPt, left of inPt
  25811. // not counting lowerY endpoints of edges and whole edges on that line
  25812. let inside = false;
  25813. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25814. let edgeLowPt = inPolygon[ p ];
  25815. let edgeHighPt = inPolygon[ q ];
  25816. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25817. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25818. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25819. // not parallel
  25820. if ( edgeDy < 0 ) {
  25821. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25822. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25823. }
  25824. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25825. if ( inPt.y === edgeLowPt.y ) {
  25826. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25827. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25828. } else {
  25829. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25830. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25831. if ( perpEdge < 0 ) continue;
  25832. inside = ! inside; // true intersection left of inPt
  25833. }
  25834. } else {
  25835. // parallel or collinear
  25836. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25837. // edge lies on the same horizontal line as inPt
  25838. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25839. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25840. // continue;
  25841. }
  25842. }
  25843. return inside;
  25844. }
  25845. const isClockWise = ShapeUtils.isClockWise;
  25846. const subPaths = this.subPaths;
  25847. if ( subPaths.length === 0 ) return [];
  25848. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25849. let solid, tmpPath, tmpShape;
  25850. const shapes = [];
  25851. if ( subPaths.length === 1 ) {
  25852. tmpPath = subPaths[ 0 ];
  25853. tmpShape = new Shape();
  25854. tmpShape.curves = tmpPath.curves;
  25855. shapes.push( tmpShape );
  25856. return shapes;
  25857. }
  25858. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25859. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25860. // console.log("Holes first", holesFirst);
  25861. const betterShapeHoles = [];
  25862. const newShapes = [];
  25863. let newShapeHoles = [];
  25864. let mainIdx = 0;
  25865. let tmpPoints;
  25866. newShapes[ mainIdx ] = undefined;
  25867. newShapeHoles[ mainIdx ] = [];
  25868. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  25869. tmpPath = subPaths[ i ];
  25870. tmpPoints = tmpPath.getPoints();
  25871. solid = isClockWise( tmpPoints );
  25872. solid = isCCW ? ! solid : solid;
  25873. if ( solid ) {
  25874. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25875. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25876. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25877. if ( holesFirst ) mainIdx ++;
  25878. newShapeHoles[ mainIdx ] = [];
  25879. //console.log('cw', i);
  25880. } else {
  25881. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25882. //console.log('ccw', i);
  25883. }
  25884. }
  25885. // only Holes? -> probably all Shapes with wrong orientation
  25886. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25887. if ( newShapes.length > 1 ) {
  25888. let ambiguous = false;
  25889. const toChange = [];
  25890. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25891. betterShapeHoles[ sIdx ] = [];
  25892. }
  25893. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25894. const sho = newShapeHoles[ sIdx ];
  25895. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25896. const ho = sho[ hIdx ];
  25897. let hole_unassigned = true;
  25898. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25899. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25900. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25901. if ( hole_unassigned ) {
  25902. hole_unassigned = false;
  25903. betterShapeHoles[ s2Idx ].push( ho );
  25904. } else {
  25905. ambiguous = true;
  25906. }
  25907. }
  25908. }
  25909. if ( hole_unassigned ) {
  25910. betterShapeHoles[ sIdx ].push( ho );
  25911. }
  25912. }
  25913. }
  25914. // console.log("ambiguous: ", ambiguous);
  25915. if ( toChange.length > 0 ) {
  25916. // console.log("to change: ", toChange);
  25917. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25918. }
  25919. }
  25920. let tmpHoles;
  25921. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  25922. tmpShape = newShapes[ i ].s;
  25923. shapes.push( tmpShape );
  25924. tmpHoles = newShapeHoles[ i ];
  25925. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25926. tmpShape.holes.push( tmpHoles[ j ].h );
  25927. }
  25928. }
  25929. //console.log("shape", shapes);
  25930. return shapes;
  25931. }
  25932. } );
  25933. function Font( data ) {
  25934. this.type = 'Font';
  25935. this.data = data;
  25936. }
  25937. Object.assign( Font.prototype, {
  25938. isFont: true,
  25939. generateShapes: function ( text, size = 100 ) {
  25940. const shapes = [];
  25941. const paths = createPaths( text, size, this.data );
  25942. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  25943. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25944. }
  25945. return shapes;
  25946. }
  25947. } );
  25948. function createPaths( text, size, data ) {
  25949. const chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  25950. const scale = size / data.resolution;
  25951. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25952. const paths = [];
  25953. let offsetX = 0, offsetY = 0;
  25954. for ( let i = 0; i < chars.length; i ++ ) {
  25955. const char = chars[ i ];
  25956. if ( char === '\n' ) {
  25957. offsetX = 0;
  25958. offsetY -= line_height;
  25959. } else {
  25960. const ret = createPath( char, scale, offsetX, offsetY, data );
  25961. offsetX += ret.offsetX;
  25962. paths.push( ret.path );
  25963. }
  25964. }
  25965. return paths;
  25966. }
  25967. function createPath( char, scale, offsetX, offsetY, data ) {
  25968. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  25969. if ( ! glyph ) {
  25970. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  25971. return;
  25972. }
  25973. const path = new ShapePath();
  25974. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25975. if ( glyph.o ) {
  25976. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25977. for ( let i = 0, l = outline.length; i < l; ) {
  25978. const action = outline[ i ++ ];
  25979. switch ( action ) {
  25980. case 'm': // moveTo
  25981. x = outline[ i ++ ] * scale + offsetX;
  25982. y = outline[ i ++ ] * scale + offsetY;
  25983. path.moveTo( x, y );
  25984. break;
  25985. case 'l': // lineTo
  25986. x = outline[ i ++ ] * scale + offsetX;
  25987. y = outline[ i ++ ] * scale + offsetY;
  25988. path.lineTo( x, y );
  25989. break;
  25990. case 'q': // quadraticCurveTo
  25991. cpx = outline[ i ++ ] * scale + offsetX;
  25992. cpy = outline[ i ++ ] * scale + offsetY;
  25993. cpx1 = outline[ i ++ ] * scale + offsetX;
  25994. cpy1 = outline[ i ++ ] * scale + offsetY;
  25995. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25996. break;
  25997. case 'b': // bezierCurveTo
  25998. cpx = outline[ i ++ ] * scale + offsetX;
  25999. cpy = outline[ i ++ ] * scale + offsetY;
  26000. cpx1 = outline[ i ++ ] * scale + offsetX;
  26001. cpy1 = outline[ i ++ ] * scale + offsetY;
  26002. cpx2 = outline[ i ++ ] * scale + offsetX;
  26003. cpy2 = outline[ i ++ ] * scale + offsetY;
  26004. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  26005. break;
  26006. }
  26007. }
  26008. }
  26009. return { offsetX: glyph.ha * scale, path: path };
  26010. }
  26011. function FontLoader( manager ) {
  26012. Loader.call( this, manager );
  26013. }
  26014. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26015. constructor: FontLoader,
  26016. load: function ( url, onLoad, onProgress, onError ) {
  26017. const scope = this;
  26018. const loader = new FileLoader( this.manager );
  26019. loader.setPath( this.path );
  26020. loader.setRequestHeader( this.requestHeader );
  26021. loader.setWithCredentials( scope.withCredentials );
  26022. loader.load( url, function ( text ) {
  26023. let json;
  26024. try {
  26025. json = JSON.parse( text );
  26026. } catch ( e ) {
  26027. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  26028. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  26029. }
  26030. const font = scope.parse( json );
  26031. if ( onLoad ) onLoad( font );
  26032. }, onProgress, onError );
  26033. },
  26034. parse: function ( json ) {
  26035. return new Font( json );
  26036. }
  26037. } );
  26038. let _context;
  26039. const AudioContext = {
  26040. getContext: function () {
  26041. if ( _context === undefined ) {
  26042. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26043. }
  26044. return _context;
  26045. },
  26046. setContext: function ( value ) {
  26047. _context = value;
  26048. }
  26049. };
  26050. function AudioLoader( manager ) {
  26051. Loader.call( this, manager );
  26052. }
  26053. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26054. constructor: AudioLoader,
  26055. load: function ( url, onLoad, onProgress, onError ) {
  26056. const scope = this;
  26057. const loader = new FileLoader( scope.manager );
  26058. loader.setResponseType( 'arraybuffer' );
  26059. loader.setPath( scope.path );
  26060. loader.setRequestHeader( scope.requestHeader );
  26061. loader.setWithCredentials( scope.withCredentials );
  26062. loader.load( url, function ( buffer ) {
  26063. try {
  26064. // Create a copy of the buffer. The `decodeAudioData` method
  26065. // detaches the buffer when complete, preventing reuse.
  26066. const bufferCopy = buffer.slice( 0 );
  26067. const context = AudioContext.getContext();
  26068. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26069. onLoad( audioBuffer );
  26070. } );
  26071. } catch ( e ) {
  26072. if ( onError ) {
  26073. onError( e );
  26074. } else {
  26075. console.error( e );
  26076. }
  26077. scope.manager.itemError( url );
  26078. }
  26079. }, onProgress, onError );
  26080. }
  26081. } );
  26082. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  26083. LightProbe.call( this, undefined, intensity );
  26084. const color1 = new Color().set( skyColor );
  26085. const color2 = new Color().set( groundColor );
  26086. const sky = new Vector3( color1.r, color1.g, color1.b );
  26087. const ground = new Vector3( color2.r, color2.g, color2.b );
  26088. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26089. const c0 = Math.sqrt( Math.PI );
  26090. const c1 = c0 * Math.sqrt( 0.75 );
  26091. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26092. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26093. }
  26094. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  26095. constructor: HemisphereLightProbe,
  26096. isHemisphereLightProbe: true,
  26097. copy: function ( source ) { // modifying colors not currently supported
  26098. LightProbe.prototype.copy.call( this, source );
  26099. return this;
  26100. },
  26101. toJSON: function ( meta ) {
  26102. const data = LightProbe.prototype.toJSON.call( this, meta );
  26103. // data.sh = this.sh.toArray(); // todo
  26104. return data;
  26105. }
  26106. } );
  26107. function AmbientLightProbe( color, intensity ) {
  26108. LightProbe.call( this, undefined, intensity );
  26109. const color1 = new Color().set( color );
  26110. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26111. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26112. }
  26113. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  26114. constructor: AmbientLightProbe,
  26115. isAmbientLightProbe: true,
  26116. copy: function ( source ) { // modifying color not currently supported
  26117. LightProbe.prototype.copy.call( this, source );
  26118. return this;
  26119. },
  26120. toJSON: function ( meta ) {
  26121. const data = LightProbe.prototype.toJSON.call( this, meta );
  26122. // data.sh = this.sh.toArray(); // todo
  26123. return data;
  26124. }
  26125. } );
  26126. const _eyeRight = new Matrix4();
  26127. const _eyeLeft = new Matrix4();
  26128. function StereoCamera() {
  26129. this.type = 'StereoCamera';
  26130. this.aspect = 1;
  26131. this.eyeSep = 0.064;
  26132. this.cameraL = new PerspectiveCamera();
  26133. this.cameraL.layers.enable( 1 );
  26134. this.cameraL.matrixAutoUpdate = false;
  26135. this.cameraR = new PerspectiveCamera();
  26136. this.cameraR.layers.enable( 2 );
  26137. this.cameraR.matrixAutoUpdate = false;
  26138. this._cache = {
  26139. focus: null,
  26140. fov: null,
  26141. aspect: null,
  26142. near: null,
  26143. far: null,
  26144. zoom: null,
  26145. eyeSep: null
  26146. };
  26147. }
  26148. Object.assign( StereoCamera.prototype, {
  26149. update: function ( camera ) {
  26150. const cache = this._cache;
  26151. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26152. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26153. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26154. if ( needsUpdate ) {
  26155. cache.focus = camera.focus;
  26156. cache.fov = camera.fov;
  26157. cache.aspect = camera.aspect * this.aspect;
  26158. cache.near = camera.near;
  26159. cache.far = camera.far;
  26160. cache.zoom = camera.zoom;
  26161. cache.eyeSep = this.eyeSep;
  26162. // Off-axis stereoscopic effect based on
  26163. // http://paulbourke.net/stereographics/stereorender/
  26164. const projectionMatrix = camera.projectionMatrix.clone();
  26165. const eyeSepHalf = cache.eyeSep / 2;
  26166. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26167. const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26168. let xmin, xmax;
  26169. // translate xOffset
  26170. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26171. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26172. // for left eye
  26173. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26174. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26175. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26176. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26177. this.cameraL.projectionMatrix.copy( projectionMatrix );
  26178. // for right eye
  26179. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26180. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26181. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26182. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26183. this.cameraR.projectionMatrix.copy( projectionMatrix );
  26184. }
  26185. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26186. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26187. }
  26188. } );
  26189. class Clock {
  26190. constructor( autoStart ) {
  26191. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  26192. this.startTime = 0;
  26193. this.oldTime = 0;
  26194. this.elapsedTime = 0;
  26195. this.running = false;
  26196. }
  26197. start() {
  26198. this.startTime = now();
  26199. this.oldTime = this.startTime;
  26200. this.elapsedTime = 0;
  26201. this.running = true;
  26202. }
  26203. stop() {
  26204. this.getElapsedTime();
  26205. this.running = false;
  26206. this.autoStart = false;
  26207. }
  26208. getElapsedTime() {
  26209. this.getDelta();
  26210. return this.elapsedTime;
  26211. }
  26212. getDelta() {
  26213. let diff = 0;
  26214. if ( this.autoStart && ! this.running ) {
  26215. this.start();
  26216. return 0;
  26217. }
  26218. if ( this.running ) {
  26219. const newTime = now();
  26220. diff = ( newTime - this.oldTime ) / 1000;
  26221. this.oldTime = newTime;
  26222. this.elapsedTime += diff;
  26223. }
  26224. return diff;
  26225. }
  26226. }
  26227. function now() {
  26228. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26229. }
  26230. const _position$2 = /*@__PURE__*/ new Vector3();
  26231. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  26232. const _scale$1 = /*@__PURE__*/ new Vector3();
  26233. const _orientation = /*@__PURE__*/ new Vector3();
  26234. class AudioListener extends Object3D {
  26235. constructor() {
  26236. super();
  26237. this.type = 'AudioListener';
  26238. this.context = AudioContext.getContext();
  26239. this.gain = this.context.createGain();
  26240. this.gain.connect( this.context.destination );
  26241. this.filter = null;
  26242. this.timeDelta = 0;
  26243. // private
  26244. this._clock = new Clock();
  26245. }
  26246. getInput() {
  26247. return this.gain;
  26248. }
  26249. removeFilter() {
  26250. if ( this.filter !== null ) {
  26251. this.gain.disconnect( this.filter );
  26252. this.filter.disconnect( this.context.destination );
  26253. this.gain.connect( this.context.destination );
  26254. this.filter = null;
  26255. }
  26256. return this;
  26257. }
  26258. getFilter() {
  26259. return this.filter;
  26260. }
  26261. setFilter( value ) {
  26262. if ( this.filter !== null ) {
  26263. this.gain.disconnect( this.filter );
  26264. this.filter.disconnect( this.context.destination );
  26265. } else {
  26266. this.gain.disconnect( this.context.destination );
  26267. }
  26268. this.filter = value;
  26269. this.gain.connect( this.filter );
  26270. this.filter.connect( this.context.destination );
  26271. return this;
  26272. }
  26273. getMasterVolume() {
  26274. return this.gain.gain.value;
  26275. }
  26276. setMasterVolume( value ) {
  26277. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26278. return this;
  26279. }
  26280. updateMatrixWorld( force ) {
  26281. super.updateMatrixWorld( force );
  26282. const listener = this.context.listener;
  26283. const up = this.up;
  26284. this.timeDelta = this._clock.getDelta();
  26285. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  26286. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  26287. if ( listener.positionX ) {
  26288. // code path for Chrome (see #14393)
  26289. const endTime = this.context.currentTime + this.timeDelta;
  26290. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  26291. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  26292. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  26293. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  26294. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  26295. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  26296. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26297. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26298. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26299. } else {
  26300. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  26301. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  26302. }
  26303. }
  26304. }
  26305. class Audio extends Object3D {
  26306. constructor( listener ) {
  26307. super();
  26308. this.type = 'Audio';
  26309. this.listener = listener;
  26310. this.context = listener.context;
  26311. this.gain = this.context.createGain();
  26312. this.gain.connect( listener.getInput() );
  26313. this.autoplay = false;
  26314. this.buffer = null;
  26315. this.detune = 0;
  26316. this.loop = false;
  26317. this.loopStart = 0;
  26318. this.loopEnd = 0;
  26319. this.offset = 0;
  26320. this.duration = undefined;
  26321. this.playbackRate = 1;
  26322. this.isPlaying = false;
  26323. this.hasPlaybackControl = true;
  26324. this.source = null;
  26325. this.sourceType = 'empty';
  26326. this._startedAt = 0;
  26327. this._progress = 0;
  26328. this._connected = false;
  26329. this.filters = [];
  26330. }
  26331. getOutput() {
  26332. return this.gain;
  26333. }
  26334. setNodeSource( audioNode ) {
  26335. this.hasPlaybackControl = false;
  26336. this.sourceType = 'audioNode';
  26337. this.source = audioNode;
  26338. this.connect();
  26339. return this;
  26340. }
  26341. setMediaElementSource( mediaElement ) {
  26342. this.hasPlaybackControl = false;
  26343. this.sourceType = 'mediaNode';
  26344. this.source = this.context.createMediaElementSource( mediaElement );
  26345. this.connect();
  26346. return this;
  26347. }
  26348. setMediaStreamSource( mediaStream ) {
  26349. this.hasPlaybackControl = false;
  26350. this.sourceType = 'mediaStreamNode';
  26351. this.source = this.context.createMediaStreamSource( mediaStream );
  26352. this.connect();
  26353. return this;
  26354. }
  26355. setBuffer( audioBuffer ) {
  26356. this.buffer = audioBuffer;
  26357. this.sourceType = 'buffer';
  26358. if ( this.autoplay ) this.play();
  26359. return this;
  26360. }
  26361. play( delay = 0 ) {
  26362. if ( this.isPlaying === true ) {
  26363. console.warn( 'THREE.Audio: Audio is already playing.' );
  26364. return;
  26365. }
  26366. if ( this.hasPlaybackControl === false ) {
  26367. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26368. return;
  26369. }
  26370. this._startedAt = this.context.currentTime + delay;
  26371. const source = this.context.createBufferSource();
  26372. source.buffer = this.buffer;
  26373. source.loop = this.loop;
  26374. source.loopStart = this.loopStart;
  26375. source.loopEnd = this.loopEnd;
  26376. source.onended = this.onEnded.bind( this );
  26377. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26378. this.isPlaying = true;
  26379. this.source = source;
  26380. this.setDetune( this.detune );
  26381. this.setPlaybackRate( this.playbackRate );
  26382. return this.connect();
  26383. }
  26384. pause() {
  26385. if ( this.hasPlaybackControl === false ) {
  26386. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26387. return;
  26388. }
  26389. if ( this.isPlaying === true ) {
  26390. // update current progress
  26391. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26392. if ( this.loop === true ) {
  26393. // ensure _progress does not exceed duration with looped audios
  26394. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26395. }
  26396. this.source.stop();
  26397. this.source.onended = null;
  26398. this.isPlaying = false;
  26399. }
  26400. return this;
  26401. }
  26402. stop() {
  26403. if ( this.hasPlaybackControl === false ) {
  26404. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26405. return;
  26406. }
  26407. this._progress = 0;
  26408. this.source.stop();
  26409. this.source.onended = null;
  26410. this.isPlaying = false;
  26411. return this;
  26412. }
  26413. connect() {
  26414. if ( this.filters.length > 0 ) {
  26415. this.source.connect( this.filters[ 0 ] );
  26416. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26417. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26418. }
  26419. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26420. } else {
  26421. this.source.connect( this.getOutput() );
  26422. }
  26423. this._connected = true;
  26424. return this;
  26425. }
  26426. disconnect() {
  26427. if ( this.filters.length > 0 ) {
  26428. this.source.disconnect( this.filters[ 0 ] );
  26429. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26430. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26431. }
  26432. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26433. } else {
  26434. this.source.disconnect( this.getOutput() );
  26435. }
  26436. this._connected = false;
  26437. return this;
  26438. }
  26439. getFilters() {
  26440. return this.filters;
  26441. }
  26442. setFilters( value ) {
  26443. if ( ! value ) value = [];
  26444. if ( this._connected === true ) {
  26445. this.disconnect();
  26446. this.filters = value.slice();
  26447. this.connect();
  26448. } else {
  26449. this.filters = value.slice();
  26450. }
  26451. return this;
  26452. }
  26453. setDetune( value ) {
  26454. this.detune = value;
  26455. if ( this.source.detune === undefined ) return; // only set detune when available
  26456. if ( this.isPlaying === true ) {
  26457. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26458. }
  26459. return this;
  26460. }
  26461. getDetune() {
  26462. return this.detune;
  26463. }
  26464. getFilter() {
  26465. return this.getFilters()[ 0 ];
  26466. }
  26467. setFilter( filter ) {
  26468. return this.setFilters( filter ? [ filter ] : [] );
  26469. }
  26470. setPlaybackRate( value ) {
  26471. if ( this.hasPlaybackControl === false ) {
  26472. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26473. return;
  26474. }
  26475. this.playbackRate = value;
  26476. if ( this.isPlaying === true ) {
  26477. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26478. }
  26479. return this;
  26480. }
  26481. getPlaybackRate() {
  26482. return this.playbackRate;
  26483. }
  26484. onEnded() {
  26485. this.isPlaying = false;
  26486. }
  26487. getLoop() {
  26488. if ( this.hasPlaybackControl === false ) {
  26489. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26490. return false;
  26491. }
  26492. return this.loop;
  26493. }
  26494. setLoop( value ) {
  26495. if ( this.hasPlaybackControl === false ) {
  26496. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26497. return;
  26498. }
  26499. this.loop = value;
  26500. if ( this.isPlaying === true ) {
  26501. this.source.loop = this.loop;
  26502. }
  26503. return this;
  26504. }
  26505. setLoopStart( value ) {
  26506. this.loopStart = value;
  26507. return this;
  26508. }
  26509. setLoopEnd( value ) {
  26510. this.loopEnd = value;
  26511. return this;
  26512. }
  26513. getVolume() {
  26514. return this.gain.gain.value;
  26515. }
  26516. setVolume( value ) {
  26517. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26518. return this;
  26519. }
  26520. }
  26521. const _position$3 = /*@__PURE__*/ new Vector3();
  26522. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  26523. const _scale$2 = /*@__PURE__*/ new Vector3();
  26524. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26525. class PositionalAudio extends Audio {
  26526. constructor( listener ) {
  26527. super( listener );
  26528. this.panner = this.context.createPanner();
  26529. this.panner.panningModel = 'HRTF';
  26530. this.panner.connect( this.gain );
  26531. }
  26532. getOutput() {
  26533. return this.panner;
  26534. }
  26535. getRefDistance() {
  26536. return this.panner.refDistance;
  26537. }
  26538. setRefDistance( value ) {
  26539. this.panner.refDistance = value;
  26540. return this;
  26541. }
  26542. getRolloffFactor() {
  26543. return this.panner.rolloffFactor;
  26544. }
  26545. setRolloffFactor( value ) {
  26546. this.panner.rolloffFactor = value;
  26547. return this;
  26548. }
  26549. getDistanceModel() {
  26550. return this.panner.distanceModel;
  26551. }
  26552. setDistanceModel( value ) {
  26553. this.panner.distanceModel = value;
  26554. return this;
  26555. }
  26556. getMaxDistance() {
  26557. return this.panner.maxDistance;
  26558. }
  26559. setMaxDistance( value ) {
  26560. this.panner.maxDistance = value;
  26561. return this;
  26562. }
  26563. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26564. this.panner.coneInnerAngle = coneInnerAngle;
  26565. this.panner.coneOuterAngle = coneOuterAngle;
  26566. this.panner.coneOuterGain = coneOuterGain;
  26567. return this;
  26568. }
  26569. updateMatrixWorld( force ) {
  26570. super.updateMatrixWorld( force );
  26571. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26572. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  26573. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  26574. const panner = this.panner;
  26575. if ( panner.positionX ) {
  26576. // code path for Chrome and Firefox (see #14393)
  26577. const endTime = this.context.currentTime + this.listener.timeDelta;
  26578. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  26579. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  26580. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  26581. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26582. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26583. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26584. } else {
  26585. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  26586. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  26587. }
  26588. }
  26589. }
  26590. class AudioAnalyser {
  26591. constructor( audio, fftSize = 2048 ) {
  26592. this.analyser = audio.context.createAnalyser();
  26593. this.analyser.fftSize = fftSize;
  26594. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26595. audio.getOutput().connect( this.analyser );
  26596. }
  26597. getFrequencyData() {
  26598. this.analyser.getByteFrequencyData( this.data );
  26599. return this.data;
  26600. }
  26601. getAverageFrequency() {
  26602. let value = 0;
  26603. const data = this.getFrequencyData();
  26604. for ( let i = 0; i < data.length; i ++ ) {
  26605. value += data[ i ];
  26606. }
  26607. return value / data.length;
  26608. }
  26609. }
  26610. function PropertyMixer( binding, typeName, valueSize ) {
  26611. this.binding = binding;
  26612. this.valueSize = valueSize;
  26613. let mixFunction,
  26614. mixFunctionAdditive,
  26615. setIdentity;
  26616. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26617. //
  26618. // interpolators can use .buffer as their .result
  26619. // the data then goes to 'incoming'
  26620. //
  26621. // 'accu0' and 'accu1' are used frame-interleaved for
  26622. // the cumulative result and are compared to detect
  26623. // changes
  26624. //
  26625. // 'orig' stores the original state of the property
  26626. //
  26627. // 'add' is used for additive cumulative results
  26628. //
  26629. // 'work' is optional and is only present for quaternion types. It is used
  26630. // to store intermediate quaternion multiplication results
  26631. switch ( typeName ) {
  26632. case 'quaternion':
  26633. mixFunction = this._slerp;
  26634. mixFunctionAdditive = this._slerpAdditive;
  26635. setIdentity = this._setAdditiveIdentityQuaternion;
  26636. this.buffer = new Float64Array( valueSize * 6 );
  26637. this._workIndex = 5;
  26638. break;
  26639. case 'string':
  26640. case 'bool':
  26641. mixFunction = this._select;
  26642. // Use the regular mix function and for additive on these types,
  26643. // additive is not relevant for non-numeric types
  26644. mixFunctionAdditive = this._select;
  26645. setIdentity = this._setAdditiveIdentityOther;
  26646. this.buffer = new Array( valueSize * 5 );
  26647. break;
  26648. default:
  26649. mixFunction = this._lerp;
  26650. mixFunctionAdditive = this._lerpAdditive;
  26651. setIdentity = this._setAdditiveIdentityNumeric;
  26652. this.buffer = new Float64Array( valueSize * 5 );
  26653. }
  26654. this._mixBufferRegion = mixFunction;
  26655. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26656. this._setIdentity = setIdentity;
  26657. this._origIndex = 3;
  26658. this._addIndex = 4;
  26659. this.cumulativeWeight = 0;
  26660. this.cumulativeWeightAdditive = 0;
  26661. this.useCount = 0;
  26662. this.referenceCount = 0;
  26663. }
  26664. Object.assign( PropertyMixer.prototype, {
  26665. // accumulate data in the 'incoming' region into 'accu<i>'
  26666. accumulate: function ( accuIndex, weight ) {
  26667. // note: happily accumulating nothing when weight = 0, the caller knows
  26668. // the weight and shouldn't have made the call in the first place
  26669. const buffer = this.buffer,
  26670. stride = this.valueSize,
  26671. offset = accuIndex * stride + stride;
  26672. let currentWeight = this.cumulativeWeight;
  26673. if ( currentWeight === 0 ) {
  26674. // accuN := incoming * weight
  26675. for ( let i = 0; i !== stride; ++ i ) {
  26676. buffer[ offset + i ] = buffer[ i ];
  26677. }
  26678. currentWeight = weight;
  26679. } else {
  26680. // accuN := accuN + incoming * weight
  26681. currentWeight += weight;
  26682. const mix = weight / currentWeight;
  26683. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26684. }
  26685. this.cumulativeWeight = currentWeight;
  26686. },
  26687. // accumulate data in the 'incoming' region into 'add'
  26688. accumulateAdditive: function ( weight ) {
  26689. const buffer = this.buffer,
  26690. stride = this.valueSize,
  26691. offset = stride * this._addIndex;
  26692. if ( this.cumulativeWeightAdditive === 0 ) {
  26693. // add = identity
  26694. this._setIdentity();
  26695. }
  26696. // add := add + incoming * weight
  26697. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26698. this.cumulativeWeightAdditive += weight;
  26699. },
  26700. // apply the state of 'accu<i>' to the binding when accus differ
  26701. apply: function ( accuIndex ) {
  26702. const stride = this.valueSize,
  26703. buffer = this.buffer,
  26704. offset = accuIndex * stride + stride,
  26705. weight = this.cumulativeWeight,
  26706. weightAdditive = this.cumulativeWeightAdditive,
  26707. binding = this.binding;
  26708. this.cumulativeWeight = 0;
  26709. this.cumulativeWeightAdditive = 0;
  26710. if ( weight < 1 ) {
  26711. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26712. const originalValueOffset = stride * this._origIndex;
  26713. this._mixBufferRegion(
  26714. buffer, offset, originalValueOffset, 1 - weight, stride );
  26715. }
  26716. if ( weightAdditive > 0 ) {
  26717. // accuN := accuN + additive accuN
  26718. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26719. }
  26720. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26721. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26722. // value has changed -> update scene graph
  26723. binding.setValue( buffer, offset );
  26724. break;
  26725. }
  26726. }
  26727. },
  26728. // remember the state of the bound property and copy it to both accus
  26729. saveOriginalState: function () {
  26730. const binding = this.binding;
  26731. const buffer = this.buffer,
  26732. stride = this.valueSize,
  26733. originalValueOffset = stride * this._origIndex;
  26734. binding.getValue( buffer, originalValueOffset );
  26735. // accu[0..1] := orig -- initially detect changes against the original
  26736. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26737. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26738. }
  26739. // Add to identity for additive
  26740. this._setIdentity();
  26741. this.cumulativeWeight = 0;
  26742. this.cumulativeWeightAdditive = 0;
  26743. },
  26744. // apply the state previously taken via 'saveOriginalState' to the binding
  26745. restoreOriginalState: function () {
  26746. const originalValueOffset = this.valueSize * 3;
  26747. this.binding.setValue( this.buffer, originalValueOffset );
  26748. },
  26749. _setAdditiveIdentityNumeric: function () {
  26750. const startIndex = this._addIndex * this.valueSize;
  26751. const endIndex = startIndex + this.valueSize;
  26752. for ( let i = startIndex; i < endIndex; i ++ ) {
  26753. this.buffer[ i ] = 0;
  26754. }
  26755. },
  26756. _setAdditiveIdentityQuaternion: function () {
  26757. this._setAdditiveIdentityNumeric();
  26758. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26759. },
  26760. _setAdditiveIdentityOther: function () {
  26761. const startIndex = this._origIndex * this.valueSize;
  26762. const targetIndex = this._addIndex * this.valueSize;
  26763. for ( let i = 0; i < this.valueSize; i ++ ) {
  26764. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26765. }
  26766. },
  26767. // mix functions
  26768. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26769. if ( t >= 0.5 ) {
  26770. for ( let i = 0; i !== stride; ++ i ) {
  26771. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26772. }
  26773. }
  26774. },
  26775. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  26776. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26777. },
  26778. _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26779. const workOffset = this._workIndex * stride;
  26780. // Store result in intermediate buffer offset
  26781. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26782. // Slerp to the intermediate result
  26783. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26784. },
  26785. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26786. const s = 1 - t;
  26787. for ( let i = 0; i !== stride; ++ i ) {
  26788. const j = dstOffset + i;
  26789. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26790. }
  26791. },
  26792. _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26793. for ( let i = 0; i !== stride; ++ i ) {
  26794. const j = dstOffset + i;
  26795. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26796. }
  26797. }
  26798. } );
  26799. // Characters [].:/ are reserved for track binding syntax.
  26800. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26801. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26802. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26803. // only latin characters, and the unicode \p{L} is not yet supported. So
  26804. // instead, we exclude reserved characters and match everything else.
  26805. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26806. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26807. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26808. // be matched to parse the rest of the track name.
  26809. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26810. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26811. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26812. // Object on target node, and accessor. May not contain reserved
  26813. // characters. Accessor may contain any character except closing bracket.
  26814. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26815. // Property and accessor. May not contain reserved characters. Accessor may
  26816. // contain any non-bracket characters.
  26817. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26818. const _trackRe = new RegExp( ''
  26819. + '^'
  26820. + _directoryRe
  26821. + _nodeRe
  26822. + _objectRe
  26823. + _propertyRe
  26824. + '$'
  26825. );
  26826. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26827. function Composite( targetGroup, path, optionalParsedPath ) {
  26828. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26829. this._targetGroup = targetGroup;
  26830. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26831. }
  26832. Object.assign( Composite.prototype, {
  26833. getValue: function ( array, offset ) {
  26834. this.bind(); // bind all binding
  26835. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26836. binding = this._bindings[ firstValidIndex ];
  26837. // and only call .getValue on the first
  26838. if ( binding !== undefined ) binding.getValue( array, offset );
  26839. },
  26840. setValue: function ( array, offset ) {
  26841. const bindings = this._bindings;
  26842. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26843. bindings[ i ].setValue( array, offset );
  26844. }
  26845. },
  26846. bind: function () {
  26847. const bindings = this._bindings;
  26848. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26849. bindings[ i ].bind();
  26850. }
  26851. },
  26852. unbind: function () {
  26853. const bindings = this._bindings;
  26854. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26855. bindings[ i ].unbind();
  26856. }
  26857. }
  26858. } );
  26859. function PropertyBinding( rootNode, path, parsedPath ) {
  26860. this.path = path;
  26861. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26862. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26863. this.rootNode = rootNode;
  26864. }
  26865. Object.assign( PropertyBinding, {
  26866. Composite: Composite,
  26867. create: function ( root, path, parsedPath ) {
  26868. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26869. return new PropertyBinding( root, path, parsedPath );
  26870. } else {
  26871. return new PropertyBinding.Composite( root, path, parsedPath );
  26872. }
  26873. },
  26874. /**
  26875. * Replaces spaces with underscores and removes unsupported characters from
  26876. * node names, to ensure compatibility with parseTrackName().
  26877. *
  26878. * @param {string} name Node name to be sanitized.
  26879. * @return {string}
  26880. */
  26881. sanitizeNodeName: function ( name ) {
  26882. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26883. },
  26884. parseTrackName: function ( trackName ) {
  26885. const matches = _trackRe.exec( trackName );
  26886. if ( ! matches ) {
  26887. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26888. }
  26889. const results = {
  26890. // directoryName: matches[ 1 ], // (tschw) currently unused
  26891. nodeName: matches[ 2 ],
  26892. objectName: matches[ 3 ],
  26893. objectIndex: matches[ 4 ],
  26894. propertyName: matches[ 5 ], // required
  26895. propertyIndex: matches[ 6 ]
  26896. };
  26897. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26898. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26899. const objectName = results.nodeName.substring( lastDot + 1 );
  26900. // Object names must be checked against an allowlist. Otherwise, there
  26901. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26902. // 'bar' could be the objectName, or part of a nodeName (which can
  26903. // include '.' characters).
  26904. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26905. results.nodeName = results.nodeName.substring( 0, lastDot );
  26906. results.objectName = objectName;
  26907. }
  26908. }
  26909. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26910. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26911. }
  26912. return results;
  26913. },
  26914. findNode: function ( root, nodeName ) {
  26915. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26916. return root;
  26917. }
  26918. // search into skeleton bones.
  26919. if ( root.skeleton ) {
  26920. const bone = root.skeleton.getBoneByName( nodeName );
  26921. if ( bone !== undefined ) {
  26922. return bone;
  26923. }
  26924. }
  26925. // search into node subtree.
  26926. if ( root.children ) {
  26927. const searchNodeSubtree = function ( children ) {
  26928. for ( let i = 0; i < children.length; i ++ ) {
  26929. const childNode = children[ i ];
  26930. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26931. return childNode;
  26932. }
  26933. const result = searchNodeSubtree( childNode.children );
  26934. if ( result ) return result;
  26935. }
  26936. return null;
  26937. };
  26938. const subTreeNode = searchNodeSubtree( root.children );
  26939. if ( subTreeNode ) {
  26940. return subTreeNode;
  26941. }
  26942. }
  26943. return null;
  26944. }
  26945. } );
  26946. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26947. // these are used to "bind" a nonexistent property
  26948. _getValue_unavailable: function () {},
  26949. _setValue_unavailable: function () {},
  26950. BindingType: {
  26951. Direct: 0,
  26952. EntireArray: 1,
  26953. ArrayElement: 2,
  26954. HasFromToArray: 3
  26955. },
  26956. Versioning: {
  26957. None: 0,
  26958. NeedsUpdate: 1,
  26959. MatrixWorldNeedsUpdate: 2
  26960. },
  26961. GetterByBindingType: [
  26962. function getValue_direct( buffer, offset ) {
  26963. buffer[ offset ] = this.node[ this.propertyName ];
  26964. },
  26965. function getValue_array( buffer, offset ) {
  26966. const source = this.resolvedProperty;
  26967. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26968. buffer[ offset ++ ] = source[ i ];
  26969. }
  26970. },
  26971. function getValue_arrayElement( buffer, offset ) {
  26972. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26973. },
  26974. function getValue_toArray( buffer, offset ) {
  26975. this.resolvedProperty.toArray( buffer, offset );
  26976. }
  26977. ],
  26978. SetterByBindingTypeAndVersioning: [
  26979. [
  26980. // Direct
  26981. function setValue_direct( buffer, offset ) {
  26982. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26983. },
  26984. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26985. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26986. this.targetObject.needsUpdate = true;
  26987. },
  26988. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26989. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26990. this.targetObject.matrixWorldNeedsUpdate = true;
  26991. }
  26992. ], [
  26993. // EntireArray
  26994. function setValue_array( buffer, offset ) {
  26995. const dest = this.resolvedProperty;
  26996. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26997. dest[ i ] = buffer[ offset ++ ];
  26998. }
  26999. },
  27000. function setValue_array_setNeedsUpdate( buffer, offset ) {
  27001. const dest = this.resolvedProperty;
  27002. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27003. dest[ i ] = buffer[ offset ++ ];
  27004. }
  27005. this.targetObject.needsUpdate = true;
  27006. },
  27007. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27008. const dest = this.resolvedProperty;
  27009. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27010. dest[ i ] = buffer[ offset ++ ];
  27011. }
  27012. this.targetObject.matrixWorldNeedsUpdate = true;
  27013. }
  27014. ], [
  27015. // ArrayElement
  27016. function setValue_arrayElement( buffer, offset ) {
  27017. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27018. },
  27019. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27020. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27021. this.targetObject.needsUpdate = true;
  27022. },
  27023. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27024. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27025. this.targetObject.matrixWorldNeedsUpdate = true;
  27026. }
  27027. ], [
  27028. // HasToFromArray
  27029. function setValue_fromArray( buffer, offset ) {
  27030. this.resolvedProperty.fromArray( buffer, offset );
  27031. },
  27032. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27033. this.resolvedProperty.fromArray( buffer, offset );
  27034. this.targetObject.needsUpdate = true;
  27035. },
  27036. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27037. this.resolvedProperty.fromArray( buffer, offset );
  27038. this.targetObject.matrixWorldNeedsUpdate = true;
  27039. }
  27040. ]
  27041. ],
  27042. getValue: function getValue_unbound( targetArray, offset ) {
  27043. this.bind();
  27044. this.getValue( targetArray, offset );
  27045. // Note: This class uses a State pattern on a per-method basis:
  27046. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27047. // prototype version of these methods with one that represents
  27048. // the bound state. When the property is not found, the methods
  27049. // become no-ops.
  27050. },
  27051. setValue: function getValue_unbound( sourceArray, offset ) {
  27052. this.bind();
  27053. this.setValue( sourceArray, offset );
  27054. },
  27055. // create getter / setter pair for a property in the scene graph
  27056. bind: function () {
  27057. let targetObject = this.node;
  27058. const parsedPath = this.parsedPath;
  27059. const objectName = parsedPath.objectName;
  27060. const propertyName = parsedPath.propertyName;
  27061. let propertyIndex = parsedPath.propertyIndex;
  27062. if ( ! targetObject ) {
  27063. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27064. this.node = targetObject;
  27065. }
  27066. // set fail state so we can just 'return' on error
  27067. this.getValue = this._getValue_unavailable;
  27068. this.setValue = this._setValue_unavailable;
  27069. // ensure there is a value node
  27070. if ( ! targetObject ) {
  27071. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27072. return;
  27073. }
  27074. if ( objectName ) {
  27075. let objectIndex = parsedPath.objectIndex;
  27076. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27077. switch ( objectName ) {
  27078. case 'materials':
  27079. if ( ! targetObject.material ) {
  27080. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27081. return;
  27082. }
  27083. if ( ! targetObject.material.materials ) {
  27084. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27085. return;
  27086. }
  27087. targetObject = targetObject.material.materials;
  27088. break;
  27089. case 'bones':
  27090. if ( ! targetObject.skeleton ) {
  27091. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27092. return;
  27093. }
  27094. // potential future optimization: skip this if propertyIndex is already an integer
  27095. // and convert the integer string to a true integer.
  27096. targetObject = targetObject.skeleton.bones;
  27097. // support resolving morphTarget names into indices.
  27098. for ( let i = 0; i < targetObject.length; i ++ ) {
  27099. if ( targetObject[ i ].name === objectIndex ) {
  27100. objectIndex = i;
  27101. break;
  27102. }
  27103. }
  27104. break;
  27105. default:
  27106. if ( targetObject[ objectName ] === undefined ) {
  27107. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27108. return;
  27109. }
  27110. targetObject = targetObject[ objectName ];
  27111. }
  27112. if ( objectIndex !== undefined ) {
  27113. if ( targetObject[ objectIndex ] === undefined ) {
  27114. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27115. return;
  27116. }
  27117. targetObject = targetObject[ objectIndex ];
  27118. }
  27119. }
  27120. // resolve property
  27121. const nodeProperty = targetObject[ propertyName ];
  27122. if ( nodeProperty === undefined ) {
  27123. const nodeName = parsedPath.nodeName;
  27124. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27125. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27126. return;
  27127. }
  27128. // determine versioning scheme
  27129. let versioning = this.Versioning.None;
  27130. this.targetObject = targetObject;
  27131. if ( targetObject.needsUpdate !== undefined ) { // material
  27132. versioning = this.Versioning.NeedsUpdate;
  27133. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27134. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27135. }
  27136. // determine how the property gets bound
  27137. let bindingType = this.BindingType.Direct;
  27138. if ( propertyIndex !== undefined ) {
  27139. // access a sub element of the property array (only primitives are supported right now)
  27140. if ( propertyName === 'morphTargetInfluences' ) {
  27141. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27142. // support resolving morphTarget names into indices.
  27143. if ( ! targetObject.geometry ) {
  27144. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27145. return;
  27146. }
  27147. if ( targetObject.geometry.isBufferGeometry ) {
  27148. if ( ! targetObject.geometry.morphAttributes ) {
  27149. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27150. return;
  27151. }
  27152. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27153. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27154. }
  27155. } else {
  27156. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  27157. return;
  27158. }
  27159. }
  27160. bindingType = this.BindingType.ArrayElement;
  27161. this.resolvedProperty = nodeProperty;
  27162. this.propertyIndex = propertyIndex;
  27163. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27164. // must use copy for Object3D.Euler/Quaternion
  27165. bindingType = this.BindingType.HasFromToArray;
  27166. this.resolvedProperty = nodeProperty;
  27167. } else if ( Array.isArray( nodeProperty ) ) {
  27168. bindingType = this.BindingType.EntireArray;
  27169. this.resolvedProperty = nodeProperty;
  27170. } else {
  27171. this.propertyName = propertyName;
  27172. }
  27173. // select getter / setter
  27174. this.getValue = this.GetterByBindingType[ bindingType ];
  27175. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27176. },
  27177. unbind: function () {
  27178. this.node = null;
  27179. // back to the prototype version of getValue / setValue
  27180. // note: avoiding to mutate the shape of 'this' via 'delete'
  27181. this.getValue = this._getValue_unbound;
  27182. this.setValue = this._setValue_unbound;
  27183. }
  27184. } );
  27185. // DECLARE ALIAS AFTER assign prototype
  27186. Object.assign( PropertyBinding.prototype, {
  27187. // initial state of these methods that calls 'bind'
  27188. _getValue_unbound: PropertyBinding.prototype.getValue,
  27189. _setValue_unbound: PropertyBinding.prototype.setValue,
  27190. } );
  27191. /**
  27192. *
  27193. * A group of objects that receives a shared animation state.
  27194. *
  27195. * Usage:
  27196. *
  27197. * - Add objects you would otherwise pass as 'root' to the
  27198. * constructor or the .clipAction method of AnimationMixer.
  27199. *
  27200. * - Instead pass this object as 'root'.
  27201. *
  27202. * - You can also add and remove objects later when the mixer
  27203. * is running.
  27204. *
  27205. * Note:
  27206. *
  27207. * Objects of this class appear as one object to the mixer,
  27208. * so cache control of the individual objects must be done
  27209. * on the group.
  27210. *
  27211. * Limitation:
  27212. *
  27213. * - The animated properties must be compatible among the
  27214. * all objects in the group.
  27215. *
  27216. * - A single property can either be controlled through a
  27217. * target group or directly, but not both.
  27218. */
  27219. function AnimationObjectGroup() {
  27220. this.uuid = MathUtils.generateUUID();
  27221. // cached objects followed by the active ones
  27222. this._objects = Array.prototype.slice.call( arguments );
  27223. this.nCachedObjects_ = 0; // threshold
  27224. // note: read by PropertyBinding.Composite
  27225. const indices = {};
  27226. this._indicesByUUID = indices; // for bookkeeping
  27227. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27228. indices[ arguments[ i ].uuid ] = i;
  27229. }
  27230. this._paths = []; // inside: string
  27231. this._parsedPaths = []; // inside: { we don't care, here }
  27232. this._bindings = []; // inside: Array< PropertyBinding >
  27233. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27234. const scope = this;
  27235. this.stats = {
  27236. objects: {
  27237. get total() {
  27238. return scope._objects.length;
  27239. },
  27240. get inUse() {
  27241. return this.total - scope.nCachedObjects_;
  27242. }
  27243. },
  27244. get bindingsPerObject() {
  27245. return scope._bindings.length;
  27246. }
  27247. };
  27248. }
  27249. Object.assign( AnimationObjectGroup.prototype, {
  27250. isAnimationObjectGroup: true,
  27251. add: function () {
  27252. const objects = this._objects,
  27253. indicesByUUID = this._indicesByUUID,
  27254. paths = this._paths,
  27255. parsedPaths = this._parsedPaths,
  27256. bindings = this._bindings,
  27257. nBindings = bindings.length;
  27258. let knownObject = undefined,
  27259. nObjects = objects.length,
  27260. nCachedObjects = this.nCachedObjects_;
  27261. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27262. const object = arguments[ i ],
  27263. uuid = object.uuid;
  27264. let index = indicesByUUID[ uuid ];
  27265. if ( index === undefined ) {
  27266. // unknown object -> add it to the ACTIVE region
  27267. index = nObjects ++;
  27268. indicesByUUID[ uuid ] = index;
  27269. objects.push( object );
  27270. // accounting is done, now do the same for all bindings
  27271. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27272. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27273. }
  27274. } else if ( index < nCachedObjects ) {
  27275. knownObject = objects[ index ];
  27276. // move existing object to the ACTIVE region
  27277. const firstActiveIndex = -- nCachedObjects,
  27278. lastCachedObject = objects[ firstActiveIndex ];
  27279. indicesByUUID[ lastCachedObject.uuid ] = index;
  27280. objects[ index ] = lastCachedObject;
  27281. indicesByUUID[ uuid ] = firstActiveIndex;
  27282. objects[ firstActiveIndex ] = object;
  27283. // accounting is done, now do the same for all bindings
  27284. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27285. const bindingsForPath = bindings[ j ],
  27286. lastCached = bindingsForPath[ firstActiveIndex ];
  27287. let binding = bindingsForPath[ index ];
  27288. bindingsForPath[ index ] = lastCached;
  27289. if ( binding === undefined ) {
  27290. // since we do not bother to create new bindings
  27291. // for objects that are cached, the binding may
  27292. // or may not exist
  27293. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27294. }
  27295. bindingsForPath[ firstActiveIndex ] = binding;
  27296. }
  27297. } else if ( objects[ index ] !== knownObject ) {
  27298. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27299. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27300. } // else the object is already where we want it to be
  27301. } // for arguments
  27302. this.nCachedObjects_ = nCachedObjects;
  27303. },
  27304. remove: function () {
  27305. const objects = this._objects,
  27306. indicesByUUID = this._indicesByUUID,
  27307. bindings = this._bindings,
  27308. nBindings = bindings.length;
  27309. let nCachedObjects = this.nCachedObjects_;
  27310. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27311. const object = arguments[ i ],
  27312. uuid = object.uuid,
  27313. index = indicesByUUID[ uuid ];
  27314. if ( index !== undefined && index >= nCachedObjects ) {
  27315. // move existing object into the CACHED region
  27316. const lastCachedIndex = nCachedObjects ++,
  27317. firstActiveObject = objects[ lastCachedIndex ];
  27318. indicesByUUID[ firstActiveObject.uuid ] = index;
  27319. objects[ index ] = firstActiveObject;
  27320. indicesByUUID[ uuid ] = lastCachedIndex;
  27321. objects[ lastCachedIndex ] = object;
  27322. // accounting is done, now do the same for all bindings
  27323. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27324. const bindingsForPath = bindings[ j ],
  27325. firstActive = bindingsForPath[ lastCachedIndex ],
  27326. binding = bindingsForPath[ index ];
  27327. bindingsForPath[ index ] = firstActive;
  27328. bindingsForPath[ lastCachedIndex ] = binding;
  27329. }
  27330. }
  27331. } // for arguments
  27332. this.nCachedObjects_ = nCachedObjects;
  27333. },
  27334. // remove & forget
  27335. uncache: function () {
  27336. const objects = this._objects,
  27337. indicesByUUID = this._indicesByUUID,
  27338. bindings = this._bindings,
  27339. nBindings = bindings.length;
  27340. let nCachedObjects = this.nCachedObjects_,
  27341. nObjects = objects.length;
  27342. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27343. const object = arguments[ i ],
  27344. uuid = object.uuid,
  27345. index = indicesByUUID[ uuid ];
  27346. if ( index !== undefined ) {
  27347. delete indicesByUUID[ uuid ];
  27348. if ( index < nCachedObjects ) {
  27349. // object is cached, shrink the CACHED region
  27350. const firstActiveIndex = -- nCachedObjects,
  27351. lastCachedObject = objects[ firstActiveIndex ],
  27352. lastIndex = -- nObjects,
  27353. lastObject = objects[ lastIndex ];
  27354. // last cached object takes this object's place
  27355. indicesByUUID[ lastCachedObject.uuid ] = index;
  27356. objects[ index ] = lastCachedObject;
  27357. // last object goes to the activated slot and pop
  27358. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27359. objects[ firstActiveIndex ] = lastObject;
  27360. objects.pop();
  27361. // accounting is done, now do the same for all bindings
  27362. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27363. const bindingsForPath = bindings[ j ],
  27364. lastCached = bindingsForPath[ firstActiveIndex ],
  27365. last = bindingsForPath[ lastIndex ];
  27366. bindingsForPath[ index ] = lastCached;
  27367. bindingsForPath[ firstActiveIndex ] = last;
  27368. bindingsForPath.pop();
  27369. }
  27370. } else {
  27371. // object is active, just swap with the last and pop
  27372. const lastIndex = -- nObjects,
  27373. lastObject = objects[ lastIndex ];
  27374. if ( lastIndex > 0 ) {
  27375. indicesByUUID[ lastObject.uuid ] = index;
  27376. }
  27377. objects[ index ] = lastObject;
  27378. objects.pop();
  27379. // accounting is done, now do the same for all bindings
  27380. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27381. const bindingsForPath = bindings[ j ];
  27382. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27383. bindingsForPath.pop();
  27384. }
  27385. } // cached or active
  27386. } // if object is known
  27387. } // for arguments
  27388. this.nCachedObjects_ = nCachedObjects;
  27389. },
  27390. // Internal interface used by befriended PropertyBinding.Composite:
  27391. subscribe_: function ( path, parsedPath ) {
  27392. // returns an array of bindings for the given path that is changed
  27393. // according to the contained objects in the group
  27394. const indicesByPath = this._bindingsIndicesByPath;
  27395. let index = indicesByPath[ path ];
  27396. const bindings = this._bindings;
  27397. if ( index !== undefined ) return bindings[ index ];
  27398. const paths = this._paths,
  27399. parsedPaths = this._parsedPaths,
  27400. objects = this._objects,
  27401. nObjects = objects.length,
  27402. nCachedObjects = this.nCachedObjects_,
  27403. bindingsForPath = new Array( nObjects );
  27404. index = bindings.length;
  27405. indicesByPath[ path ] = index;
  27406. paths.push( path );
  27407. parsedPaths.push( parsedPath );
  27408. bindings.push( bindingsForPath );
  27409. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27410. const object = objects[ i ];
  27411. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27412. }
  27413. return bindingsForPath;
  27414. },
  27415. unsubscribe_: function ( path ) {
  27416. // tells the group to forget about a property path and no longer
  27417. // update the array previously obtained with 'subscribe_'
  27418. const indicesByPath = this._bindingsIndicesByPath,
  27419. index = indicesByPath[ path ];
  27420. if ( index !== undefined ) {
  27421. const paths = this._paths,
  27422. parsedPaths = this._parsedPaths,
  27423. bindings = this._bindings,
  27424. lastBindingsIndex = bindings.length - 1,
  27425. lastBindings = bindings[ lastBindingsIndex ],
  27426. lastBindingsPath = path[ lastBindingsIndex ];
  27427. indicesByPath[ lastBindingsPath ] = index;
  27428. bindings[ index ] = lastBindings;
  27429. bindings.pop();
  27430. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27431. parsedPaths.pop();
  27432. paths[ index ] = paths[ lastBindingsIndex ];
  27433. paths.pop();
  27434. }
  27435. }
  27436. } );
  27437. class AnimationAction {
  27438. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27439. this._mixer = mixer;
  27440. this._clip = clip;
  27441. this._localRoot = localRoot;
  27442. this.blendMode = blendMode;
  27443. const tracks = clip.tracks,
  27444. nTracks = tracks.length,
  27445. interpolants = new Array( nTracks );
  27446. const interpolantSettings = {
  27447. endingStart: ZeroCurvatureEnding,
  27448. endingEnd: ZeroCurvatureEnding
  27449. };
  27450. for ( let i = 0; i !== nTracks; ++ i ) {
  27451. const interpolant = tracks[ i ].createInterpolant( null );
  27452. interpolants[ i ] = interpolant;
  27453. interpolant.settings = interpolantSettings;
  27454. }
  27455. this._interpolantSettings = interpolantSettings;
  27456. this._interpolants = interpolants; // bound by the mixer
  27457. // inside: PropertyMixer (managed by the mixer)
  27458. this._propertyBindings = new Array( nTracks );
  27459. this._cacheIndex = null; // for the memory manager
  27460. this._byClipCacheIndex = null; // for the memory manager
  27461. this._timeScaleInterpolant = null;
  27462. this._weightInterpolant = null;
  27463. this.loop = LoopRepeat;
  27464. this._loopCount = - 1;
  27465. // global mixer time when the action is to be started
  27466. // it's set back to 'null' upon start of the action
  27467. this._startTime = null;
  27468. // scaled local time of the action
  27469. // gets clamped or wrapped to 0..clip.duration according to loop
  27470. this.time = 0;
  27471. this.timeScale = 1;
  27472. this._effectiveTimeScale = 1;
  27473. this.weight = 1;
  27474. this._effectiveWeight = 1;
  27475. this.repetitions = Infinity; // no. of repetitions when looping
  27476. this.paused = false; // true -> zero effective time scale
  27477. this.enabled = true; // false -> zero effective weight
  27478. this.clampWhenFinished = false;// keep feeding the last frame?
  27479. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27480. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27481. }
  27482. // State & Scheduling
  27483. play() {
  27484. this._mixer._activateAction( this );
  27485. return this;
  27486. }
  27487. stop() {
  27488. this._mixer._deactivateAction( this );
  27489. return this.reset();
  27490. }
  27491. reset() {
  27492. this.paused = false;
  27493. this.enabled = true;
  27494. this.time = 0; // restart clip
  27495. this._loopCount = - 1;// forget previous loops
  27496. this._startTime = null;// forget scheduling
  27497. return this.stopFading().stopWarping();
  27498. }
  27499. isRunning() {
  27500. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27501. this._startTime === null && this._mixer._isActiveAction( this );
  27502. }
  27503. // return true when play has been called
  27504. isScheduled() {
  27505. return this._mixer._isActiveAction( this );
  27506. }
  27507. startAt( time ) {
  27508. this._startTime = time;
  27509. return this;
  27510. }
  27511. setLoop( mode, repetitions ) {
  27512. this.loop = mode;
  27513. this.repetitions = repetitions;
  27514. return this;
  27515. }
  27516. // Weight
  27517. // set the weight stopping any scheduled fading
  27518. // although .enabled = false yields an effective weight of zero, this
  27519. // method does *not* change .enabled, because it would be confusing
  27520. setEffectiveWeight( weight ) {
  27521. this.weight = weight;
  27522. // note: same logic as when updated at runtime
  27523. this._effectiveWeight = this.enabled ? weight : 0;
  27524. return this.stopFading();
  27525. }
  27526. // return the weight considering fading and .enabled
  27527. getEffectiveWeight() {
  27528. return this._effectiveWeight;
  27529. }
  27530. fadeIn( duration ) {
  27531. return this._scheduleFading( duration, 0, 1 );
  27532. }
  27533. fadeOut( duration ) {
  27534. return this._scheduleFading( duration, 1, 0 );
  27535. }
  27536. crossFadeFrom( fadeOutAction, duration, warp ) {
  27537. fadeOutAction.fadeOut( duration );
  27538. this.fadeIn( duration );
  27539. if ( warp ) {
  27540. const fadeInDuration = this._clip.duration,
  27541. fadeOutDuration = fadeOutAction._clip.duration,
  27542. startEndRatio = fadeOutDuration / fadeInDuration,
  27543. endStartRatio = fadeInDuration / fadeOutDuration;
  27544. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27545. this.warp( endStartRatio, 1.0, duration );
  27546. }
  27547. return this;
  27548. }
  27549. crossFadeTo( fadeInAction, duration, warp ) {
  27550. return fadeInAction.crossFadeFrom( this, duration, warp );
  27551. }
  27552. stopFading() {
  27553. const weightInterpolant = this._weightInterpolant;
  27554. if ( weightInterpolant !== null ) {
  27555. this._weightInterpolant = null;
  27556. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27557. }
  27558. return this;
  27559. }
  27560. // Time Scale Control
  27561. // set the time scale stopping any scheduled warping
  27562. // although .paused = true yields an effective time scale of zero, this
  27563. // method does *not* change .paused, because it would be confusing
  27564. setEffectiveTimeScale( timeScale ) {
  27565. this.timeScale = timeScale;
  27566. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27567. return this.stopWarping();
  27568. }
  27569. // return the time scale considering warping and .paused
  27570. getEffectiveTimeScale() {
  27571. return this._effectiveTimeScale;
  27572. }
  27573. setDuration( duration ) {
  27574. this.timeScale = this._clip.duration / duration;
  27575. return this.stopWarping();
  27576. }
  27577. syncWith( action ) {
  27578. this.time = action.time;
  27579. this.timeScale = action.timeScale;
  27580. return this.stopWarping();
  27581. }
  27582. halt( duration ) {
  27583. return this.warp( this._effectiveTimeScale, 0, duration );
  27584. }
  27585. warp( startTimeScale, endTimeScale, duration ) {
  27586. const mixer = this._mixer,
  27587. now = mixer.time,
  27588. timeScale = this.timeScale;
  27589. let interpolant = this._timeScaleInterpolant;
  27590. if ( interpolant === null ) {
  27591. interpolant = mixer._lendControlInterpolant();
  27592. this._timeScaleInterpolant = interpolant;
  27593. }
  27594. const times = interpolant.parameterPositions,
  27595. values = interpolant.sampleValues;
  27596. times[ 0 ] = now;
  27597. times[ 1 ] = now + duration;
  27598. values[ 0 ] = startTimeScale / timeScale;
  27599. values[ 1 ] = endTimeScale / timeScale;
  27600. return this;
  27601. }
  27602. stopWarping() {
  27603. const timeScaleInterpolant = this._timeScaleInterpolant;
  27604. if ( timeScaleInterpolant !== null ) {
  27605. this._timeScaleInterpolant = null;
  27606. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27607. }
  27608. return this;
  27609. }
  27610. // Object Accessors
  27611. getMixer() {
  27612. return this._mixer;
  27613. }
  27614. getClip() {
  27615. return this._clip;
  27616. }
  27617. getRoot() {
  27618. return this._localRoot || this._mixer._root;
  27619. }
  27620. // Interna
  27621. _update( time, deltaTime, timeDirection, accuIndex ) {
  27622. // called by the mixer
  27623. if ( ! this.enabled ) {
  27624. // call ._updateWeight() to update ._effectiveWeight
  27625. this._updateWeight( time );
  27626. return;
  27627. }
  27628. const startTime = this._startTime;
  27629. if ( startTime !== null ) {
  27630. // check for scheduled start of action
  27631. const timeRunning = ( time - startTime ) * timeDirection;
  27632. if ( timeRunning < 0 || timeDirection === 0 ) {
  27633. return; // yet to come / don't decide when delta = 0
  27634. }
  27635. // start
  27636. this._startTime = null; // unschedule
  27637. deltaTime = timeDirection * timeRunning;
  27638. }
  27639. // apply time scale and advance time
  27640. deltaTime *= this._updateTimeScale( time );
  27641. const clipTime = this._updateTime( deltaTime );
  27642. // note: _updateTime may disable the action resulting in
  27643. // an effective weight of 0
  27644. const weight = this._updateWeight( time );
  27645. if ( weight > 0 ) {
  27646. const interpolants = this._interpolants;
  27647. const propertyMixers = this._propertyBindings;
  27648. switch ( this.blendMode ) {
  27649. case AdditiveAnimationBlendMode:
  27650. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27651. interpolants[ j ].evaluate( clipTime );
  27652. propertyMixers[ j ].accumulateAdditive( weight );
  27653. }
  27654. break;
  27655. case NormalAnimationBlendMode:
  27656. default:
  27657. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27658. interpolants[ j ].evaluate( clipTime );
  27659. propertyMixers[ j ].accumulate( accuIndex, weight );
  27660. }
  27661. }
  27662. }
  27663. }
  27664. _updateWeight( time ) {
  27665. let weight = 0;
  27666. if ( this.enabled ) {
  27667. weight = this.weight;
  27668. const interpolant = this._weightInterpolant;
  27669. if ( interpolant !== null ) {
  27670. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27671. weight *= interpolantValue;
  27672. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27673. this.stopFading();
  27674. if ( interpolantValue === 0 ) {
  27675. // faded out, disable
  27676. this.enabled = false;
  27677. }
  27678. }
  27679. }
  27680. }
  27681. this._effectiveWeight = weight;
  27682. return weight;
  27683. }
  27684. _updateTimeScale( time ) {
  27685. let timeScale = 0;
  27686. if ( ! this.paused ) {
  27687. timeScale = this.timeScale;
  27688. const interpolant = this._timeScaleInterpolant;
  27689. if ( interpolant !== null ) {
  27690. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27691. timeScale *= interpolantValue;
  27692. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27693. this.stopWarping();
  27694. if ( timeScale === 0 ) {
  27695. // motion has halted, pause
  27696. this.paused = true;
  27697. } else {
  27698. // warp done - apply final time scale
  27699. this.timeScale = timeScale;
  27700. }
  27701. }
  27702. }
  27703. }
  27704. this._effectiveTimeScale = timeScale;
  27705. return timeScale;
  27706. }
  27707. _updateTime( deltaTime ) {
  27708. const duration = this._clip.duration;
  27709. const loop = this.loop;
  27710. let time = this.time + deltaTime;
  27711. let loopCount = this._loopCount;
  27712. const pingPong = ( loop === LoopPingPong );
  27713. if ( deltaTime === 0 ) {
  27714. if ( loopCount === - 1 ) return time;
  27715. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27716. }
  27717. if ( loop === LoopOnce ) {
  27718. if ( loopCount === - 1 ) {
  27719. // just started
  27720. this._loopCount = 0;
  27721. this._setEndings( true, true, false );
  27722. }
  27723. handle_stop: {
  27724. if ( time >= duration ) {
  27725. time = duration;
  27726. } else if ( time < 0 ) {
  27727. time = 0;
  27728. } else {
  27729. this.time = time;
  27730. break handle_stop;
  27731. }
  27732. if ( this.clampWhenFinished ) this.paused = true;
  27733. else this.enabled = false;
  27734. this.time = time;
  27735. this._mixer.dispatchEvent( {
  27736. type: 'finished', action: this,
  27737. direction: deltaTime < 0 ? - 1 : 1
  27738. } );
  27739. }
  27740. } else { // repetitive Repeat or PingPong
  27741. if ( loopCount === - 1 ) {
  27742. // just started
  27743. if ( deltaTime >= 0 ) {
  27744. loopCount = 0;
  27745. this._setEndings( true, this.repetitions === 0, pingPong );
  27746. } else {
  27747. // when looping in reverse direction, the initial
  27748. // transition through zero counts as a repetition,
  27749. // so leave loopCount at -1
  27750. this._setEndings( this.repetitions === 0, true, pingPong );
  27751. }
  27752. }
  27753. if ( time >= duration || time < 0 ) {
  27754. // wrap around
  27755. const loopDelta = Math.floor( time / duration ); // signed
  27756. time -= duration * loopDelta;
  27757. loopCount += Math.abs( loopDelta );
  27758. const pending = this.repetitions - loopCount;
  27759. if ( pending <= 0 ) {
  27760. // have to stop (switch state, clamp time, fire event)
  27761. if ( this.clampWhenFinished ) this.paused = true;
  27762. else this.enabled = false;
  27763. time = deltaTime > 0 ? duration : 0;
  27764. this.time = time;
  27765. this._mixer.dispatchEvent( {
  27766. type: 'finished', action: this,
  27767. direction: deltaTime > 0 ? 1 : - 1
  27768. } );
  27769. } else {
  27770. // keep running
  27771. if ( pending === 1 ) {
  27772. // entering the last round
  27773. const atStart = deltaTime < 0;
  27774. this._setEndings( atStart, ! atStart, pingPong );
  27775. } else {
  27776. this._setEndings( false, false, pingPong );
  27777. }
  27778. this._loopCount = loopCount;
  27779. this.time = time;
  27780. this._mixer.dispatchEvent( {
  27781. type: 'loop', action: this, loopDelta: loopDelta
  27782. } );
  27783. }
  27784. } else {
  27785. this.time = time;
  27786. }
  27787. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27788. // invert time for the "pong round"
  27789. return duration - time;
  27790. }
  27791. }
  27792. return time;
  27793. }
  27794. _setEndings( atStart, atEnd, pingPong ) {
  27795. const settings = this._interpolantSettings;
  27796. if ( pingPong ) {
  27797. settings.endingStart = ZeroSlopeEnding;
  27798. settings.endingEnd = ZeroSlopeEnding;
  27799. } else {
  27800. // assuming for LoopOnce atStart == atEnd == true
  27801. if ( atStart ) {
  27802. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27803. } else {
  27804. settings.endingStart = WrapAroundEnding;
  27805. }
  27806. if ( atEnd ) {
  27807. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27808. } else {
  27809. settings.endingEnd = WrapAroundEnding;
  27810. }
  27811. }
  27812. }
  27813. _scheduleFading( duration, weightNow, weightThen ) {
  27814. const mixer = this._mixer, now = mixer.time;
  27815. let interpolant = this._weightInterpolant;
  27816. if ( interpolant === null ) {
  27817. interpolant = mixer._lendControlInterpolant();
  27818. this._weightInterpolant = interpolant;
  27819. }
  27820. const times = interpolant.parameterPositions,
  27821. values = interpolant.sampleValues;
  27822. times[ 0 ] = now;
  27823. values[ 0 ] = weightNow;
  27824. times[ 1 ] = now + duration;
  27825. values[ 1 ] = weightThen;
  27826. return this;
  27827. }
  27828. }
  27829. function AnimationMixer( root ) {
  27830. this._root = root;
  27831. this._initMemoryManager();
  27832. this._accuIndex = 0;
  27833. this.time = 0;
  27834. this.timeScale = 1.0;
  27835. }
  27836. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  27837. constructor: AnimationMixer,
  27838. _bindAction: function ( action, prototypeAction ) {
  27839. const root = action._localRoot || this._root,
  27840. tracks = action._clip.tracks,
  27841. nTracks = tracks.length,
  27842. bindings = action._propertyBindings,
  27843. interpolants = action._interpolants,
  27844. rootUuid = root.uuid,
  27845. bindingsByRoot = this._bindingsByRootAndName;
  27846. let bindingsByName = bindingsByRoot[ rootUuid ];
  27847. if ( bindingsByName === undefined ) {
  27848. bindingsByName = {};
  27849. bindingsByRoot[ rootUuid ] = bindingsByName;
  27850. }
  27851. for ( let i = 0; i !== nTracks; ++ i ) {
  27852. const track = tracks[ i ],
  27853. trackName = track.name;
  27854. let binding = bindingsByName[ trackName ];
  27855. if ( binding !== undefined ) {
  27856. bindings[ i ] = binding;
  27857. } else {
  27858. binding = bindings[ i ];
  27859. if ( binding !== undefined ) {
  27860. // existing binding, make sure the cache knows
  27861. if ( binding._cacheIndex === null ) {
  27862. ++ binding.referenceCount;
  27863. this._addInactiveBinding( binding, rootUuid, trackName );
  27864. }
  27865. continue;
  27866. }
  27867. const path = prototypeAction && prototypeAction.
  27868. _propertyBindings[ i ].binding.parsedPath;
  27869. binding = new PropertyMixer(
  27870. PropertyBinding.create( root, trackName, path ),
  27871. track.ValueTypeName, track.getValueSize() );
  27872. ++ binding.referenceCount;
  27873. this._addInactiveBinding( binding, rootUuid, trackName );
  27874. bindings[ i ] = binding;
  27875. }
  27876. interpolants[ i ].resultBuffer = binding.buffer;
  27877. }
  27878. },
  27879. _activateAction: function ( action ) {
  27880. if ( ! this._isActiveAction( action ) ) {
  27881. if ( action._cacheIndex === null ) {
  27882. // this action has been forgotten by the cache, but the user
  27883. // appears to be still using it -> rebind
  27884. const rootUuid = ( action._localRoot || this._root ).uuid,
  27885. clipUuid = action._clip.uuid,
  27886. actionsForClip = this._actionsByClip[ clipUuid ];
  27887. this._bindAction( action,
  27888. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27889. this._addInactiveAction( action, clipUuid, rootUuid );
  27890. }
  27891. const bindings = action._propertyBindings;
  27892. // increment reference counts / sort out state
  27893. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27894. const binding = bindings[ i ];
  27895. if ( binding.useCount ++ === 0 ) {
  27896. this._lendBinding( binding );
  27897. binding.saveOriginalState();
  27898. }
  27899. }
  27900. this._lendAction( action );
  27901. }
  27902. },
  27903. _deactivateAction: function ( action ) {
  27904. if ( this._isActiveAction( action ) ) {
  27905. const bindings = action._propertyBindings;
  27906. // decrement reference counts / sort out state
  27907. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27908. const binding = bindings[ i ];
  27909. if ( -- binding.useCount === 0 ) {
  27910. binding.restoreOriginalState();
  27911. this._takeBackBinding( binding );
  27912. }
  27913. }
  27914. this._takeBackAction( action );
  27915. }
  27916. },
  27917. // Memory manager
  27918. _initMemoryManager: function () {
  27919. this._actions = []; // 'nActiveActions' followed by inactive ones
  27920. this._nActiveActions = 0;
  27921. this._actionsByClip = {};
  27922. // inside:
  27923. // {
  27924. // knownActions: Array< AnimationAction > - used as prototypes
  27925. // actionByRoot: AnimationAction - lookup
  27926. // }
  27927. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27928. this._nActiveBindings = 0;
  27929. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27930. this._controlInterpolants = []; // same game as above
  27931. this._nActiveControlInterpolants = 0;
  27932. const scope = this;
  27933. this.stats = {
  27934. actions: {
  27935. get total() {
  27936. return scope._actions.length;
  27937. },
  27938. get inUse() {
  27939. return scope._nActiveActions;
  27940. }
  27941. },
  27942. bindings: {
  27943. get total() {
  27944. return scope._bindings.length;
  27945. },
  27946. get inUse() {
  27947. return scope._nActiveBindings;
  27948. }
  27949. },
  27950. controlInterpolants: {
  27951. get total() {
  27952. return scope._controlInterpolants.length;
  27953. },
  27954. get inUse() {
  27955. return scope._nActiveControlInterpolants;
  27956. }
  27957. }
  27958. };
  27959. },
  27960. // Memory management for AnimationAction objects
  27961. _isActiveAction: function ( action ) {
  27962. const index = action._cacheIndex;
  27963. return index !== null && index < this._nActiveActions;
  27964. },
  27965. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27966. const actions = this._actions,
  27967. actionsByClip = this._actionsByClip;
  27968. let actionsForClip = actionsByClip[ clipUuid ];
  27969. if ( actionsForClip === undefined ) {
  27970. actionsForClip = {
  27971. knownActions: [ action ],
  27972. actionByRoot: {}
  27973. };
  27974. action._byClipCacheIndex = 0;
  27975. actionsByClip[ clipUuid ] = actionsForClip;
  27976. } else {
  27977. const knownActions = actionsForClip.knownActions;
  27978. action._byClipCacheIndex = knownActions.length;
  27979. knownActions.push( action );
  27980. }
  27981. action._cacheIndex = actions.length;
  27982. actions.push( action );
  27983. actionsForClip.actionByRoot[ rootUuid ] = action;
  27984. },
  27985. _removeInactiveAction: function ( action ) {
  27986. const actions = this._actions,
  27987. lastInactiveAction = actions[ actions.length - 1 ],
  27988. cacheIndex = action._cacheIndex;
  27989. lastInactiveAction._cacheIndex = cacheIndex;
  27990. actions[ cacheIndex ] = lastInactiveAction;
  27991. actions.pop();
  27992. action._cacheIndex = null;
  27993. const clipUuid = action._clip.uuid,
  27994. actionsByClip = this._actionsByClip,
  27995. actionsForClip = actionsByClip[ clipUuid ],
  27996. knownActionsForClip = actionsForClip.knownActions,
  27997. lastKnownAction =
  27998. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27999. byClipCacheIndex = action._byClipCacheIndex;
  28000. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28001. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28002. knownActionsForClip.pop();
  28003. action._byClipCacheIndex = null;
  28004. const actionByRoot = actionsForClip.actionByRoot,
  28005. rootUuid = ( action._localRoot || this._root ).uuid;
  28006. delete actionByRoot[ rootUuid ];
  28007. if ( knownActionsForClip.length === 0 ) {
  28008. delete actionsByClip[ clipUuid ];
  28009. }
  28010. this._removeInactiveBindingsForAction( action );
  28011. },
  28012. _removeInactiveBindingsForAction: function ( action ) {
  28013. const bindings = action._propertyBindings;
  28014. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28015. const binding = bindings[ i ];
  28016. if ( -- binding.referenceCount === 0 ) {
  28017. this._removeInactiveBinding( binding );
  28018. }
  28019. }
  28020. },
  28021. _lendAction: function ( action ) {
  28022. // [ active actions | inactive actions ]
  28023. // [ active actions >| inactive actions ]
  28024. // s a
  28025. // <-swap->
  28026. // a s
  28027. const actions = this._actions,
  28028. prevIndex = action._cacheIndex,
  28029. lastActiveIndex = this._nActiveActions ++,
  28030. firstInactiveAction = actions[ lastActiveIndex ];
  28031. action._cacheIndex = lastActiveIndex;
  28032. actions[ lastActiveIndex ] = action;
  28033. firstInactiveAction._cacheIndex = prevIndex;
  28034. actions[ prevIndex ] = firstInactiveAction;
  28035. },
  28036. _takeBackAction: function ( action ) {
  28037. // [ active actions | inactive actions ]
  28038. // [ active actions |< inactive actions ]
  28039. // a s
  28040. // <-swap->
  28041. // s a
  28042. const actions = this._actions,
  28043. prevIndex = action._cacheIndex,
  28044. firstInactiveIndex = -- this._nActiveActions,
  28045. lastActiveAction = actions[ firstInactiveIndex ];
  28046. action._cacheIndex = firstInactiveIndex;
  28047. actions[ firstInactiveIndex ] = action;
  28048. lastActiveAction._cacheIndex = prevIndex;
  28049. actions[ prevIndex ] = lastActiveAction;
  28050. },
  28051. // Memory management for PropertyMixer objects
  28052. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  28053. const bindingsByRoot = this._bindingsByRootAndName,
  28054. bindings = this._bindings;
  28055. let bindingByName = bindingsByRoot[ rootUuid ];
  28056. if ( bindingByName === undefined ) {
  28057. bindingByName = {};
  28058. bindingsByRoot[ rootUuid ] = bindingByName;
  28059. }
  28060. bindingByName[ trackName ] = binding;
  28061. binding._cacheIndex = bindings.length;
  28062. bindings.push( binding );
  28063. },
  28064. _removeInactiveBinding: function ( binding ) {
  28065. const bindings = this._bindings,
  28066. propBinding = binding.binding,
  28067. rootUuid = propBinding.rootNode.uuid,
  28068. trackName = propBinding.path,
  28069. bindingsByRoot = this._bindingsByRootAndName,
  28070. bindingByName = bindingsByRoot[ rootUuid ],
  28071. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28072. cacheIndex = binding._cacheIndex;
  28073. lastInactiveBinding._cacheIndex = cacheIndex;
  28074. bindings[ cacheIndex ] = lastInactiveBinding;
  28075. bindings.pop();
  28076. delete bindingByName[ trackName ];
  28077. if ( Object.keys( bindingByName ).length === 0 ) {
  28078. delete bindingsByRoot[ rootUuid ];
  28079. }
  28080. },
  28081. _lendBinding: function ( binding ) {
  28082. const bindings = this._bindings,
  28083. prevIndex = binding._cacheIndex,
  28084. lastActiveIndex = this._nActiveBindings ++,
  28085. firstInactiveBinding = bindings[ lastActiveIndex ];
  28086. binding._cacheIndex = lastActiveIndex;
  28087. bindings[ lastActiveIndex ] = binding;
  28088. firstInactiveBinding._cacheIndex = prevIndex;
  28089. bindings[ prevIndex ] = firstInactiveBinding;
  28090. },
  28091. _takeBackBinding: function ( binding ) {
  28092. const bindings = this._bindings,
  28093. prevIndex = binding._cacheIndex,
  28094. firstInactiveIndex = -- this._nActiveBindings,
  28095. lastActiveBinding = bindings[ firstInactiveIndex ];
  28096. binding._cacheIndex = firstInactiveIndex;
  28097. bindings[ firstInactiveIndex ] = binding;
  28098. lastActiveBinding._cacheIndex = prevIndex;
  28099. bindings[ prevIndex ] = lastActiveBinding;
  28100. },
  28101. // Memory management of Interpolants for weight and time scale
  28102. _lendControlInterpolant: function () {
  28103. const interpolants = this._controlInterpolants,
  28104. lastActiveIndex = this._nActiveControlInterpolants ++;
  28105. let interpolant = interpolants[ lastActiveIndex ];
  28106. if ( interpolant === undefined ) {
  28107. interpolant = new LinearInterpolant(
  28108. new Float32Array( 2 ), new Float32Array( 2 ),
  28109. 1, this._controlInterpolantsResultBuffer );
  28110. interpolant.__cacheIndex = lastActiveIndex;
  28111. interpolants[ lastActiveIndex ] = interpolant;
  28112. }
  28113. return interpolant;
  28114. },
  28115. _takeBackControlInterpolant: function ( interpolant ) {
  28116. const interpolants = this._controlInterpolants,
  28117. prevIndex = interpolant.__cacheIndex,
  28118. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28119. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28120. interpolant.__cacheIndex = firstInactiveIndex;
  28121. interpolants[ firstInactiveIndex ] = interpolant;
  28122. lastActiveInterpolant.__cacheIndex = prevIndex;
  28123. interpolants[ prevIndex ] = lastActiveInterpolant;
  28124. },
  28125. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  28126. // return an action for a clip optionally using a custom root target
  28127. // object (this method allocates a lot of dynamic memory in case a
  28128. // previously unknown clip/root combination is specified)
  28129. clipAction: function ( clip, optionalRoot, blendMode ) {
  28130. const root = optionalRoot || this._root,
  28131. rootUuid = root.uuid;
  28132. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28133. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28134. const actionsForClip = this._actionsByClip[ clipUuid ];
  28135. let prototypeAction = null;
  28136. if ( blendMode === undefined ) {
  28137. if ( clipObject !== null ) {
  28138. blendMode = clipObject.blendMode;
  28139. } else {
  28140. blendMode = NormalAnimationBlendMode;
  28141. }
  28142. }
  28143. if ( actionsForClip !== undefined ) {
  28144. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28145. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28146. return existingAction;
  28147. }
  28148. // we know the clip, so we don't have to parse all
  28149. // the bindings again but can just copy
  28150. prototypeAction = actionsForClip.knownActions[ 0 ];
  28151. // also, take the clip from the prototype action
  28152. if ( clipObject === null )
  28153. clipObject = prototypeAction._clip;
  28154. }
  28155. // clip must be known when specified via string
  28156. if ( clipObject === null ) return null;
  28157. // allocate all resources required to run it
  28158. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28159. this._bindAction( newAction, prototypeAction );
  28160. // and make the action known to the memory manager
  28161. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28162. return newAction;
  28163. },
  28164. // get an existing action
  28165. existingAction: function ( clip, optionalRoot ) {
  28166. const root = optionalRoot || this._root,
  28167. rootUuid = root.uuid,
  28168. clipObject = typeof clip === 'string' ?
  28169. AnimationClip.findByName( root, clip ) : clip,
  28170. clipUuid = clipObject ? clipObject.uuid : clip,
  28171. actionsForClip = this._actionsByClip[ clipUuid ];
  28172. if ( actionsForClip !== undefined ) {
  28173. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28174. }
  28175. return null;
  28176. },
  28177. // deactivates all previously scheduled actions
  28178. stopAllAction: function () {
  28179. const actions = this._actions,
  28180. nActions = this._nActiveActions;
  28181. for ( let i = nActions - 1; i >= 0; -- i ) {
  28182. actions[ i ].stop();
  28183. }
  28184. return this;
  28185. },
  28186. // advance the time and update apply the animation
  28187. update: function ( deltaTime ) {
  28188. deltaTime *= this.timeScale;
  28189. const actions = this._actions,
  28190. nActions = this._nActiveActions,
  28191. time = this.time += deltaTime,
  28192. timeDirection = Math.sign( deltaTime ),
  28193. accuIndex = this._accuIndex ^= 1;
  28194. // run active actions
  28195. for ( let i = 0; i !== nActions; ++ i ) {
  28196. const action = actions[ i ];
  28197. action._update( time, deltaTime, timeDirection, accuIndex );
  28198. }
  28199. // update scene graph
  28200. const bindings = this._bindings,
  28201. nBindings = this._nActiveBindings;
  28202. for ( let i = 0; i !== nBindings; ++ i ) {
  28203. bindings[ i ].apply( accuIndex );
  28204. }
  28205. return this;
  28206. },
  28207. // Allows you to seek to a specific time in an animation.
  28208. setTime: function ( timeInSeconds ) {
  28209. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28210. for ( let i = 0; i < this._actions.length; i ++ ) {
  28211. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28212. }
  28213. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28214. },
  28215. // return this mixer's root target object
  28216. getRoot: function () {
  28217. return this._root;
  28218. },
  28219. // free all resources specific to a particular clip
  28220. uncacheClip: function ( clip ) {
  28221. const actions = this._actions,
  28222. clipUuid = clip.uuid,
  28223. actionsByClip = this._actionsByClip,
  28224. actionsForClip = actionsByClip[ clipUuid ];
  28225. if ( actionsForClip !== undefined ) {
  28226. // note: just calling _removeInactiveAction would mess up the
  28227. // iteration state and also require updating the state we can
  28228. // just throw away
  28229. const actionsToRemove = actionsForClip.knownActions;
  28230. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28231. const action = actionsToRemove[ i ];
  28232. this._deactivateAction( action );
  28233. const cacheIndex = action._cacheIndex,
  28234. lastInactiveAction = actions[ actions.length - 1 ];
  28235. action._cacheIndex = null;
  28236. action._byClipCacheIndex = null;
  28237. lastInactiveAction._cacheIndex = cacheIndex;
  28238. actions[ cacheIndex ] = lastInactiveAction;
  28239. actions.pop();
  28240. this._removeInactiveBindingsForAction( action );
  28241. }
  28242. delete actionsByClip[ clipUuid ];
  28243. }
  28244. },
  28245. // free all resources specific to a particular root target object
  28246. uncacheRoot: function ( root ) {
  28247. const rootUuid = root.uuid,
  28248. actionsByClip = this._actionsByClip;
  28249. for ( const clipUuid in actionsByClip ) {
  28250. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28251. action = actionByRoot[ rootUuid ];
  28252. if ( action !== undefined ) {
  28253. this._deactivateAction( action );
  28254. this._removeInactiveAction( action );
  28255. }
  28256. }
  28257. const bindingsByRoot = this._bindingsByRootAndName,
  28258. bindingByName = bindingsByRoot[ rootUuid ];
  28259. if ( bindingByName !== undefined ) {
  28260. for ( const trackName in bindingByName ) {
  28261. const binding = bindingByName[ trackName ];
  28262. binding.restoreOriginalState();
  28263. this._removeInactiveBinding( binding );
  28264. }
  28265. }
  28266. },
  28267. // remove a targeted clip from the cache
  28268. uncacheAction: function ( clip, optionalRoot ) {
  28269. const action = this.existingAction( clip, optionalRoot );
  28270. if ( action !== null ) {
  28271. this._deactivateAction( action );
  28272. this._removeInactiveAction( action );
  28273. }
  28274. }
  28275. } );
  28276. class Uniform {
  28277. constructor( value ) {
  28278. if ( typeof value === 'string' ) {
  28279. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  28280. value = arguments[ 1 ];
  28281. }
  28282. this.value = value;
  28283. }
  28284. clone() {
  28285. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28286. }
  28287. }
  28288. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  28289. InterleavedBuffer.call( this, array, stride );
  28290. this.meshPerAttribute = meshPerAttribute || 1;
  28291. }
  28292. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  28293. constructor: InstancedInterleavedBuffer,
  28294. isInstancedInterleavedBuffer: true,
  28295. copy: function ( source ) {
  28296. InterleavedBuffer.prototype.copy.call( this, source );
  28297. this.meshPerAttribute = source.meshPerAttribute;
  28298. return this;
  28299. },
  28300. clone: function ( data ) {
  28301. const ib = InterleavedBuffer.prototype.clone.call( this, data );
  28302. ib.meshPerAttribute = this.meshPerAttribute;
  28303. return ib;
  28304. },
  28305. toJSON: function ( data ) {
  28306. const json = InterleavedBuffer.prototype.toJSON.call( this, data );
  28307. json.isInstancedInterleavedBuffer = true;
  28308. json.meshPerAttribute = this.meshPerAttribute;
  28309. return json;
  28310. }
  28311. } );
  28312. function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) {
  28313. this.buffer = buffer;
  28314. this.type = type;
  28315. this.itemSize = itemSize;
  28316. this.elementSize = elementSize;
  28317. this.count = count;
  28318. this.version = 0;
  28319. }
  28320. Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', {
  28321. set: function ( value ) {
  28322. if ( value === true ) this.version ++;
  28323. }
  28324. } );
  28325. Object.assign( GLBufferAttribute.prototype, {
  28326. isGLBufferAttribute: true,
  28327. setBuffer: function ( buffer ) {
  28328. this.buffer = buffer;
  28329. return this;
  28330. },
  28331. setType: function ( type, elementSize ) {
  28332. this.type = type;
  28333. this.elementSize = elementSize;
  28334. return this;
  28335. },
  28336. setItemSize: function ( itemSize ) {
  28337. this.itemSize = itemSize;
  28338. return this;
  28339. },
  28340. setCount: function ( count ) {
  28341. this.count = count;
  28342. return this;
  28343. },
  28344. } );
  28345. function Raycaster( origin, direction, near, far ) {
  28346. this.ray = new Ray( origin, direction );
  28347. // direction is assumed to be normalized (for accurate distance calculations)
  28348. this.near = near || 0;
  28349. this.far = far || Infinity;
  28350. this.camera = null;
  28351. this.layers = new Layers();
  28352. this.params = {
  28353. Mesh: {},
  28354. Line: { threshold: 1 },
  28355. LOD: {},
  28356. Points: { threshold: 1 },
  28357. Sprite: {}
  28358. };
  28359. Object.defineProperties( this.params, {
  28360. PointCloud: {
  28361. get: function () {
  28362. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  28363. return this.Points;
  28364. }
  28365. }
  28366. } );
  28367. }
  28368. function ascSort( a, b ) {
  28369. return a.distance - b.distance;
  28370. }
  28371. function intersectObject( object, raycaster, intersects, recursive ) {
  28372. if ( object.layers.test( raycaster.layers ) ) {
  28373. object.raycast( raycaster, intersects );
  28374. }
  28375. if ( recursive === true ) {
  28376. const children = object.children;
  28377. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28378. intersectObject( children[ i ], raycaster, intersects, true );
  28379. }
  28380. }
  28381. }
  28382. Object.assign( Raycaster.prototype, {
  28383. set: function ( origin, direction ) {
  28384. // direction is assumed to be normalized (for accurate distance calculations)
  28385. this.ray.set( origin, direction );
  28386. },
  28387. setFromCamera: function ( coords, camera ) {
  28388. if ( camera && camera.isPerspectiveCamera ) {
  28389. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28390. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28391. this.camera = camera;
  28392. } else if ( camera && camera.isOrthographicCamera ) {
  28393. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28394. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28395. this.camera = camera;
  28396. } else {
  28397. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28398. }
  28399. },
  28400. intersectObject: function ( object, recursive, optionalTarget ) {
  28401. const intersects = optionalTarget || [];
  28402. intersectObject( object, this, intersects, recursive );
  28403. intersects.sort( ascSort );
  28404. return intersects;
  28405. },
  28406. intersectObjects: function ( objects, recursive, optionalTarget ) {
  28407. const intersects = optionalTarget || [];
  28408. if ( Array.isArray( objects ) === false ) {
  28409. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  28410. return intersects;
  28411. }
  28412. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28413. intersectObject( objects[ i ], this, intersects, recursive );
  28414. }
  28415. intersects.sort( ascSort );
  28416. return intersects;
  28417. }
  28418. } );
  28419. /**
  28420. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28421. *
  28422. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28423. * The azimuthal angle (theta) is measured from the positive z-axis.
  28424. */
  28425. class Spherical {
  28426. constructor( radius = 1, phi = 0, theta = 0 ) {
  28427. this.radius = radius;
  28428. this.phi = phi; // polar angle
  28429. this.theta = theta; // azimuthal angle
  28430. return this;
  28431. }
  28432. set( radius, phi, theta ) {
  28433. this.radius = radius;
  28434. this.phi = phi;
  28435. this.theta = theta;
  28436. return this;
  28437. }
  28438. clone() {
  28439. return new this.constructor().copy( this );
  28440. }
  28441. copy( other ) {
  28442. this.radius = other.radius;
  28443. this.phi = other.phi;
  28444. this.theta = other.theta;
  28445. return this;
  28446. }
  28447. // restrict phi to be betwee EPS and PI-EPS
  28448. makeSafe() {
  28449. const EPS = 0.000001;
  28450. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28451. return this;
  28452. }
  28453. setFromVector3( v ) {
  28454. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28455. }
  28456. setFromCartesianCoords( x, y, z ) {
  28457. this.radius = Math.sqrt( x * x + y * y + z * z );
  28458. if ( this.radius === 0 ) {
  28459. this.theta = 0;
  28460. this.phi = 0;
  28461. } else {
  28462. this.theta = Math.atan2( x, z );
  28463. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  28464. }
  28465. return this;
  28466. }
  28467. }
  28468. /**
  28469. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28470. */
  28471. class Cylindrical {
  28472. constructor( radius, theta, y ) {
  28473. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  28474. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28475. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  28476. return this;
  28477. }
  28478. set( radius, theta, y ) {
  28479. this.radius = radius;
  28480. this.theta = theta;
  28481. this.y = y;
  28482. return this;
  28483. }
  28484. clone() {
  28485. return new this.constructor().copy( this );
  28486. }
  28487. copy( other ) {
  28488. this.radius = other.radius;
  28489. this.theta = other.theta;
  28490. this.y = other.y;
  28491. return this;
  28492. }
  28493. setFromVector3( v ) {
  28494. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28495. }
  28496. setFromCartesianCoords( x, y, z ) {
  28497. this.radius = Math.sqrt( x * x + z * z );
  28498. this.theta = Math.atan2( x, z );
  28499. this.y = y;
  28500. return this;
  28501. }
  28502. }
  28503. const _vector$8 = /*@__PURE__*/ new Vector2$1();
  28504. class Box2 {
  28505. constructor( min, max ) {
  28506. Object.defineProperty( this, 'isBox2', { value: true } );
  28507. this.min = ( min !== undefined ) ? min : new Vector2$1( + Infinity, + Infinity );
  28508. this.max = ( max !== undefined ) ? max : new Vector2$1( - Infinity, - Infinity );
  28509. }
  28510. set( min, max ) {
  28511. this.min.copy( min );
  28512. this.max.copy( max );
  28513. return this;
  28514. }
  28515. setFromPoints( points ) {
  28516. this.makeEmpty();
  28517. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28518. this.expandByPoint( points[ i ] );
  28519. }
  28520. return this;
  28521. }
  28522. setFromCenterAndSize( center, size ) {
  28523. const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 );
  28524. this.min.copy( center ).sub( halfSize );
  28525. this.max.copy( center ).add( halfSize );
  28526. return this;
  28527. }
  28528. clone() {
  28529. return new this.constructor().copy( this );
  28530. }
  28531. copy( box ) {
  28532. this.min.copy( box.min );
  28533. this.max.copy( box.max );
  28534. return this;
  28535. }
  28536. makeEmpty() {
  28537. this.min.x = this.min.y = + Infinity;
  28538. this.max.x = this.max.y = - Infinity;
  28539. return this;
  28540. }
  28541. isEmpty() {
  28542. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28543. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28544. }
  28545. getCenter( target ) {
  28546. if ( target === undefined ) {
  28547. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  28548. target = new Vector2$1();
  28549. }
  28550. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28551. }
  28552. getSize( target ) {
  28553. if ( target === undefined ) {
  28554. console.warn( 'THREE.Box2: .getSize() target is now required' );
  28555. target = new Vector2$1();
  28556. }
  28557. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28558. }
  28559. expandByPoint( point ) {
  28560. this.min.min( point );
  28561. this.max.max( point );
  28562. return this;
  28563. }
  28564. expandByVector( vector ) {
  28565. this.min.sub( vector );
  28566. this.max.add( vector );
  28567. return this;
  28568. }
  28569. expandByScalar( scalar ) {
  28570. this.min.addScalar( - scalar );
  28571. this.max.addScalar( scalar );
  28572. return this;
  28573. }
  28574. containsPoint( point ) {
  28575. return point.x < this.min.x || point.x > this.max.x ||
  28576. point.y < this.min.y || point.y > this.max.y ? false : true;
  28577. }
  28578. containsBox( box ) {
  28579. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28580. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28581. }
  28582. getParameter( point, target ) {
  28583. // This can potentially have a divide by zero if the box
  28584. // has a size dimension of 0.
  28585. if ( target === undefined ) {
  28586. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  28587. target = new Vector2$1();
  28588. }
  28589. return target.set(
  28590. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28591. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28592. );
  28593. }
  28594. intersectsBox( box ) {
  28595. // using 4 splitting planes to rule out intersections
  28596. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28597. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28598. }
  28599. clampPoint( point, target ) {
  28600. if ( target === undefined ) {
  28601. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  28602. target = new Vector2$1();
  28603. }
  28604. return target.copy( point ).clamp( this.min, this.max );
  28605. }
  28606. distanceToPoint( point ) {
  28607. const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max );
  28608. return clampedPoint.sub( point ).length();
  28609. }
  28610. intersect( box ) {
  28611. this.min.max( box.min );
  28612. this.max.min( box.max );
  28613. return this;
  28614. }
  28615. union( box ) {
  28616. this.min.min( box.min );
  28617. this.max.max( box.max );
  28618. return this;
  28619. }
  28620. translate( offset ) {
  28621. this.min.add( offset );
  28622. this.max.add( offset );
  28623. return this;
  28624. }
  28625. equals( box ) {
  28626. return box.min.equals( this.min ) && box.max.equals( this.max );
  28627. }
  28628. }
  28629. const _startP = /*@__PURE__*/ new Vector3();
  28630. const _startEnd = /*@__PURE__*/ new Vector3();
  28631. class Line3 {
  28632. constructor( start, end ) {
  28633. this.start = ( start !== undefined ) ? start : new Vector3();
  28634. this.end = ( end !== undefined ) ? end : new Vector3();
  28635. }
  28636. set( start, end ) {
  28637. this.start.copy( start );
  28638. this.end.copy( end );
  28639. return this;
  28640. }
  28641. clone() {
  28642. return new this.constructor().copy( this );
  28643. }
  28644. copy( line ) {
  28645. this.start.copy( line.start );
  28646. this.end.copy( line.end );
  28647. return this;
  28648. }
  28649. getCenter( target ) {
  28650. if ( target === undefined ) {
  28651. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  28652. target = new Vector3();
  28653. }
  28654. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28655. }
  28656. delta( target ) {
  28657. if ( target === undefined ) {
  28658. console.warn( 'THREE.Line3: .delta() target is now required' );
  28659. target = new Vector3();
  28660. }
  28661. return target.subVectors( this.end, this.start );
  28662. }
  28663. distanceSq() {
  28664. return this.start.distanceToSquared( this.end );
  28665. }
  28666. distance() {
  28667. return this.start.distanceTo( this.end );
  28668. }
  28669. at( t, target ) {
  28670. if ( target === undefined ) {
  28671. console.warn( 'THREE.Line3: .at() target is now required' );
  28672. target = new Vector3();
  28673. }
  28674. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28675. }
  28676. closestPointToPointParameter( point, clampToLine ) {
  28677. _startP.subVectors( point, this.start );
  28678. _startEnd.subVectors( this.end, this.start );
  28679. const startEnd2 = _startEnd.dot( _startEnd );
  28680. const startEnd_startP = _startEnd.dot( _startP );
  28681. let t = startEnd_startP / startEnd2;
  28682. if ( clampToLine ) {
  28683. t = MathUtils.clamp( t, 0, 1 );
  28684. }
  28685. return t;
  28686. }
  28687. closestPointToPoint( point, clampToLine, target ) {
  28688. const t = this.closestPointToPointParameter( point, clampToLine );
  28689. if ( target === undefined ) {
  28690. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  28691. target = new Vector3();
  28692. }
  28693. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28694. }
  28695. applyMatrix4( matrix ) {
  28696. this.start.applyMatrix4( matrix );
  28697. this.end.applyMatrix4( matrix );
  28698. return this;
  28699. }
  28700. equals( line ) {
  28701. return line.start.equals( this.start ) && line.end.equals( this.end );
  28702. }
  28703. }
  28704. function ImmediateRenderObject( material ) {
  28705. Object3D.call( this );
  28706. this.material = material;
  28707. this.render = function ( /* renderCallback */ ) {};
  28708. this.hasPositions = false;
  28709. this.hasNormals = false;
  28710. this.hasColors = false;
  28711. this.hasUvs = false;
  28712. this.positionArray = null;
  28713. this.normalArray = null;
  28714. this.colorArray = null;
  28715. this.uvArray = null;
  28716. this.count = 0;
  28717. }
  28718. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  28719. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28720. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28721. const _vector$9 = /*@__PURE__*/ new Vector3();
  28722. class SpotLightHelper extends Object3D {
  28723. constructor( light, color ) {
  28724. super();
  28725. this.light = light;
  28726. this.light.updateMatrixWorld();
  28727. this.matrix = light.matrixWorld;
  28728. this.matrixAutoUpdate = false;
  28729. this.color = color;
  28730. const geometry = new BufferGeometry();
  28731. const positions = [
  28732. 0, 0, 0, 0, 0, 1,
  28733. 0, 0, 0, 1, 0, 1,
  28734. 0, 0, 0, - 1, 0, 1,
  28735. 0, 0, 0, 0, 1, 1,
  28736. 0, 0, 0, 0, - 1, 1
  28737. ];
  28738. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28739. const p1 = ( i / l ) * Math.PI * 2;
  28740. const p2 = ( j / l ) * Math.PI * 2;
  28741. positions.push(
  28742. Math.cos( p1 ), Math.sin( p1 ), 1,
  28743. Math.cos( p2 ), Math.sin( p2 ), 1
  28744. );
  28745. }
  28746. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28747. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28748. this.cone = new LineSegments( geometry, material );
  28749. this.add( this.cone );
  28750. this.update();
  28751. }
  28752. dispose() {
  28753. this.cone.geometry.dispose();
  28754. this.cone.material.dispose();
  28755. }
  28756. update() {
  28757. this.light.updateMatrixWorld();
  28758. const coneLength = this.light.distance ? this.light.distance : 1000;
  28759. const coneWidth = coneLength * Math.tan( this.light.angle );
  28760. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28761. _vector$9.setFromMatrixPosition( this.light.target.matrixWorld );
  28762. this.cone.lookAt( _vector$9 );
  28763. if ( this.color !== undefined ) {
  28764. this.cone.material.color.set( this.color );
  28765. } else {
  28766. this.cone.material.color.copy( this.light.color );
  28767. }
  28768. }
  28769. }
  28770. const _vector$a = /*@__PURE__*/ new Vector3();
  28771. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28772. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28773. class SkeletonHelper extends LineSegments {
  28774. constructor( object ) {
  28775. const bones = getBoneList( object );
  28776. const geometry = new BufferGeometry();
  28777. const vertices = [];
  28778. const colors = [];
  28779. const color1 = new Color( 0, 0, 1 );
  28780. const color2 = new Color( 0, 1, 0 );
  28781. for ( let i = 0; i < bones.length; i ++ ) {
  28782. const bone = bones[ i ];
  28783. if ( bone.parent && bone.parent.isBone ) {
  28784. vertices.push( 0, 0, 0 );
  28785. vertices.push( 0, 0, 0 );
  28786. colors.push( color1.r, color1.g, color1.b );
  28787. colors.push( color2.r, color2.g, color2.b );
  28788. }
  28789. }
  28790. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28791. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28792. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28793. super( geometry, material );
  28794. this.type = 'SkeletonHelper';
  28795. this.isSkeletonHelper = true;
  28796. this.root = object;
  28797. this.bones = bones;
  28798. this.matrix = object.matrixWorld;
  28799. this.matrixAutoUpdate = false;
  28800. }
  28801. updateMatrixWorld( force ) {
  28802. const bones = this.bones;
  28803. const geometry = this.geometry;
  28804. const position = geometry.getAttribute( 'position' );
  28805. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28806. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28807. const bone = bones[ i ];
  28808. if ( bone.parent && bone.parent.isBone ) {
  28809. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28810. _vector$a.setFromMatrixPosition( _boneMatrix );
  28811. position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z );
  28812. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28813. _vector$a.setFromMatrixPosition( _boneMatrix );
  28814. position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z );
  28815. j += 2;
  28816. }
  28817. }
  28818. geometry.getAttribute( 'position' ).needsUpdate = true;
  28819. super.updateMatrixWorld( force );
  28820. }
  28821. }
  28822. function getBoneList( object ) {
  28823. const boneList = [];
  28824. if ( object && object.isBone ) {
  28825. boneList.push( object );
  28826. }
  28827. for ( let i = 0; i < object.children.length; i ++ ) {
  28828. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28829. }
  28830. return boneList;
  28831. }
  28832. class PointLightHelper extends Mesh {
  28833. constructor( light, sphereSize, color ) {
  28834. const geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28835. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28836. super( geometry, material );
  28837. this.light = light;
  28838. this.light.updateMatrixWorld();
  28839. this.color = color;
  28840. this.type = 'PointLightHelper';
  28841. this.matrix = this.light.matrixWorld;
  28842. this.matrixAutoUpdate = false;
  28843. this.update();
  28844. /*
  28845. // TODO: delete this comment?
  28846. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28847. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28848. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28849. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28850. const d = light.distance;
  28851. if ( d === 0.0 ) {
  28852. this.lightDistance.visible = false;
  28853. } else {
  28854. this.lightDistance.scale.set( d, d, d );
  28855. }
  28856. this.add( this.lightDistance );
  28857. */
  28858. }
  28859. dispose() {
  28860. this.geometry.dispose();
  28861. this.material.dispose();
  28862. }
  28863. update() {
  28864. if ( this.color !== undefined ) {
  28865. this.material.color.set( this.color );
  28866. } else {
  28867. this.material.color.copy( this.light.color );
  28868. }
  28869. /*
  28870. const d = this.light.distance;
  28871. if ( d === 0.0 ) {
  28872. this.lightDistance.visible = false;
  28873. } else {
  28874. this.lightDistance.visible = true;
  28875. this.lightDistance.scale.set( d, d, d );
  28876. }
  28877. */
  28878. }
  28879. }
  28880. const _vector$b = /*@__PURE__*/ new Vector3();
  28881. const _color1 = /*@__PURE__*/ new Color();
  28882. const _color2 = /*@__PURE__*/ new Color();
  28883. class HemisphereLightHelper extends Object3D {
  28884. constructor( light, size, color ) {
  28885. super();
  28886. this.light = light;
  28887. this.light.updateMatrixWorld();
  28888. this.matrix = light.matrixWorld;
  28889. this.matrixAutoUpdate = false;
  28890. this.color = color;
  28891. const geometry = new OctahedronBufferGeometry( size );
  28892. geometry.rotateY( Math.PI * 0.5 );
  28893. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28894. if ( this.color === undefined ) this.material.vertexColors = true;
  28895. const position = geometry.getAttribute( 'position' );
  28896. const colors = new Float32Array( position.count * 3 );
  28897. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28898. this.add( new Mesh( geometry, this.material ) );
  28899. this.update();
  28900. }
  28901. dispose() {
  28902. this.children[ 0 ].geometry.dispose();
  28903. this.children[ 0 ].material.dispose();
  28904. }
  28905. update() {
  28906. const mesh = this.children[ 0 ];
  28907. if ( this.color !== undefined ) {
  28908. this.material.color.set( this.color );
  28909. } else {
  28910. const colors = mesh.geometry.getAttribute( 'color' );
  28911. _color1.copy( this.light.color );
  28912. _color2.copy( this.light.groundColor );
  28913. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28914. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28915. colors.setXYZ( i, color.r, color.g, color.b );
  28916. }
  28917. colors.needsUpdate = true;
  28918. }
  28919. mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28920. }
  28921. }
  28922. class GridHelper extends LineSegments {
  28923. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28924. color1 = new Color( color1 );
  28925. color2 = new Color( color2 );
  28926. const center = divisions / 2;
  28927. const step = size / divisions;
  28928. const halfSize = size / 2;
  28929. const vertices = [], colors = [];
  28930. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28931. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28932. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28933. const color = i === center ? color1 : color2;
  28934. color.toArray( colors, j ); j += 3;
  28935. color.toArray( colors, j ); j += 3;
  28936. color.toArray( colors, j ); j += 3;
  28937. color.toArray( colors, j ); j += 3;
  28938. }
  28939. const geometry = new BufferGeometry();
  28940. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28941. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28942. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28943. super( geometry, material );
  28944. this.type = 'GridHelper';
  28945. }
  28946. }
  28947. class PolarGridHelper extends LineSegments {
  28948. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28949. color1 = new Color( color1 );
  28950. color2 = new Color( color2 );
  28951. const vertices = [];
  28952. const colors = [];
  28953. // create the radials
  28954. for ( let i = 0; i <= radials; i ++ ) {
  28955. const v = ( i / radials ) * ( Math.PI * 2 );
  28956. const x = Math.sin( v ) * radius;
  28957. const z = Math.cos( v ) * radius;
  28958. vertices.push( 0, 0, 0 );
  28959. vertices.push( x, 0, z );
  28960. const color = ( i & 1 ) ? color1 : color2;
  28961. colors.push( color.r, color.g, color.b );
  28962. colors.push( color.r, color.g, color.b );
  28963. }
  28964. // create the circles
  28965. for ( let i = 0; i <= circles; i ++ ) {
  28966. const color = ( i & 1 ) ? color1 : color2;
  28967. const r = radius - ( radius / circles * i );
  28968. for ( let j = 0; j < divisions; j ++ ) {
  28969. // first vertex
  28970. let v = ( j / divisions ) * ( Math.PI * 2 );
  28971. let x = Math.sin( v ) * r;
  28972. let z = Math.cos( v ) * r;
  28973. vertices.push( x, 0, z );
  28974. colors.push( color.r, color.g, color.b );
  28975. // second vertex
  28976. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28977. x = Math.sin( v ) * r;
  28978. z = Math.cos( v ) * r;
  28979. vertices.push( x, 0, z );
  28980. colors.push( color.r, color.g, color.b );
  28981. }
  28982. }
  28983. const geometry = new BufferGeometry();
  28984. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28985. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28986. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28987. super( geometry, material );
  28988. this.type = 'PolarGridHelper';
  28989. }
  28990. }
  28991. const _v1$6 = /*@__PURE__*/ new Vector3();
  28992. const _v2$3 = /*@__PURE__*/ new Vector3();
  28993. const _v3$1 = /*@__PURE__*/ new Vector3();
  28994. class DirectionalLightHelper extends Object3D {
  28995. constructor( light, size, color ) {
  28996. super();
  28997. this.light = light;
  28998. this.light.updateMatrixWorld();
  28999. this.matrix = light.matrixWorld;
  29000. this.matrixAutoUpdate = false;
  29001. this.color = color;
  29002. if ( size === undefined ) size = 1;
  29003. let geometry = new BufferGeometry();
  29004. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29005. - size, size, 0,
  29006. size, size, 0,
  29007. size, - size, 0,
  29008. - size, - size, 0,
  29009. - size, size, 0
  29010. ], 3 ) );
  29011. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29012. this.lightPlane = new Line( geometry, material );
  29013. this.add( this.lightPlane );
  29014. geometry = new BufferGeometry();
  29015. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29016. this.targetLine = new Line( geometry, material );
  29017. this.add( this.targetLine );
  29018. this.update();
  29019. }
  29020. dispose() {
  29021. this.lightPlane.geometry.dispose();
  29022. this.lightPlane.material.dispose();
  29023. this.targetLine.geometry.dispose();
  29024. this.targetLine.material.dispose();
  29025. }
  29026. update() {
  29027. _v1$6.setFromMatrixPosition( this.light.matrixWorld );
  29028. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29029. _v3$1.subVectors( _v2$3, _v1$6 );
  29030. this.lightPlane.lookAt( _v2$3 );
  29031. if ( this.color !== undefined ) {
  29032. this.lightPlane.material.color.set( this.color );
  29033. this.targetLine.material.color.set( this.color );
  29034. } else {
  29035. this.lightPlane.material.color.copy( this.light.color );
  29036. this.targetLine.material.color.copy( this.light.color );
  29037. }
  29038. this.targetLine.lookAt( _v2$3 );
  29039. this.targetLine.scale.z = _v3$1.length();
  29040. }
  29041. }
  29042. const _vector$c = /*@__PURE__*/ new Vector3();
  29043. const _camera = /*@__PURE__*/ new Camera();
  29044. /**
  29045. * - shows frustum, line of sight and up of the camera
  29046. * - suitable for fast updates
  29047. * - based on frustum visualization in lightgl.js shadowmap example
  29048. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29049. */
  29050. class CameraHelper extends LineSegments {
  29051. constructor( camera ) {
  29052. const geometry = new BufferGeometry();
  29053. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29054. const vertices = [];
  29055. const colors = [];
  29056. const pointMap = {};
  29057. // colors
  29058. const colorFrustum = new Color( 0xffaa00 );
  29059. const colorCone = new Color( 0xff0000 );
  29060. const colorUp = new Color( 0x00aaff );
  29061. const colorTarget = new Color( 0xffffff );
  29062. const colorCross = new Color( 0x333333 );
  29063. // near
  29064. addLine( 'n1', 'n2', colorFrustum );
  29065. addLine( 'n2', 'n4', colorFrustum );
  29066. addLine( 'n4', 'n3', colorFrustum );
  29067. addLine( 'n3', 'n1', colorFrustum );
  29068. // far
  29069. addLine( 'f1', 'f2', colorFrustum );
  29070. addLine( 'f2', 'f4', colorFrustum );
  29071. addLine( 'f4', 'f3', colorFrustum );
  29072. addLine( 'f3', 'f1', colorFrustum );
  29073. // sides
  29074. addLine( 'n1', 'f1', colorFrustum );
  29075. addLine( 'n2', 'f2', colorFrustum );
  29076. addLine( 'n3', 'f3', colorFrustum );
  29077. addLine( 'n4', 'f4', colorFrustum );
  29078. // cone
  29079. addLine( 'p', 'n1', colorCone );
  29080. addLine( 'p', 'n2', colorCone );
  29081. addLine( 'p', 'n3', colorCone );
  29082. addLine( 'p', 'n4', colorCone );
  29083. // up
  29084. addLine( 'u1', 'u2', colorUp );
  29085. addLine( 'u2', 'u3', colorUp );
  29086. addLine( 'u3', 'u1', colorUp );
  29087. // target
  29088. addLine( 'c', 't', colorTarget );
  29089. addLine( 'p', 'c', colorCross );
  29090. // cross
  29091. addLine( 'cn1', 'cn2', colorCross );
  29092. addLine( 'cn3', 'cn4', colorCross );
  29093. addLine( 'cf1', 'cf2', colorCross );
  29094. addLine( 'cf3', 'cf4', colorCross );
  29095. function addLine( a, b, color ) {
  29096. addPoint( a, color );
  29097. addPoint( b, color );
  29098. }
  29099. function addPoint( id, color ) {
  29100. vertices.push( 0, 0, 0 );
  29101. colors.push( color.r, color.g, color.b );
  29102. if ( pointMap[ id ] === undefined ) {
  29103. pointMap[ id ] = [];
  29104. }
  29105. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29106. }
  29107. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29108. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29109. super( geometry, material );
  29110. this.type = 'CameraHelper';
  29111. this.camera = camera;
  29112. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29113. this.matrix = camera.matrixWorld;
  29114. this.matrixAutoUpdate = false;
  29115. this.pointMap = pointMap;
  29116. this.update();
  29117. }
  29118. update() {
  29119. const geometry = this.geometry;
  29120. const pointMap = this.pointMap;
  29121. const w = 1, h = 1;
  29122. // we need just camera projection matrix inverse
  29123. // world matrix must be identity
  29124. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29125. // center / target
  29126. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29127. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29128. // near
  29129. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29130. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29131. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29132. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29133. // far
  29134. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29135. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29136. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29137. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29138. // up
  29139. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29140. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29141. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29142. // cross
  29143. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29144. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29145. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29146. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29147. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29148. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29149. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29150. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29151. geometry.getAttribute( 'position' ).needsUpdate = true;
  29152. }
  29153. }
  29154. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29155. _vector$c.set( x, y, z ).unproject( camera );
  29156. const points = pointMap[ point ];
  29157. if ( points !== undefined ) {
  29158. const position = geometry.getAttribute( 'position' );
  29159. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29160. position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z );
  29161. }
  29162. }
  29163. }
  29164. const _box$3 = /*@__PURE__*/ new Box3();
  29165. class BoxHelper extends LineSegments {
  29166. constructor( object, color = 0xffff00 ) {
  29167. const 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 ] );
  29168. const positions = new Float32Array( 8 * 3 );
  29169. const geometry = new BufferGeometry();
  29170. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29171. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29172. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29173. this.object = object;
  29174. this.type = 'BoxHelper';
  29175. this.matrixAutoUpdate = false;
  29176. this.update();
  29177. }
  29178. update( object ) {
  29179. if ( object !== undefined ) {
  29180. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29181. }
  29182. if ( this.object !== undefined ) {
  29183. _box$3.setFromObject( this.object );
  29184. }
  29185. if ( _box$3.isEmpty() ) return;
  29186. const min = _box$3.min;
  29187. const max = _box$3.max;
  29188. /*
  29189. 5____4
  29190. 1/___0/|
  29191. | 6__|_7
  29192. 2/___3/
  29193. 0: max.x, max.y, max.z
  29194. 1: min.x, max.y, max.z
  29195. 2: min.x, min.y, max.z
  29196. 3: max.x, min.y, max.z
  29197. 4: max.x, max.y, min.z
  29198. 5: min.x, max.y, min.z
  29199. 6: min.x, min.y, min.z
  29200. 7: max.x, min.y, min.z
  29201. */
  29202. const position = this.geometry.attributes.position;
  29203. const array = position.array;
  29204. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29205. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29206. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29207. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29208. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29209. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29210. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29211. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29212. position.needsUpdate = true;
  29213. this.geometry.computeBoundingSphere();
  29214. }
  29215. setFromObject( object ) {
  29216. this.object = object;
  29217. this.update();
  29218. return this;
  29219. }
  29220. copy( source ) {
  29221. LineSegments.prototype.copy.call( this, source );
  29222. this.object = source.object;
  29223. return this;
  29224. }
  29225. }
  29226. class Box3Helper extends LineSegments {
  29227. constructor( box, color = 0xffff00 ) {
  29228. const 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 ] );
  29229. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  29230. const geometry = new BufferGeometry();
  29231. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29232. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29233. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29234. this.box = box;
  29235. this.type = 'Box3Helper';
  29236. this.geometry.computeBoundingSphere();
  29237. }
  29238. updateMatrixWorld( force ) {
  29239. const box = this.box;
  29240. if ( box.isEmpty() ) return;
  29241. box.getCenter( this.position );
  29242. box.getSize( this.scale );
  29243. this.scale.multiplyScalar( 0.5 );
  29244. super.updateMatrixWorld( force );
  29245. }
  29246. }
  29247. class PlaneHelper extends Line {
  29248. constructor( plane, size = 1, hex = 0xffff00 ) {
  29249. const color = hex;
  29250. const positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  29251. const geometry = new BufferGeometry();
  29252. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29253. geometry.computeBoundingSphere();
  29254. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29255. this.type = 'PlaneHelper';
  29256. this.plane = plane;
  29257. this.size = size;
  29258. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  29259. const geometry2 = new BufferGeometry();
  29260. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29261. geometry2.computeBoundingSphere();
  29262. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29263. }
  29264. updateMatrixWorld( force ) {
  29265. let scale = - this.plane.constant;
  29266. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  29267. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  29268. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29269. this.lookAt( this.plane.normal );
  29270. super.updateMatrixWorld( force );
  29271. }
  29272. }
  29273. const _axis = /*@__PURE__*/ new Vector3();
  29274. let _lineGeometry, _coneGeometry;
  29275. class ArrowHelper extends Object3D {
  29276. constructor( dir, origin, length, color, headLength, headWidth ) {
  29277. super();
  29278. // dir is assumed to be normalized
  29279. this.type = 'ArrowHelper';
  29280. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  29281. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  29282. if ( length === undefined ) length = 1;
  29283. if ( color === undefined ) color = 0xffff00;
  29284. if ( headLength === undefined ) headLength = 0.2 * length;
  29285. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29286. if ( _lineGeometry === undefined ) {
  29287. _lineGeometry = new BufferGeometry();
  29288. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29289. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  29290. _coneGeometry.translate( 0, - 0.5, 0 );
  29291. }
  29292. this.position.copy( origin );
  29293. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29294. this.line.matrixAutoUpdate = false;
  29295. this.add( this.line );
  29296. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29297. this.cone.matrixAutoUpdate = false;
  29298. this.add( this.cone );
  29299. this.setDirection( dir );
  29300. this.setLength( length, headLength, headWidth );
  29301. }
  29302. setDirection( dir ) {
  29303. // dir is assumed to be normalized
  29304. if ( dir.y > 0.99999 ) {
  29305. this.quaternion.set( 0, 0, 0, 1 );
  29306. } else if ( dir.y < - 0.99999 ) {
  29307. this.quaternion.set( 1, 0, 0, 0 );
  29308. } else {
  29309. _axis.set( dir.z, 0, - dir.x ).normalize();
  29310. const radians = Math.acos( dir.y );
  29311. this.quaternion.setFromAxisAngle( _axis, radians );
  29312. }
  29313. }
  29314. setLength( length, headLength, headWidth ) {
  29315. if ( headLength === undefined ) headLength = 0.2 * length;
  29316. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29317. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29318. this.line.updateMatrix();
  29319. this.cone.scale.set( headWidth, headLength, headWidth );
  29320. this.cone.position.y = length;
  29321. this.cone.updateMatrix();
  29322. }
  29323. setColor( color ) {
  29324. this.line.material.color.set( color );
  29325. this.cone.material.color.set( color );
  29326. }
  29327. copy( source ) {
  29328. super.copy( source, false );
  29329. this.line.copy( source.line );
  29330. this.cone.copy( source.cone );
  29331. return this;
  29332. }
  29333. }
  29334. class AxesHelper extends LineSegments {
  29335. constructor( size = 1 ) {
  29336. const vertices = [
  29337. 0, 0, 0, size, 0, 0,
  29338. 0, 0, 0, 0, size, 0,
  29339. 0, 0, 0, 0, 0, size
  29340. ];
  29341. const colors = [
  29342. 1, 0, 0, 1, 0.6, 0,
  29343. 0, 1, 0, 0.6, 1, 0,
  29344. 0, 0, 1, 0, 0.6, 1
  29345. ];
  29346. const geometry = new BufferGeometry();
  29347. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29348. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29349. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29350. super( geometry, material );
  29351. this.type = 'AxesHelper';
  29352. }
  29353. }
  29354. const _floatView = new Float32Array( 1 );
  29355. const _int32View = new Int32Array( _floatView.buffer );
  29356. const DataUtils = {
  29357. // Converts float32 to float16 (stored as uint16 value).
  29358. toHalfFloat: function ( val ) {
  29359. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  29360. /* This method is faster than the OpenEXR implementation (very often
  29361. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  29362. * by James Tursa?s half-precision code. */
  29363. _floatView[ 0 ] = val;
  29364. const x = _int32View[ 0 ];
  29365. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  29366. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  29367. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  29368. /* If zero, or denormal, or exponent underflows too much for a denormal
  29369. * half, return signed zero. */
  29370. if ( e < 103 ) return bits;
  29371. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  29372. if ( e > 142 ) {
  29373. bits |= 0x7c00;
  29374. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  29375. * not Inf, so make sure we set one mantissa bit too. */
  29376. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  29377. return bits;
  29378. }
  29379. /* If exponent underflows but not too much, return a denormal */
  29380. if ( e < 113 ) {
  29381. m |= 0x0800;
  29382. /* Extra rounding may overflow and set mantissa to 0 and exponent
  29383. * to 1, which is OK. */
  29384. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  29385. return bits;
  29386. }
  29387. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  29388. /* Extra rounding. An overflow will set mantissa to 0 and increment
  29389. * the exponent, which is OK. */
  29390. bits += m & 1;
  29391. return bits;
  29392. }
  29393. };
  29394. const LOD_MIN = 4;
  29395. const LOD_MAX = 8;
  29396. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  29397. // The standard deviations (radians) associated with the extra mips. These are
  29398. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29399. // geometric shadowing function. These sigma values squared must match the
  29400. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29401. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29402. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29403. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29404. // samples and exit early, but not recompile the shader.
  29405. const MAX_SAMPLES = 20;
  29406. const ENCODINGS = {
  29407. [ LinearEncoding ]: 0,
  29408. [ sRGBEncoding ]: 1,
  29409. [ RGBEEncoding ]: 2,
  29410. [ RGBM7Encoding ]: 3,
  29411. [ RGBM16Encoding ]: 4,
  29412. [ RGBDEncoding ]: 5,
  29413. [ GammaEncoding ]: 6
  29414. };
  29415. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  29416. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  29417. const _clearColor = /*@__PURE__*/ new Color();
  29418. let _oldTarget = null;
  29419. // Golden Ratio
  29420. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29421. const INV_PHI = 1 / PHI;
  29422. // Vertices of a dodecahedron (except the opposites, which represent the
  29423. // same axis), used as axis directions evenly spread on a sphere.
  29424. const _axisDirections = [
  29425. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  29426. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  29427. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  29428. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  29429. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29430. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29431. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29432. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29433. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29434. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  29435. /**
  29436. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29437. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29438. * blur to be quickly accessed based on material roughness. It is packed into a
  29439. * special CubeUV format that allows us to perform custom interpolation so that
  29440. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29441. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29442. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29443. * higher roughness levels. In this way we maintain resolution to smoothly
  29444. * interpolate diffuse lighting while limiting sampling computation.
  29445. */
  29446. class PMREMGenerator {
  29447. constructor( renderer ) {
  29448. this._renderer = renderer;
  29449. this._pingPongRenderTarget = null;
  29450. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  29451. this._equirectShader = null;
  29452. this._cubemapShader = null;
  29453. this._compileMaterial( this._blurMaterial );
  29454. }
  29455. /**
  29456. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29457. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29458. * in radians to be applied to the scene before PMREM generation. Optional near
  29459. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29460. * is placed at the origin).
  29461. */
  29462. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  29463. _oldTarget = this._renderer.getRenderTarget();
  29464. const cubeUVRenderTarget = this._allocateTargets();
  29465. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29466. if ( sigma > 0 ) {
  29467. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29468. }
  29469. this._applyPMREM( cubeUVRenderTarget );
  29470. this._cleanup( cubeUVRenderTarget );
  29471. return cubeUVRenderTarget;
  29472. }
  29473. /**
  29474. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29475. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  29476. * as this matches best with the 256 x 256 cubemap output.
  29477. */
  29478. fromEquirectangular( equirectangular ) {
  29479. return this._fromTexture( equirectangular );
  29480. }
  29481. /**
  29482. * Generates a PMREM from an cubemap texture, which can be either LDR
  29483. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  29484. * as this matches best with the 256 x 256 cubemap output.
  29485. */
  29486. fromCubemap( cubemap ) {
  29487. return this._fromTexture( cubemap );
  29488. }
  29489. /**
  29490. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29491. * your texture's network fetch for increased concurrency.
  29492. */
  29493. compileCubemapShader() {
  29494. if ( this._cubemapShader === null ) {
  29495. this._cubemapShader = _getCubemapShader();
  29496. this._compileMaterial( this._cubemapShader );
  29497. }
  29498. }
  29499. /**
  29500. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29501. * your texture's network fetch for increased concurrency.
  29502. */
  29503. compileEquirectangularShader() {
  29504. if ( this._equirectShader === null ) {
  29505. this._equirectShader = _getEquirectShader();
  29506. this._compileMaterial( this._equirectShader );
  29507. }
  29508. }
  29509. /**
  29510. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29511. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29512. * one of them will cause any others to also become unusable.
  29513. */
  29514. dispose() {
  29515. this._blurMaterial.dispose();
  29516. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  29517. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  29518. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  29519. _lodPlanes[ i ].dispose();
  29520. }
  29521. }
  29522. // private interface
  29523. _cleanup( outputTarget ) {
  29524. this._pingPongRenderTarget.dispose();
  29525. this._renderer.setRenderTarget( _oldTarget );
  29526. outputTarget.scissorTest = false;
  29527. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29528. }
  29529. _fromTexture( texture ) {
  29530. _oldTarget = this._renderer.getRenderTarget();
  29531. const cubeUVRenderTarget = this._allocateTargets( texture );
  29532. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29533. this._applyPMREM( cubeUVRenderTarget );
  29534. this._cleanup( cubeUVRenderTarget );
  29535. return cubeUVRenderTarget;
  29536. }
  29537. _allocateTargets( texture ) { // warning: null texture is valid
  29538. const params = {
  29539. magFilter: NearestFilter,
  29540. minFilter: NearestFilter,
  29541. generateMipmaps: false,
  29542. type: UnsignedByteType,
  29543. format: RGBEFormat,
  29544. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  29545. depthBuffer: false
  29546. };
  29547. const cubeUVRenderTarget = _createRenderTarget( params );
  29548. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  29549. this._pingPongRenderTarget = _createRenderTarget( params );
  29550. return cubeUVRenderTarget;
  29551. }
  29552. _compileMaterial( material ) {
  29553. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  29554. this._renderer.compile( tmpMesh, _flatCamera );
  29555. }
  29556. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29557. const fov = 90;
  29558. const aspect = 1;
  29559. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  29560. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  29561. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  29562. const renderer = this._renderer;
  29563. const outputEncoding = renderer.outputEncoding;
  29564. const toneMapping = renderer.toneMapping;
  29565. renderer.getClearColor( _clearColor );
  29566. const clearAlpha = renderer.getClearAlpha();
  29567. renderer.toneMapping = NoToneMapping;
  29568. renderer.outputEncoding = LinearEncoding;
  29569. let background = scene.background;
  29570. if ( background && background.isColor ) {
  29571. background.convertSRGBToLinear();
  29572. // Convert linear to RGBE
  29573. const maxComponent = Math.max( background.r, background.g, background.b );
  29574. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  29575. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  29576. const alpha = ( fExp + 128.0 ) / 255.0;
  29577. renderer.setClearColor( background, alpha );
  29578. scene.background = null;
  29579. }
  29580. for ( let i = 0; i < 6; i ++ ) {
  29581. const col = i % 3;
  29582. if ( col == 0 ) {
  29583. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29584. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29585. } else if ( col == 1 ) {
  29586. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29587. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29588. } else {
  29589. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29590. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29591. }
  29592. _setViewport( cubeUVRenderTarget,
  29593. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  29594. renderer.setRenderTarget( cubeUVRenderTarget );
  29595. renderer.render( scene, cubeCamera );
  29596. }
  29597. renderer.toneMapping = toneMapping;
  29598. renderer.outputEncoding = outputEncoding;
  29599. renderer.setClearColor( _clearColor, clearAlpha );
  29600. }
  29601. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29602. const renderer = this._renderer;
  29603. if ( texture.isCubeTexture ) {
  29604. if ( this._cubemapShader == null ) {
  29605. this._cubemapShader = _getCubemapShader();
  29606. }
  29607. } else {
  29608. if ( this._equirectShader == null ) {
  29609. this._equirectShader = _getEquirectShader();
  29610. }
  29611. }
  29612. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  29613. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  29614. const uniforms = material.uniforms;
  29615. uniforms[ 'envMap' ].value = texture;
  29616. if ( ! texture.isCubeTexture ) {
  29617. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  29618. }
  29619. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  29620. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  29621. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  29622. renderer.setRenderTarget( cubeUVRenderTarget );
  29623. renderer.render( mesh, _flatCamera );
  29624. }
  29625. _applyPMREM( cubeUVRenderTarget ) {
  29626. const renderer = this._renderer;
  29627. const autoClear = renderer.autoClear;
  29628. renderer.autoClear = false;
  29629. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  29630. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  29631. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  29632. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29633. }
  29634. renderer.autoClear = autoClear;
  29635. }
  29636. /**
  29637. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29638. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29639. * the blur latitudinally (around the poles), and then longitudinally (towards
  29640. * the poles) to approximate the orthogonally-separable blur. It is least
  29641. * accurate at the poles, but still does a decent job.
  29642. */
  29643. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29644. const pingPongRenderTarget = this._pingPongRenderTarget;
  29645. this._halfBlur(
  29646. cubeUVRenderTarget,
  29647. pingPongRenderTarget,
  29648. lodIn,
  29649. lodOut,
  29650. sigma,
  29651. 'latitudinal',
  29652. poleAxis );
  29653. this._halfBlur(
  29654. pingPongRenderTarget,
  29655. cubeUVRenderTarget,
  29656. lodOut,
  29657. lodOut,
  29658. sigma,
  29659. 'longitudinal',
  29660. poleAxis );
  29661. }
  29662. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29663. const renderer = this._renderer;
  29664. const blurMaterial = this._blurMaterial;
  29665. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29666. console.error(
  29667. 'blur direction must be either latitudinal or longitudinal!' );
  29668. }
  29669. // Number of standard deviations at which to cut off the discrete approximation.
  29670. const STANDARD_DEVIATIONS = 3;
  29671. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  29672. const blurUniforms = blurMaterial.uniforms;
  29673. const pixels = _sizeLods[ lodIn ] - 1;
  29674. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29675. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29676. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29677. if ( samples > MAX_SAMPLES ) {
  29678. console.warn( `sigmaRadians, ${
  29679. sigmaRadians}, is too large and will clip, as it requested ${
  29680. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29681. }
  29682. const weights = [];
  29683. let sum = 0;
  29684. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29685. const x = i / sigmaPixels;
  29686. const weight = Math.exp( - x * x / 2 );
  29687. weights.push( weight );
  29688. if ( i == 0 ) {
  29689. sum += weight;
  29690. } else if ( i < samples ) {
  29691. sum += 2 * weight;
  29692. }
  29693. }
  29694. for ( let i = 0; i < weights.length; i ++ ) {
  29695. weights[ i ] = weights[ i ] / sum;
  29696. }
  29697. blurUniforms[ 'envMap' ].value = targetIn.texture;
  29698. blurUniforms[ 'samples' ].value = samples;
  29699. blurUniforms[ 'weights' ].value = weights;
  29700. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  29701. if ( poleAxis ) {
  29702. blurUniforms[ 'poleAxis' ].value = poleAxis;
  29703. }
  29704. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  29705. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  29706. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  29707. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  29708. const outputSize = _sizeLods[ lodOut ];
  29709. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  29710. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  29711. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29712. renderer.setRenderTarget( targetOut );
  29713. renderer.render( blurMesh, _flatCamera );
  29714. }
  29715. }
  29716. function _isLDR( texture ) {
  29717. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  29718. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  29719. }
  29720. function _createPlanes() {
  29721. const _lodPlanes = [];
  29722. const _sizeLods = [];
  29723. const _sigmas = [];
  29724. let lod = LOD_MAX;
  29725. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  29726. const sizeLod = Math.pow( 2, lod );
  29727. _sizeLods.push( sizeLod );
  29728. let sigma = 1.0 / sizeLod;
  29729. if ( i > LOD_MAX - LOD_MIN ) {
  29730. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  29731. } else if ( i == 0 ) {
  29732. sigma = 0;
  29733. }
  29734. _sigmas.push( sigma );
  29735. const texelSize = 1.0 / ( sizeLod - 1 );
  29736. const min = - texelSize / 2;
  29737. const max = 1 + texelSize / 2;
  29738. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29739. const cubeFaces = 6;
  29740. const vertices = 6;
  29741. const positionSize = 3;
  29742. const uvSize = 2;
  29743. const faceIndexSize = 1;
  29744. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29745. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29746. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29747. for ( let face = 0; face < cubeFaces; face ++ ) {
  29748. const x = ( face % 3 ) * 2 / 3 - 1;
  29749. const y = face > 2 ? 0 : - 1;
  29750. const coordinates = [
  29751. x, y, 0,
  29752. x + 2 / 3, y, 0,
  29753. x + 2 / 3, y + 1, 0,
  29754. x, y, 0,
  29755. x + 2 / 3, y + 1, 0,
  29756. x, y + 1, 0
  29757. ];
  29758. position.set( coordinates, positionSize * vertices * face );
  29759. uv.set( uv1, uvSize * vertices * face );
  29760. const fill = [ face, face, face, face, face, face ];
  29761. faceIndex.set( fill, faceIndexSize * vertices * face );
  29762. }
  29763. const planes = new BufferGeometry();
  29764. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29765. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29766. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29767. _lodPlanes.push( planes );
  29768. if ( lod > LOD_MIN ) {
  29769. lod --;
  29770. }
  29771. }
  29772. return { _lodPlanes, _sizeLods, _sigmas };
  29773. }
  29774. function _createRenderTarget( params ) {
  29775. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  29776. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29777. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29778. cubeUVRenderTarget.scissorTest = true;
  29779. return cubeUVRenderTarget;
  29780. }
  29781. function _setViewport( target, x, y, width, height ) {
  29782. target.viewport.set( x, y, width, height );
  29783. target.scissor.set( x, y, width, height );
  29784. }
  29785. function _getBlurShader( maxSamples ) {
  29786. const weights = new Float32Array( maxSamples );
  29787. const poleAxis = new Vector3( 0, 1, 0 );
  29788. const shaderMaterial = new RawShaderMaterial( {
  29789. name: 'SphericalGaussianBlur',
  29790. defines: { 'n': maxSamples },
  29791. uniforms: {
  29792. 'envMap': { value: null },
  29793. 'samples': { value: 1 },
  29794. 'weights': { value: weights },
  29795. 'latitudinal': { value: false },
  29796. 'dTheta': { value: 0 },
  29797. 'mipInt': { value: 0 },
  29798. 'poleAxis': { value: poleAxis },
  29799. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29800. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29801. },
  29802. vertexShader: _getCommonVertexShader(),
  29803. fragmentShader: /* glsl */`
  29804. precision mediump float;
  29805. precision mediump int;
  29806. varying vec3 vOutputDirection;
  29807. uniform sampler2D envMap;
  29808. uniform int samples;
  29809. uniform float weights[ n ];
  29810. uniform bool latitudinal;
  29811. uniform float dTheta;
  29812. uniform float mipInt;
  29813. uniform vec3 poleAxis;
  29814. ${ _getEncodings() }
  29815. #define ENVMAP_TYPE_CUBE_UV
  29816. #include <cube_uv_reflection_fragment>
  29817. vec3 getSample( float theta, vec3 axis ) {
  29818. float cosTheta = cos( theta );
  29819. // Rodrigues' axis-angle rotation
  29820. vec3 sampleDirection = vOutputDirection * cosTheta
  29821. + cross( axis, vOutputDirection ) * sin( theta )
  29822. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29823. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29824. }
  29825. void main() {
  29826. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29827. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29828. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29829. }
  29830. axis = normalize( axis );
  29831. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29832. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29833. for ( int i = 1; i < n; i++ ) {
  29834. if ( i >= samples ) {
  29835. break;
  29836. }
  29837. float theta = dTheta * float( i );
  29838. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29839. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29840. }
  29841. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29842. }
  29843. `,
  29844. blending: NoBlending,
  29845. depthTest: false,
  29846. depthWrite: false
  29847. } );
  29848. return shaderMaterial;
  29849. }
  29850. function _getEquirectShader() {
  29851. const texelSize = new Vector2$1( 1, 1 );
  29852. const shaderMaterial = new RawShaderMaterial( {
  29853. name: 'EquirectangularToCubeUV',
  29854. uniforms: {
  29855. 'envMap': { value: null },
  29856. 'texelSize': { value: texelSize },
  29857. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29858. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29859. },
  29860. vertexShader: _getCommonVertexShader(),
  29861. fragmentShader: /* glsl */`
  29862. precision mediump float;
  29863. precision mediump int;
  29864. varying vec3 vOutputDirection;
  29865. uniform sampler2D envMap;
  29866. uniform vec2 texelSize;
  29867. ${ _getEncodings() }
  29868. #include <common>
  29869. void main() {
  29870. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29871. vec3 outputDirection = normalize( vOutputDirection );
  29872. vec2 uv = equirectUv( outputDirection );
  29873. vec2 f = fract( uv / texelSize - 0.5 );
  29874. uv -= f * texelSize;
  29875. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29876. uv.x += texelSize.x;
  29877. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29878. uv.y += texelSize.y;
  29879. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29880. uv.x -= texelSize.x;
  29881. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29882. vec3 tm = mix( tl, tr, f.x );
  29883. vec3 bm = mix( bl, br, f.x );
  29884. gl_FragColor.rgb = mix( tm, bm, f.y );
  29885. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29886. }
  29887. `,
  29888. blending: NoBlending,
  29889. depthTest: false,
  29890. depthWrite: false
  29891. } );
  29892. return shaderMaterial;
  29893. }
  29894. function _getCubemapShader() {
  29895. const shaderMaterial = new RawShaderMaterial( {
  29896. name: 'CubemapToCubeUV',
  29897. uniforms: {
  29898. 'envMap': { value: null },
  29899. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29900. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29901. },
  29902. vertexShader: _getCommonVertexShader(),
  29903. fragmentShader: /* glsl */`
  29904. precision mediump float;
  29905. precision mediump int;
  29906. varying vec3 vOutputDirection;
  29907. uniform samplerCube envMap;
  29908. ${ _getEncodings() }
  29909. void main() {
  29910. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29911. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29912. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29913. }
  29914. `,
  29915. blending: NoBlending,
  29916. depthTest: false,
  29917. depthWrite: false
  29918. } );
  29919. return shaderMaterial;
  29920. }
  29921. function _getCommonVertexShader() {
  29922. return /* glsl */`
  29923. precision mediump float;
  29924. precision mediump int;
  29925. attribute vec3 position;
  29926. attribute vec2 uv;
  29927. attribute float faceIndex;
  29928. varying vec3 vOutputDirection;
  29929. // RH coordinate system; PMREM face-indexing convention
  29930. vec3 getDirection( vec2 uv, float face ) {
  29931. uv = 2.0 * uv - 1.0;
  29932. vec3 direction = vec3( uv, 1.0 );
  29933. if ( face == 0.0 ) {
  29934. direction = direction.zyx; // ( 1, v, u ) pos x
  29935. } else if ( face == 1.0 ) {
  29936. direction = direction.xzy;
  29937. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29938. } else if ( face == 2.0 ) {
  29939. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29940. } else if ( face == 3.0 ) {
  29941. direction = direction.zyx;
  29942. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29943. } else if ( face == 4.0 ) {
  29944. direction = direction.xzy;
  29945. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29946. } else if ( face == 5.0 ) {
  29947. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29948. }
  29949. return direction;
  29950. }
  29951. void main() {
  29952. vOutputDirection = getDirection( uv, faceIndex );
  29953. gl_Position = vec4( position, 1.0 );
  29954. }
  29955. `;
  29956. }
  29957. function _getEncodings() {
  29958. return /* glsl */`
  29959. uniform int inputEncoding;
  29960. uniform int outputEncoding;
  29961. #include <encodings_pars_fragment>
  29962. vec4 inputTexelToLinear( vec4 value ) {
  29963. if ( inputEncoding == 0 ) {
  29964. return value;
  29965. } else if ( inputEncoding == 1 ) {
  29966. return sRGBToLinear( value );
  29967. } else if ( inputEncoding == 2 ) {
  29968. return RGBEToLinear( value );
  29969. } else if ( inputEncoding == 3 ) {
  29970. return RGBMToLinear( value, 7.0 );
  29971. } else if ( inputEncoding == 4 ) {
  29972. return RGBMToLinear( value, 16.0 );
  29973. } else if ( inputEncoding == 5 ) {
  29974. return RGBDToLinear( value, 256.0 );
  29975. } else {
  29976. return GammaToLinear( value, 2.2 );
  29977. }
  29978. }
  29979. vec4 linearToOutputTexel( vec4 value ) {
  29980. if ( outputEncoding == 0 ) {
  29981. return value;
  29982. } else if ( outputEncoding == 1 ) {
  29983. return LinearTosRGB( value );
  29984. } else if ( outputEncoding == 2 ) {
  29985. return LinearToRGBE( value );
  29986. } else if ( outputEncoding == 3 ) {
  29987. return LinearToRGBM( value, 7.0 );
  29988. } else if ( outputEncoding == 4 ) {
  29989. return LinearToRGBM( value, 16.0 );
  29990. } else if ( outputEncoding == 5 ) {
  29991. return LinearToRGBD( value, 256.0 );
  29992. } else {
  29993. return LinearToGamma( value, 2.2 );
  29994. }
  29995. }
  29996. vec4 envMapTexelToLinear( vec4 color ) {
  29997. return inputTexelToLinear( color );
  29998. }
  29999. `;
  30000. }
  30001. function Face4( a, b, c, d, normal, color, materialIndex ) {
  30002. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  30003. return new Face3( a, b, c, normal, color, materialIndex );
  30004. }
  30005. const LineStrip = 0;
  30006. const LinePieces = 1;
  30007. const NoColors = 0;
  30008. const FaceColors = 1;
  30009. const VertexColors = 2;
  30010. function MeshFaceMaterial( materials ) {
  30011. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  30012. return materials;
  30013. }
  30014. function MultiMaterial( materials = [] ) {
  30015. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  30016. materials.isMultiMaterial = true;
  30017. materials.materials = materials;
  30018. materials.clone = function () {
  30019. return materials.slice();
  30020. };
  30021. return materials;
  30022. }
  30023. function PointCloud( geometry, material ) {
  30024. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  30025. return new Points( geometry, material );
  30026. }
  30027. function Particle( material ) {
  30028. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  30029. return new Sprite( material );
  30030. }
  30031. function ParticleSystem( geometry, material ) {
  30032. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  30033. return new Points( geometry, material );
  30034. }
  30035. function PointCloudMaterial( parameters ) {
  30036. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  30037. return new PointsMaterial( parameters );
  30038. }
  30039. function ParticleBasicMaterial( parameters ) {
  30040. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  30041. return new PointsMaterial( parameters );
  30042. }
  30043. function ParticleSystemMaterial( parameters ) {
  30044. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  30045. return new PointsMaterial( parameters );
  30046. }
  30047. function Vertex( x, y, z ) {
  30048. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  30049. return new Vector3( x, y, z );
  30050. }
  30051. //
  30052. function DynamicBufferAttribute( array, itemSize ) {
  30053. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  30054. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  30055. }
  30056. function Int8Attribute( array, itemSize ) {
  30057. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  30058. return new Int8BufferAttribute( array, itemSize );
  30059. }
  30060. function Uint8Attribute( array, itemSize ) {
  30061. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  30062. return new Uint8BufferAttribute( array, itemSize );
  30063. }
  30064. function Uint8ClampedAttribute( array, itemSize ) {
  30065. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  30066. return new Uint8ClampedBufferAttribute( array, itemSize );
  30067. }
  30068. function Int16Attribute( array, itemSize ) {
  30069. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  30070. return new Int16BufferAttribute( array, itemSize );
  30071. }
  30072. function Uint16Attribute( array, itemSize ) {
  30073. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  30074. return new Uint16BufferAttribute( array, itemSize );
  30075. }
  30076. function Int32Attribute( array, itemSize ) {
  30077. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  30078. return new Int32BufferAttribute( array, itemSize );
  30079. }
  30080. function Uint32Attribute( array, itemSize ) {
  30081. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  30082. return new Uint32BufferAttribute( array, itemSize );
  30083. }
  30084. function Float32Attribute( array, itemSize ) {
  30085. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  30086. return new Float32BufferAttribute( array, itemSize );
  30087. }
  30088. function Float64Attribute( array, itemSize ) {
  30089. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  30090. return new Float64BufferAttribute( array, itemSize );
  30091. }
  30092. //
  30093. Curve.create = function ( construct, getPoint ) {
  30094. console.log( 'THREE.Curve.create() has been deprecated' );
  30095. construct.prototype = Object.create( Curve.prototype );
  30096. construct.prototype.constructor = construct;
  30097. construct.prototype.getPoint = getPoint;
  30098. return construct;
  30099. };
  30100. //
  30101. Object.assign( CurvePath.prototype, {
  30102. createPointsGeometry: function ( divisions ) {
  30103. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30104. // generate geometry from path points (for Line or Points objects)
  30105. const pts = this.getPoints( divisions );
  30106. return this.createGeometry( pts );
  30107. },
  30108. createSpacedPointsGeometry: function ( divisions ) {
  30109. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30110. // generate geometry from equidistant sampling along the path
  30111. const pts = this.getSpacedPoints( divisions );
  30112. return this.createGeometry( pts );
  30113. },
  30114. createGeometry: function ( points ) {
  30115. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30116. const geometry = new Geometry();
  30117. for ( let i = 0, l = points.length; i < l; i ++ ) {
  30118. const point = points[ i ];
  30119. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  30120. }
  30121. return geometry;
  30122. }
  30123. } );
  30124. //
  30125. Object.assign( Path.prototype, {
  30126. fromPoints: function ( points ) {
  30127. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  30128. return this.setFromPoints( points );
  30129. }
  30130. } );
  30131. //
  30132. function ClosedSplineCurve3( points ) {
  30133. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30134. CatmullRomCurve3.call( this, points );
  30135. this.type = 'catmullrom';
  30136. this.closed = true;
  30137. }
  30138. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30139. //
  30140. function SplineCurve3( points ) {
  30141. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30142. CatmullRomCurve3.call( this, points );
  30143. this.type = 'catmullrom';
  30144. }
  30145. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30146. //
  30147. function Spline( points ) {
  30148. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  30149. CatmullRomCurve3.call( this, points );
  30150. this.type = 'catmullrom';
  30151. }
  30152. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  30153. Object.assign( Spline.prototype, {
  30154. initFromArray: function ( /* a */ ) {
  30155. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  30156. },
  30157. getControlPointsArray: function ( /* optionalTarget */ ) {
  30158. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  30159. },
  30160. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  30161. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  30162. }
  30163. } );
  30164. //
  30165. function AxisHelper( size ) {
  30166. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  30167. return new AxesHelper( size );
  30168. }
  30169. function BoundingBoxHelper( object, color ) {
  30170. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  30171. return new BoxHelper( object, color );
  30172. }
  30173. function EdgesHelper( object, hex ) {
  30174. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  30175. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30176. }
  30177. GridHelper.prototype.setColors = function () {
  30178. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  30179. };
  30180. SkeletonHelper.prototype.update = function () {
  30181. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  30182. };
  30183. function WireframeHelper( object, hex ) {
  30184. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  30185. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30186. }
  30187. //
  30188. Object.assign( Loader.prototype, {
  30189. extractUrlBase: function ( url ) {
  30190. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  30191. return LoaderUtils.extractUrlBase( url );
  30192. }
  30193. } );
  30194. Loader.Handlers = {
  30195. add: function ( /* regex, loader */ ) {
  30196. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  30197. },
  30198. get: function ( /* file */ ) {
  30199. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  30200. }
  30201. };
  30202. function XHRLoader( manager ) {
  30203. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  30204. return new FileLoader( manager );
  30205. }
  30206. function BinaryTextureLoader( manager ) {
  30207. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  30208. return new DataTextureLoader( manager );
  30209. }
  30210. //
  30211. Object.assign( Box2.prototype, {
  30212. center: function ( optionalTarget ) {
  30213. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  30214. return this.getCenter( optionalTarget );
  30215. },
  30216. empty: function () {
  30217. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  30218. return this.isEmpty();
  30219. },
  30220. isIntersectionBox: function ( box ) {
  30221. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30222. return this.intersectsBox( box );
  30223. },
  30224. size: function ( optionalTarget ) {
  30225. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  30226. return this.getSize( optionalTarget );
  30227. }
  30228. } );
  30229. Object.assign( Box3.prototype, {
  30230. center: function ( optionalTarget ) {
  30231. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  30232. return this.getCenter( optionalTarget );
  30233. },
  30234. empty: function () {
  30235. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  30236. return this.isEmpty();
  30237. },
  30238. isIntersectionBox: function ( box ) {
  30239. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30240. return this.intersectsBox( box );
  30241. },
  30242. isIntersectionSphere: function ( sphere ) {
  30243. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30244. return this.intersectsSphere( sphere );
  30245. },
  30246. size: function ( optionalTarget ) {
  30247. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  30248. return this.getSize( optionalTarget );
  30249. }
  30250. } );
  30251. Object.assign( Sphere.prototype, {
  30252. empty: function () {
  30253. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  30254. return this.isEmpty();
  30255. },
  30256. } );
  30257. Frustum.prototype.setFromMatrix = function ( m ) {
  30258. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  30259. return this.setFromProjectionMatrix( m );
  30260. };
  30261. Line3.prototype.center = function ( optionalTarget ) {
  30262. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  30263. return this.getCenter( optionalTarget );
  30264. };
  30265. Object.assign( MathUtils, {
  30266. random16: function () {
  30267. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  30268. return Math.random();
  30269. },
  30270. nearestPowerOfTwo: function ( value ) {
  30271. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  30272. return MathUtils.floorPowerOfTwo( value );
  30273. },
  30274. nextPowerOfTwo: function ( value ) {
  30275. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  30276. return MathUtils.ceilPowerOfTwo( value );
  30277. }
  30278. } );
  30279. Object.assign( Matrix3.prototype, {
  30280. flattenToArrayOffset: function ( array, offset ) {
  30281. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30282. return this.toArray( array, offset );
  30283. },
  30284. multiplyVector3: function ( vector ) {
  30285. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  30286. return vector.applyMatrix3( this );
  30287. },
  30288. multiplyVector3Array: function ( /* a */ ) {
  30289. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  30290. },
  30291. applyToBufferAttribute: function ( attribute ) {
  30292. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  30293. return attribute.applyMatrix3( this );
  30294. },
  30295. applyToVector3Array: function ( /* array, offset, length */ ) {
  30296. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  30297. },
  30298. getInverse: function ( matrix ) {
  30299. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30300. return this.copy( matrix ).invert();
  30301. }
  30302. } );
  30303. Object.assign( Matrix4.prototype, {
  30304. extractPosition: function ( m ) {
  30305. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  30306. return this.copyPosition( m );
  30307. },
  30308. flattenToArrayOffset: function ( array, offset ) {
  30309. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30310. return this.toArray( array, offset );
  30311. },
  30312. getPosition: function () {
  30313. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  30314. return new Vector3().setFromMatrixColumn( this, 3 );
  30315. },
  30316. setRotationFromQuaternion: function ( q ) {
  30317. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  30318. return this.makeRotationFromQuaternion( q );
  30319. },
  30320. multiplyToArray: function () {
  30321. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  30322. },
  30323. multiplyVector3: function ( vector ) {
  30324. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30325. return vector.applyMatrix4( this );
  30326. },
  30327. multiplyVector4: function ( vector ) {
  30328. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30329. return vector.applyMatrix4( this );
  30330. },
  30331. multiplyVector3Array: function ( /* a */ ) {
  30332. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  30333. },
  30334. rotateAxis: function ( v ) {
  30335. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  30336. v.transformDirection( this );
  30337. },
  30338. crossVector: function ( vector ) {
  30339. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30340. return vector.applyMatrix4( this );
  30341. },
  30342. translate: function () {
  30343. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  30344. },
  30345. rotateX: function () {
  30346. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  30347. },
  30348. rotateY: function () {
  30349. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  30350. },
  30351. rotateZ: function () {
  30352. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  30353. },
  30354. rotateByAxis: function () {
  30355. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  30356. },
  30357. applyToBufferAttribute: function ( attribute ) {
  30358. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  30359. return attribute.applyMatrix4( this );
  30360. },
  30361. applyToVector3Array: function ( /* array, offset, length */ ) {
  30362. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  30363. },
  30364. makeFrustum: function ( left, right, bottom, top, near, far ) {
  30365. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  30366. return this.makePerspective( left, right, top, bottom, near, far );
  30367. },
  30368. getInverse: function ( matrix ) {
  30369. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30370. return this.copy( matrix ).invert();
  30371. }
  30372. } );
  30373. Plane.prototype.isIntersectionLine = function ( line ) {
  30374. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  30375. return this.intersectsLine( line );
  30376. };
  30377. Object.assign( Quaternion.prototype, {
  30378. multiplyVector3: function ( vector ) {
  30379. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  30380. return vector.applyQuaternion( this );
  30381. },
  30382. inverse: function ( ) {
  30383. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  30384. return this.invert();
  30385. }
  30386. } );
  30387. Object.assign( Ray.prototype, {
  30388. isIntersectionBox: function ( box ) {
  30389. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30390. return this.intersectsBox( box );
  30391. },
  30392. isIntersectionPlane: function ( plane ) {
  30393. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  30394. return this.intersectsPlane( plane );
  30395. },
  30396. isIntersectionSphere: function ( sphere ) {
  30397. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30398. return this.intersectsSphere( sphere );
  30399. }
  30400. } );
  30401. Object.assign( Triangle.prototype, {
  30402. area: function () {
  30403. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  30404. return this.getArea();
  30405. },
  30406. barycoordFromPoint: function ( point, target ) {
  30407. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30408. return this.getBarycoord( point, target );
  30409. },
  30410. midpoint: function ( target ) {
  30411. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  30412. return this.getMidpoint( target );
  30413. },
  30414. normal: function ( target ) {
  30415. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30416. return this.getNormal( target );
  30417. },
  30418. plane: function ( target ) {
  30419. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  30420. return this.getPlane( target );
  30421. }
  30422. } );
  30423. Object.assign( Triangle, {
  30424. barycoordFromPoint: function ( point, a, b, c, target ) {
  30425. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30426. return Triangle.getBarycoord( point, a, b, c, target );
  30427. },
  30428. normal: function ( a, b, c, target ) {
  30429. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30430. return Triangle.getNormal( a, b, c, target );
  30431. }
  30432. } );
  30433. Object.assign( Shape.prototype, {
  30434. extractAllPoints: function ( divisions ) {
  30435. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  30436. return this.extractPoints( divisions );
  30437. },
  30438. extrude: function ( options ) {
  30439. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  30440. return new ExtrudeGeometry( this, options );
  30441. },
  30442. makeGeometry: function ( options ) {
  30443. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  30444. return new ShapeGeometry( this, options );
  30445. }
  30446. } );
  30447. Object.assign( Vector2$1.prototype, {
  30448. fromAttribute: function ( attribute, index, offset ) {
  30449. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30450. return this.fromBufferAttribute( attribute, index, offset );
  30451. },
  30452. distanceToManhattan: function ( v ) {
  30453. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30454. return this.manhattanDistanceTo( v );
  30455. },
  30456. lengthManhattan: function () {
  30457. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  30458. return this.manhattanLength();
  30459. }
  30460. } );
  30461. Object.assign( Vector3.prototype, {
  30462. setEulerFromRotationMatrix: function () {
  30463. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  30464. },
  30465. setEulerFromQuaternion: function () {
  30466. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  30467. },
  30468. getPositionFromMatrix: function ( m ) {
  30469. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  30470. return this.setFromMatrixPosition( m );
  30471. },
  30472. getScaleFromMatrix: function ( m ) {
  30473. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  30474. return this.setFromMatrixScale( m );
  30475. },
  30476. getColumnFromMatrix: function ( index, matrix ) {
  30477. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  30478. return this.setFromMatrixColumn( matrix, index );
  30479. },
  30480. applyProjection: function ( m ) {
  30481. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  30482. return this.applyMatrix4( m );
  30483. },
  30484. fromAttribute: function ( attribute, index, offset ) {
  30485. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30486. return this.fromBufferAttribute( attribute, index, offset );
  30487. },
  30488. distanceToManhattan: function ( v ) {
  30489. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30490. return this.manhattanDistanceTo( v );
  30491. },
  30492. lengthManhattan: function () {
  30493. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  30494. return this.manhattanLength();
  30495. }
  30496. } );
  30497. Object.assign( Vector4.prototype, {
  30498. fromAttribute: function ( attribute, index, offset ) {
  30499. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30500. return this.fromBufferAttribute( attribute, index, offset );
  30501. },
  30502. lengthManhattan: function () {
  30503. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  30504. return this.manhattanLength();
  30505. }
  30506. } );
  30507. //
  30508. Object.assign( Geometry.prototype, {
  30509. computeTangents: function () {
  30510. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  30511. },
  30512. computeLineDistances: function () {
  30513. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  30514. },
  30515. applyMatrix: function ( matrix ) {
  30516. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30517. return this.applyMatrix4( matrix );
  30518. }
  30519. } );
  30520. Object.assign( Object3D.prototype, {
  30521. getChildByName: function ( name ) {
  30522. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  30523. return this.getObjectByName( name );
  30524. },
  30525. renderDepth: function () {
  30526. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  30527. },
  30528. translate: function ( distance, axis ) {
  30529. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  30530. return this.translateOnAxis( axis, distance );
  30531. },
  30532. getWorldRotation: function () {
  30533. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  30534. },
  30535. applyMatrix: function ( matrix ) {
  30536. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  30537. return this.applyMatrix4( matrix );
  30538. }
  30539. } );
  30540. Object.defineProperties( Object3D.prototype, {
  30541. eulerOrder: {
  30542. get: function () {
  30543. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30544. return this.rotation.order;
  30545. },
  30546. set: function ( value ) {
  30547. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30548. this.rotation.order = value;
  30549. }
  30550. },
  30551. useQuaternion: {
  30552. get: function () {
  30553. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30554. },
  30555. set: function () {
  30556. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30557. }
  30558. }
  30559. } );
  30560. Object.assign( Mesh.prototype, {
  30561. setDrawMode: function () {
  30562. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30563. },
  30564. } );
  30565. Object.defineProperties( Mesh.prototype, {
  30566. drawMode: {
  30567. get: function () {
  30568. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  30569. return TrianglesDrawMode;
  30570. },
  30571. set: function () {
  30572. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30573. }
  30574. }
  30575. } );
  30576. Object.defineProperties( LOD.prototype, {
  30577. objects: {
  30578. get: function () {
  30579. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  30580. return this.levels;
  30581. }
  30582. }
  30583. } );
  30584. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  30585. get: function () {
  30586. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30587. },
  30588. set: function () {
  30589. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30590. }
  30591. } );
  30592. SkinnedMesh.prototype.initBones = function () {
  30593. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  30594. };
  30595. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  30596. get: function () {
  30597. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30598. return this.arcLengthDivisions;
  30599. },
  30600. set: function ( value ) {
  30601. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30602. this.arcLengthDivisions = value;
  30603. }
  30604. } );
  30605. //
  30606. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  30607. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  30608. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  30609. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  30610. this.setFocalLength( focalLength );
  30611. };
  30612. //
  30613. Object.defineProperties( Light.prototype, {
  30614. onlyShadow: {
  30615. set: function () {
  30616. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  30617. }
  30618. },
  30619. shadowCameraFov: {
  30620. set: function ( value ) {
  30621. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  30622. this.shadow.camera.fov = value;
  30623. }
  30624. },
  30625. shadowCameraLeft: {
  30626. set: function ( value ) {
  30627. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  30628. this.shadow.camera.left = value;
  30629. }
  30630. },
  30631. shadowCameraRight: {
  30632. set: function ( value ) {
  30633. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  30634. this.shadow.camera.right = value;
  30635. }
  30636. },
  30637. shadowCameraTop: {
  30638. set: function ( value ) {
  30639. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  30640. this.shadow.camera.top = value;
  30641. }
  30642. },
  30643. shadowCameraBottom: {
  30644. set: function ( value ) {
  30645. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  30646. this.shadow.camera.bottom = value;
  30647. }
  30648. },
  30649. shadowCameraNear: {
  30650. set: function ( value ) {
  30651. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  30652. this.shadow.camera.near = value;
  30653. }
  30654. },
  30655. shadowCameraFar: {
  30656. set: function ( value ) {
  30657. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  30658. this.shadow.camera.far = value;
  30659. }
  30660. },
  30661. shadowCameraVisible: {
  30662. set: function () {
  30663. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  30664. }
  30665. },
  30666. shadowBias: {
  30667. set: function ( value ) {
  30668. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  30669. this.shadow.bias = value;
  30670. }
  30671. },
  30672. shadowDarkness: {
  30673. set: function () {
  30674. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  30675. }
  30676. },
  30677. shadowMapWidth: {
  30678. set: function ( value ) {
  30679. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  30680. this.shadow.mapSize.width = value;
  30681. }
  30682. },
  30683. shadowMapHeight: {
  30684. set: function ( value ) {
  30685. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  30686. this.shadow.mapSize.height = value;
  30687. }
  30688. }
  30689. } );
  30690. //
  30691. Object.defineProperties( BufferAttribute.prototype, {
  30692. length: {
  30693. get: function () {
  30694. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  30695. return this.array.length;
  30696. }
  30697. },
  30698. dynamic: {
  30699. get: function () {
  30700. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30701. return this.usage === DynamicDrawUsage;
  30702. },
  30703. set: function ( /* value */ ) {
  30704. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30705. this.setUsage( DynamicDrawUsage );
  30706. }
  30707. }
  30708. } );
  30709. Object.assign( BufferAttribute.prototype, {
  30710. setDynamic: function ( value ) {
  30711. //console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30712. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30713. return this;
  30714. },
  30715. copyIndicesArray: function ( /* indices */ ) {
  30716. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  30717. },
  30718. setArray: function ( /* array */ ) {
  30719. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30720. }
  30721. } );
  30722. Object.assign( BufferGeometry.prototype, {
  30723. addIndex: function ( index ) {
  30724. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  30725. this.setIndex( index );
  30726. },
  30727. addAttribute: function ( name, attribute ) {
  30728. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  30729. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  30730. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  30731. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  30732. }
  30733. if ( name === 'index' ) {
  30734. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  30735. this.setIndex( attribute );
  30736. return this;
  30737. }
  30738. return this.setAttribute( name, attribute );
  30739. },
  30740. addDrawCall: function ( start, count, indexOffset ) {
  30741. if ( indexOffset !== undefined ) {
  30742. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  30743. }
  30744. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30745. this.addGroup( start, count );
  30746. },
  30747. clearDrawCalls: function () {
  30748. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30749. this.clearGroups();
  30750. },
  30751. computeTangents: function () {
  30752. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  30753. },
  30754. computeOffsets: function () {
  30755. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30756. },
  30757. removeAttribute: function ( name ) {
  30758. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  30759. return this.deleteAttribute( name );
  30760. },
  30761. applyMatrix: function ( matrix ) {
  30762. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30763. return this.applyMatrix4( matrix );
  30764. }
  30765. } );
  30766. Object.defineProperties( BufferGeometry.prototype, {
  30767. drawcalls: {
  30768. get: function () {
  30769. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30770. return this.groups;
  30771. }
  30772. },
  30773. offsets: {
  30774. get: function () {
  30775. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30776. return this.groups;
  30777. }
  30778. }
  30779. } );
  30780. Object.defineProperties( InstancedBufferGeometry.prototype, {
  30781. maxInstancedCount: {
  30782. get: function () {
  30783. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30784. return this.instanceCount;
  30785. },
  30786. set: function ( value ) {
  30787. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30788. this.instanceCount = value;
  30789. }
  30790. }
  30791. } );
  30792. Object.defineProperties( Raycaster.prototype, {
  30793. linePrecision: {
  30794. get: function () {
  30795. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30796. return this.params.Line.threshold;
  30797. },
  30798. set: function ( value ) {
  30799. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30800. this.params.Line.threshold = value;
  30801. }
  30802. }
  30803. } );
  30804. Object.defineProperties( InterleavedBuffer.prototype, {
  30805. dynamic: {
  30806. get: function () {
  30807. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30808. return this.usage === DynamicDrawUsage;
  30809. },
  30810. set: function ( value ) {
  30811. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30812. this.setUsage( value );
  30813. }
  30814. }
  30815. } );
  30816. Object.assign( InterleavedBuffer.prototype, {
  30817. setDynamic: function ( value ) {
  30818. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30819. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30820. return this;
  30821. },
  30822. setArray: function ( /* array */ ) {
  30823. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30824. }
  30825. } );
  30826. //
  30827. Object.assign( ExtrudeBufferGeometry.prototype, {
  30828. getArrays: function () {
  30829. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  30830. },
  30831. addShapeList: function () {
  30832. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  30833. },
  30834. addShape: function () {
  30835. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  30836. }
  30837. } );
  30838. //
  30839. Object.assign( Scene.prototype, {
  30840. dispose: function () {
  30841. console.error( 'THREE.Scene: .dispose() has been removed.' );
  30842. }
  30843. } );
  30844. //
  30845. Object.defineProperties( Uniform.prototype, {
  30846. dynamic: {
  30847. set: function () {
  30848. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  30849. }
  30850. },
  30851. onUpdate: {
  30852. value: function () {
  30853. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30854. return this;
  30855. }
  30856. }
  30857. } );
  30858. //
  30859. Object.defineProperties( Material.prototype, {
  30860. wrapAround: {
  30861. get: function () {
  30862. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30863. },
  30864. set: function () {
  30865. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30866. }
  30867. },
  30868. overdraw: {
  30869. get: function () {
  30870. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30871. },
  30872. set: function () {
  30873. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30874. }
  30875. },
  30876. wrapRGB: {
  30877. get: function () {
  30878. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30879. return new Color();
  30880. }
  30881. },
  30882. shading: {
  30883. get: function () {
  30884. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30885. },
  30886. set: function ( value ) {
  30887. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30888. this.flatShading = ( value === FlatShading );
  30889. }
  30890. },
  30891. stencilMask: {
  30892. get: function () {
  30893. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30894. return this.stencilFuncMask;
  30895. },
  30896. set: function ( value ) {
  30897. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30898. this.stencilFuncMask = value;
  30899. }
  30900. }
  30901. } );
  30902. Object.defineProperties( MeshPhongMaterial.prototype, {
  30903. metal: {
  30904. get: function () {
  30905. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  30906. return false;
  30907. },
  30908. set: function () {
  30909. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  30910. }
  30911. }
  30912. } );
  30913. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  30914. transparency: {
  30915. get: function () {
  30916. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30917. return this.transmission;
  30918. },
  30919. set: function ( value ) {
  30920. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30921. this.transmission = value;
  30922. }
  30923. }
  30924. } );
  30925. Object.defineProperties( ShaderMaterial.prototype, {
  30926. derivatives: {
  30927. get: function () {
  30928. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30929. return this.extensions.derivatives;
  30930. },
  30931. set: function ( value ) {
  30932. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30933. this.extensions.derivatives = value;
  30934. }
  30935. }
  30936. } );
  30937. //
  30938. Object.assign( WebGLRenderer.prototype, {
  30939. clearTarget: function ( renderTarget, color, depth, stencil ) {
  30940. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  30941. this.setRenderTarget( renderTarget );
  30942. this.clear( color, depth, stencil );
  30943. },
  30944. animate: function ( callback ) {
  30945. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  30946. this.setAnimationLoop( callback );
  30947. },
  30948. getCurrentRenderTarget: function () {
  30949. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30950. return this.getRenderTarget();
  30951. },
  30952. getMaxAnisotropy: function () {
  30953. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30954. return this.capabilities.getMaxAnisotropy();
  30955. },
  30956. getPrecision: function () {
  30957. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30958. return this.capabilities.precision;
  30959. },
  30960. resetGLState: function () {
  30961. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  30962. return this.state.reset();
  30963. },
  30964. supportsFloatTextures: function () {
  30965. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30966. return this.extensions.get( 'OES_texture_float' );
  30967. },
  30968. supportsHalfFloatTextures: function () {
  30969. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30970. return this.extensions.get( 'OES_texture_half_float' );
  30971. },
  30972. supportsStandardDerivatives: function () {
  30973. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30974. return this.extensions.get( 'OES_standard_derivatives' );
  30975. },
  30976. supportsCompressedTextureS3TC: function () {
  30977. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30978. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30979. },
  30980. supportsCompressedTexturePVRTC: function () {
  30981. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30982. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30983. },
  30984. supportsBlendMinMax: function () {
  30985. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30986. return this.extensions.get( 'EXT_blend_minmax' );
  30987. },
  30988. supportsVertexTextures: function () {
  30989. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30990. return this.capabilities.vertexTextures;
  30991. },
  30992. supportsInstancedArrays: function () {
  30993. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30994. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30995. },
  30996. enableScissorTest: function ( boolean ) {
  30997. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30998. this.setScissorTest( boolean );
  30999. },
  31000. initMaterial: function () {
  31001. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  31002. },
  31003. addPrePlugin: function () {
  31004. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  31005. },
  31006. addPostPlugin: function () {
  31007. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  31008. },
  31009. updateShadowMap: function () {
  31010. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  31011. },
  31012. setFaceCulling: function () {
  31013. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  31014. },
  31015. allocTextureUnit: function () {
  31016. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  31017. },
  31018. setTexture: function () {
  31019. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  31020. },
  31021. setTexture2D: function () {
  31022. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  31023. },
  31024. setTextureCube: function () {
  31025. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  31026. },
  31027. getActiveMipMapLevel: function () {
  31028. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  31029. return this.getActiveMipmapLevel();
  31030. }
  31031. } );
  31032. Object.defineProperties( WebGLRenderer.prototype, {
  31033. shadowMapEnabled: {
  31034. get: function () {
  31035. return this.shadowMap.enabled;
  31036. },
  31037. set: function ( value ) {
  31038. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  31039. this.shadowMap.enabled = value;
  31040. }
  31041. },
  31042. shadowMapType: {
  31043. get: function () {
  31044. return this.shadowMap.type;
  31045. },
  31046. set: function ( value ) {
  31047. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  31048. this.shadowMap.type = value;
  31049. }
  31050. },
  31051. shadowMapCullFace: {
  31052. get: function () {
  31053. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31054. return undefined;
  31055. },
  31056. set: function ( /* value */ ) {
  31057. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31058. }
  31059. },
  31060. context: {
  31061. get: function () {
  31062. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  31063. return this.getContext();
  31064. }
  31065. },
  31066. vr: {
  31067. get: function () {
  31068. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  31069. return this.xr;
  31070. }
  31071. },
  31072. gammaInput: {
  31073. get: function () {
  31074. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  31075. return false;
  31076. },
  31077. set: function () {
  31078. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  31079. }
  31080. },
  31081. gammaOutput: {
  31082. get: function () {
  31083. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  31084. return false;
  31085. },
  31086. set: function ( value ) {
  31087. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  31088. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  31089. }
  31090. },
  31091. toneMappingWhitePoint: {
  31092. get: function () {
  31093. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  31094. return 1.0;
  31095. },
  31096. set: function () {
  31097. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  31098. }
  31099. },
  31100. } );
  31101. Object.defineProperties( WebGLShadowMap.prototype, {
  31102. cullFace: {
  31103. get: function () {
  31104. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31105. return undefined;
  31106. },
  31107. set: function ( /* cullFace */ ) {
  31108. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31109. }
  31110. },
  31111. renderReverseSided: {
  31112. get: function () {
  31113. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31114. return undefined;
  31115. },
  31116. set: function () {
  31117. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31118. }
  31119. },
  31120. renderSingleSided: {
  31121. get: function () {
  31122. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31123. return undefined;
  31124. },
  31125. set: function () {
  31126. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31127. }
  31128. }
  31129. } );
  31130. function WebGLRenderTargetCube( width, height, options ) {
  31131. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  31132. return new WebGLCubeRenderTarget( width, options );
  31133. }
  31134. //
  31135. Object.defineProperties( WebGLRenderTarget.prototype, {
  31136. wrapS: {
  31137. get: function () {
  31138. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31139. return this.texture.wrapS;
  31140. },
  31141. set: function ( value ) {
  31142. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31143. this.texture.wrapS = value;
  31144. }
  31145. },
  31146. wrapT: {
  31147. get: function () {
  31148. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31149. return this.texture.wrapT;
  31150. },
  31151. set: function ( value ) {
  31152. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31153. this.texture.wrapT = value;
  31154. }
  31155. },
  31156. magFilter: {
  31157. get: function () {
  31158. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31159. return this.texture.magFilter;
  31160. },
  31161. set: function ( value ) {
  31162. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31163. this.texture.magFilter = value;
  31164. }
  31165. },
  31166. minFilter: {
  31167. get: function () {
  31168. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31169. return this.texture.minFilter;
  31170. },
  31171. set: function ( value ) {
  31172. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31173. this.texture.minFilter = value;
  31174. }
  31175. },
  31176. anisotropy: {
  31177. get: function () {
  31178. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31179. return this.texture.anisotropy;
  31180. },
  31181. set: function ( value ) {
  31182. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31183. this.texture.anisotropy = value;
  31184. }
  31185. },
  31186. offset: {
  31187. get: function () {
  31188. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31189. return this.texture.offset;
  31190. },
  31191. set: function ( value ) {
  31192. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31193. this.texture.offset = value;
  31194. }
  31195. },
  31196. repeat: {
  31197. get: function () {
  31198. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31199. return this.texture.repeat;
  31200. },
  31201. set: function ( value ) {
  31202. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31203. this.texture.repeat = value;
  31204. }
  31205. },
  31206. format: {
  31207. get: function () {
  31208. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31209. return this.texture.format;
  31210. },
  31211. set: function ( value ) {
  31212. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31213. this.texture.format = value;
  31214. }
  31215. },
  31216. type: {
  31217. get: function () {
  31218. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31219. return this.texture.type;
  31220. },
  31221. set: function ( value ) {
  31222. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31223. this.texture.type = value;
  31224. }
  31225. },
  31226. generateMipmaps: {
  31227. get: function () {
  31228. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31229. return this.texture.generateMipmaps;
  31230. },
  31231. set: function ( value ) {
  31232. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31233. this.texture.generateMipmaps = value;
  31234. }
  31235. }
  31236. } );
  31237. //
  31238. Object.defineProperties( Audio.prototype, {
  31239. load: {
  31240. value: function ( file ) {
  31241. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  31242. const scope = this;
  31243. const audioLoader = new AudioLoader();
  31244. audioLoader.load( file, function ( buffer ) {
  31245. scope.setBuffer( buffer );
  31246. } );
  31247. return this;
  31248. }
  31249. },
  31250. startTime: {
  31251. set: function () {
  31252. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  31253. }
  31254. }
  31255. } );
  31256. AudioAnalyser.prototype.getData = function () {
  31257. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  31258. return this.getFrequencyData();
  31259. };
  31260. //
  31261. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  31262. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  31263. return this.update( renderer, scene );
  31264. };
  31265. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  31266. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  31267. return this.renderTarget.clear( renderer, color, depth, stencil );
  31268. };
  31269. //
  31270. const GeometryUtils = {
  31271. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  31272. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  31273. let matrix;
  31274. if ( geometry2.isMesh ) {
  31275. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  31276. matrix = geometry2.matrix;
  31277. geometry2 = geometry2.geometry;
  31278. }
  31279. geometry1.merge( geometry2, matrix, materialIndexOffset );
  31280. },
  31281. center: function ( geometry ) {
  31282. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  31283. return geometry.center();
  31284. }
  31285. };
  31286. ImageUtils.crossOrigin = undefined;
  31287. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  31288. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  31289. const loader = new TextureLoader();
  31290. loader.setCrossOrigin( this.crossOrigin );
  31291. const texture = loader.load( url, onLoad, undefined, onError );
  31292. if ( mapping ) texture.mapping = mapping;
  31293. return texture;
  31294. };
  31295. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  31296. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  31297. const loader = new CubeTextureLoader();
  31298. loader.setCrossOrigin( this.crossOrigin );
  31299. const texture = loader.load( urls, onLoad, undefined, onError );
  31300. if ( mapping ) texture.mapping = mapping;
  31301. return texture;
  31302. };
  31303. ImageUtils.loadCompressedTexture = function () {
  31304. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  31305. };
  31306. ImageUtils.loadCompressedTextureCube = function () {
  31307. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  31308. };
  31309. //
  31310. function CanvasRenderer() {
  31311. console.error( 'THREE.CanvasRenderer has been removed' );
  31312. }
  31313. //
  31314. function JSONLoader() {
  31315. console.error( 'THREE.JSONLoader has been removed.' );
  31316. }
  31317. //
  31318. const SceneUtils = {
  31319. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  31320. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31321. },
  31322. detach: function ( /* child, parent, scene */ ) {
  31323. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31324. },
  31325. attach: function ( /* child, scene, parent */ ) {
  31326. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31327. }
  31328. };
  31329. //
  31330. function LensFlare() {
  31331. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  31332. }
  31333. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31334. /* eslint-disable no-undef */
  31335. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31336. revision: REVISION,
  31337. } } ) );
  31338. /* eslint-enable no-undef */
  31339. }
  31340. var THREE$1 = /*#__PURE__*/Object.freeze({
  31341. __proto__: null,
  31342. ACESFilmicToneMapping: ACESFilmicToneMapping,
  31343. AddEquation: AddEquation,
  31344. AddOperation: AddOperation,
  31345. AdditiveAnimationBlendMode: AdditiveAnimationBlendMode,
  31346. AdditiveBlending: AdditiveBlending,
  31347. AlphaFormat: AlphaFormat,
  31348. AlwaysDepth: AlwaysDepth,
  31349. AlwaysStencilFunc: AlwaysStencilFunc,
  31350. AmbientLight: AmbientLight,
  31351. AmbientLightProbe: AmbientLightProbe,
  31352. AnimationClip: AnimationClip,
  31353. AnimationLoader: AnimationLoader,
  31354. AnimationMixer: AnimationMixer,
  31355. AnimationObjectGroup: AnimationObjectGroup,
  31356. AnimationUtils: AnimationUtils,
  31357. ArcCurve: ArcCurve,
  31358. ArrayCamera: ArrayCamera,
  31359. ArrowHelper: ArrowHelper,
  31360. Audio: Audio,
  31361. AudioAnalyser: AudioAnalyser,
  31362. AudioContext: AudioContext,
  31363. AudioListener: AudioListener,
  31364. AudioLoader: AudioLoader,
  31365. AxesHelper: AxesHelper,
  31366. AxisHelper: AxisHelper,
  31367. BackSide: BackSide,
  31368. BasicDepthPacking: BasicDepthPacking,
  31369. BasicShadowMap: BasicShadowMap,
  31370. BinaryTextureLoader: BinaryTextureLoader,
  31371. Bone: Bone,
  31372. BooleanKeyframeTrack: BooleanKeyframeTrack,
  31373. BoundingBoxHelper: BoundingBoxHelper,
  31374. Box2: Box2,
  31375. Box3: Box3,
  31376. Box3Helper: Box3Helper,
  31377. BoxBufferGeometry: BoxBufferGeometry,
  31378. BoxGeometry: BoxGeometry,
  31379. BoxHelper: BoxHelper,
  31380. BufferAttribute: BufferAttribute,
  31381. BufferGeometry: BufferGeometry,
  31382. BufferGeometryLoader: BufferGeometryLoader,
  31383. ByteType: ByteType,
  31384. Cache: Cache,
  31385. Camera: Camera,
  31386. CameraHelper: CameraHelper,
  31387. CanvasRenderer: CanvasRenderer,
  31388. CanvasTexture: CanvasTexture,
  31389. CatmullRomCurve3: CatmullRomCurve3,
  31390. CineonToneMapping: CineonToneMapping,
  31391. CircleBufferGeometry: CircleBufferGeometry,
  31392. CircleGeometry: CircleGeometry,
  31393. ClampToEdgeWrapping: ClampToEdgeWrapping,
  31394. Clock: Clock,
  31395. ClosedSplineCurve3: ClosedSplineCurve3,
  31396. Color: Color,
  31397. ColorKeyframeTrack: ColorKeyframeTrack,
  31398. CompressedTexture: CompressedTexture,
  31399. CompressedTextureLoader: CompressedTextureLoader,
  31400. ConeBufferGeometry: ConeBufferGeometry,
  31401. ConeGeometry: ConeGeometry,
  31402. CubeCamera: CubeCamera,
  31403. CubeGeometry: BoxGeometry,
  31404. CubeReflectionMapping: CubeReflectionMapping,
  31405. CubeRefractionMapping: CubeRefractionMapping,
  31406. CubeTexture: CubeTexture,
  31407. CubeTextureLoader: CubeTextureLoader,
  31408. CubeUVReflectionMapping: CubeUVReflectionMapping,
  31409. CubeUVRefractionMapping: CubeUVRefractionMapping,
  31410. CubicBezierCurve: CubicBezierCurve,
  31411. CubicBezierCurve3: CubicBezierCurve3,
  31412. CubicInterpolant: CubicInterpolant,
  31413. CullFaceBack: CullFaceBack,
  31414. CullFaceFront: CullFaceFront,
  31415. CullFaceFrontBack: CullFaceFrontBack,
  31416. CullFaceNone: CullFaceNone,
  31417. Curve: Curve,
  31418. CurvePath: CurvePath,
  31419. CustomBlending: CustomBlending,
  31420. CustomToneMapping: CustomToneMapping,
  31421. CylinderBufferGeometry: CylinderBufferGeometry,
  31422. CylinderGeometry: CylinderGeometry,
  31423. Cylindrical: Cylindrical,
  31424. DataTexture: DataTexture,
  31425. DataTexture2DArray: DataTexture2DArray,
  31426. DataTexture3D: DataTexture3D,
  31427. DataTextureLoader: DataTextureLoader,
  31428. DataUtils: DataUtils,
  31429. DecrementStencilOp: DecrementStencilOp,
  31430. DecrementWrapStencilOp: DecrementWrapStencilOp,
  31431. DefaultLoadingManager: DefaultLoadingManager,
  31432. DepthFormat: DepthFormat,
  31433. DepthStencilFormat: DepthStencilFormat,
  31434. DepthTexture: DepthTexture,
  31435. DirectionalLight: DirectionalLight,
  31436. DirectionalLightHelper: DirectionalLightHelper,
  31437. DiscreteInterpolant: DiscreteInterpolant,
  31438. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  31439. DodecahedronGeometry: DodecahedronGeometry,
  31440. DoubleSide: DoubleSide,
  31441. DstAlphaFactor: DstAlphaFactor,
  31442. DstColorFactor: DstColorFactor,
  31443. DynamicBufferAttribute: DynamicBufferAttribute,
  31444. DynamicCopyUsage: DynamicCopyUsage,
  31445. DynamicDrawUsage: DynamicDrawUsage,
  31446. DynamicReadUsage: DynamicReadUsage,
  31447. EdgesGeometry: EdgesGeometry,
  31448. EdgesHelper: EdgesHelper,
  31449. EllipseCurve: EllipseCurve,
  31450. EqualDepth: EqualDepth,
  31451. EqualStencilFunc: EqualStencilFunc,
  31452. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  31453. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  31454. Euler: Euler,
  31455. EventDispatcher: EventDispatcher,
  31456. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  31457. ExtrudeGeometry: ExtrudeGeometry,
  31458. Face3: Face3,
  31459. Face4: Face4,
  31460. FaceColors: FaceColors,
  31461. FileLoader: FileLoader,
  31462. FlatShading: FlatShading,
  31463. Float16BufferAttribute: Float16BufferAttribute,
  31464. Float32Attribute: Float32Attribute,
  31465. Float32BufferAttribute: Float32BufferAttribute,
  31466. Float64Attribute: Float64Attribute,
  31467. Float64BufferAttribute: Float64BufferAttribute,
  31468. FloatType: FloatType,
  31469. Fog: Fog,
  31470. FogExp2: FogExp2,
  31471. Font: Font,
  31472. FontLoader: FontLoader,
  31473. FrontSide: FrontSide,
  31474. Frustum: Frustum,
  31475. GLBufferAttribute: GLBufferAttribute,
  31476. GLSL1: GLSL1,
  31477. GLSL3: GLSL3,
  31478. GammaEncoding: GammaEncoding,
  31479. Geometry: Geometry,
  31480. GeometryUtils: GeometryUtils,
  31481. GreaterDepth: GreaterDepth,
  31482. GreaterEqualDepth: GreaterEqualDepth,
  31483. GreaterEqualStencilFunc: GreaterEqualStencilFunc,
  31484. GreaterStencilFunc: GreaterStencilFunc,
  31485. GridHelper: GridHelper,
  31486. Group: Group,
  31487. HalfFloatType: HalfFloatType,
  31488. HemisphereLight: HemisphereLight,
  31489. HemisphereLightHelper: HemisphereLightHelper,
  31490. HemisphereLightProbe: HemisphereLightProbe,
  31491. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  31492. IcosahedronGeometry: IcosahedronGeometry,
  31493. ImageBitmapLoader: ImageBitmapLoader,
  31494. ImageLoader: ImageLoader,
  31495. ImageUtils: ImageUtils,
  31496. ImmediateRenderObject: ImmediateRenderObject,
  31497. IncrementStencilOp: IncrementStencilOp,
  31498. IncrementWrapStencilOp: IncrementWrapStencilOp,
  31499. InstancedBufferAttribute: InstancedBufferAttribute,
  31500. InstancedBufferGeometry: InstancedBufferGeometry,
  31501. InstancedInterleavedBuffer: InstancedInterleavedBuffer,
  31502. InstancedMesh: InstancedMesh,
  31503. Int16Attribute: Int16Attribute,
  31504. Int16BufferAttribute: Int16BufferAttribute,
  31505. Int32Attribute: Int32Attribute,
  31506. Int32BufferAttribute: Int32BufferAttribute,
  31507. Int8Attribute: Int8Attribute,
  31508. Int8BufferAttribute: Int8BufferAttribute,
  31509. IntType: IntType,
  31510. InterleavedBuffer: InterleavedBuffer,
  31511. InterleavedBufferAttribute: InterleavedBufferAttribute,
  31512. Interpolant: Interpolant,
  31513. InterpolateDiscrete: InterpolateDiscrete,
  31514. InterpolateLinear: InterpolateLinear,
  31515. InterpolateSmooth: InterpolateSmooth,
  31516. InvertStencilOp: InvertStencilOp,
  31517. JSONLoader: JSONLoader,
  31518. KeepStencilOp: KeepStencilOp,
  31519. KeyframeTrack: KeyframeTrack,
  31520. LOD: LOD,
  31521. LatheBufferGeometry: LatheBufferGeometry,
  31522. LatheGeometry: LatheGeometry,
  31523. Layers: Layers,
  31524. LensFlare: LensFlare,
  31525. LessDepth: LessDepth,
  31526. LessEqualDepth: LessEqualDepth,
  31527. LessEqualStencilFunc: LessEqualStencilFunc,
  31528. LessStencilFunc: LessStencilFunc,
  31529. Light: Light,
  31530. LightProbe: LightProbe,
  31531. Line: Line,
  31532. Line3: Line3,
  31533. LineBasicMaterial: LineBasicMaterial,
  31534. LineCurve: LineCurve,
  31535. LineCurve3: LineCurve3,
  31536. LineDashedMaterial: LineDashedMaterial,
  31537. LineLoop: LineLoop,
  31538. LinePieces: LinePieces,
  31539. LineSegments: LineSegments,
  31540. LineStrip: LineStrip,
  31541. LinearEncoding: LinearEncoding,
  31542. LinearFilter: LinearFilter,
  31543. LinearInterpolant: LinearInterpolant,
  31544. LinearMipMapLinearFilter: LinearMipMapLinearFilter,
  31545. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  31546. LinearMipmapLinearFilter: LinearMipmapLinearFilter,
  31547. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  31548. LinearToneMapping: LinearToneMapping,
  31549. Loader: Loader,
  31550. LoaderUtils: LoaderUtils,
  31551. LoadingManager: LoadingManager,
  31552. LogLuvEncoding: LogLuvEncoding,
  31553. LoopOnce: LoopOnce,
  31554. LoopPingPong: LoopPingPong,
  31555. LoopRepeat: LoopRepeat,
  31556. LuminanceAlphaFormat: LuminanceAlphaFormat,
  31557. LuminanceFormat: LuminanceFormat,
  31558. MOUSE: MOUSE,
  31559. Material: Material,
  31560. MaterialLoader: MaterialLoader,
  31561. Math: MathUtils,
  31562. MathUtils: MathUtils,
  31563. Matrix3: Matrix3,
  31564. Matrix4: Matrix4,
  31565. MaxEquation: MaxEquation,
  31566. Mesh: Mesh,
  31567. MeshBasicMaterial: MeshBasicMaterial,
  31568. MeshDepthMaterial: MeshDepthMaterial,
  31569. MeshDistanceMaterial: MeshDistanceMaterial,
  31570. MeshFaceMaterial: MeshFaceMaterial,
  31571. MeshLambertMaterial: MeshLambertMaterial,
  31572. MeshMatcapMaterial: MeshMatcapMaterial,
  31573. MeshNormalMaterial: MeshNormalMaterial,
  31574. MeshPhongMaterial: MeshPhongMaterial,
  31575. MeshPhysicalMaterial: MeshPhysicalMaterial,
  31576. MeshStandardMaterial: MeshStandardMaterial,
  31577. MeshToonMaterial: MeshToonMaterial,
  31578. MinEquation: MinEquation,
  31579. MirroredRepeatWrapping: MirroredRepeatWrapping,
  31580. MixOperation: MixOperation,
  31581. MultiMaterial: MultiMaterial,
  31582. MultiplyBlending: MultiplyBlending,
  31583. MultiplyOperation: MultiplyOperation,
  31584. NearestFilter: NearestFilter,
  31585. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  31586. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  31587. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  31588. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  31589. NeverDepth: NeverDepth,
  31590. NeverStencilFunc: NeverStencilFunc,
  31591. NoBlending: NoBlending,
  31592. NoColors: NoColors,
  31593. NoToneMapping: NoToneMapping,
  31594. NormalAnimationBlendMode: NormalAnimationBlendMode,
  31595. NormalBlending: NormalBlending,
  31596. NotEqualDepth: NotEqualDepth,
  31597. NotEqualStencilFunc: NotEqualStencilFunc,
  31598. NumberKeyframeTrack: NumberKeyframeTrack,
  31599. Object3D: Object3D,
  31600. ObjectLoader: ObjectLoader,
  31601. ObjectSpaceNormalMap: ObjectSpaceNormalMap,
  31602. OctahedronBufferGeometry: OctahedronBufferGeometry,
  31603. OctahedronGeometry: OctahedronGeometry,
  31604. OneFactor: OneFactor,
  31605. OneMinusDstAlphaFactor: OneMinusDstAlphaFactor,
  31606. OneMinusDstColorFactor: OneMinusDstColorFactor,
  31607. OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor,
  31608. OneMinusSrcColorFactor: OneMinusSrcColorFactor,
  31609. OrthographicCamera: OrthographicCamera,
  31610. PCFShadowMap: PCFShadowMap,
  31611. PCFSoftShadowMap: PCFSoftShadowMap,
  31612. PMREMGenerator: PMREMGenerator,
  31613. ParametricBufferGeometry: ParametricBufferGeometry,
  31614. ParametricGeometry: ParametricGeometry,
  31615. Particle: Particle,
  31616. ParticleBasicMaterial: ParticleBasicMaterial,
  31617. ParticleSystem: ParticleSystem,
  31618. ParticleSystemMaterial: ParticleSystemMaterial,
  31619. Path: Path,
  31620. PerspectiveCamera: PerspectiveCamera,
  31621. Plane: Plane,
  31622. PlaneBufferGeometry: PlaneBufferGeometry,
  31623. PlaneGeometry: PlaneGeometry,
  31624. PlaneHelper: PlaneHelper,
  31625. PointCloud: PointCloud,
  31626. PointCloudMaterial: PointCloudMaterial,
  31627. PointLight: PointLight,
  31628. PointLightHelper: PointLightHelper,
  31629. Points: Points,
  31630. PointsMaterial: PointsMaterial,
  31631. PolarGridHelper: PolarGridHelper,
  31632. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  31633. PolyhedronGeometry: PolyhedronGeometry,
  31634. PositionalAudio: PositionalAudio,
  31635. PropertyBinding: PropertyBinding,
  31636. PropertyMixer: PropertyMixer,
  31637. QuadraticBezierCurve: QuadraticBezierCurve,
  31638. QuadraticBezierCurve3: QuadraticBezierCurve3,
  31639. Quaternion: Quaternion,
  31640. QuaternionKeyframeTrack: QuaternionKeyframeTrack,
  31641. QuaternionLinearInterpolant: QuaternionLinearInterpolant,
  31642. REVISION: REVISION,
  31643. RGBADepthPacking: RGBADepthPacking,
  31644. RGBAFormat: RGBAFormat,
  31645. RGBAIntegerFormat: RGBAIntegerFormat,
  31646. RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format,
  31647. RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format,
  31648. RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format,
  31649. RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format,
  31650. RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format,
  31651. RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format,
  31652. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  31653. RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format,
  31654. RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format,
  31655. RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format,
  31656. RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format,
  31657. RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format,
  31658. RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format,
  31659. RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format,
  31660. RGBA_BPTC_Format: RGBA_BPTC_Format,
  31661. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  31662. RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format,
  31663. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  31664. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format$1,
  31665. RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format,
  31666. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  31667. RGBDEncoding: RGBDEncoding,
  31668. RGBEEncoding: RGBEEncoding,
  31669. RGBEFormat: RGBEFormat,
  31670. RGBFormat: RGBFormat,
  31671. RGBIntegerFormat: RGBIntegerFormat,
  31672. RGBM16Encoding: RGBM16Encoding,
  31673. RGBM7Encoding: RGBM7Encoding,
  31674. RGB_ETC1_Format: RGB_ETC1_Format,
  31675. RGB_ETC2_Format: RGB_ETC2_Format,
  31676. RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format,
  31677. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  31678. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  31679. RGFormat: RGFormat,
  31680. RGIntegerFormat: RGIntegerFormat,
  31681. RawShaderMaterial: RawShaderMaterial,
  31682. Ray: Ray,
  31683. Raycaster: Raycaster,
  31684. RectAreaLight: RectAreaLight,
  31685. RedFormat: RedFormat,
  31686. RedIntegerFormat: RedIntegerFormat,
  31687. ReinhardToneMapping: ReinhardToneMapping,
  31688. RepeatWrapping: RepeatWrapping,
  31689. ReplaceStencilOp: ReplaceStencilOp,
  31690. ReverseSubtractEquation: ReverseSubtractEquation,
  31691. RingBufferGeometry: RingBufferGeometry,
  31692. RingGeometry: RingGeometry,
  31693. SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format,
  31694. SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format,
  31695. SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format,
  31696. SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format,
  31697. SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format,
  31698. SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format,
  31699. SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format,
  31700. SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format,
  31701. SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format,
  31702. SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format,
  31703. SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format,
  31704. SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format,
  31705. SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format,
  31706. SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format,
  31707. Scene: Scene,
  31708. SceneUtils: SceneUtils,
  31709. ShaderChunk: ShaderChunk,
  31710. ShaderLib: ShaderLib,
  31711. ShaderMaterial: ShaderMaterial,
  31712. ShadowMaterial: ShadowMaterial,
  31713. Shape: Shape,
  31714. ShapeBufferGeometry: ShapeBufferGeometry,
  31715. ShapeGeometry: ShapeGeometry,
  31716. ShapePath: ShapePath,
  31717. ShapeUtils: ShapeUtils,
  31718. ShortType: ShortType,
  31719. Skeleton: Skeleton,
  31720. SkeletonHelper: SkeletonHelper,
  31721. SkinnedMesh: SkinnedMesh,
  31722. SmoothShading: SmoothShading,
  31723. Sphere: Sphere,
  31724. SphereBufferGeometry: SphereBufferGeometry,
  31725. SphereGeometry: SphereGeometry,
  31726. Spherical: Spherical,
  31727. SphericalHarmonics3: SphericalHarmonics3,
  31728. Spline: Spline,
  31729. SplineCurve: SplineCurve,
  31730. SplineCurve3: SplineCurve3,
  31731. SpotLight: SpotLight,
  31732. SpotLightHelper: SpotLightHelper,
  31733. Sprite: Sprite,
  31734. SpriteMaterial: SpriteMaterial,
  31735. SrcAlphaFactor: SrcAlphaFactor,
  31736. SrcAlphaSaturateFactor: SrcAlphaSaturateFactor,
  31737. SrcColorFactor: SrcColorFactor,
  31738. StaticCopyUsage: StaticCopyUsage,
  31739. StaticDrawUsage: StaticDrawUsage,
  31740. StaticReadUsage: StaticReadUsage,
  31741. StereoCamera: StereoCamera,
  31742. StreamCopyUsage: StreamCopyUsage,
  31743. StreamDrawUsage: StreamDrawUsage,
  31744. StreamReadUsage: StreamReadUsage,
  31745. StringKeyframeTrack: StringKeyframeTrack,
  31746. SubtractEquation: SubtractEquation,
  31747. SubtractiveBlending: SubtractiveBlending,
  31748. TOUCH: TOUCH,
  31749. TangentSpaceNormalMap: TangentSpaceNormalMap,
  31750. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  31751. TetrahedronGeometry: TetrahedronGeometry,
  31752. TextBufferGeometry: TextBufferGeometry,
  31753. TextGeometry: TextGeometry,
  31754. Texture: Texture,
  31755. TextureLoader: TextureLoader,
  31756. TorusBufferGeometry: TorusBufferGeometry,
  31757. TorusGeometry: TorusGeometry,
  31758. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  31759. TorusKnotGeometry: TorusKnotGeometry,
  31760. Triangle: Triangle,
  31761. TriangleFanDrawMode: TriangleFanDrawMode,
  31762. TriangleStripDrawMode: TriangleStripDrawMode,
  31763. TrianglesDrawMode: TrianglesDrawMode,
  31764. TubeBufferGeometry: TubeBufferGeometry,
  31765. TubeGeometry: TubeGeometry,
  31766. UVMapping: UVMapping,
  31767. Uint16Attribute: Uint16Attribute,
  31768. Uint16BufferAttribute: Uint16BufferAttribute,
  31769. Uint32Attribute: Uint32Attribute,
  31770. Uint32BufferAttribute: Uint32BufferAttribute,
  31771. Uint8Attribute: Uint8Attribute,
  31772. Uint8BufferAttribute: Uint8BufferAttribute,
  31773. Uint8ClampedAttribute: Uint8ClampedAttribute,
  31774. Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute,
  31775. Uniform: Uniform,
  31776. UniformsLib: UniformsLib,
  31777. UniformsUtils: UniformsUtils,
  31778. UnsignedByteType: UnsignedByteType,
  31779. UnsignedInt248Type: UnsignedInt248Type$1,
  31780. UnsignedIntType: UnsignedIntType,
  31781. UnsignedShort4444Type: UnsignedShort4444Type,
  31782. UnsignedShort5551Type: UnsignedShort5551Type,
  31783. UnsignedShort565Type: UnsignedShort565Type,
  31784. UnsignedShortType: UnsignedShortType,
  31785. VSMShadowMap: VSMShadowMap,
  31786. Vector2: Vector2$1,
  31787. Vector3: Vector3,
  31788. Vector4: Vector4,
  31789. VectorKeyframeTrack: VectorKeyframeTrack,
  31790. Vertex: Vertex,
  31791. VertexColors: VertexColors,
  31792. VideoTexture: VideoTexture,
  31793. WebGL1Renderer: WebGL1Renderer,
  31794. WebGLCubeRenderTarget: WebGLCubeRenderTarget,
  31795. WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget,
  31796. WebGLRenderTarget: WebGLRenderTarget,
  31797. WebGLRenderTargetCube: WebGLRenderTargetCube,
  31798. WebGLRenderer: WebGLRenderer,
  31799. WebGLUtils: WebGLUtils,
  31800. WireframeGeometry: WireframeGeometry,
  31801. WireframeHelper: WireframeHelper,
  31802. WrapAroundEnding: WrapAroundEnding,
  31803. XHRLoader: XHRLoader,
  31804. ZeroCurvatureEnding: ZeroCurvatureEnding,
  31805. ZeroFactor: ZeroFactor,
  31806. ZeroSlopeEnding: ZeroSlopeEnding,
  31807. ZeroStencilOp: ZeroStencilOp,
  31808. sRGBEncoding: sRGBEncoding
  31809. });
  31810. var points = [];
  31811. var lines = [];
  31812. var rings = [];
  31813. var precision = 0.1; //容错精度 //正常是0.01 但是在编辑时容易出现交错的线看不出来,导致需要getSliceLines 然后多出新增点
  31814. var getPoint = function(o, type){
  31815. var point;
  31816. if(typeof o == "string" || typeof o == "number")point = points.find(p=> p.ids.includes(o));
  31817. else {
  31818. point = points.find(p=> math.closeTo(p.x , o.x, precision) && math.closeTo(p.y , o.y, precision) );
  31819. if(!point) point = new Point(o.x, o.y,{record:true, id:o.id}, type);
  31820. else {
  31821. //console.log('addPoint', point, o)
  31822. point.addPoint(o.id);
  31823. }
  31824. }
  31825. if(!point){
  31826. console.log("no point!");
  31827. }
  31828. return point
  31829. };
  31830. var getLine = function(id){
  31831. return lines.find(line=> line.ids.includes(id));
  31832. };
  31833. var getAngleInfo = function(points){
  31834. var info = {};
  31835. info.angle = points[1].clone().sub(points[0]).angle();
  31836. if(math.closeTo(info.angle, Math.PI*2)){ //如360-0.01
  31837. info.angle -= Math.PI*2; //有可能得到负数-0.001
  31838. }else if(info.angle > Math.PI || math.closeTo(info.angle, Math.PI)){//如180+-0.01
  31839. info.angle -= Math.PI;
  31840. info.reverse = true;
  31841. }
  31842. return info //结果大约是 0 - 3.14
  31843. };
  31844. class Point extends Vector2$1{
  31845. constructor(x, y, o={}){
  31846. super(x, y);
  31847. if(o.record){
  31848. this.id = o.id;
  31849. if(this.id == void 0) this.id = "add_"+points.length;
  31850. this.ids = [this.id] ;//存储拥有该坐标的点原始数据的id
  31851. points.push(this);
  31852. }
  31853. this.type = o.type || "";
  31854. this.lines = [];
  31855. }
  31856. addPoint(id){
  31857. this.ids.push(id);
  31858. }
  31859. searchLineByFactor(dir, type, comeLine){
  31860. var lines = this.lines.filter(line=>line.searchTime<2);
  31861. if(lines.length==0)return;
  31862. else if(lines.length==1)return lines[0];
  31863. else lines = lines.filter(line=>line!=comeLine);
  31864. if(lines.length==1)return lines[0];
  31865. var result;
  31866. lines.forEach(line=>{
  31867. var vec = line.getVector();
  31868. if(line.points[1] == this) vec.negate();
  31869. var factor = math.getVec2Angle(dir, vec);
  31870. if(new Vector3(dir.x, dir.y, 0).cross(new Vector3(vec.x, vec.y, 0)).z<0) factor*= -1; /////
  31871. if(!result){
  31872. result = {line, factor};
  31873. }
  31874. else {
  31875. if(type == "min" && factor<result.factor || type == "max" && factor>result.factor) result = {line, factor};
  31876. }
  31877. });
  31878. return result.line;
  31879. }
  31880. }
  31881. var lineLen=0;
  31882. class Line$1{
  31883. constructor(o){
  31884. if(o.points[0] == o.points[1])return;
  31885. this.points = o.points;
  31886. this.type = o.type || 'line';
  31887. if(this.type == 'line'){
  31888. var oldLine = lines.find(line=>line.points.includes(o.points[0]) && line.points.includes(o.points[1]));
  31889. if(oldLine){
  31890. o.id != void 0 && oldLine.ids.push(o.id);
  31891. return oldLine;
  31892. }
  31893. this.id = o.id == void 0 ? ("line"+lineLen ++) : o.id;
  31894. this.ids = [this.id];
  31895. o.dontWriteToPoint || this.points.forEach((point)=>{point.lines.push(this);});
  31896. o.isChild || lines.push(this);
  31897. this.searchTime = 0; // 最多两次
  31898. }
  31899. this.children = [];//分割
  31900. this.parents = [];//分割
  31901. this.match = [];
  31902. }
  31903. getAngleInfo(){
  31904. var angleInfo = getAngleInfo(this.points);
  31905. this.angle = angleInfo.angle;
  31906. this.reverse = angleInfo.reverse;
  31907. }
  31908. getIntersectWithLine(line, precision){
  31909. var joint = line.points.find(point=>this.points.includes(point));
  31910. if(joint)return {point:joint, type:"joint"};
  31911. var intersect = math.isLineIntersect( line.points , this.points , false, precision );
  31912. if(intersect) return {point: intersect, type:"intersect"};
  31913. }
  31914. writeToPoint(){
  31915. this.points.forEach((point)=>{point.lines.includes(this) || point.lines.push(this);});
  31916. }
  31917. checkIfParent(line){
  31918. if(this == line){
  31919. return true;//原因就是slice的点和端点很近 误差导致
  31920. }
  31921. else return this.parents.find(e=>e.checkIfParent(line))
  31922. }
  31923. splitByPoint(point){
  31924. var line1 = new Line$1({points:[point, this.points[0]], dontWriteToPoint:true, hasntsure:true});
  31925. var line2 = new Line$1({points:[point, this.points[1]], dontWriteToPoint:true, hasntsure:true});
  31926. if(!line1.points || !line2.points){//有至少一个是点相同的,没写到group.lines里
  31927. console.warn('splitByPoint 线有点相同');
  31928. return;
  31929. }
  31930. if(this.checkIfParent(line1)||this.checkIfParent(line2) || line1.checkIfParent(this) || line2.checkIfParent(this)){
  31931. console.warn("splitByPoint 发现parent和children一样");//,请检查getSliceWalls,尤其 if(math.closeTo(line1.angle,line2.angle)){ 处
  31932. return;
  31933. }
  31934. var deal = (line)=>{
  31935. this.children.push(line);
  31936. line.parents.push(this);
  31937. if(!lines.includes(line))lines.push(line);
  31938. line.writeToPoint();
  31939. };
  31940. deal(line1);
  31941. deal(line2);
  31942. var index = this.points[0].lines.indexOf(this);
  31943. index > -1 && this.points[0].lines.splice(index,1);
  31944. var index = this.points[1].lines.indexOf(this);
  31945. index > -1 && this.points[1].lines.splice(index,1);
  31946. return [line1,line2]
  31947. }
  31948. splitByPoints(points){
  31949. points = points.map(point=>{return {dis:point.distanceTo(this.points[0]), point:point}});
  31950. points.sort((point1, point2)=>{return point1.dis - point2.dis});
  31951. var children = [];
  31952. points.forEach((point, index)=>{
  31953. var line1 = new Line$1({points:[point.point, index==0?this.points[0]:points[index-1].point ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31954. children.push(line1);
  31955. });
  31956. var line2 = new Line$1({points:[points[points.length-1].point, this.points[1] ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31957. children.push(line2);
  31958. var a = children.find(line=> !line.points || this.checkIfParent(line) || line.checkIfParent(this));
  31959. if(a){
  31960. console.error("splitByPoints return");
  31961. return;
  31962. }
  31963. children.forEach(line=>{
  31964. this.children.push(line);
  31965. line.parents.push(this);
  31966. if(!lines.includes(line))lines.push(line);
  31967. line.writeToPoint();
  31968. line.writeToPoint();
  31969. });
  31970. var index = this.points[0].lines.indexOf(this);
  31971. index > -1 && this.points[0].lines.splice(index,1);
  31972. var index = this.points[1].lines.indexOf(this);
  31973. index > -1 && this.points[1].lines.splice(index,1);
  31974. }
  31975. getAllSlices(){//如果有被分割的片段 就返回片段,否则返回自身
  31976. var children = [];
  31977. var traverse = function(elem){
  31978. if(elem.children.length == 0) children.push(elem);
  31979. else elem.children.forEach(traverse);
  31980. };
  31981. traverse(this);
  31982. return children
  31983. }
  31984. getVector(){
  31985. return this.points[1].clone().sub(this.points[0]);
  31986. }
  31987. getLength(){
  31988. return this.points[0].distanceTo(this.points[1])
  31989. }
  31990. getCenter(){
  31991. return this.points[1].clone().add(this.points[0]).multiplyScalar(.5);
  31992. }
  31993. }
  31994. var getMixedSet = function(arr1, arr2){//交集
  31995. return arr1.filter(item=>arr2.includes(item));
  31996. };
  31997. var getUnionSet = function(arr1, arr2){//并集
  31998. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  31999. };
  32000. var getDifferenceSet = function(arr1, arr2){//差集
  32001. var arr11 = arr1.filter(item=>!arr2.includes(item));
  32002. var arr22 = arr2.filter(item=>!arr1.includes(item));
  32003. return arr11.concat(arr22)
  32004. };
  32005. var getDifferenceSetMuti = function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  32006. var set = [];
  32007. arr.forEach(arr1=>{
  32008. arr1.forEach(item=>{
  32009. var index = set.indexOf(item);
  32010. if(index>-1){
  32011. set.splice(index, 1);
  32012. }else {
  32013. set.push(item);
  32014. }
  32015. });
  32016. });
  32017. return set;
  32018. };
  32019. function DoorAtWhichLine(points, lines){
  32020. var mid = points[0].clone().add(points[1]).multiplyScalar(0.5);
  32021. lines = lines.filter(line=>math.ifPointAtLineBound(mid, line.points, precision));
  32022. if(lines.length == 0)return
  32023. var result = {line:null, dis:Infinity};
  32024. lines.forEach(line=>{
  32025. var foot = math.getFootPoint(mid, line.points[0], line.points[1] );
  32026. var dis = foot.distanceTo(mid);
  32027. if(dis<result.dis){
  32028. result.line = line; result.dis = dis;
  32029. }
  32030. });
  32031. return result
  32032. }
  32033. var ringLen = 0;
  32034. class Ring{
  32035. constructor(o){
  32036. this.id = ringLen ++;
  32037. this.type = o.type || 'normal';
  32038. this.points = o.points;
  32039. this.lines = o.lines;
  32040. rings.push(this);
  32041. this.child = [];//包含的环
  32042. this.parent = [];//被包含的环
  32043. this.smallNeibours = [];//相邻最小环(存在和它有一个以上的相同边的最小环)
  32044. var area = math.getArea(this.points);
  32045. this.area = Math.abs(area);
  32046. this.isClockwise = area<0;//是否逆时针。一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  32047. }
  32048. }
  32049. var findLine = function(p1,p2){
  32050. return lines.find(line=>line.points.includes(p1) && line.points.includes(p2) )
  32051. };
  32052. var ifSamePart = function(checkPart , part){//checkPart中所包含的part片段是否和基准part的顺序一样(逆序也可以, 中间有其他数也可以,起始不同也行。比如 01234和204一样的)
  32053. var axis, startIndex, newCheckPart=[];
  32054. for(var j=0,len1 = checkPart.length; j<len1; j++){//将checkPart中比part多的数除去,使两个数组中包含的数完全相同。
  32055. if(part.indexOf(checkPart[j])>-1)newCheckPart.push(checkPart[j]);
  32056. }
  32057. for(var i=0,len = part.length; i<len; i++){
  32058. var index = newCheckPart.indexOf(part[i]);
  32059. if(index == -1)return false;
  32060. if(i == 0) startIndex = index;//标记第一个查找点对应的index
  32061. else if(i == 1){//标记查找顺序是正还是逆
  32062. axis = index - startIndex;
  32063. if(axis == len - 1) axis = -1;//刚好是首和尾
  32064. else if(axis == 1- len) axis = 1;
  32065. if(axis != -1 && axis != 1){
  32066. return false
  32067. }
  32068. }else {//判断是否是按顺序的
  32069. if(index != ((startIndex+axis * i + len) % len) ) return false;
  32070. }
  32071. }
  32072. return {sameAxis:axis>0}; //如果一样的话返回正逆是否相同
  32073. };
  32074. //或者判断是否有相同边(但是相同点是可以组成不同环)
  32075. var ifSameRing = function(ring1, ring2){//判断两个环是否相等。 除了可以逆向外顺序要对
  32076. if(ring1 instanceof Ring)ring1 = ring1.points;
  32077. if(ring2 instanceof Ring)ring2 = ring2.points;
  32078. if(ring1.length != ring2.length)return false;
  32079. if(ring1.lines && ring2.lines){
  32080. if(getDifferenceSet(ring1.lines , ring2.lines).length == 0)return true;//差集个数为0
  32081. }else {
  32082. if(ifSamePart(ring1, ring2))return true
  32083. }
  32084. };
  32085. var atWhichChildLine = function(point, line, precision){
  32086. if(line.children.length == 0){//这里可能要放低精度 保证能找到
  32087. if(math.ifPointAtLineBound(point, line.points, precision)) return line;
  32088. }else {
  32089. for(var i=0;i<line.children.length;i++){
  32090. var at = atWhichChildLine(point, line.children[i], precision);
  32091. if(at)return at
  32092. }
  32093. }
  32094. };
  32095. function getSliceLines(){
  32096. var len = lines.length;
  32097. var deal = function(line1,line2){
  32098. if(line1 == line2)return;
  32099. if(line1.angle == void 0) line1.getAngleInfo();
  32100. if(line2.angle == void 0) line2.getAngleInfo();
  32101. var intersect = line1.getIntersectWithLine(line2, precision);
  32102. if(intersect){
  32103. var point; //得到交点
  32104. if(intersect.type == "intersect"){
  32105. point = getPoint(intersect.point, "whenGetSliceLines");
  32106. var line1_ = atWhichChildLine(point, line1);
  32107. var line2_ = atWhichChildLine(point, line2);
  32108. //重合的情况还没考虑(平行)
  32109. if(!line1_) line1_ = atWhichChildLine(point, line1, precision);//降低精度
  32110. if(!line1_) line1_ = atWhichChildLine(point, line1, precision*2);//降低精度
  32111. if(!line2_) line2_ = atWhichChildLine(point, line2, precision);
  32112. if(!line2_) line2_ = atWhichChildLine(point, line2, precision*2);//降低精度
  32113. //拆分线条:
  32114. //如果还报错,找不到ChildLine,就直接返回吧 或者搞个循环 逐渐降低精度
  32115. if(!line1_ || !line2_){
  32116. console.warn("atWhichChildLine仍旧找不到 :" + line1.id + ',' + line2.id + ", pointId: "+point.id);
  32117. line1_ || console.warn("找不到line1");
  32118. line2_ || console.warn("找不到line2");
  32119. return;
  32120. }
  32121. if(line1_.points.find(p=>p == point) && line2_.points.find(p=>p == point)){//这个点是line1_、 line2_端点,不做处理
  32122. //console.log("joint型 "+point.id)
  32123. }else if(line1_.points.find(p=>p == point)){//T型交叉
  32124. line2_.splitByPoint(point);//加入到母线中,之后还先用母线判断交点
  32125. //console.log("T型交叉1 "+point.id)
  32126. }else if(line2_.points.find(p=>p == point)){//T型交叉
  32127. line1_.splitByPoint(point);
  32128. //console.log("T型交叉2 "+point.id)
  32129. }else {//十字交叉
  32130. line1_.splitByPoint(point);
  32131. line2_.splitByPoint(point);
  32132. }
  32133. }else {
  32134. point = intersect.point;//交点是端点
  32135. if(math.closeTo(line1.angle,line2.angle)){ //重合一部分
  32136. var children1 = line1.getAllSlices();
  32137. var children2 = line2.getAllSlices();
  32138. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  32139. children1.forEach(child1=>{
  32140. children2.forEach(child2=>{
  32141. deal(child1, child2);
  32142. });
  32143. });
  32144. return;
  32145. }
  32146. var anotherPoint1 = line1.points.find(point_=>point_!=point);
  32147. var anotherPoint2 = line2.points.find(point_=>point_!=point);
  32148. if(math.ifPointAtLineBound(anotherPoint1, line2.points)){
  32149. line2.splitByPoint(anotherPoint1);
  32150. }else if(math.ifPointAtLineBound(anotherPoint2, line1.points)){
  32151. line1.splitByPoint(anotherPoint2);
  32152. }
  32153. }
  32154. }
  32155. }else if(math.closeTo(line1.angle,line2.angle)){
  32156. var vec1 = line1.getVector();
  32157. var vec = line1.points[0].clone().sub(line2.points[0]);
  32158. var cos = math.getVec2Cos(vec1, vec);
  32159. if(math.closeTo(cos, -1, 1e-4) || math.closeTo(cos, 1, 1e-4)){ //共线
  32160. var children1 = line1.getAllSlices();
  32161. var children2 = line2.getAllSlices();
  32162. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  32163. children1.forEach(child1=>{
  32164. children2.forEach(child2=>{
  32165. deal(child1, child2);
  32166. });
  32167. });
  32168. return;
  32169. }
  32170. //判断是否重叠
  32171. var A = line1.points[0];
  32172. var C = line1.reverse == line2.reverse ? line2.points[0] : line2.points[1];
  32173. var B = line1.points[1];
  32174. var D = line1.reverse == line2.reverse ? line2.points[1] : line2.points[0];
  32175. var BC = C.clone().sub(B);
  32176. var AD = D.clone().sub(A);
  32177. if(BC.length()<AD.length()){
  32178. var BA = A.clone().sub(B);
  32179. if(math.getVec2Angle(BC, BA) >= 1.57 )return;//没有重叠部分
  32180. }else {
  32181. var AB = B.clone().sub(A);
  32182. if(math.getVec2Angle(AD, AB) >= 1.57 )return;
  32183. }
  32184. var f = function(line1,line2){
  32185. var one = math.ifPointAtLineBound(line1.points[0], line2.points);
  32186. var two = math.ifPointAtLineBound(line1.points[1], line2.points);
  32187. if(one && two){//line1在line2上
  32188. line2.splitByPoints( line1.points );
  32189. return true
  32190. }else if(one || two){//错开
  32191. var point1 = one ? line1.points[0] : line1.points[1];
  32192. var anotherPoint1 = one ? line1.points[1] : line1.points[0];
  32193. var dis1 = line2.points[0].distanceTo(anotherPoint1);
  32194. var dis2 = line2.points[1].distanceTo(anotherPoint1);
  32195. var point2 = dis1 < dis2 ? line2.points[0] : line2.points[1];
  32196. line1.splitByPoint(point2);
  32197. line2.splitByPoint(point1);
  32198. return true
  32199. }
  32200. };
  32201. f(line1, line2) || f(line2, line1);
  32202. }
  32203. }
  32204. };
  32205. for(let i=0;i<len;i++){
  32206. let line1 = lines[i];
  32207. for(let j=i+1;j<len;j++){
  32208. let line2 = lines[j];
  32209. deal(line1,line2);
  32210. }
  32211. }
  32212. //console.log("原有线条个数:"+len)
  32213. //lines = lines.filter((line)=>{return line.children.length == 0})
  32214. //console.log("现有线条个数:"+lines.length)
  32215. }
  32216. var bound = new Box2();
  32217. var build = function(o){
  32218. //融合了相近点
  32219. //根据bound 处理precision
  32220. o.points.forEach(p=>{
  32221. bound.expandByPoint(new Vector2$1(p.x,p.y));
  32222. });
  32223. if(o.precision != void 0){
  32224. precision = o.precision;
  32225. }else {
  32226. var boundSize = bound.getSize(new Vector2$1);
  32227. precision = MathUtils.clamp(Math.max(boundSize.x, boundSize.y) / 70, 0.2, 2);
  32228. }
  32229. o.points.forEach(point=>getPoint(point));//{x:..,y:..}
  32230. o.lines.forEach(line=>{ //{p1:id1. p2:id2}
  32231. new Line$1({points:[getPoint(line.p1), getPoint(line.p2)], id:line.id });
  32232. });
  32233. //注意:不能出现一条线的两个点坐标一致,否则寻路时方向出错。 所以手动融合下相近点。
  32234. };
  32235. var searchRings = function(o={}){
  32236. points = [];
  32237. lines = [];
  32238. rings = [];
  32239. lineLen = ringLen = 0;
  32240. o.points = o.points || [];
  32241. o.lines = o.lines || [];
  32242. build(o);
  32243. if(!o.dontSliceLines){
  32244. getSliceLines();
  32245. }
  32246. //查找最小回路:
  32247. //参考: 引入方向因子的最小回路、最大回路搜索算法.pdf
  32248. //方法: 逆时针寻找(标记)最外层大环 -->从走过的点开始逆时针寻找最小环(直到所有可走的路被走过两次)-->逆时针寻找最外层大环(直到所有可走的路被走过两次)-->..
  32249. //其中找大环时选择方向因子最小的路, 而小环则相反(但只有开始第一条路是一样的, 都是选择最左边的点的因子最小的路)。
  32250. //标记方法: 每条线需要被搜索两次才算完毕。搜索完毕的线退出搜索。(依据:搜索完全部最小回路后 , 在无向图中删除搜索过 2 次的边及孤立节点得到退化图 , 恰好构成最大回路。)
  32251. var searchTime = 0;
  32252. var addRingJudgeCount = 0;
  32253. var addRingJudge = function(ring, lines, connectedLines, type){// 处理拣出的片段
  32254. addRingJudgeCount++;
  32255. //console.log("addRingJudge points("+ type+"):"+ ring.map(point=>point.id) )
  32256. if(o.onlyGetOutRing && type == "small")return
  32257. if(type == "small" || o.onlyGetOutRing){//挑出回路:
  32258. var newRings = [];
  32259. while(ring.length){
  32260. var road = [];
  32261. var turnBack = false;
  32262. for(let i=0;i<ring.length;i++){
  32263. if(road.includes(ring[i])){//如果走到方才的点,可能形成回路。 无论是不是回路都要摘去这段。
  32264. var index = road.indexOf(ring[i]);
  32265. var pointArr = ring.slice(index, i);
  32266. var linesArr = lines.slice(index, i);
  32267. ring.splice(index,i-index);
  32268. lines.splice(index,i-index);
  32269. if(pointArr.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  32270. if( !rings.find(ring_=>ifSameRing(pointArr, ring_))) newRings.push( new Ring({points: pointArr, lines:linesArr}) );
  32271. }
  32272. turnBack = true;
  32273. break;
  32274. }else {
  32275. road.push(ring[i]);
  32276. turnBack = false;
  32277. }
  32278. }
  32279. if(!turnBack){//没有重复的点,那么就直接处理整条。
  32280. if(ring.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  32281. if( !rings.find(ring_=>ifSameRing(ring, ring_))) newRings.push( new Ring({points: ring, lines}) );
  32282. }
  32283. break;
  32284. }
  32285. }
  32286. if(type != 'small'){
  32287. newRings.forEach(e=>e.isOutRing = true);
  32288. }
  32289. //console.log(newRings)
  32290. }else {
  32291. return ring
  32292. }
  32293. };
  32294. var search = function(point2d, comeRoad, type, connectedLines){
  32295. searchTime++;
  32296. var goLine;
  32297. var direction;
  32298. if(type.includes("big")){
  32299. if(!comeRoad){
  32300. if(type.includes("Left")){//逆时针
  32301. direction = new Vector2$1(1,0);
  32302. }else {
  32303. direction = new Vector2$1(-1,0);
  32304. }
  32305. goLine = point2d.searchLineByFactor(direction,"min");
  32306. }else {
  32307. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  32308. direction = point2d.clone().sub(lastPoint);
  32309. goLine = point2d.searchLineByFactor(direction,"min", findLine(point2d, lastPoint));
  32310. }
  32311. }else {
  32312. if(!comeRoad){
  32313. //似乎找最小环时,第一条线也是找最小的因子,这样才能保证逆时针(除非只有顺时针一条路)
  32314. direction = new Vector2$1(1,0);
  32315. goLine = point2d.searchLineByFactor(direction,"min");
  32316. }else {
  32317. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  32318. direction = point2d.clone().sub(lastPoint);
  32319. goLine = point2d.searchLineByFactor(direction,"max", findLine(point2d, lastPoint));
  32320. }
  32321. }
  32322. if(!goLine)return
  32323. goLine.searchTime++;
  32324. connectedLines.includes(goLine) || connectedLines.push(goLine);
  32325. var nextPoint = goLine.points.find( point => point2d!=point );
  32326. //if( comeRoad && comeRoad.points[comeRoad.points.length - 1] == nextPoint ) return;//不能查找来时的方向(反方向)
  32327. //走不通就原路返回
  32328. var roadPoints = comeRoad ? comeRoad.points.concat([point2d]) : [point2d];//每个分叉都能构成一条新的road
  32329. var roadLines = comeRoad ? comeRoad.lines.concat([goLine]) : [goLine];
  32330. //走到第一个点就算停止,这时候可能得到一个环、或者一段走了两遍的线、或者一条线上带了些环。
  32331. if(nextPoint == roadPoints[0]) return addRingJudge(roadPoints, roadLines, connectedLines, type) //形成环
  32332. else {
  32333. /* var len = roadPoints.indexOf(nextPoint);
  32334. if( len > -1){ //走到走过的路的某一点 构成这段路的回路
  32335. var points = roadPoints.slice(len, roadPoints.length);
  32336. var lines = roadLines.slice(len, roadPoints.length);
  32337. addRingJudge(points, lines)
  32338. }else{ */
  32339. return search(nextPoint, {lines:roadLines, points:roadPoints}, type, connectedLines);//继续寻路
  32340. //}
  32341. }
  32342. };
  32343. while(1){//搜寻一次大环
  32344. var connectedLines = [];//被搜寻过的且searchTime<2的线。一旦全部搜完就说明该连通区域搜寻完毕,继续查下一个连通区域。
  32345. var startPoint = null;
  32346. points.forEach(point=>{//找出x最小的点
  32347. if(!point.lines.find(line=>line.searchTime<2))return;
  32348. if(!startPoint)startPoint = point;
  32349. else if(point.x < startPoint.x)startPoint = point;
  32350. });
  32351. if(!startPoint)break; //说明全部找完
  32352. var ring = search(startPoint, null, "bigLeft", connectedLines);//逆时针
  32353. //search(startPoint, null, "bigRight", connectedLines);//顺时针(为了防止最外层不是回路之前写了顺时针,但如果是回路就会走重复。后来发现只要逆时针即可,因为走完后剩下的可以再次找大环)
  32354. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  32355. while(connectedLines.length>0){//目标是顺着connectedLines把所有连通的小环都找到
  32356. let points_ = [];//connectedLines中所有的点
  32357. connectedLines.forEach(line=>line.points.forEach(point=>{if(!points_.includes(point))points_.push(point); }));
  32358. var startPoint = null;
  32359. points_.forEach(point=>{//找出x最小的点
  32360. if(!point.lines.find(line=>line.searchTime<2))return;
  32361. if(!startPoint)startPoint = point;
  32362. else if(point.x < startPoint.x)startPoint = point;
  32363. });
  32364. if(!startPoint)break;
  32365. search(startPoint, null, "small", connectedLines);
  32366. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  32367. }
  32368. }
  32369. /* if(o.onlyGetOutRing){
  32370. rings = rings.filter(e=>e.isOutRing)
  32371. } */
  32372. //console.log("searchTime "+searchTime + ", addRingJudgeCount " +addRingJudgeCount)
  32373. //找出所有的相邻关系,包括公共边
  32374. var len = rings.length;
  32375. for(let i=0; i<len; i++){
  32376. let ring1 = rings[i];
  32377. for(let j=i+1; j<len; j++){
  32378. let ring2 = rings[j];
  32379. var bothHasLines = getMixedSet(ring1.lines, ring2.lines);
  32380. if(bothHasLines.length){//ring1oíring2?àáú
  32381. ring1.smallNeibours.push(ring2);
  32382. ring2.smallNeibours.push(ring1);
  32383. }else {
  32384. }
  32385. }
  32386. }
  32387. rings.forEach(ring1=>{
  32388. for(let i=0; i<len; i++){
  32389. var ring2 = rings[i];
  32390. if(ring1 == ring2 || ring1.smallNeibours.includes(ring2))continue;
  32391. let inside;
  32392. for(let u=0;u<ring1.points.length;u++){
  32393. inside = math.isPointInArea(ring2.points, null, ring1.points[u]);
  32394. if(!inside)break
  32395. else if(inside && !inside.atLine){
  32396. break
  32397. }
  32398. }
  32399. if(inside){ //只要其中一个点在ring2内,就说明ring1是内环
  32400. if(inside.atLine){//(还是会存在点全在线上的情况,这时候判断中心点)
  32401. var center = math.getCenterOfGravityPoint(ring1.points);
  32402. let inside1 = math.isPointInArea(ring2.points, null, center);
  32403. if(!inside1){
  32404. continue
  32405. }
  32406. }
  32407. ring2.child.push(ring1);
  32408. ring1.parent.push(ring2);
  32409. }
  32410. }
  32411. });
  32412. //去除非最小的ring 是否应该检测parent child?
  32413. /*
  32414. like this:
  32415. |———————————————————————|
  32416. |———|———————|———————| |
  32417. | | | | |
  32418. | |———————|———————| |
  32419. |———————————————————————|
  32420. */
  32421. var wiseRings = rings.filter(r=>!r.isClockwise);//一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  32422. if(wiseRings.length > 0){
  32423. //console.log('%c存在非最小的ring! 进行处理:',"color:#00f");
  32424. wiseRings.forEach(ring=>{ //(此案例验证出smallNeibours就是它的最小构成,可以再看看别的案例)
  32425. if(ring.smallNeibours.length>0){//另:如果内部只有一个,说明它是最小环,不需要处理
  32426. var is = false;
  32427. var difference = getDifferenceSet(ring.lines , getDifferenceSetMuti(ring.smallNeibours.concat(ring.child).map(ring=>ring.lines)));//获取所有smallNeibours和child的边中没有重复过的边(就是outline) 和该ring的线比较
  32428. is = difference.every(line=> ring.child.find(r=>r.lines.includes(line)) ); //多出的线只能是child中的线
  32429. if(is){
  32430. console.log('%c删除非最小环 ring'+ring.id,"color:#00f");
  32431. console.log(ring);
  32432. rings.splice(rings.indexOf(ring), 1);
  32433. ring.child.forEach(c=>{var index = c.parent.indexOf(ring);index>-1 && c.parent.splice(index,1);});
  32434. ring.parent.forEach(c=>{var index = c.child.indexOf(ring);index>-1 && c.child.splice(index,1);});
  32435. ring.smallNeibours.forEach(c=>{var index = c.smallNeibours.indexOf(ring);index>-1 && c.smallNeibours.splice(index,1);});
  32436. }
  32437. }
  32438. });
  32439. }
  32440. /* rings = rings.filter(ring=>{
  32441. rings = rings.filter(ring=>{
  32442. var enoughSize = ring.area > 0.5
  32443. if(!enoughSize){console.log('因面积过小去除ring '+ring.id + " , area: "+ring.area)}
  32444. return enoughSize
  32445. })
  32446. rings.forEach(ring=>{
  32447. if(ring.closetChilds){
  32448. ring.closetChilds = ring.closetChilds.filter(e=>rings.includes(e))
  32449. }
  32450. })
  32451. return rings
  32452. }) */ //在dealRings前不能随意删除rings,因为判断是否是最小环时需要全部的环
  32453. rings.forEach(ring=>{ //这里和cad中的不太一样, cad中双数个parent算外环,单数内环; 这里不分内外, 只看有无parent child
  32454. if(ring.parent.length){
  32455. ring.closetParent = ring.parent.find(ring_ => ring_.parent.length == ring.parent.length - 1);//最近一层的大环就是比它的parent个数少一的
  32456. ring.closetParent.closetChilds || (ring.closetParent.closetChilds = []);//内环可能多个
  32457. ring.closetParent.closetChilds.push(ring);
  32458. }
  32459. });
  32460. //console.log(rings)
  32461. var _ring = rings.map(ring=>{
  32462. var data = {
  32463. id: ring.id,
  32464. points: ring.points.map(point=>{return {id: point.ids[0], x:point.x, y:point.y}}),
  32465. /* doors : o.doors.filter(door=>{
  32466. if(ring.closetChilds){
  32467. var childOutLines = getDifferenceSetMuti(ring.closetChilds.map(ring=>ring.lines)) //最近子环的外边
  32468. return ring.lines.concat(childOutLines).includes(door.atLine)
  32469. }else{
  32470. return ring.lines.includes(door.atLine)
  32471. }
  32472. }), */
  32473. area:ring.area,
  32474. closetParent : ring.closetParent && ring.closetParent.id,
  32475. closetChilds : ring.closetChilds && ring.closetChilds.map(e=>e.id)
  32476. };
  32477. return data
  32478. });
  32479. //console.log(JSON.stringify(_ring))
  32480. return _ring
  32481. };
  32482. var math = {
  32483. getBaseLog(x, y) {//返回以 x 为底 y 的对数(即 logx y) . Math.log 返回一个数的自然对数
  32484. return Math.log(y) / Math.log(x);
  32485. }
  32486. ,
  32487. convertVector : {
  32488. ZupToYup: function(e){//navvis -> 4dkk
  32489. return new Vector3(e.x,e.z,-e.y)
  32490. },
  32491. YupToZup: function(e){//4dkk -> navvis
  32492. return new Vector3(e.x,-e.z,e.y)
  32493. },
  32494. },
  32495. convertQuaternion: {
  32496. ZupToYup: function(e){//navvis -> 4dkk //不同于convertVisionQuaternion
  32497. let rotation = new Euler(-Math.PI/2,0,0);
  32498. let quaternion = new Quaternion().setFromEuler(rotation);
  32499. return e.clone().premultiply(quaternion)
  32500. //return new THREE.Quaternion(e.x,e.z,-e.y,e.w).multiply((new THREE.Quaternion).setFromAxisAngle(new THREE.Vector3(1,0,0), THREE.Math.degToRad(90)))
  32501. },
  32502. YupToZup: function(e){//4dkk -> navvis
  32503. let rotation = new Euler(Math.PI/2,0,0);
  32504. let quaternion = new Quaternion().setFromEuler(rotation);
  32505. return e.clone().premultiply(quaternion)
  32506. },
  32507. },
  32508. convertVisionQuaternion: function(e) {
  32509. return new Quaternion(e.x,e.z,-e.y,e.w).multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(90)))
  32510. },
  32511. invertVisionQuaternion : function(e) {//反转给算法部
  32512. var a = e.clone().multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(-90)));
  32513. return new Quaternion(a.x,-a.z,a.y,a.w)
  32514. },
  32515. //------------
  32516. getVec2Angle : function(dir1,dir2){
  32517. return Math.acos( MathUtils.clamp(this.getVec2Cos(dir1,dir2), -1,1) )
  32518. },
  32519. getVec2Cos : function(dir1,dir2){
  32520. return dir1.dot(dir2) / dir1.length() / dir2.length()
  32521. },
  32522. getAngle:function(vec1, vec2, axis){//带方向的角度 vector3
  32523. var angle = vec1.angleTo(vec2);
  32524. var axis_ = vec1.clone().cross(vec2);
  32525. if(axis_[axis] < 0){
  32526. angle *= -1;
  32527. }
  32528. return angle
  32529. },
  32530. closeTo : function(a,b, precision=1e-6){
  32531. let f = (a,b)=>{
  32532. return Math.abs(a-b) < precision;
  32533. };
  32534. if(typeof (a) == 'number'){
  32535. return f(a, b);
  32536. }else {
  32537. let judge = (name)=>{
  32538. if(a[name] == void 0)return true //有值就判断,没值就不判断
  32539. else return f(a[name],b[name])
  32540. };
  32541. return judge('x') && judge('y') && judge('z') && judge('w')
  32542. }
  32543. },
  32544. toPrecision: function (e, t) {//xzw change 保留小数
  32545. var f = function (e, t) {
  32546. var i = Math.pow(10, t);
  32547. return Math.round(e * i) / i
  32548. };
  32549. if (e instanceof Array) {
  32550. for (var s = 0; s < e.length; s++) {
  32551. e[s] = f(e[s], t);
  32552. }
  32553. return e;
  32554. } else if (e instanceof Object) {
  32555. for (var s in e) {
  32556. e[s] = f(e[s], t);
  32557. }
  32558. return e;
  32559. } else return f(e, t)
  32560. },
  32561. isEmptyQuaternion: function(e) {
  32562. return 0 === Math.abs(e.x) && 0 === Math.abs(e.y) && 0 === Math.abs(e.z) && 0 === Math.abs(e.w)
  32563. },
  32564. projectPositionToCanvas: function(e, t, i) {
  32565. i = i || new Vector3,
  32566. i.copy(e);
  32567. var r = .5 * $('#player').width()
  32568. , o = .5 * $('#player').height();
  32569. return i.project(t),
  32570. i.x = i.x * r + r,
  32571. i.y = -(i.y * o) + o,
  32572. i
  32573. },
  32574. handelPadResize:false,
  32575. /* handelPadding : function () { //去除player左边和上面的宽高,因为pc的player左上有其他element 许钟文
  32576. var pads = [];//记录下来避免反复计算
  32577. var index = [];
  32578. var resetPad = function(){
  32579. pads = [];
  32580. index = [];
  32581. math.handelPadResize = false; //switchview时resized为true
  32582. }
  32583. if(config.isEdit && !config.isMobile){
  32584. window.addEventListener('resize',resetPad);
  32585. }
  32586. return function(x, y, domE){
  32587. if(!config.isEdit || config.isMobile) {
  32588. return {
  32589. x: x,
  32590. y: y
  32591. }
  32592. }
  32593. if(this.handelPadResize)resetPad();
  32594. domE = domE || $('#player')[0];
  32595. var pad;
  32596. var i = index.indexOf(domE);
  32597. if (i == -1){
  32598. index.push(domE);
  32599. pad = {
  32600. x: this.getOffset("left", domE),
  32601. y: this.getOffset("top", domE)
  32602. }
  32603. pads.push(pad)
  32604. }
  32605. else pad = pads[i];
  32606. return {
  32607. x: x - pad.x,
  32608. y: y - pad.y
  32609. }
  32610. }
  32611. }(), */
  32612. getOffset: function (type, element, parent) {//获取元素的边距 许钟文
  32613. var offset = (type == "left") ? element.offsetLeft : element.offsetTop;
  32614. if (!parent) parent = $("body")[0];
  32615. while (element = element.offsetParent) {
  32616. if (element == parent) break;
  32617. offset += (type == "left") ? element.offsetLeft : element.offsetTop;
  32618. }
  32619. return offset;
  32620. }
  32621. ,
  32622. constrainedTurn: function(e) {
  32623. var t = e % (2 * Math.PI);
  32624. return t = t > Math.PI ? t -= 2 * Math.PI : t < -Math.PI ? t += 2 * Math.PI : t
  32625. },
  32626. getFOVDotThreshold: function(e) {
  32627. return Math.cos(MathUtils.degToRad(e / 2))
  32628. },
  32629. transform2DForwardVectorByCubeFace: function(e, t, i, n) {
  32630. switch (e) {
  32631. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  32632. i.set(1, t.y, t.x);
  32633. break;
  32634. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  32635. i.set(-1, t.y, -t.x);
  32636. break;
  32637. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  32638. i.set(-t.x, 1, -t.y);
  32639. break;
  32640. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  32641. i.set(-t.x, -1, t.y);
  32642. break;
  32643. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  32644. i.set(-t.x, t.y, 1);
  32645. break;
  32646. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  32647. i.set(t.x, t.y, -1);
  32648. }
  32649. n && i.normalize();
  32650. },
  32651. getFootPoint : function(oldPos, p1, p2, restricInline){ //找oldPos在线段p1, p2上的垂足
  32652. /* if(isWorld){//输出全局坐标 需要考虑meshGroup.position
  32653. p1 = p1.clone();
  32654. p2 = p2.clone();
  32655. p1.y += mainDesign.meshGroup.position.y;
  32656. p2.y += mainDesign.meshGroup.position.y;
  32657. } */
  32658. if(p1.equals(p2))return p1.clone()
  32659. var op1 = oldPos.clone().sub(p1);
  32660. var p1p2 = p1.clone().sub(p2);
  32661. var p1p2Len = p1p2.length();
  32662. var leftLen = op1.dot(p1p2) / p1p2Len;
  32663. var pos = p1.clone().add(p1p2.multiplyScalar( leftLen/p1p2Len ));
  32664. if(restricInline && pos.clone().sub(p1).dot( pos.clone().sub(p2) ) > 0){//foot不在线段上
  32665. if(pos.distanceTo(p1) < pos.distanceTo(p2)) pos = p1.clone();
  32666. else pos = p2.clone();
  32667. }
  32668. return pos;
  32669. },
  32670. /**
  32671. * 计算多边形的重心
  32672. * @param {*} points
  32673. */
  32674. getCenterOfGravityPoint : function(mPoints){
  32675. var area = 0.0;//多边形面积
  32676. var Gx = 0.0, Gy = 0.0;// 重心的x、y
  32677. for (var i = 1; i <= mPoints.length; i++) {
  32678. var ix = mPoints[i % mPoints.length].x;
  32679. var iy = mPoints[i % mPoints.length].y;
  32680. var nx = mPoints[i - 1].x;
  32681. var ny = mPoints[i - 1].y;
  32682. var temp = (ix * ny - iy * nx) / 2.0;
  32683. area += temp;
  32684. Gx += temp * (ix + nx) / 3.0;
  32685. Gy += temp * (iy + ny) / 3.0;
  32686. }
  32687. Gx = Gx / area;
  32688. Gy = Gy / area;
  32689. return { x: Gx, y: Gy };
  32690. },
  32691. getBound : function(ring){
  32692. var bound = new Box2();
  32693. for(var j=0,len = ring.length; j<len; j++){
  32694. bound.expandByPoint(ring[j]);
  32695. }
  32696. return bound;
  32697. },
  32698. isPointInArea : function(ring, holes, point, ifAtLine){//判断点是否在某个环内, 若传递了holes代表还要不能在内环内
  32699. var bound = this.getBound(ring);
  32700. if(point.x < bound.min.x || point.x > bound.max.x || point.y < bound.min.y || point.y > bound.max.y)return false;
  32701. var inside = false;
  32702. var x = point.x,
  32703. y = point.y;
  32704. for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
  32705. var xi = ring[i].x,
  32706. yi = ring[i].y;
  32707. var xj = ring[j].x,
  32708. yj = ring[j].y;
  32709. if((xi - x)*(yj - y) == (xi - x)*(yi - y) && x>=Math.min(xi,xj) && x<=Math.max(xi,xj)//xzw add
  32710. && y>=Math.min(yi,yj) && y<=Math.max(yi,yj)
  32711. ){
  32712. //return !!ifAtLine;//在线段上,则判断为…… (默认在外)
  32713. return {atLine:true}
  32714. }
  32715. if (((yi > y) != (yj > y)) &&
  32716. (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
  32717. ) {
  32718. inside = !inside;
  32719. }
  32720. }
  32721. if(inside && holes){
  32722. return !holes.some(ring=>this.isPointInArea(ring, null, point, ifAtLine) ) //不能存在于任何一个二级内环内
  32723. }else {
  32724. return inside;
  32725. }
  32726. },
  32727. getArea : function (ring) { //求面积 顺时针为正 来自three shape
  32728. for (var t = ring.length, i = 0, n = t - 1, r = 0; r < t; n = r++)
  32729. i += ring[n].x * ring[r].y - ring[r].x * ring[n].y;
  32730. return -.5 * i
  32731. },
  32732. isInBetween : function(a, b, c, precision) {
  32733. // 如果b几乎等于a或c,返回false.为了避免浮点运行时两值几乎相等,但存在相差0.00000...0001的这种情况出现使用下面方式进行避免
  32734. /* if (Math.abs(a - b) < 0.000001 || Math.abs(b - c) < 0.000001) {
  32735. return false;
  32736. }
  32737. return (a <= b && b <= c) || (c <= b && b <= a);*/
  32738. //更改:如果b和a或c中一个接近 就算在a和c之间
  32739. return (a <= b && b <= c) || (c <= b && b <= a) || this.closeTo(a,b,precision) || this.closeTo(b,c,precision);
  32740. },
  32741. ifPointAtLineBound:function(point, linePoints, precision){
  32742. //待验证 横线和竖线比较特殊
  32743. return math.isInBetween(linePoints[0].x, point.x, linePoints[1].x, precision) && math.isInBetween(linePoints[0].y, point.y, linePoints[1].y, precision)
  32744. }
  32745. ,
  32746. isLineIntersect: function (line1, line2, notSegment, precision) {//线段和线段是否有交点. notSegment代表是直线而不是线段
  32747. var a1 = line1[1].y - line1[0].y;
  32748. var b1 = line1[0].x - line1[1].x;
  32749. var c1 = a1 * line1[0].x + b1 * line1[0].y;
  32750. //转换成一般式: Ax+By = C
  32751. var a2 = line2[1].y - line2[0].y;
  32752. var b2 = line2[0].x - line2[1].x;
  32753. var c2 = a2 * line2[0].x + b2 * line2[0].y;
  32754. // 计算交点
  32755. var d = a1 * b2 - a2 * b1;
  32756. // 当d==0时,两线平行
  32757. if (d == 0) {
  32758. return false;
  32759. } else {
  32760. var x = (b2 * c1 - b1 * c2) / d;
  32761. var y = (a1 * c2 - a2 * c1) / d;
  32762. // 检测交点是否在两条线段上
  32763. /* if (notSegment || (isInBetween(line1[0].x, x, line1[1].x) || isInBetween(line1[0].y, y, line1[1].y)) &&
  32764. (isInBetween(line2[0].x, x, line2[1].x) || isInBetween(line2[0].y, y, line2[1].y))) {
  32765. return {x,y};
  32766. } */
  32767. if (notSegment || math.ifPointAtLineBound({x,y}, line1, precision) && math.ifPointAtLineBound({x,y}, line2, precision)){
  32768. return {x,y};
  32769. }
  32770. }
  32771. },
  32772. getNormal2d : function(o={} ){//获取二维法向量 方向向内
  32773. var x,y, x1,y1;
  32774. //line2d的向量
  32775. if(o.vec){
  32776. x1 = o.vec.x; y1 = o.vec.y;
  32777. }else {
  32778. x1 = o.p1.x - o.p2.x;
  32779. y1 = o.p1.y - o.p2.y;
  32780. }
  32781. //假设法向量的x或y固定为1或-1
  32782. if(y1 != 0){
  32783. x = 1;
  32784. y = - (x1 * x) / y1;
  32785. }else if(x1 != 0){//y如果为0,正常情况x不会是0
  32786. y = 1;
  32787. x = - (y1 * y) / x1;
  32788. }else {
  32789. console.log("两个点一样");
  32790. return null;
  32791. }
  32792. //判断方向里或者外:
  32793. var vNormal = new Vector3(x, 0, y);
  32794. var vLine = new Vector3(x1, 0, y1);
  32795. var vDir = vNormal.cross(vLine);
  32796. if(vDir.y>0){
  32797. x *= -1;
  32798. y *= -1;
  32799. }
  32800. return new Vector2$1(x, y).normalize();
  32801. },
  32802. getQuaBetween2Vector:function(oriVec, newVec, upVec){ //获取从oriVec旋转到newVec可以应用的quaternion
  32803. var angle = oriVec.angleTo(newVec);
  32804. var axis = oriVec.clone().cross( newVec).normalize();//两个up之间
  32805. if(axis.length() == 0){//当夹角为180 或 0 度时,得到的axis为(0,0,0),故使用备用的指定upVec
  32806. return new Quaternion().setFromAxisAngle( upVec, angle );
  32807. }
  32808. return new Quaternion().setFromAxisAngle( axis, angle );
  32809. }
  32810. /* ,
  32811. getQuaBetween2Vector2 : function(oriVec, newVec ){//not camera
  32812. var _ = (new THREE.Matrix4).lookAt( oriVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  32813. var aimQua = (new THREE.Quaternion).setFromRotationMatrix(_)
  32814. var _2 = (new THREE.Matrix4).lookAt( newVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  32815. var aimQua2 = (new THREE.Quaternion).setFromRotationMatrix(_2)
  32816. return aimQua2.multiply(aimQua.clone().inverse())
  32817. } */
  32818. ,
  32819. getScaleForConstantSize : function(){ //获得规定二维大小的mesh的scale值。可以避免因camera的projection造成的mesh视觉大小改变。 来源:tag.updateDisc
  32820. var w;
  32821. var i = new Vector3, o = new Vector3, l = new Vector3, c = new Vector3, h = new Vector3;
  32822. return function(op={}){
  32823. if(op.width2d) w = op.width2d; //如果恒定二维宽度
  32824. else {//否则考虑上距离,加一丢丢近大远小的效果
  32825. var currentDis, nearBound, farBound;
  32826. if(op.camera.type == "OrthographicCamera"){
  32827. currentDis = 200 / op.camera.zoom; //(op.camera.right - op.camera.left) / op.camera.zoom
  32828. }else {
  32829. currentDis = op.position.distanceTo(op.camera.position);
  32830. }
  32831. w = op.maxSize - ( op.maxSize - op.minSize) * MathUtils.smoothstep(currentDis, op.nearBound, op.farBound);
  32832. //maxSize : mesh要表现的最大像素宽度; nearBound: 最近距离,若比nearBound近,则使用maxSize
  32833. }
  32834. i.copy(op.position).project(op.camera), //tag中心在屏幕上的二维坐标
  32835. o.set(op.resolution.x / 2, op.resolution.y / 2, 1).multiply(i), //转化成px -w/2 到 w/2的范围
  32836. l.set(w / 2, 0, 0).add(o), //加上tag宽度的一半
  32837. c.set(2 / op.resolution.x, 2 / op.resolution.y, 1).multiply(l), //再转回 -1 到 1的范围
  32838. h.copy(c).unproject(op.camera);//再转成三维坐标,求得tag边缘的位置
  32839. var g = h.distanceTo(op.position);//就能得到tag的三维半径
  32840. //这里使用的都是resolution2, 好处是手机端不会太小, 坏处是pc更改网页显示百分比时显示的大小会变(或许可以自己算出设备真实的deviceRatio, 因window.screen是不会改变的),但考虑到用户可以自行调节字大小也许是好的
  32841. return g //可能NAN 当相机和position重叠时
  32842. }
  32843. }()
  32844. ,
  32845. //W , H, left, top分别是rect的宽、高、左、上
  32846. getCrossPointAtRect : function(p1, aim, W , H, left, top){//求射线p1-aim在rect边界上的交点,其中aim在rect范围内,p1则不一定(交点在aim这边的延长线上)
  32847. var x,y, borderX;
  32848. var r = (aim.x - p1.x) / (aim.y - p1.y);//根据相似三角形原理先求出这个比值
  32849. var getX = function(y){
  32850. return r * (y-p1.y) + p1.x;
  32851. };
  32852. var getY = function(x){
  32853. return 1/r * (x-p1.x) + p1.y;
  32854. };
  32855. if(aim.x >= p1.x){
  32856. borderX = W+left;
  32857. }else {
  32858. borderX = left;
  32859. }
  32860. x = borderX;
  32861. y = getY(x);
  32862. if(y < top || y > top+H){
  32863. if(y < top){
  32864. y = top;
  32865. }else {
  32866. y = top+H;
  32867. }
  32868. x = getX(y);
  32869. }
  32870. return new Vector2$1(x, y);
  32871. },
  32872. getDirFromUV : function(uv){ //获取dir 反向计算 - - 二维转三维比较麻烦
  32873. var dirB; //所求 单位向量
  32874. var y = Math.cos(uv.y * Math.PI); //uv中纵向可以直接确定y, 根据上面getUVfromDir的反向计算
  32875. // 故 uv.y * Math.PI 就是到垂直线(向上)的夹角
  32876. var angle = 2 * Math.PI * uv.x - Math.PI; //x/z代表的是角度
  32877. var axisX, axisZ; //axis为1代表是正,-1是负数
  32878. if (-Math.PI <= angle && angle < 0) {
  32879. axisX = -1; //下半圆
  32880. } else {
  32881. axisX = 1; //上半圆
  32882. }
  32883. if (-Math.PI / 2 <= angle && angle < Math.PI / 2) {
  32884. axisZ = 1; //右半圆
  32885. } else {
  32886. axisZ = -1; //左半圆
  32887. }
  32888. var XDivideZ = Math.tan(angle);
  32889. var z = Math.sqrt((1 - y * y) / (1 + XDivideZ * XDivideZ));
  32890. var x = XDivideZ * z;
  32891. if (z * axisZ < 0) { //异号
  32892. z *= -1;
  32893. x *= -1;
  32894. if (x * axisX < 0) {
  32895. // console.log("wrong!!!!!??????????")
  32896. }
  32897. }
  32898. x *= -1; //计算完成后这里不能漏掉 *= -1
  32899. dirB = this.convertVector.YupToZup(new Vector3(x, y, z));
  32900. //理想状态下x和z和anotherDir相同
  32901. return dirB
  32902. },
  32903. getUVfromDir : function(dir) { //获取UV 同shader里的计算
  32904. var dir = this.convertVector.ZupToYup(dir);
  32905. dir.x *= -1; //计算前这里不能漏掉 *= -1 见shader
  32906. var tx = Math.atan2(dir.x, dir.z) / (Math.PI * 2.0) + 0.5; //atan2(y,x) 返回从 X 轴正向逆时针旋转到点 (x,y) 时经过的角度。区间是-PI 到 PI 之间的值
  32907. var ty = Math.acos(dir.y) / Math.PI;
  32908. return new Vector2$1(tx, ty)
  32909. //理想状态下tx相同
  32910. },
  32911. getDirByLonLat : function(lon,lat){
  32912. var dir = new Vector3;
  32913. var phi = MathUtils.degToRad(90 - lat);
  32914. var theta = MathUtils.degToRad(lon);
  32915. dir.x = Math.sin(phi) * Math.cos(theta);
  32916. dir.y = Math.cos(phi);
  32917. dir.z = Math.sin(phi) * Math.sin(theta);
  32918. return dir
  32919. } //0,0 => (1,0,0) 270=>(0,0,-1)
  32920. ,
  32921. projectPointAtPlane:function(o={}){//获取一个点在一个面上的投影 {facePoints:[a,b,c], point:}
  32922. var plane = new Plane().setFromCoplanarPoints(...o.facePoints);
  32923. return plane.projectPoint(o.point, new Vector3() )
  32924. }
  32925. ,
  32926. getPolygonsMixedRings:function( polygons, onlyGetOutRing){//{points:[vector2,...],holes:[[],[]]}
  32927. let points = [];
  32928. let lines = [];
  32929. let i = 0;
  32930. polygons.forEach(e=> points.push(...e.map(a=>new Vector2$1().copy(a) )) );
  32931. polygons.forEach((ps,j)=>{
  32932. let length = ps.length;
  32933. let index = 0;
  32934. while(index<length){
  32935. lines.push({p1:index+i,p2:(index+1)%length+i});
  32936. index ++;
  32937. }
  32938. i+=length;
  32939. });
  32940. points.forEach((p,j)=>{p.id = j;});
  32941. let rings = searchRings({
  32942. points,
  32943. lines,
  32944. onlyGetOutRing
  32945. });
  32946. //console.log(rings)
  32947. rings = rings.filter(e=>e.closetParent == void 0);// 子环不加,被外环包含了
  32948. return rings
  32949. },
  32950. getQuaFromPosAim( position, target ){
  32951. let matrix = (new Matrix4).lookAt(position, target, new Vector3(0,0,1));
  32952. return (new Quaternion).setFromRotationMatrix(matrix)
  32953. },
  32954. getBoundByPoints(points, minSize){
  32955. var bound = new Box3;
  32956. points.forEach(point=>{
  32957. bound.expandByPoint(point);
  32958. });
  32959. let center = bound.getCenter(new Vector3);
  32960. if(minSize){
  32961. let minBound = (new Box3()).setFromCenterAndSize(center, minSize);
  32962. bound.union(minBound);
  32963. }
  32964. return {
  32965. bounding:bound,
  32966. size: bound.getSize(new Vector3),
  32967. center,
  32968. }
  32969. },
  32970. };
  32971. Potree.math = math;
  32972. !function() {
  32973. if ("performance"in window == 0 && (window.performance = {}),
  32974. "now"in window.performance == 0) {
  32975. var e = Date.now();
  32976. performance.timing && performance.timing.navigationStart && (e = performance.timing.navigationStart),
  32977. window.performance.now = function() {
  32978. return Date.now() - e
  32979. };
  32980. }
  32981. }(),
  32982. WebGLRenderer.prototype.paramThreeToGL = function(e) {
  32983. var t, i = this.extensions, r = this.getContext();//context;
  32984. if (e === RepeatWrapping)
  32985. return r.REPEAT;
  32986. if (e === ClampToEdgeWrapping)
  32987. return r.CLAMP_TO_EDGE;
  32988. if (e === MirroredRepeatWrapping)
  32989. return r.MIRRORED_REPEAT;
  32990. if (e === NearestFilter)
  32991. return r.NEAREST;
  32992. if (e === NearestMipMapNearestFilter)
  32993. return r.NEAREST_MIPMAP_NEAREST;
  32994. if (e === NearestMipMapLinearFilter)
  32995. return r.NEAREST_MIPMAP_LINEAR;
  32996. if (e === LinearFilter)
  32997. return r.LINEAR;
  32998. if (e === LinearMipMapNearestFilter)
  32999. return r.LINEAR_MIPMAP_NEAREST;
  33000. if (e === LinearMipMapLinearFilter)
  33001. return r.LINEAR_MIPMAP_LINEAR;
  33002. if (e === UnsignedByteType)
  33003. return r.UNSIGNED_BYTE;
  33004. if (e === UnsignedShort4444Type)
  33005. return r.UNSIGNED_SHORT_4_4_4_4;
  33006. if (e === UnsignedShort5551Type)
  33007. return r.UNSIGNED_SHORT_5_5_5_1;
  33008. if (e === UnsignedShort565Type)
  33009. return r.UNSIGNED_SHORT_5_6_5;
  33010. if (e === ByteType)
  33011. return r.BYTE;
  33012. if (e === ShortType)
  33013. return r.SHORT;
  33014. if (e === UnsignedShortType)
  33015. return r.UNSIGNED_SHORT;
  33016. if (e === IntType)
  33017. return r.INT;
  33018. if (e === UnsignedIntType)
  33019. return r.UNSIGNED_INT;
  33020. if (e === FloatType)
  33021. return r.FLOAT;
  33022. if (t = i.get("OES_texture_half_float"),
  33023. null !== t && e === HalfFloatType)
  33024. return t.HALF_FLOAT_OES;
  33025. if (e === AlphaFormat)
  33026. return r.ALPHA;
  33027. if (e === RGBFormat)
  33028. return r.RGB;
  33029. if (e === RGBAFormat)
  33030. return r.RGBA;
  33031. if (e === LuminanceFormat)
  33032. return r.LUMINANCE;
  33033. if (e === LuminanceAlphaFormat)
  33034. return r.LUMINANCE_ALPHA;
  33035. if (e === AddEquation)
  33036. return r.FUNC_ADD;
  33037. if (e === SubtractEquation)
  33038. return r.FUNC_SUBTRACT;
  33039. if (e === ReverseSubtractEquation)
  33040. return r.FUNC_REVERSE_SUBTRACT;
  33041. if (e === ZeroFactor)
  33042. return r.ZERO;
  33043. if (e === OneFactor)
  33044. return r.ONE;
  33045. if (e === SrcColorFactor)
  33046. return r.SRC_COLOR;
  33047. if (e === OneMinusSrcColorFactor)
  33048. return r.ONE_MINUS_SRC_COLOR;
  33049. if (e === SrcAlphaFactor)
  33050. return r.SRC_ALPHA;
  33051. if (e === OneMinusSrcAlphaFactor)
  33052. return r.ONE_MINUS_SRC_ALPHA;
  33053. if (e === DstAlphaFactor)
  33054. return r.DST_ALPHA;
  33055. if (e === OneMinusDstAlphaFactor)
  33056. return r.ONE_MINUS_DST_ALPHA;
  33057. if (e === DstColorFactor)
  33058. return r.DST_COLOR;
  33059. if (e === OneMinusDstColorFactor)
  33060. return r.ONE_MINUS_DST_COLOR;
  33061. if (e === SrcAlphaSaturateFactor)
  33062. return r.SRC_ALPHA_SATURATE;
  33063. if (t = i.get("WEBGL_compressed_texture_s3tc"),
  33064. null !== t) {
  33065. if (e === RGB_S3TC_DXT1_Format)
  33066. return t.COMPRESSED_RGB_S3TC_DXT1_EXT;
  33067. if (e === RGBA_S3TC_DXT1_Format$1)
  33068. return t.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33069. if (e === RGBA_S3TC_DXT3_Format)
  33070. return t.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33071. if (e === RGBA_S3TC_DXT5_Format$1)
  33072. return t.COMPRESSED_RGBA_S3TC_DXT5_EXT
  33073. }
  33074. if (t = i.get("WEBGL_compressed_texture_pvrtc"),
  33075. null !== t) {
  33076. if (e === RGB_PVRTC_4BPPV1_Format)
  33077. return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  33078. if (e === RGB_PVRTC_2BPPV1_Format)
  33079. return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  33080. if (e === RGBA_PVRTC_4BPPV1_Format)
  33081. return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  33082. if (e === RGBA_PVRTC_2BPPV1_Format)
  33083. return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  33084. }
  33085. if (t = i.get("WEBGL_compressed_texture_etc1"),
  33086. null !== t && e === RGB_ETC1_Format)
  33087. return t.COMPRESSED_RGB_ETC1_WEBGL;
  33088. if (t = i.get("EXT_blend_minmax"),
  33089. null !== t) {
  33090. if (e === MinEquation)
  33091. return t.MIN_EXT;
  33092. if (e === MaxEquation)
  33093. return t.MAX_EXT
  33094. }
  33095. return 0
  33096. };
  33097. /* ,
  33098. THREE.WebGLState = function(e, t, i) {
  33099. var r = this
  33100. , o = new THREE.Vector4
  33101. , a = e.getParameter(e.MAX_VERTEX_ATTRIBS)
  33102. , s = new Uint8Array(a)
  33103. , l = new Uint8Array(a)
  33104. , c = new Uint8Array(a)
  33105. , h = {}
  33106. , u = null
  33107. , d = null
  33108. , p = null
  33109. , f = null
  33110. , g = null
  33111. , m = null
  33112. , v = null
  33113. , A = null
  33114. , y = !1
  33115. , C = null
  33116. , I = null
  33117. , E = null
  33118. , b = null
  33119. , w = null
  33120. , _ = null
  33121. , T = null
  33122. , x = null
  33123. , S = null
  33124. , M = null
  33125. , R = null
  33126. , P = null
  33127. , O = null
  33128. , L = null
  33129. , D = null
  33130. , N = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)
  33131. , B = void 0
  33132. , F = {}
  33133. , V = new THREE.Vector4
  33134. , U = null
  33135. , k = null
  33136. , H = new THREE.Vector4
  33137. , G = new THREE.Vector4;
  33138. this.init = function() {
  33139. this.clearColor(0, 0, 0, 1),
  33140. this.clearDepth(1),
  33141. this.clearStencil(0),
  33142. this.enable(e.DEPTH_TEST),
  33143. e.depthFunc(e.LEQUAL),
  33144. e.frontFace(e.CCW),
  33145. e.cullFace(e.BACK),
  33146. this.enable(e.CULL_FACE),
  33147. this.enable(e.BLEND),
  33148. e.blendEquation(e.FUNC_ADD),
  33149. e.blendFunc(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA)
  33150. }
  33151. ,
  33152. this.initAttributes = function() {
  33153. for (var e = 0, t = s.length; e < t; e++)
  33154. s[e] = 0
  33155. }
  33156. ,
  33157. this.enableAttribute = function(i) {
  33158. if (s[i] = 1,
  33159. 0 === l[i] && (e.enableVertexAttribArray(i),
  33160. l[i] = 1),
  33161. 0 !== c[i]) {
  33162. var n = t.get("ANGLE_instanced_arrays");
  33163. n.vertexAttribDivisorANGLE(i, 0),
  33164. c[i] = 0
  33165. }
  33166. }
  33167. ,
  33168. this.enableAttributeAndDivisor = function(t, i, n) {
  33169. s[t] = 1,
  33170. 0 === l[t] && (e.enableVertexAttribArray(t),
  33171. l[t] = 1),
  33172. c[t] !== i && (n.vertexAttribDivisorANGLE(t, i),
  33173. c[t] = i)
  33174. }
  33175. ,
  33176. this.disableUnusedAttributes = function() {
  33177. for (var t = 0, i = l.length; t < i; t++)
  33178. l[t] !== s[t] && (e.disableVertexAttribArray(t),
  33179. l[t] = 0)
  33180. }
  33181. ,
  33182. this.enable = function(t) {
  33183. h[t] !== !0 && (e.enable(t),
  33184. h[t] = !0)
  33185. }
  33186. ,
  33187. this.disable = function(t) {
  33188. h[t] !== !1 && (e.disable(t),
  33189. h[t] = !1)
  33190. }
  33191. ,
  33192. this.getCompressedTextureFormats = function() {
  33193. if (null === u && (u = [],
  33194. t.get("WEBGL_compressed_texture_pvrtc") || t.get("WEBGL_compressed_texture_s3tc") || t.get("WEBGL_compressed_texture_etc1")))
  33195. for (var i = e.getParameter(e.COMPRESSED_TEXTURE_FORMATS), n = 0; n < i.length; n++)
  33196. u.push(i[n]);
  33197. return u
  33198. }
  33199. ,
  33200. this.setBlending = function(t, r, o, a, s, l, c, h) {
  33201. t === THREE.NoBlending ? this.disable(e.BLEND) : this.enable(e.BLEND),
  33202. t === d && h === y || (t === THREE.AdditiveBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33203. e.blendFuncSeparate(e.ONE, e.ONE, e.ONE, e.ONE)) : (e.blendEquation(e.FUNC_ADD),
  33204. e.blendFunc(e.SRC_ALPHA, e.ONE)) : t === THREE.SubtractiveBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33205. e.blendFuncSeparate(e.ZERO, e.ZERO, e.ONE_MINUS_SRC_COLOR, e.ONE_MINUS_SRC_ALPHA)) : (e.blendEquation(e.FUNC_ADD),
  33206. e.blendFunc(e.ZERO, e.ONE_MINUS_SRC_COLOR)) : t === THREE.MultiplyBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33207. e.blendFuncSeparate(e.ZERO, e.ZERO, e.SRC_COLOR, e.SRC_ALPHA)) : (e.blendEquation(e.FUNC_ADD),
  33208. e.blendFunc(e.ZERO, e.SRC_COLOR)) : h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33209. e.blendFuncSeparate(e.ONE, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA)) : (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33210. e.blendFuncSeparate(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA)),
  33211. d = t,
  33212. y = h),
  33213. t === THREE.CustomBlending ? (s = s || r,
  33214. l = l || o,
  33215. c = c || a,
  33216. r === p && s === m || (e.blendEquationSeparate(i(r), i(s)),
  33217. p = r,
  33218. m = s),
  33219. o === f && a === g && l === v && c === A || (e.blendFuncSeparate(i(o), i(a), i(l), i(c)),
  33220. f = o,
  33221. g = a,
  33222. v = l,
  33223. A = c)) : (p = null,
  33224. f = null,
  33225. g = null,
  33226. m = null,
  33227. v = null,
  33228. A = null)
  33229. }
  33230. ,
  33231. this.setDepthFunc = function(t) {
  33232. if (C !== t) {
  33233. if (t)
  33234. switch (t) {
  33235. case THREE.NeverDepth:
  33236. e.depthFunc(e.NEVER);
  33237. break;
  33238. case THREE.AlwaysDepth:
  33239. e.depthFunc(e.ALWAYS);
  33240. break;
  33241. case THREE.LessDepth:
  33242. e.depthFunc(e.LESS);
  33243. break;
  33244. case THREE.LessEqualDepth:
  33245. e.depthFunc(e.LEQUAL);
  33246. break;
  33247. case THREE.EqualDepth:
  33248. e.depthFunc(e.EQUAL);
  33249. break;
  33250. case THREE.GreaterEqualDepth:
  33251. e.depthFunc(e.GEQUAL);
  33252. break;
  33253. case THREE.GreaterDepth:
  33254. e.depthFunc(e.GREATER);
  33255. break;
  33256. case THREE.NotEqualDepth:
  33257. e.depthFunc(e.NOTEQUAL);
  33258. break;
  33259. default:
  33260. e.depthFunc(e.LEQUAL)
  33261. }
  33262. else
  33263. e.depthFunc(e.LEQUAL);
  33264. C = t
  33265. }
  33266. }
  33267. ,
  33268. this.setDepthTest = function(t) {
  33269. t ? this.enable(e.DEPTH_TEST) : this.disable(e.DEPTH_TEST)
  33270. }
  33271. ,
  33272. this.setDepthWrite = function(t) {
  33273. I !== t && (e.depthMask(t),
  33274. I = t)
  33275. }
  33276. ,
  33277. this.setColorWrite = function(t) {
  33278. E !== t && (e.colorMask(t, t, t, t),
  33279. E = t)
  33280. }
  33281. ,
  33282. this.setStencilFunc = function(t, i, n) {
  33283. w === t && _ === i && T === n || (e.stencilFunc(t, i, n),
  33284. w = t,
  33285. _ = i,
  33286. T = n)
  33287. }
  33288. ,
  33289. this.setStencilOp = function(t, i, n) {
  33290. x === t && S === i && M === n || (e.stencilOp(t, i, n),
  33291. x = t,
  33292. S = i,
  33293. M = n)
  33294. }
  33295. ,
  33296. this.setStencilTest = function(t) {
  33297. t ? this.enable(e.STENCIL_TEST) : this.disable(e.STENCIL_TEST)
  33298. }
  33299. ,
  33300. this.setStencilWrite = function(t) {
  33301. b !== t && (e.stencilMask(t),
  33302. b = t)
  33303. }
  33304. ,
  33305. this.setFlipSided = function(t) {
  33306. R !== t && (t ? e.frontFace(e.CW) : e.frontFace(e.CCW),
  33307. R = t)
  33308. }
  33309. ,
  33310. this.setLineWidth = function(t) {
  33311. t !== P && (e.lineWidth(t),
  33312. P = t)
  33313. }
  33314. ,
  33315. this.setPolygonOffset = function(t, i, n) {
  33316. t ? this.enable(e.POLYGON_OFFSET_FILL) : this.disable(e.POLYGON_OFFSET_FILL),
  33317. !t || O === i && L === n || (e.polygonOffset(i, n),
  33318. O = i,
  33319. L = n)
  33320. }
  33321. ,
  33322. this.getScissorTest = function() {
  33323. return D
  33324. }
  33325. ,
  33326. this.setScissorTest = function(t) {
  33327. D = t,
  33328. t ? this.enable(e.SCISSOR_TEST) : this.disable(e.SCISSOR_TEST)
  33329. }
  33330. ,
  33331. this.activeTexture = function(t) {
  33332. void 0 === t && (t = e.TEXTURE0 + N - 1),
  33333. B !== t && (e.activeTexture(t),
  33334. B = t)
  33335. }
  33336. ,
  33337. this.bindTexture = function(t, i) {
  33338. void 0 === B && r.activeTexture();
  33339. var n = F[B];
  33340. void 0 === n && (n = {
  33341. type: void 0,
  33342. texture: void 0
  33343. },
  33344. F[B] = n),
  33345. n.type === t && n.texture === i || (e.bindTexture(t, i),
  33346. n.type = t,
  33347. n.texture = i)
  33348. }
  33349. ,
  33350. this.compressedTexImage2D = function() {
  33351. try {
  33352. e.compressedTexImage2D.apply(e, arguments)
  33353. } catch (e) {
  33354. console.error(e)
  33355. }
  33356. }
  33357. ,
  33358. this.texImage2D = function() {
  33359. try {
  33360. e.texImage2D.apply(e, arguments)
  33361. } catch (e) {
  33362. console.error(e)
  33363. }
  33364. }
  33365. ,
  33366. this.clearColor = function(t, i, n, r) {
  33367. o.set(t, i, n, r),
  33368. V.equals(o) === !1 && (e.clearColor(t, i, n, r),
  33369. V.copy(o))
  33370. }
  33371. ,
  33372. this.clearDepth = function(t) {
  33373. U !== t && (e.clearDepth(t),
  33374. U = t)
  33375. }
  33376. ,
  33377. this.clearStencil = function(t) {
  33378. k !== t && (e.clearStencil(t),
  33379. k = t)
  33380. }
  33381. ,
  33382. this.scissor = function(t) {
  33383. H.equals(t) === !1 && (e.scissor(t.x, t.y, t.z, t.w),
  33384. H.copy(t))
  33385. }
  33386. ,
  33387. this.viewport = function(t) {
  33388. G.equals(t) === !1 && (e.viewport(t.x, t.y, t.z, t.w),
  33389. G.copy(t))
  33390. }
  33391. ,
  33392. this.reset = function() {
  33393. for (var t = 0; t < l.length; t++)
  33394. 1 === l[t] && (e.disableVertexAttribArray(t),
  33395. l[t] = 0);
  33396. h = {},
  33397. u = null,
  33398. B = void 0,
  33399. F = {},
  33400. d = null,
  33401. E = null,
  33402. I = null,
  33403. b = null,
  33404. R = null
  33405. }
  33406. } */
  33407. const XHRFactory = {
  33408. config: {
  33409. withCredentials: false,
  33410. customHeaders: [
  33411. { header: null, value: null }
  33412. ]
  33413. },
  33414. createXMLHttpRequest: function () {
  33415. let xhr = new XMLHttpRequest();
  33416. if (this.config.customHeaders &&
  33417. Array.isArray(this.config.customHeaders) &&
  33418. this.config.customHeaders.length > 0) {
  33419. let baseOpen = xhr.open;
  33420. let customHeaders = this.config.customHeaders;
  33421. xhr.open = function () {
  33422. baseOpen.apply(this, [].slice.call(arguments));
  33423. customHeaders.forEach(function (customHeader) {
  33424. if (!!customHeader.header && !!customHeader.value) {
  33425. xhr.setRequestHeader(customHeader.header, customHeader.value);
  33426. }
  33427. });
  33428. };
  33429. }
  33430. return xhr;
  33431. }
  33432. };
  33433. let Shaders = {};
  33434. Shaders["pointcloud.vs"] = `
  33435. precision highp float;
  33436. precision highp int;
  33437. #define max_clip_polygons 8
  33438. #define PI 3.141592653589793
  33439. #if defined(usePanoMap)
  33440. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  33441. uniform samplerCube pano1Map;
  33442. uniform float progress;
  33443. uniform float easeInOutRatio;
  33444. uniform vec3 pano0Position;
  33445. uniform mat4 pano0Matrix;
  33446. uniform vec3 pano1Position;
  33447. uniform mat4 pano1Matrix;
  33448. /*
  33449. varying vec3 vWorldPosition0;
  33450. varying vec3 vWorldPosition1;
  33451. */
  33452. #endif
  33453. //--------------
  33454. attribute vec3 position;
  33455. attribute vec3 color;
  33456. attribute float intensity;
  33457. attribute float classification;
  33458. attribute float returnNumber;
  33459. attribute float numberOfReturns;
  33460. attribute float pointSourceID;
  33461. attribute vec4 indices; //每个点的index
  33462. attribute float spacing;
  33463. attribute float gpsTime;
  33464. attribute vec3 normal;
  33465. attribute float aExtra;
  33466. uniform mat4 modelMatrix;
  33467. uniform mat4 modelViewMatrix;
  33468. uniform mat4 projectionMatrix;
  33469. uniform mat4 viewMatrix;
  33470. uniform mat4 uViewInv;
  33471. //uniform float uScreenWidth;
  33472. //uniform float uScreenHeight;
  33473. uniform vec2 resolution;
  33474. uniform float fov;
  33475. uniform float near;
  33476. uniform float far;
  33477. uniform bool uDebug;
  33478. uniform bool uUseOrthographicCamera;
  33479. uniform float uOrthoWidth;
  33480. uniform float uOrthoHeight;
  33481. #define CLIPTASK_NONE 0
  33482. #define CLIPTASK_HIGHLIGHT 1
  33483. #define CLIPTASK_SHOW_INSIDE 2
  33484. #define CLIPTASK_SHOW_OUTSIDE 3
  33485. #define CLIPMETHOD_INSIDE_ANY 0
  33486. #define CLIPMETHOD_INSIDE_ALL 1
  33487. uniform int clipTask;
  33488. uniform int clipMethod;
  33489. #if defined(num_clipboxes) && num_clipboxes > 0
  33490. uniform mat4 clipBoxes[num_clipboxes];
  33491. #endif
  33492. #if defined(num_clipspheres) && num_clipspheres > 0
  33493. uniform mat4 uClipSpheres[num_clipspheres];
  33494. #endif
  33495. #if defined(num_clippolygons) && num_clippolygons > 0
  33496. uniform int uClipPolygonVCount[num_clippolygons];
  33497. uniform vec3 uClipPolygonVertices[num_clippolygons * 8];
  33498. uniform mat4 uClipPolygonWVP[num_clippolygons];
  33499. #endif
  33500. uniform float size;
  33501. uniform float minSize;
  33502. uniform float maxSize;
  33503. uniform float uPCIndex;
  33504. uniform float uOctreeSpacing;
  33505. uniform float uNodeSpacing;
  33506. uniform float uOctreeSize;
  33507. uniform vec3 uBBSize;
  33508. uniform float uLevel;
  33509. uniform float uVNStart;
  33510. uniform bool uIsLeafNode;
  33511. uniform vec3 uColor;
  33512. uniform float uOpacity;
  33513. varying float vOpacity; //add
  33514. uniform vec2 elevationRange;
  33515. uniform vec2 intensityRange;
  33516. uniform vec2 uFilterReturnNumberRange;
  33517. uniform vec2 uFilterNumberOfReturnsRange;
  33518. uniform vec2 uFilterPointSourceIDClipRange;
  33519. uniform vec2 uFilterGPSTimeClipRange;
  33520. //uniform float ufilterByNormalThreshold;
  33521. uniform float uGpsScale;
  33522. uniform float uGpsOffset;
  33523. uniform vec2 uNormalizedGpsBufferRange;
  33524. uniform vec3 uIntensity_gbc;
  33525. uniform vec3 uRGB_gbc;
  33526. uniform vec3 uExtra_gbc;
  33527. uniform float uTransition;
  33528. uniform float wRGB;
  33529. uniform float wIntensity;
  33530. uniform float wElevation;
  33531. uniform float wClassification;
  33532. uniform float wReturnNumber;
  33533. uniform float wSourceID;
  33534. uniform vec2 uExtraNormalizedRange;
  33535. uniform vec2 uExtraRange;
  33536. uniform float uExtraScale;
  33537. uniform float uExtraOffset;
  33538. uniform vec3 uShadowColor;
  33539. uniform sampler2D visibleNodes;
  33540. uniform sampler2D gradient;
  33541. uniform sampler2D classificationLUT;
  33542. #if defined(color_type_matcap)
  33543. uniform sampler2D matcapTextureUniform;
  33544. #endif
  33545. uniform bool backfaceCulling;
  33546. #if defined(num_shadowmaps) && num_shadowmaps > 0
  33547. uniform sampler2D uShadowMap[num_shadowmaps];
  33548. uniform mat4 uShadowWorldView[num_shadowmaps];
  33549. uniform mat4 uShadowProj[num_shadowmaps];
  33550. #endif
  33551. varying vec3 vColor;
  33552. varying float vLogDepth;
  33553. varying vec3 vViewPosition;
  33554. varying float vRadius;
  33555. varying float vPointSize;
  33556. float round(float number){
  33557. return floor(number + 0.5);
  33558. }
  33559. //
  33560. // ### ######## ### ######## ######## #### ## ## ######## ###### #### ######## ######## ######
  33561. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33562. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33563. // ## ## ## ## ## ## ######## ## ## ## ## ###### ###### ## ## ###### ######
  33564. // ######### ## ## ######### ## ## ## ## ## ## ## ## ## ## ##
  33565. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33566. // ## ## ######## ## ## ## ## #### ### ######## ###### #### ######## ######## ######
  33567. //
  33568. // ---------------------
  33569. // OCTREE
  33570. // ---------------------
  33571. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_octree)
  33572. /**
  33573. * number of 1-bits up to inclusive index position
  33574. * number is treated as if it were an integer in the range 0-255
  33575. *
  33576. */
  33577. int numberOfOnes(int number, int index){
  33578. int numOnes = 0;
  33579. int tmp = 128;
  33580. for(int i = 7; i >= 0; i--){
  33581. if(number >= tmp){
  33582. number = number - tmp;
  33583. if(i <= index){
  33584. numOnes++;
  33585. }
  33586. }
  33587. tmp = tmp / 2;
  33588. }
  33589. return numOnes;
  33590. }
  33591. /**
  33592. * checks whether the bit at index is 1
  33593. * number is treated as if it were an integer in the range 0-255
  33594. *
  33595. */
  33596. bool isBitSet(int number, int index){
  33597. // weird multi else if due to lack of proper array, int and bitwise support in WebGL 1.0
  33598. int powi = 1;
  33599. if(index == 0){
  33600. powi = 1;
  33601. }else if(index == 1){
  33602. powi = 2;
  33603. }else if(index == 2){
  33604. powi = 4;
  33605. }else if(index == 3){
  33606. powi = 8;
  33607. }else if(index == 4){
  33608. powi = 16;
  33609. }else if(index == 5){
  33610. powi = 32;
  33611. }else if(index == 6){
  33612. powi = 64;
  33613. }else if(index == 7){
  33614. powi = 128;
  33615. }else{
  33616. return false;
  33617. }
  33618. int ndp = number / powi;
  33619. return mod(float(ndp), 2.0) != 0.0;
  33620. }
  33621. /**
  33622. * find the LOD at the point position
  33623. */
  33624. float getLOD(){//////
  33625. vec3 offset = vec3(0.0, 0.0, 0.0);
  33626. int iOffset = int(uVNStart);
  33627. float depth = uLevel;
  33628. for(float i = 0.0; i <= 30.0; i++){
  33629. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  33630. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  33631. index3d = floor(index3d + 0.5);
  33632. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  33633. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  33634. int mask = int(round(value.r * 255.0));
  33635. if(isBitSet(mask, index)){
  33636. // there are more visible child nodes at this position
  33637. int advanceG = int(round(value.g * 255.0)) * 256;
  33638. int advanceB = int(round(value.b * 255.0));
  33639. int advanceChild = numberOfOnes(mask, index - 1);
  33640. int advance = advanceG + advanceB + advanceChild;
  33641. iOffset = iOffset + advance;
  33642. depth++;
  33643. }else{
  33644. // no more visible child nodes at this position
  33645. //return value.a * 255.0;
  33646. float lodOffset = (255.0 * value.a) / 10.0 - 10.0;
  33647. return depth + lodOffset;
  33648. }
  33649. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  33650. }
  33651. return depth;
  33652. }
  33653. float getSpacing(){
  33654. vec3 offset = vec3(0.0, 0.0, 0.0);
  33655. int iOffset = int(uVNStart);
  33656. float depth = uLevel;
  33657. float spacing = uNodeSpacing;
  33658. for(float i = 0.0; i <= 30.0; i++){
  33659. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  33660. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  33661. index3d = floor(index3d + 0.5);
  33662. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  33663. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  33664. int mask = int(round(value.r * 255.0));
  33665. float spacingFactor = value.a;
  33666. if(i > 0.0){
  33667. spacing = spacing / (255.0 * spacingFactor);
  33668. }
  33669. if(isBitSet(mask, index)){
  33670. // there are more visible child nodes at this position
  33671. int advanceG = int(round(value.g * 255.0)) * 256;
  33672. int advanceB = int(round(value.b * 255.0));
  33673. int advanceChild = numberOfOnes(mask, index - 1);
  33674. int advance = advanceG + advanceB + advanceChild;
  33675. iOffset = iOffset + advance;
  33676. //spacing = spacing / (255.0 * spacingFactor);
  33677. //spacing = spacing / 3.0;
  33678. depth++;
  33679. }else{
  33680. // no more visible child nodes at this position
  33681. return spacing;
  33682. }
  33683. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  33684. }
  33685. return spacing;
  33686. }
  33687. float getPointSizeAttenuation(){
  33688. return pow(2.0, getLOD());
  33689. }
  33690. #endif
  33691. // ---------------------
  33692. // KD-TREE
  33693. // ---------------------
  33694. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_kdtree)
  33695. float getLOD(){
  33696. vec3 offset = vec3(0.0, 0.0, 0.0);
  33697. float iOffset = 0.0;
  33698. float depth = 0.0;
  33699. vec3 size = uBBSize;
  33700. vec3 pos = position;
  33701. for(float i = 0.0; i <= 1000.0; i++){
  33702. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  33703. int children = int(value.r * 255.0);
  33704. float next = value.g * 255.0;
  33705. int split = int(value.b * 255.0);
  33706. if(next == 0.0){
  33707. return depth;
  33708. }
  33709. vec3 splitv = vec3(0.0, 0.0, 0.0);
  33710. if(split == 1){
  33711. splitv.x = 1.0;
  33712. }else if(split == 2){
  33713. splitv.y = 1.0;
  33714. }else if(split == 4){
  33715. splitv.z = 1.0;
  33716. }
  33717. iOffset = iOffset + next;
  33718. float factor = length(pos * splitv / size);
  33719. if(factor < 0.5){
  33720. // left
  33721. if(children == 0 || children == 2){
  33722. return depth;
  33723. }
  33724. }else{
  33725. // right
  33726. pos = pos - size * splitv * 0.5;
  33727. if(children == 0 || children == 1){
  33728. return depth;
  33729. }
  33730. if(children == 3){
  33731. iOffset = iOffset + 1.0;
  33732. }
  33733. }
  33734. size = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);
  33735. depth++;
  33736. }
  33737. return depth;
  33738. }
  33739. float getPointSizeAttenuation(){
  33740. return 0.5 * pow(1.3, getLOD());
  33741. }
  33742. #endif
  33743. //
  33744. // ### ######## ######## ######## #### ######## ## ## ######## ######## ######
  33745. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33746. // ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33747. // ## ## ## ## ######## ## ######## ## ## ## ###### ######
  33748. // ######### ## ## ## ## ## ## ## ## ## ## ## ##
  33749. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33750. // ## ## ## ## ## ## #### ######## ####### ## ######## ######
  33751. //
  33752. // formula adapted from: http://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/
  33753. float getContrastFactor(float contrast){
  33754. return (1.0158730158730156 * (contrast + 1.0)) / (1.0158730158730156 - contrast);
  33755. }
  33756. vec3 getRGB(){
  33757. vec3 rgb = color;
  33758. rgb = pow(rgb, vec3(uRGB_gbc.x));
  33759. rgb = rgb + uRGB_gbc.y;
  33760. rgb = (rgb - 0.5) * getContrastFactor(uRGB_gbc.z) + 0.5;
  33761. rgb = clamp(rgb, 0.0, 1.0);
  33762. return rgb;
  33763. }
  33764. float getIntensity(){
  33765. float w = (intensity - intensityRange.x) / (intensityRange.y - intensityRange.x);
  33766. w = pow(w, uIntensity_gbc.x);
  33767. w = w + uIntensity_gbc.y;
  33768. w = (w - 0.5) * getContrastFactor(uIntensity_gbc.z) + 0.5;
  33769. w = clamp(w, 0.0, 1.0);
  33770. return w;
  33771. }
  33772. vec3 getGpsTime(){
  33773. float w = (gpsTime + uGpsOffset) * uGpsScale;
  33774. vec3 c = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  33775. // vec2 r = uNormalizedGpsBufferRange;
  33776. // float w = gpsTime * (r.y - r.x) + r.x;
  33777. // w = clamp(w, 0.0, 1.0);
  33778. // vec3 c = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33779. return c;
  33780. }
  33781. vec3 getElevation(){
  33782. vec4 world = modelMatrix * vec4( position, 1.0 );
  33783. float w = (world.z - elevationRange.x) / (elevationRange.y - elevationRange.x);
  33784. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33785. return cElevation;
  33786. }
  33787. vec4 getClassification(){
  33788. vec2 uv = vec2(classification / 255.0, 0.5);
  33789. vec4 classColor = texture2D(classificationLUT, uv);
  33790. return classColor;
  33791. }
  33792. vec3 getReturns(){
  33793. // 0b 00_000_111
  33794. float rn = mod(returnNumber, 8.0);
  33795. // 0b 00_111_000
  33796. float nr = mod(returnNumber / 8.0, 8.0);
  33797. if(nr <= 1.0){
  33798. return vec3(1.0, 0.0, 0.0);
  33799. }else{
  33800. return vec3(0.0, 1.0, 0.0);
  33801. }
  33802. // return vec3(nr / 4.0, 0.0, 0.0);
  33803. // if(nr == 1.0){
  33804. // return vec3(1.0, 1.0, 0.0);
  33805. // }else{
  33806. // if(rn == 1.0){
  33807. // return vec3(1.0, 0.0, 0.0);
  33808. // }else if(rn == nr){
  33809. // return vec3(0.0, 0.0, 1.0);
  33810. // }else{
  33811. // return vec3(0.0, 1.0, 0.0);
  33812. // }
  33813. // }
  33814. // if(numberOfReturns == 1.0){
  33815. // return vec3(1.0, 1.0, 0.0);
  33816. // }else{
  33817. // if(returnNumber == 1.0){
  33818. // return vec3(1.0, 0.0, 0.0);
  33819. // }else if(returnNumber == numberOfReturns){
  33820. // return vec3(0.0, 0.0, 1.0);
  33821. // }else{
  33822. // return vec3(0.0, 1.0, 0.0);
  33823. // }
  33824. // }
  33825. }
  33826. vec3 getReturnNumber(){
  33827. if(numberOfReturns == 1.0){
  33828. return vec3(1.0, 1.0, 0.0);
  33829. }else{
  33830. if(returnNumber == 1.0){
  33831. return vec3(1.0, 0.0, 0.0);
  33832. }else if(returnNumber == numberOfReturns){
  33833. return vec3(0.0, 0.0, 1.0);
  33834. }else{
  33835. return vec3(0.0, 1.0, 0.0);
  33836. }
  33837. }
  33838. }
  33839. vec3 getNumberOfReturns(){
  33840. float value = numberOfReturns;
  33841. float w = value / 6.0;
  33842. vec3 color = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  33843. return color;
  33844. }
  33845. vec3 getSourceID(){
  33846. float w = mod(pointSourceID, 10.0) / 10.0;
  33847. return texture2D(gradient, vec2(w,1.0 - w)).rgb;
  33848. }
  33849. vec3 getCompositeColor(){
  33850. vec3 c;
  33851. float w;
  33852. c += wRGB * getRGB();
  33853. w += wRGB;
  33854. c += wIntensity * getIntensity() * vec3(1.0, 1.0, 1.0);
  33855. w += wIntensity;
  33856. c += wElevation * getElevation();
  33857. w += wElevation;
  33858. c += wReturnNumber * getReturnNumber();
  33859. w += wReturnNumber;
  33860. c += wSourceID * getSourceID();
  33861. w += wSourceID;
  33862. vec4 cl = wClassification * getClassification();
  33863. c += cl.a * cl.rgb;
  33864. w += wClassification * cl.a;
  33865. c = c / w;
  33866. if(w == 0.0){
  33867. //c = color;
  33868. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  33869. }
  33870. return c;
  33871. }
  33872. vec3 getNormal(){
  33873. //vec3 n_hsv = vec3( modelMatrix * vec4( normal, 0.0 )) * 0.5 + 0.5; // (n_world.xyz + vec3(1.,1.,1.)) / 2.;
  33874. vec3 n_view = normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  33875. return n_view;
  33876. }
  33877. bool applyBackfaceCulling() {
  33878. // Black not facing vertices / Backface culling
  33879. vec3 e = normalize(vec3(modelViewMatrix * vec4( position, 1. )));
  33880. vec3 n = getNormal(); // normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  33881. if((uUseOrthographicCamera && n.z <= 0.) || (!uUseOrthographicCamera && dot( n, e ) >= 0.)) {
  33882. return true;
  33883. } else {
  33884. return false;
  33885. }
  33886. }
  33887. #if defined(color_type_matcap)
  33888. // Matcap Material
  33889. vec3 getMatcap(){
  33890. vec3 eye = normalize( vec3( modelViewMatrix * vec4( position, 1. ) ) );
  33891. if(uUseOrthographicCamera) {
  33892. eye = vec3(0., 0., -1.);
  33893. }
  33894. vec3 r_en = reflect( eye, getNormal() ); // or r_en = e - 2. * dot( n, e ) * n;
  33895. float m = 2. * sqrt(pow( r_en.x, 2. ) + pow( r_en.y, 2. ) + pow( r_en.z + 1., 2. ));
  33896. vec2 vN = r_en.xy / m + .5;
  33897. return texture2D(matcapTextureUniform, vN).rgb;
  33898. }
  33899. #endif
  33900. vec3 getExtra(){
  33901. float w = (aExtra + uExtraOffset) * uExtraScale;
  33902. w = clamp(w, 0.0, 1.0);
  33903. vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33904. // vec2 r = uExtraNormalizedRange;
  33905. // float w = aExtra * (r.y - r.x) + r.x;
  33906. // w = (w - uExtraRange.x) / (uExtraRange.y - uExtraRange.x);
  33907. // w = clamp(w, 0.0, 1.0);
  33908. // vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33909. return color;
  33910. }
  33911. vec3 getColor(){
  33912. vec3 color;
  33913. #ifdef color_type_rgba
  33914. color = getRGB();
  33915. #elif defined color_type_height || defined color_type_elevation
  33916. color = getElevation();
  33917. #elif defined color_type_rgb_height
  33918. vec3 cHeight = getElevation();
  33919. color = (1.0 - uTransition) * getRGB() + uTransition * cHeight;
  33920. #elif defined color_type_depth
  33921. float linearDepth = gl_Position.w;
  33922. float expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;
  33923. color = vec3(linearDepth, expDepth, 0.0);
  33924. //color = vec3(1.0, 0.5, 0.3);
  33925. #elif defined color_type_intensity
  33926. float w = getIntensity();
  33927. color = vec3(w, w, w);
  33928. #elif defined color_type_gps_time
  33929. color = getGpsTime();
  33930. #elif defined color_type_intensity_gradient
  33931. float w = getIntensity();
  33932. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33933. #elif defined color_type_color
  33934. color = uColor;
  33935. #elif defined color_type_level_of_detail
  33936. float depth = getLOD();
  33937. float w = depth / 10.0;
  33938. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33939. #elif defined color_type_indices
  33940. color = indices.rgb;
  33941. #elif defined color_type_classification
  33942. vec4 cl = getClassification();
  33943. color = cl.rgb;
  33944. #elif defined color_type_return_number
  33945. color = getReturnNumber();
  33946. #elif defined color_type_returns
  33947. color = getReturns();
  33948. #elif defined color_type_number_of_returns
  33949. color = getNumberOfReturns();
  33950. #elif defined color_type_source_id
  33951. color = getSourceID();
  33952. #elif defined color_type_point_source_id
  33953. color = getSourceID();
  33954. #elif defined color_type_normal
  33955. color = (modelMatrix * vec4(normal, 0.0)).xyz;
  33956. #elif defined color_type_phong
  33957. color = color;
  33958. #elif defined color_type_composite
  33959. color = getCompositeColor();
  33960. #elif defined color_type_matcap
  33961. color = getMatcap();
  33962. #else
  33963. color = getExtra();
  33964. #endif
  33965. if (backfaceCulling && applyBackfaceCulling()){
  33966. //color = vec3(0.);
  33967. }
  33968. //applyBackfaceCulling直接返回false或者注释color = vec3(0.);都没问题
  33969. return color;
  33970. }
  33971. float getPointSize(){
  33972. float pointSize = 1.0;
  33973. float slope = tan(fov / 2.0);
  33974. float projFactor = -0.5 * resolution.y / (slope * vViewPosition.z);
  33975. /*
  33976. float scale = length(
  33977. modelViewMatrix * vec4(0, 0, 0, 1) -
  33978. modelViewMatrix * vec4(uOctreeSpacing, 0, 0, 1)
  33979. ) / uOctreeSpacing;
  33980. projFactor = projFactor * scale;
  33981. */
  33982. float r = uOctreeSpacing * 1.7;
  33983. //vRadius = r;
  33984. #if defined fixed_point_size
  33985. pointSize = size;
  33986. #elif defined attenuated_point_size
  33987. if(uUseOrthographicCamera){
  33988. pointSize = size * 10.0; //加个乘数
  33989. }else{ //近大远小,模拟真实mesh,边缘放大
  33990. //pointSize = size * spacing * projFactor; //spacing是attribute 为空 如果有这个值就能更自适应填补
  33991. //pointSize = size * uOctreeSpacing * projFactor / 18.0; //直接用cloud的spacing里,不过因为都一样所以可能没有什么意义
  33992. //pointSize = pointSize * projFactor;
  33993. pointSize = size * projFactor ;
  33994. }
  33995. #elif defined adaptive_point_size
  33996. if(uUseOrthographicCamera) {
  33997. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  33998. pointSize = (worldSpaceSize / uOrthoWidth) * resolution.x; //uScreenWidth;
  33999. } else {
  34000. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  34001. pointSize = worldSpaceSize * projFactor;
  34002. }
  34003. #endif
  34004. pointSize = max(minSize, pointSize);
  34005. pointSize = min(maxSize, pointSize);
  34006. vRadius = pointSize / projFactor;
  34007. return pointSize;
  34008. }
  34009. #if defined(num_clippolygons) && num_clippolygons > 0
  34010. bool pointInClipPolygon(vec3 point, int polyIdx) {
  34011. mat4 wvp = uClipPolygonWVP[polyIdx];
  34012. //vec4 screenClipPos = uClipPolygonVP[polyIdx] * modelMatrix * vec4(point, 1.0);
  34013. //screenClipPos.xy = screenClipPos.xy / screenClipPos.w * 0.5 + 0.5;
  34014. vec4 pointNDC = wvp * vec4(point, 1.0);
  34015. pointNDC.xy = pointNDC.xy / pointNDC.w;
  34016. int j = uClipPolygonVCount[polyIdx] - 1;
  34017. bool c = false;
  34018. for(int i = 0; i < 8; i++) {
  34019. if(i == uClipPolygonVCount[polyIdx]) {
  34020. break;
  34021. }
  34022. //vec4 verti = wvp * vec4(uClipPolygonVertices[polyIdx * 8 + i], 1);
  34023. //vec4 vertj = wvp * vec4(uClipPolygonVertices[polyIdx * 8 + j], 1);
  34024. //verti.xy = verti.xy / verti.w;
  34025. //vertj.xy = vertj.xy / vertj.w;
  34026. //verti.xy = verti.xy / verti.w * 0.5 + 0.5;
  34027. //vertj.xy = vertj.xy / vertj.w * 0.5 + 0.5;
  34028. vec3 verti = uClipPolygonVertices[polyIdx * 8 + i];
  34029. vec3 vertj = uClipPolygonVertices[polyIdx * 8 + j];
  34030. if( ((verti.y > pointNDC.y) != (vertj.y > pointNDC.y)) &&
  34031. (pointNDC.x < (vertj.x-verti.x) * (pointNDC.y-verti.y) / (vertj.y-verti.y) + verti.x) ) {
  34032. c = !c;
  34033. }
  34034. j = i;
  34035. }
  34036. return c;
  34037. }
  34038. #endif
  34039. void doClipping(){
  34040. {
  34041. vec4 cl = getClassification();
  34042. if(cl.a == 0.0){
  34043. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34044. return;
  34045. }
  34046. }
  34047. #if defined(clip_return_number_enabled)
  34048. { // return number filter
  34049. vec2 range = uFilterReturnNumberRange;
  34050. if(returnNumber < range.x || returnNumber > range.y){
  34051. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34052. return;
  34053. }
  34054. }
  34055. #endif
  34056. #if defined(clip_number_of_returns_enabled)
  34057. { // number of return filter
  34058. vec2 range = uFilterNumberOfReturnsRange;
  34059. if(numberOfReturns < range.x || numberOfReturns > range.y){
  34060. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34061. return;
  34062. }
  34063. }
  34064. #endif
  34065. #if defined(clip_gps_enabled)
  34066. { // GPS time filter
  34067. float time = (gpsTime + uGpsOffset) * uGpsScale;
  34068. vec2 range = uFilterGPSTimeClipRange;
  34069. if(time < range.x || time > range.y){
  34070. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34071. return;
  34072. }
  34073. }
  34074. #endif
  34075. #if defined(clip_point_source_id_enabled)
  34076. { // point source id filter
  34077. vec2 range = uFilterPointSourceIDClipRange;
  34078. if(pointSourceID < range.x || pointSourceID > range.y){
  34079. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34080. return;
  34081. }
  34082. }
  34083. #endif
  34084. int clipVolumesCount = 0;
  34085. int insideCount = 0;
  34086. #if defined(num_clipboxes) && num_clipboxes > 0
  34087. for(int i = 0; i < num_clipboxes; i++){
  34088. vec4 clipPosition = clipBoxes[i] * modelMatrix * vec4( position, 1.0 );
  34089. bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;
  34090. inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;
  34091. inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;
  34092. insideCount = insideCount + (inside ? 1 : 0);
  34093. clipVolumesCount++;
  34094. }
  34095. #endif
  34096. #if defined(num_clippolygons) && num_clippolygons > 0
  34097. for(int i = 0; i < num_clippolygons; i++) {
  34098. bool inside = pointInClipPolygon(position, i);
  34099. insideCount = insideCount + (inside ? 1 : 0);
  34100. clipVolumesCount++;
  34101. }
  34102. #endif
  34103. bool insideAny = insideCount > 0;
  34104. bool insideAll = (clipVolumesCount > 0) && (clipVolumesCount == insideCount);
  34105. if(clipMethod == CLIPMETHOD_INSIDE_ANY){
  34106. if(insideAny && clipTask == CLIPTASK_HIGHLIGHT){
  34107. vColor.r += 0.5;
  34108. }else if(!insideAny && clipTask == CLIPTASK_SHOW_INSIDE){
  34109. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34110. }else if(insideAny && clipTask == CLIPTASK_SHOW_OUTSIDE){
  34111. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34112. }
  34113. }else if(clipMethod == CLIPMETHOD_INSIDE_ALL){
  34114. if(insideAll && clipTask == CLIPTASK_HIGHLIGHT){
  34115. vColor.r += 0.5;
  34116. }else if(!insideAll && clipTask == CLIPTASK_SHOW_INSIDE){
  34117. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34118. }else if(insideAll && clipTask == CLIPTASK_SHOW_OUTSIDE){
  34119. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34120. }
  34121. }
  34122. }
  34123. //
  34124. // ## ## ### #### ## ##
  34125. // ### ### ## ## ## ### ##
  34126. // #### #### ## ## ## #### ##
  34127. // ## ### ## ## ## ## ## ## ##
  34128. // ## ## ######### ## ## ####
  34129. // ## ## ## ## ## ## ###
  34130. // ## ## ## ## #### ## ##
  34131. //
  34132. vec2 getSamplerCoord( vec3 direction )
  34133. {
  34134. direction = normalize(direction);
  34135. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  34136. float ty=acos(direction.z)/PI;
  34137. return vec2(tx,ty);
  34138. }
  34139. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  34140. {
  34141. float y = direction.y;
  34142. direction.y = direction.z;
  34143. direction.z = -y;
  34144. return direction;
  34145. }
  34146. void main() {
  34147. //bool filtered_by_normal = false;
  34148. float normalZ = 0.0;
  34149. #ifdef use_filter_by_normal
  34150. /*if(abs(getNormal().z) > 0.4) { //ufilterByNormalThreshold 暂定 3
  34151. // Move point outside clip space space to discard it.
  34152. //gl_Position = vec4(0.0, 0.0, 2.0, 1.0); //gl_Position的可视区域是 x,y,z都是[-1,1]
  34153. //return;
  34154. //filtered_by_normal = true; //标记一下。不直接不绘制,因为有的法线都是垂直向上
  34155. }*/
  34156. normalZ = abs(getNormal().z);
  34157. #endif
  34158. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 );
  34159. vViewPosition = mvPosition.xyz;
  34160. gl_Position = projectionMatrix * mvPosition;
  34161. vLogDepth = log2(-mvPosition.z);
  34162. // COLOR
  34163. //加-------------------
  34164. #if defined(usePanoMap)
  34165. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  34166. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  34167. vec3 vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  34168. vWorldPosition0.x *= -1.0;
  34169. vWorldPosition0 = transformAxis(vWorldPosition0);
  34170. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  34171. vec3 vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  34172. vWorldPosition1.x *= -1.0;
  34173. vWorldPosition1 = transformAxis(vWorldPosition1);
  34174. /*
  34175. vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  34176. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  34177. vec4 colorFromPano0 = texture2D(pano0Map,samplerCoord0);
  34178. vec4 colorFromPano1 = texture2D(pano1Map,samplerCoord1);
  34179. */
  34180. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  34181. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  34182. vColor = mix(colorFromPano0,colorFromPano1,progress).xyz;
  34183. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  34184. if(progress < easeInOutRatio){
  34185. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  34186. vec3 vColor1 = getColor();
  34187. vColor = mix(vColor,vColor1,easeProgress);
  34188. }else if(progress > 1.0 - easeInOutRatio){
  34189. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  34190. vec3 vColor1 = getColor();
  34191. vColor = mix(vColor,vColor1,easeProgress);
  34192. }
  34193. #else
  34194. vColor = getColor();
  34195. #endif
  34196. //-------------------
  34197. #ifdef attenuated_opacity
  34198. //zoom不会改变z 所以这并不是用在分屏时候的
  34199. //vOpacity = uOpacity * exp(-length(-mvPosition.xyz) / 1000.0); // e为底的指数函数 opacityAttenuation = 1000
  34200. vOpacity = uOpacity * exp(gl_Position.z/50.0);
  34201. vOpacity = clamp(vOpacity, 0.001, 1.0);
  34202. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34203. vOpacity *= 0.2;
  34204. vOpacity = clamp(vOpacity, 0.0001, 0.1);
  34205. } */
  34206. #else
  34207. vOpacity = uOpacity;
  34208. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34209. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34210. vOpacity *= 0.3;
  34211. vOpacity = clamp(vOpacity, 0.0001, 0.1);
  34212. }*/
  34213. vOpacity *= max(0.1, (1.0 - normalZ));
  34214. #endif
  34215. // POINT SIZE
  34216. float pointSize = getPointSize();
  34217. gl_PointSize = pointSize;
  34218. vPointSize = pointSize;
  34219. // only for "replacing" approaches
  34220. // if(getLOD() != uLevel){
  34221. // gl_Position = vec4(10.0, 10.0, 10.0, 1.0);
  34222. // }
  34223. #if defined hq_depth_pass
  34224. float originalDepth = gl_Position.w;
  34225. float adjustedDepth = originalDepth + 2.0 * vRadius;
  34226. float adjust = adjustedDepth / originalDepth;
  34227. mvPosition.xyz = mvPosition.xyz * adjust;
  34228. gl_Position = projectionMatrix * mvPosition;
  34229. #endif
  34230. // CLIPPING
  34231. doClipping();
  34232. #if defined(num_clipspheres) && num_clipspheres > 0
  34233. for(int i = 0; i < num_clipspheres; i++){
  34234. vec4 sphereLocal = uClipSpheres[i] * mvPosition;
  34235. float distance = length(sphereLocal.xyz);
  34236. if(distance < 1.0){
  34237. float w = distance;
  34238. vec3 cGradient = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  34239. vColor = cGradient;
  34240. //vColor = cGradient * 0.7 + vColor * 0.3;
  34241. }
  34242. }
  34243. #endif
  34244. #if defined(num_shadowmaps) && num_shadowmaps > 0
  34245. const float sm_near = 0.1;
  34246. const float sm_far = 10000.0;
  34247. for(int i = 0; i < num_shadowmaps; i++){
  34248. vec3 viewPos = (uShadowWorldView[i] * vec4(position, 1.0)).xyz;
  34249. float distanceToLight = abs(viewPos.z);
  34250. vec4 projPos = uShadowProj[i] * uShadowWorldView[i] * vec4(position, 1);
  34251. vec3 nc = projPos.xyz / projPos.w;
  34252. float u = nc.x * 0.5 + 0.5;
  34253. float v = nc.y * 0.5 + 0.5;
  34254. vec2 sampleStep = vec2(1.0 / (2.0*1024.0), 1.0 / (2.0*1024.0)) * 1.5;
  34255. vec2 sampleLocations[9];
  34256. sampleLocations[0] = vec2(0.0, 0.0);
  34257. sampleLocations[1] = sampleStep;
  34258. sampleLocations[2] = -sampleStep;
  34259. sampleLocations[3] = vec2(sampleStep.x, -sampleStep.y);
  34260. sampleLocations[4] = vec2(-sampleStep.x, sampleStep.y);
  34261. sampleLocations[5] = vec2(0.0, sampleStep.y);
  34262. sampleLocations[6] = vec2(0.0, -sampleStep.y);
  34263. sampleLocations[7] = vec2(sampleStep.x, 0.0);
  34264. sampleLocations[8] = vec2(-sampleStep.x, 0.0);
  34265. float visibleSamples = 0.0;
  34266. float numSamples = 0.0;
  34267. float bias = vRadius * 2.0;
  34268. for(int j = 0; j < 9; j++){
  34269. vec4 depthMapValue = texture2D(uShadowMap[i], vec2(u, v) + sampleLocations[j]);
  34270. float linearDepthFromSM = depthMapValue.x + bias;
  34271. float linearDepthFromViewer = distanceToLight;
  34272. if(linearDepthFromSM > linearDepthFromViewer){
  34273. visibleSamples += 1.0;
  34274. }
  34275. numSamples += 1.0;
  34276. }
  34277. float visibility = visibleSamples / numSamples;
  34278. if(u < 0.0 || u > 1.0 || v < 0.0 || v > 1.0 || nc.x < -1.0 || nc.x > 1.0 || nc.y < -1.0 || nc.y > 1.0 || nc.z < -1.0 || nc.z > 1.0){
  34279. //vColor = vec3(0.0, 0.0, 0.2);
  34280. }else{
  34281. //vColor = vec3(1.0, 1.0, 1.0) * visibility + vec3(1.0, 1.0, 1.0) * vec3(0.5, 0.0, 0.0) * (1.0 - visibility);
  34282. vColor = vColor * visibility + vColor * uShadowColor * (1.0 - visibility);
  34283. }
  34284. }
  34285. #endif
  34286. }
  34287. `;
  34288. Shaders["pointcloud.fs"] = `
  34289. #if defined paraboloid_point_shape
  34290. #extension GL_EXT_frag_depth : enable
  34291. #endif
  34292. #define PI 3.141592653589793
  34293. precision highp float;
  34294. precision highp int;
  34295. /*
  34296. #if defined(usePanoMap)
  34297. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  34298. uniform samplerCube pano1Map;
  34299. uniform float progress;
  34300. uniform float easeInOutRatio;
  34301. uniform vec3 pano0Position;
  34302. uniform mat4 pano0Matrix;
  34303. uniform vec3 pano1Position;
  34304. uniform mat4 pano1Matrix;
  34305. varying vec3 vWorldPosition0;
  34306. varying vec3 vWorldPosition1;
  34307. #endif
  34308. */
  34309. //------------
  34310. uniform mat4 viewMatrix;
  34311. uniform mat4 uViewInv;
  34312. uniform mat4 uProjInv;
  34313. uniform vec3 cameraPosition;
  34314. uniform mat4 projectionMatrix;
  34315. //uniform float uOpacity;
  34316. varying float vOpacity; //add
  34317. uniform float blendHardness;
  34318. uniform float blendDepthSupplement;
  34319. uniform float fov;
  34320. uniform float uSpacing;
  34321. uniform float near;
  34322. uniform float far;
  34323. uniform float uPCIndex;
  34324. uniform float uScreenWidth;
  34325. uniform float uScreenHeight;
  34326. varying vec3 vColor;
  34327. varying float vLogDepth;
  34328. varying vec3 vViewPosition;
  34329. varying float vRadius;
  34330. varying float vPointSize;
  34331. varying vec3 vPosition;
  34332. float specularStrength = 1.0;
  34333. vec2 getSamplerCoord( vec3 direction )
  34334. {
  34335. direction = normalize(direction);
  34336. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  34337. float ty=acos(direction.z)/PI;
  34338. return vec2(tx,ty);
  34339. }
  34340. void main() {
  34341. vec3 color = vColor;
  34342. /*#if defined(usePanoMap) //加 经测试,即使全部写在fragment里也是无论pointsize多大都是一个点一个颜色,所以干脆写在vectex里
  34343. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  34344. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  34345. color = mix(colorFromPano0,colorFromPano1,progress).xyz;
  34346. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  34347. if(progress < easeInOutRatio){
  34348. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  34349. color = mix(color,vColor,easeProgress);
  34350. }else if(progress > 1.0 - easeInOutRatio){
  34351. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  34352. color = mix(color,vColor,easeProgress);
  34353. }
  34354. #else
  34355. color = vColor;
  34356. #endif*/
  34357. float depth = gl_FragCoord.z;
  34358. #if defined(circle_point_shape) || defined(paraboloid_point_shape)
  34359. float u = 2.0 * gl_PointCoord.x - 1.0;
  34360. float v = 2.0 * gl_PointCoord.y - 1.0;
  34361. #endif
  34362. #if defined(circle_point_shape)
  34363. float cc = u*u + v*v;
  34364. if(cc > 1.0){
  34365. discard;
  34366. }
  34367. #endif
  34368. #if defined color_type_indices //pick point recognize
  34369. gl_FragColor = vec4(color, uPCIndex / 255.0); //uPCIndex : node Index
  34370. #else
  34371. gl_FragColor = vec4(color, vOpacity);
  34372. #endif
  34373. #if defined paraboloid_point_shape
  34374. float wi = 0.0 - ( u*u + v*v);
  34375. vec4 pos = vec4(vViewPosition, 1.0);
  34376. pos.z += wi * vRadius;
  34377. float linearDepth = -pos.z;
  34378. pos = projectionMatrix * pos;
  34379. pos = pos / pos.w;
  34380. float expDepth = pos.z;
  34381. depth = (pos.z + 1.0) / 2.0;
  34382. gl_FragDepthEXT = depth;
  34383. #if defined(color_type_depth)
  34384. color.r = linearDepth;
  34385. color.g = expDepth;
  34386. #endif
  34387. #if defined(use_edl)
  34388. gl_FragColor.a = log2(linearDepth);
  34389. #endif
  34390. #else
  34391. #if defined(use_edl)
  34392. gl_FragColor.a = vLogDepth;
  34393. #endif
  34394. #endif
  34395. #if defined(weighted_splats)
  34396. float distance = 2.0 * length(gl_PointCoord.xy - 0.5);
  34397. float weight = max(0.0, 1.0 - distance);
  34398. weight = pow(weight, 1.5);
  34399. gl_FragColor.a = weight;
  34400. gl_FragColor.xyz = gl_FragColor.xyz * weight;
  34401. #endif
  34402. //gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);
  34403. }
  34404. `;
  34405. Shaders["pointcloud_sm.vs"] = `
  34406. precision mediump float;
  34407. precision mediump int;
  34408. attribute vec3 position;
  34409. attribute vec3 color;
  34410. uniform mat4 modelMatrix;
  34411. uniform mat4 modelViewMatrix;
  34412. uniform mat4 projectionMatrix;
  34413. uniform mat4 viewMatrix;
  34414. uniform float uScreenWidth;
  34415. uniform float uScreenHeight;
  34416. uniform float near;
  34417. uniform float far;
  34418. uniform float uSpacing;
  34419. uniform float uOctreeSize;
  34420. uniform float uLevel;
  34421. uniform float uVNStart;
  34422. uniform sampler2D visibleNodes;
  34423. varying float vLinearDepth;
  34424. varying vec3 vColor;
  34425. #define PI 3.141592653589793
  34426. // ---------------------
  34427. // OCTREE
  34428. // ---------------------
  34429. #if defined(adaptive_point_size)
  34430. /**
  34431. * number of 1-bits up to inclusive index position
  34432. * number is treated as if it were an integer in the range 0-255
  34433. *
  34434. */
  34435. float numberOfOnes(float number, float index){
  34436. float tmp = mod(number, pow(2.0, index + 1.0));
  34437. float numOnes = 0.0;
  34438. for(float i = 0.0; i < 8.0; i++){
  34439. if(mod(tmp, 2.0) != 0.0){
  34440. numOnes++;
  34441. }
  34442. tmp = floor(tmp / 2.0);
  34443. }
  34444. return numOnes;
  34445. }
  34446. /**
  34447. * checks whether the bit at index is 1
  34448. * number is treated as if it were an integer in the range 0-255
  34449. *
  34450. */
  34451. bool isBitSet(float number, float index){
  34452. return mod(floor(number / pow(2.0, index)), 2.0) != 0.0;
  34453. }
  34454. /**
  34455. * find the LOD at the point position
  34456. */
  34457. float getLOD(){
  34458. vec3 offset = vec3(0.0, 0.0, 0.0);
  34459. float iOffset = uVNStart;
  34460. float depth = uLevel;
  34461. for(float i = 0.0; i <= 30.0; i++){
  34462. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  34463. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  34464. index3d = floor(index3d + 0.5);
  34465. float index = 4.0 * index3d.x + 2.0 * index3d.y + index3d.z;
  34466. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  34467. float mask = value.r * 255.0;
  34468. if(isBitSet(mask, index)){
  34469. // there are more visible child nodes at this position
  34470. iOffset = iOffset + value.g * 255.0 * 256.0 + value.b * 255.0 + numberOfOnes(mask, index - 1.0);
  34471. depth++;
  34472. }else{
  34473. // no more visible child nodes at this position
  34474. return depth;
  34475. }
  34476. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  34477. }
  34478. return depth;
  34479. }
  34480. #endif
  34481. float getPointSize(){
  34482. float pointSize = 1.0;
  34483. float slope = tan(fov / 2.0);
  34484. float projFactor = -0.5 * uScreenHeight / (slope * vViewPosition.z);
  34485. float r = uOctreeSpacing * 1.5;
  34486. vRadius = r;
  34487. #if defined fixed_point_size
  34488. pointSize = size;
  34489. #elif defined attenuated_point_size
  34490. if(uUseOrthographicCamera){
  34491. pointSize = size;
  34492. }else{
  34493. pointSize = pointSize * projFactor;
  34494. }
  34495. #elif defined adaptive_point_size
  34496. if(uUseOrthographicCamera) {
  34497. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  34498. pointSize = (worldSpaceSize / uOrthoWidth) * uScreenWidth;
  34499. } else {
  34500. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  34501. pointSize = worldSpaceSize * projFactor;
  34502. }
  34503. #endif
  34504. pointSize = max(minSize, pointSize);
  34505. pointSize = min(maxSize, pointSize);
  34506. vRadius = pointSize / projFactor;
  34507. return pointSize;
  34508. }
  34509. void main() {
  34510. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  34511. vLinearDepth = gl_Position.w;
  34512. float pointSize = getPointSize();
  34513. gl_PointSize = pointSize;
  34514. }
  34515. `;
  34516. Shaders["pointcloud_sm.fs"] = `
  34517. precision mediump float;
  34518. precision mediump int;
  34519. varying vec3 vColor;
  34520. varying float vLinearDepth;
  34521. void main() {
  34522. //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  34523. //gl_FragColor = vec4(vColor, 1.0);
  34524. //gl_FragColor = vec4(vLinearDepth, pow(vLinearDepth, 2.0), 0.0, 1.0);
  34525. gl_FragColor = vec4(vLinearDepth, vLinearDepth / 30.0, vLinearDepth / 30.0, 1.0);
  34526. }
  34527. `;
  34528. Shaders["normalize.vs"] = `
  34529. precision mediump float;
  34530. precision mediump int;
  34531. attribute vec3 position;
  34532. attribute vec2 uv;
  34533. uniform mat4 projectionMatrix;
  34534. uniform mat4 modelViewMatrix;
  34535. varying vec2 vUv;
  34536. void main() {
  34537. vUv = uv;
  34538. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  34539. }`;
  34540. Shaders["normalize.fs"] = `
  34541. #extension GL_EXT_frag_depth : enable
  34542. precision mediump float;
  34543. precision mediump int;
  34544. uniform sampler2D uWeightMap;
  34545. uniform sampler2D uDepthMap;
  34546. varying vec2 vUv;
  34547. void main() {
  34548. float depth = texture2D(uDepthMap, vUv).r;
  34549. if(depth >= 1.0){
  34550. discard;
  34551. }
  34552. gl_FragColor = vec4(depth, 1.0, 0.0, 1.0);
  34553. vec4 color = texture2D(uWeightMap, vUv);
  34554. color = color / color.w;
  34555. gl_FragColor = vec4(color.xyz, 1.0);
  34556. gl_FragDepthEXT = depth;
  34557. }`;
  34558. Shaders["normalize_and_edl.fs"] = `
  34559. #extension GL_EXT_frag_depth : enable
  34560. //
  34561. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  34562. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  34563. //
  34564. precision mediump float;
  34565. precision mediump int;
  34566. uniform sampler2D uWeightMap;
  34567. uniform sampler2D uEDLMap;
  34568. uniform sampler2D uDepthMap;
  34569. uniform float screenWidth;
  34570. uniform float screenHeight;
  34571. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  34572. uniform float edlStrength;
  34573. uniform float radius;
  34574. varying vec2 vUv;
  34575. float response(float depth){
  34576. vec2 uvRadius = radius / vec2(screenWidth, screenHeight);
  34577. float sum = 0.0;
  34578. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  34579. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  34580. float neighbourDepth = texture2D(uEDLMap, uvNeighbor).a;
  34581. if(neighbourDepth != 0.0){
  34582. if(depth == 0.0){
  34583. sum += 100.0;
  34584. }else{
  34585. sum += max(0.0, depth - neighbourDepth);
  34586. }
  34587. }
  34588. }
  34589. return sum / float(NEIGHBOUR_COUNT);
  34590. }
  34591. void main() {
  34592. float edlDepth = texture2D(uEDLMap, vUv).a;
  34593. float res = response(edlDepth);
  34594. float shade = exp(-res * 300.0 * edlStrength);
  34595. float depth = texture2D(uDepthMap, vUv).r;
  34596. if(depth >= 1.0 && res == 0.0){
  34597. discard;
  34598. }
  34599. vec4 color = texture2D(uWeightMap, vUv);
  34600. color = color / color.w;
  34601. color = color * shade;
  34602. gl_FragColor = vec4(color.xyz, 1.0);
  34603. gl_FragDepthEXT = depth;
  34604. }`;
  34605. Shaders["edl.vs"] = `
  34606. precision mediump float;
  34607. precision mediump int;
  34608. attribute vec3 position;
  34609. attribute vec2 uv;
  34610. uniform mat4 projectionMatrix;
  34611. uniform mat4 modelViewMatrix;
  34612. varying vec2 vUv;
  34613. void main() {
  34614. vUv = uv;
  34615. vec4 mvPosition = modelViewMatrix * vec4(position,1.0);
  34616. gl_Position = projectionMatrix * mvPosition;
  34617. }`;
  34618. Shaders["edl.fs"] = `
  34619. #extension GL_EXT_frag_depth : enable
  34620. //
  34621. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  34622. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  34623. //
  34624. precision mediump float;
  34625. precision mediump int;
  34626. //uniform float screenWidth;
  34627. //uniform float screenHeight;
  34628. uniform vec2 resolution;
  34629. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  34630. uniform float edlStrength;
  34631. uniform float radius;
  34632. uniform float opacity;
  34633. //uniform float uNear;
  34634. //uniform float uFar;
  34635. uniform mat4 uProj;
  34636. uniform sampler2D uEDLColor;
  34637. uniform sampler2D uEDLDepth;
  34638. varying vec2 vUv;
  34639. uniform int useEDL;
  34640. float response(float depth){
  34641. vec2 uvRadius = radius / resolution; //vec2(screenWidth, screenHeight);
  34642. float sum = 0.0;
  34643. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  34644. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  34645. //获取周围八个格子的值
  34646. float neighbourDepth = texture2D(uEDLColor, uvNeighbor).a;
  34647. neighbourDepth = (neighbourDepth == 1.0) ? 0.0 : neighbourDepth;
  34648. if(neighbourDepth != 0.0){
  34649. //if(depth == 0.0){
  34650. // sum += 100.0;
  34651. //}else{
  34652. sum += max(0.0, depth - neighbourDepth); //获取差值
  34653. //}
  34654. }
  34655. }
  34656. return sum / float(NEIGHBOUR_COUNT);
  34657. }
  34658. void main(){
  34659. vec4 cEDL = texture2D(uEDLColor, vUv);
  34660. float depth = cEDL.a;
  34661. depth = (depth == 1.0) ? 0.0 : depth;
  34662. if(depth == 0.0){ //去掉这句就能在无点云像素的地方渲染outline,但会遮住其他mesh
  34663. discard;
  34664. }
  34665. if(useEDL == 1){
  34666. float res = response(depth);
  34667. //if(depth == 0.0 && res == 0.0){ //test
  34668. // discard;
  34669. //}
  34670. float shade = exp(-res * 300.0 * edlStrength); //自然常数e为底的指数函数
  34671. gl_FragColor = vec4(cEDL.rgb * shade, opacity);
  34672. //const vec3 outlineColor = vec3(1.0,0.0,0.0);//test -outline
  34673. //gl_FragColor = vec4(mix(cEDL.rgb, outlineColor, -res), opacity );
  34674. }else{//加 不改颜色的情况
  34675. gl_FragColor = vec4(cEDL.rgb, opacity);
  34676. }
  34677. { // write regular hyperbolic depth values to depth buffer 修改深度
  34678. float dl = pow(2.0, depth);
  34679. vec4 dp = uProj * vec4(0.0, 0.0, -dl, 1.0);
  34680. float pz = dp.z / dp.w;
  34681. float fragDepth = (pz + 1.0) / 2.0;
  34682. gl_FragDepthEXT = fragDepth;
  34683. }
  34684. }
  34685. `;
  34686. Shaders["blur.vs"] = `
  34687. varying vec2 vUv;
  34688. void main() {
  34689. vUv = uv;
  34690. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  34691. }`;
  34692. Shaders["blur.fs"] = `
  34693. uniform mat4 projectionMatrix;
  34694. uniform float screenWidth;
  34695. uniform float screenHeight;
  34696. uniform float near;
  34697. uniform float far;
  34698. uniform sampler2D map;
  34699. varying vec2 vUv;
  34700. void main() {
  34701. float dx = 1.0 / screenWidth;
  34702. float dy = 1.0 / screenHeight;
  34703. vec3 color = vec3(0.0, 0.0, 0.0);
  34704. color += texture2D(map, vUv + vec2(-dx, -dy)).rgb;
  34705. color += texture2D(map, vUv + vec2( 0, -dy)).rgb;
  34706. color += texture2D(map, vUv + vec2(+dx, -dy)).rgb;
  34707. color += texture2D(map, vUv + vec2(-dx, 0)).rgb;
  34708. color += texture2D(map, vUv + vec2( 0, 0)).rgb;
  34709. color += texture2D(map, vUv + vec2(+dx, 0)).rgb;
  34710. color += texture2D(map, vUv + vec2(-dx, dy)).rgb;
  34711. color += texture2D(map, vUv + vec2( 0, dy)).rgb;
  34712. color += texture2D(map, vUv + vec2(+dx, dy)).rgb;
  34713. color = color / 9.0;
  34714. gl_FragColor = vec4(color, 1.0);
  34715. }`;
  34716. Shaders["depthBasic.vs"] = `
  34717. varying vec2 vUv;
  34718. void main() {
  34719. vUv = uv;
  34720. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34721. }
  34722. `;
  34723. Shaders["depthBasic.fs"] = `varying vec2 vUv;
  34724. uniform float opacity;
  34725. uniform vec3 baseColor;
  34726. uniform vec3 backColor;
  34727. uniform float occlusionDistance;
  34728. uniform float clipDistance;
  34729. uniform float maxClipFactor;
  34730. #if defined use_map
  34731. uniform sampler2D map;
  34732. #endif
  34733. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  34734. //似乎通过gl.getExtension('EXT_frag_depth')得到的GL_EXT_frag_depth
  34735. uniform sampler2D depthTexture;
  34736. uniform float nearPlane;
  34737. uniform float farPlane;
  34738. uniform vec2 resolution;
  34739. uniform vec2 viewportOffset; // viewportOffset 范围从0-整个画布的像素
  34740. float convertToLinear(float zValue)
  34741. {
  34742. float z = zValue * 2.0 - 1.0;
  34743. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  34744. }
  34745. #endif
  34746. void main() {
  34747. vec4 color = vec4(baseColor, opacity);
  34748. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  34749. // mixFactor and clipFactor define the color mixing proportion between the states of
  34750. // full visibility and occluded visibility
  34751. // and
  34752. // full visibility and total invisibility
  34753. float mixFactor = 0.0;
  34754. float clipFactor = 0.0;
  34755. // The linear depth value of the current fragment
  34756. float fragDepth = convertToLinear(gl_FragCoord.z);
  34757. // The coordinates of the current fragment in the depth texture
  34758. vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  34759. // The linear depth value of the pixel occupied by this fragment in the depth buffer
  34760. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  34761. // The difference between the two depths
  34762. float delta = fragDepth - textureDepth;
  34763. if (delta > 0.0)//差距
  34764. {
  34765. // occlusionDistance and clipDistance define the width of the respective zones and
  34766. // mixFactor and clipFactor express the interpolation between the two colors depending on the position
  34767. // of the current fragment withing those zones.
  34768. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  34769. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  34770. }
  34771. // If the fragment is totally transparent, don't bother drawing it
  34772. if (clipFactor == 1.0)
  34773. {
  34774. discard;
  34775. }else{
  34776. #if defined use_map
  34777. color = texture2D(map, vUv) * color;
  34778. #endif
  34779. color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));
  34780. }
  34781. #else
  34782. #if defined use_map
  34783. color = texture2D(map, vUv) * color;
  34784. #endif
  34785. #endif
  34786. gl_FragColor = color;
  34787. }
  34788. `;
  34789. Shaders["copyCubeMap.vs"] = `varying vec3 vWorldPos;
  34790. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  34791. {
  34792. float y = direction.y;
  34793. direction.y = direction.z;
  34794. direction.z = -y;
  34795. return direction;
  34796. }
  34797. void main() {
  34798. vWorldPos = vec3(-position.x, -position.y, position.z);
  34799. //vWorldPos = transformAxis(vWorldPos);
  34800. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34801. }
  34802. `;
  34803. Shaders["copyCubeMap.fs"] = `varying vec3 vWorldPos;
  34804. uniform float alpha;
  34805. uniform samplerCube tDiffuse;
  34806. void main() {
  34807. vec4 texColor = textureCube(tDiffuse, vWorldPos);
  34808. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  34809. }
  34810. `;
  34811. Shaders["basicTextured.vs"] = `varying vec2 vUv;
  34812. void main() {
  34813. vUv = uv;
  34814. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34815. }
  34816. `;
  34817. Shaders["basicTextured.fs"] = `varying vec2 vUv;
  34818. uniform float alpha;
  34819. uniform sampler2D tDiffuse;
  34820. void main() {
  34821. vec4 texColor = texture2D(tDiffuse, vUv);
  34822. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  34823. }
  34824. `;
  34825. let ftCanvas = document.createElement('canvas');
  34826. const Features = (function () {
  34827. let gl = ftCanvas.getContext('webgl') || ftCanvas.getContext('experimental-webgl');
  34828. if (gl === null){
  34829. return null;
  34830. }
  34831. // -- code taken from THREE.WebGLRenderer --
  34832. let _vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT);
  34833. let _vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT);
  34834. // Unused: let _vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
  34835. let _fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  34836. let _fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT);
  34837. // Unused: let _fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT);
  34838. let highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  34839. let mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  34840. // -----------------------------------------
  34841. let precision;
  34842. if (highpAvailable) {
  34843. precision = 'highp';
  34844. } else if (mediumpAvailable) {
  34845. precision = 'mediump';
  34846. } else {
  34847. precision = 'lowp';
  34848. }
  34849. return {
  34850. SHADER_INTERPOLATION: {
  34851. isSupported: function () {
  34852. let supported = true;
  34853. supported = supported && gl.getExtension('EXT_frag_depth');
  34854. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34855. return supported;
  34856. }
  34857. },
  34858. SHADER_SPLATS: {
  34859. isSupported: function () {
  34860. let supported = true;
  34861. supported = supported && gl.getExtension('EXT_frag_depth');
  34862. supported = supported && gl.getExtension('OES_texture_float');
  34863. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34864. return supported;
  34865. }
  34866. },
  34867. SHADER_EDL: {
  34868. isSupported: function () {
  34869. let supported = true;
  34870. supported = supported && gl.getExtension('EXT_frag_depth');
  34871. supported = supported && gl.getExtension('OES_texture_float');
  34872. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34873. //supported = supported || (gl instanceof WebGL2RenderingContext);
  34874. return supported;
  34875. }
  34876. },
  34877. //add:
  34878. EXT_DEPTH:{
  34879. isSupported: function () {
  34880. if(browser.detectIOS()){
  34881. let {major,minor,patch} = browser.iosVersion();
  34882. if(major == 15 && minor == 4 && patch == 1){
  34883. console.warn('检测到是ios15.4.1, 关闭EXT_frag_depth');//该版本ext_depth有问题,导致clear错乱。没有解决办法先关闭。
  34884. return false
  34885. }
  34886. }
  34887. return gl.getExtension('EXT_frag_depth'); //shader中的GL_EXT_frag_depth需要判断一下detectIOS吗。。
  34888. }
  34889. },
  34890. //WEBGL2: {
  34891. // isSupported: function(){
  34892. // return gl instanceof WebGL2RenderingContext;
  34893. // }
  34894. //},
  34895. precision: precision
  34896. };
  34897. }());
  34898. class DepthBasicMaterial extends ShaderMaterial{
  34899. constructor(o={}){
  34900. let {width, height} = viewer.renderer.getSize(new Vector2$1());
  34901. let uniforms = {
  34902. resolution: { type: 'v2', value: new Vector2$1(width, height ) },
  34903. viewportOffset: { type: 'v2', value: new Vector2$1(0, 0 ) }, //left, top
  34904. nearPlane: { type: 'f', value: 0.1 },
  34905. farPlane: { type: 'f', value: 10000 },
  34906. depthTexture: { type: 't', value: null },
  34907. opacity: { type: 'f', value: 1 },
  34908. map: { type: 't', value: o.map },
  34909. baseColor: {type:'v3', value: o.color ? new Color(o.color) : new Color("#ffffff")},
  34910. backColor: {type:'v3', value: o.backColor ? new Color(o.backColor) : new Color("#ddd")},
  34911. clipDistance : { type: 'f', value:o.clipDistance || 4}, //消失距离
  34912. occlusionDistance : { type: 'f', value: o.occlusionDistance || 1 }, //变为backColor距离
  34913. maxClipFactor : { type: 'f', value: o.maxClipFactor || 1 }, //0-1
  34914. };
  34915. let defines = {};
  34916. let useDepth = o.useDepth && Features.EXT_DEPTH.isSupported();/* && Potree.settings.matUseDepth */
  34917. if(useDepth )defines.useDepth = '';
  34918. if(o.map)defines.use_map = '';
  34919. super({
  34920. uniforms,
  34921. vertexShader: Shaders['depthBasic.vs'],
  34922. fragmentShader: Shaders['depthBasic.fs'],
  34923. depthWrite: !1,
  34924. depthTest: !1,
  34925. transparent: o.transparent == void 0 ? true : o.transparent,
  34926. side: o.side || 0 /* THREE.DoubleSide */,
  34927. defines,
  34928. });
  34929. if(o.opacity != void 0){
  34930. this.opacity = o.opacity;
  34931. }
  34932. if(useDepth) this.useDepth_ = true;
  34933. if(this.useDepth){
  34934. let setSize = (e)=>{//如果出现横条状的异常,往往是viewportOffset出错
  34935. let viewport = e.viewport;
  34936. let viewportOffset = viewport.offset || new Vector2$1();
  34937. this.uniforms.resolution.value.copy(viewport.resolution2);
  34938. this.uniforms.viewportOffset.value.copy(viewportOffset);
  34939. //console.log('depth '+viewportOffset.toArray())
  34940. };
  34941. let viewport = viewer.mainViewport;
  34942. setSize( {viewport} );
  34943. viewer.addEventListener('resize',(e)=>{
  34944. if(!this.useDepth || !e.viewport || e.viewport.camera.isPerspectiveCamera){//地图不需要
  34945. setSize(e);
  34946. }
  34947. });
  34948. /* viewer.addEventListener('camera_changed', (e)=>{
  34949. if(e.viewport.name != 'mapViewport') this.updateDepthParams(e)
  34950. }) */
  34951. viewer.addEventListener("render.begin", (e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  34952. if(e.viewport.camera.isPerspectiveCamera) this.updateDepthParams(e);
  34953. });
  34954. this.updateDepthParams();
  34955. }
  34956. //点云变化时要一直触发updateDepthParams??
  34957. //viewer.once("render.pass.end",this.updateDepthParams.bind(this))
  34958. }
  34959. updateDepthParams(e={}){//主要用于点云遮住mesh
  34960. if(this.useDepth){
  34961. var viewport = e.viewport || viewer.mainViewport;
  34962. var camera = viewport.camera;
  34963. /* if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.depthTex){
  34964. this.uniforms.depthTexture.value = viewer.images360.currentPano.depthTex
  34965. }else{ */
  34966. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  34967. //}
  34968. this.uniforms.nearPlane.value = camera.near;
  34969. this.uniforms.farPlane.value = camera.far;
  34970. }
  34971. }
  34972. set map(map){
  34973. this.uniforms.map.value = map;
  34974. }
  34975. get useDepth(){
  34976. return this.useDepth_
  34977. }
  34978. set useDepth(value){//如果不支持 EXT_DEPTH 的话会失效
  34979. if(this.useDepth_ != value){
  34980. if(value && Features.EXT_DEPTH.isSupported()){
  34981. this.defines.useDepth = '';
  34982. this.updateDepthParams();
  34983. }else {
  34984. delete this.defines.useDepth;
  34985. }
  34986. this.useDepth_ = value;
  34987. this.needsUpdate = true;
  34988. }
  34989. }
  34990. get opacity(){
  34991. return this.uniforms.opacity.value
  34992. }
  34993. set opacity(o){
  34994. this.uniforms && (this.uniforms.opacity.value = o);
  34995. }
  34996. /* dispose(){
  34997. super.dispose()
  34998. viewer.depthBasic
  34999. } */
  35000. }
  35001. const geo = new PlaneBufferGeometry(1,1);
  35002. class Sprite$1 extends Mesh{
  35003. constructor(options){
  35004. super(geo, options.mat || new DepthBasicMaterial({map:options.map, useDepth:options.useDepth}));
  35005. this.root = options.root || this;
  35006. this.renderOrder = options.renderOrder != void 0 ? options.renderOrder : 4;
  35007. this.pickOrder = options.pickOrder || 0;
  35008. this.sizeInfo = options.sizeInfo;
  35009. this.dontFixOrient = options.dontFixOrient;
  35010. this.root.matrixAutoUpdate = false;
  35011. this.matrixMap = new Map();
  35012. this.name = options.name || 'sprite';
  35013. this.useViewport = null;
  35014. this.viewports = options.viewports;//指定更新的viewports
  35015. this.visible_ = true;
  35016. let update = (e)=>{
  35017. this.update(e);
  35018. };
  35019. viewer.mapViewer && viewer.mapViewer.addEventListener("camera_changed", update);
  35020. viewer.addEventListener("camera_changed", update);
  35021. /* if(viewer.viewports.length == 1){//直接更新。如果有多个不在这更新,在"render.begin"
  35022. this.update(e)
  35023. } */
  35024. let applyMatrix = (e)=>{
  35025. this.applyMatrix(e);
  35026. };
  35027. viewer.addEventListener("raycaster", applyMatrix); //before render
  35028. viewer.addEventListener("render.begin", applyMatrix); //before render //magnifier时要禁止吗
  35029. this.addEventListener('dispose', ()=>{
  35030. viewer.mapViewer && viewer.mapViewer.removeEventListener("camera_changed", update);
  35031. viewer.removeEventListener("camera_changed", update);
  35032. viewer.removeEventListener("raycaster", applyMatrix); //before render
  35033. viewer.removeEventListener("render.begin", applyMatrix);
  35034. this.dispose();
  35035. });
  35036. }
  35037. set visible(v){
  35038. this.visible_ = v;
  35039. if(v){
  35040. this.update();
  35041. }
  35042. }
  35043. get visible(){
  35044. return this.visible_
  35045. }
  35046. realVisible(){
  35047. let parent = this;
  35048. let v;
  35049. while(parent){
  35050. if(parent.visible === false){
  35051. v = false;
  35052. break;
  35053. }
  35054. parent = parent.parent;
  35055. }
  35056. v = true;
  35057. if(!this.latestRealVisi && v){//变为可见后先update
  35058. this.latestRealVisi = true;
  35059. setTimeout(()=>{
  35060. this.update();
  35061. },1);//延迟 防止无限调用
  35062. return false
  35063. }
  35064. this.latestRealVisi = v;
  35065. return v;
  35066. }
  35067. update(e){
  35068. if(!e){
  35069. (this.viewports || viewer.viewports).forEach(view=>{
  35070. this.update({viewport:view});
  35071. });
  35072. return;
  35073. }
  35074. if(!this.root || ! this.realVisible() /* this.visible */ )return
  35075. if(this.viewports && !this.viewports.includes(e.viewport) )return
  35076. if(e.viewport.name == 'magnifier')return
  35077. let camera = e.viewport.camera;
  35078. //rotation
  35079. this.dontFixOrient || this.root.quaternion.copy(camera.quaternion);
  35080. //scale
  35081. var info = this.sizeInfo;
  35082. if(info){
  35083. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  35084. this.root.updateMatrixWorld(true);
  35085. var scale;
  35086. if(info.restricMeshScale){//仅限制最大或最小的话,不判断像素大小,直接限制mesh的scale
  35087. var dis = camera.position.distanceTo(this.root.getWorldPosition(new Vector3()));
  35088. if(dis < info.nearBound){
  35089. scale = info.scale * dis / info.nearBound;
  35090. }else {
  35091. scale = info.scale;
  35092. }
  35093. }else {
  35094. scale = math.getScaleForConstantSize($.extend(info,{//规定下最小最大像素
  35095. camera , position:this.root.getWorldPosition(new Vector3()) ,
  35096. resolution: e.viewport.resolution//2
  35097. }));
  35098. }
  35099. if(!isNaN(scale)){
  35100. this.root.scale.set(scale, scale, scale);
  35101. }
  35102. }
  35103. this.root.updateMatrix();
  35104. this.root.updateMatrixWorld(true);
  35105. this.matrixMap.set(e.viewport, this.root.matrix.clone());
  35106. this.useViewport = e.viewport;
  35107. }
  35108. applyMatrix(e){
  35109. if(!e)e = {viewport:viewer.mainViewport};//随便写一个viewport
  35110. if(e.viewport.name == 'magnifier')return
  35111. if(this.viewports && !this.viewports.includes(e.viewport) )return
  35112. if( !this.root || !this.realVisible() )return
  35113. var matrix = this.matrixMap.get(e.viewport);
  35114. if(!matrix){
  35115. this.update(e);
  35116. matrix = this.matrixMap.get(e.viewport);
  35117. }
  35118. if(e.viewport == this.useViewport){
  35119. return
  35120. }
  35121. this.useViewport = e.viewport;
  35122. this.root.matrix.copy(matrix);
  35123. this.root.updateMatrixWorld(true);
  35124. //console.log(this.root.name + e.viewport.name + " : "+this.root.matrixWorld.elements)
  35125. }
  35126. setUniforms(name,value){
  35127. this.material.setUniforms(name,value);
  35128. }
  35129. dispose(){
  35130. this.removeAllListeners();
  35131. this.parent && this.parent.remove(this);
  35132. }
  35133. }
  35134. //可能还是要用html写,因为要加按钮和图片
  35135. class TextSprite extends Object3D{
  35136. //注:为了分两层控制scale,不直接extend Sprite
  35137. constructor( options={}){
  35138. super();
  35139. let map = new Texture();
  35140. map.minFilter = LinearFilter;
  35141. map.magFilter = LinearFilter;
  35142. this.sprite = new Sprite$1( Object.assign({
  35143. root:this
  35144. }
  35145. ,options,
  35146. {
  35147. map,
  35148. })
  35149. );
  35150. this.add(this.sprite);
  35151. this.fontWeight = options.fontWeight == void 0 ? 'Bold' : options.fontWeight;
  35152. this.rectBorderThick = options.rectBorderThick || 0;
  35153. this.textBorderThick = options.textBorderThick || 0;
  35154. this.fontface = 'Arial';
  35155. this.fontsize = options.fontsize || 16;
  35156. this.textBorderColor = options.textBorderColor || { r: 0, g: 0, b: 0, a: 0.0 };
  35157. this.backgroundColor = options.backgroundColor || { r: 255, g: 255, b: 255, a: 1.0 };
  35158. this.textColor = options.textColor || {r: 0, g: 0, b: 0, a: 1.0};
  35159. this.borderColor = options.borderColor || { r: 0, g: 0, b: 0, a: 0.0 };
  35160. this.borderRadius = options.borderRadius || 6;
  35161. if(options.text != void 0)this.setText(options.text);
  35162. this.name = options.name;
  35163. //this.setText(text);
  35164. this.addEventListener('dispose', this.dispose.bind(this));
  35165. }
  35166. setText(text){
  35167. if (this.text !== text){
  35168. this.text = text + '';
  35169. this.updateTexture();
  35170. }
  35171. }
  35172. setTextColor(color){
  35173. this.textColor = color;
  35174. this.updateTexture();
  35175. }
  35176. setBorderColor(color){
  35177. this.borderColor = color;
  35178. this.updateTexture();
  35179. }
  35180. setBackgroundColor(color){
  35181. this.backgroundColor = color;
  35182. this.updateTexture();
  35183. }
  35184. setPos(pos){
  35185. this.position.copy(pos);
  35186. this.sprite.update();
  35187. }
  35188. update(){
  35189. this.sprite.update();
  35190. }
  35191. setVisible(v){
  35192. this.visible = v;
  35193. }
  35194. setUniforms(name,value){
  35195. this.sprite.setUniforms(name,value);
  35196. }
  35197. updateTexture(){
  35198. let canvas = document.createElement('canvas');
  35199. let context = canvas.getContext('2d');
  35200. context.font = this.fontWeight + ' ' + this.fontsize + 'px ' + this.fontface;
  35201. //context["font-weight"] = 100; //语法与 CSS font 属性相同。
  35202. // get size data (height depends only on font size)
  35203. //this.text = '啊啊啊啊啊啊fag'
  35204. let metrics = context.measureText(this.text );
  35205. let textWidth = metrics.width;
  35206. let margin = new Vector2$1(this.fontsize, Math.max( this.fontsize*0.4, 10) );
  35207. let spriteWidth = 2 * margin.x + textWidth + 2 * this.rectBorderThick;
  35208. let spriteHeight = 2 * margin.y + this.fontsize + 2 * this.rectBorderThick;
  35209. context.canvas.width = spriteWidth;
  35210. context.canvas.height = spriteHeight;
  35211. context.font = this.fontWeight + ' ' + this.fontsize + 'px ' + this.fontface;
  35212. let diff = 2;//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
  35213. context.textBaseline = "middle";
  35214. // border color
  35215. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' +
  35216. this.borderColor.b + ',' + this.borderColor.a + ')';
  35217. context.lineWidth = this.rectBorderThick;
  35218. // background color
  35219. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' +
  35220. this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  35221. this.roundRect(context, this.rectBorderThick / 2, this.rectBorderThick / 2,
  35222. spriteWidth - this.rectBorderThick, spriteHeight - this.rectBorderThick, this.borderRadius);
  35223. // text color
  35224. if(this.textBorderThick){
  35225. context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' +
  35226. this.textBorderColor.b + ',' + this.textBorderColor.a + ')';
  35227. context.lineWidth = this.textBorderThick;
  35228. context.strokeText(this.text , this.rectBorderThick + margin.x,spriteHeight/2 + diff );
  35229. }
  35230. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' +
  35231. this.textColor.b + ',' + this.textColor.a + ')';
  35232. context.fillText(this.text , this.rectBorderThick + margin.x, spriteHeight/2 + diff );//x,y
  35233. let texture = new Texture(canvas);
  35234. texture.minFilter = LinearFilter;
  35235. texture.magFilter = LinearFilter;
  35236. texture.needsUpdate = true;
  35237. //this.material.needsUpdate = true;
  35238. if(this.sprite.material.map){
  35239. this.sprite.material.map.dispose();
  35240. }
  35241. this.sprite.material.map = texture;
  35242. this.sprite.scale.set(spriteWidth * 0.01, spriteHeight * 0.01, 1.0);
  35243. }
  35244. roundRect(ctx, x, y, w, h, r){
  35245. ctx.beginPath();
  35246. ctx.moveTo(x + r, y);
  35247. ctx.lineTo(x + w - r, y);
  35248. ctx.arcTo(x + w, y, x + w, y + r, r );//圆弧。前四个参数同quadraticCurveTo
  35249. //ctx.quadraticCurveTo(x + w, y, x + w, y + r); //二次贝塞尔曲线需要两个点。第一个点是用于二次贝塞尔计算中的控制点,第二个点是曲线的结束点。
  35250. ctx.lineTo(x + w, y + h - r);
  35251. ctx.arcTo(x + w, y + h, x + w - r, y + h, r );
  35252. ctx.lineTo(x + r, y + h);
  35253. ctx.arcTo(x, y + h, x, y + h - r, r );
  35254. ctx.lineTo(x, y + r);
  35255. ctx.arcTo(x, y, x + r, y, r );
  35256. ctx.closePath();
  35257. ctx.fill();
  35258. ctx.stroke();
  35259. }
  35260. dispose(){
  35261. this.sprite.material.uniforms.map.value.dispose();
  35262. this.parent && this.parent.remove(this);
  35263. this.sprite.dispatchEvent({type:'dispose'});
  35264. this.removeAllListeners();
  35265. }
  35266. }
  35267. class Volume extends Object3D {
  35268. constructor (args = {}) {
  35269. super();
  35270. if(this.constructor.name === "Volume"){
  35271. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  35272. }
  35273. //console.log(this);
  35274. //console.log(this.constructor);
  35275. //console.log(this.constructor.name);
  35276. this._clip = args.clip || false;
  35277. this._visible = true;
  35278. this._modifiable = args.modifiable || true;
  35279. { // event listeners
  35280. this.addEventListener('select', e => {});
  35281. this.addEventListener('deselect', e => {});
  35282. }
  35283. }
  35284. get visible(){
  35285. return this._visible;
  35286. }
  35287. set visible(value){
  35288. if(this._visible !== value){
  35289. this._visible = value;
  35290. this.dispatchEvent({type: "visibility_changed", object: this});
  35291. }
  35292. }
  35293. getVolume () {
  35294. console.warn("override this in subclass");
  35295. }
  35296. update () {
  35297. };
  35298. raycast (raycaster, intersects) {
  35299. }
  35300. get clip () {
  35301. return this._clip;
  35302. }
  35303. set clip (value) {
  35304. if(this._clip !== value){
  35305. this._clip = value;
  35306. this.update();
  35307. this.dispatchEvent({
  35308. type: "clip_changed",
  35309. object: this
  35310. });
  35311. }
  35312. }
  35313. get modifieable () {
  35314. return this._modifiable;
  35315. }
  35316. set modifieable (value) {
  35317. this._modifiable = value;
  35318. this.update();
  35319. }
  35320. };
  35321. class BoxVolume extends Volume{
  35322. constructor(args = {}){
  35323. super(args);
  35324. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35325. this.name = 'box_' + this.constructor.counter;
  35326. let boxGeometry = new BoxGeometry(1, 1, 1);
  35327. boxGeometry.computeBoundingBox();
  35328. let boxFrameGeometry = new Geometry();
  35329. {
  35330. let Vector3$1 = Vector3;
  35331. boxFrameGeometry.vertices.push(
  35332. // bottom
  35333. new Vector3$1(-0.5, -0.5, 0.5),
  35334. new Vector3$1(0.5, -0.5, 0.5),
  35335. new Vector3$1(0.5, -0.5, 0.5),
  35336. new Vector3$1(0.5, -0.5, -0.5),
  35337. new Vector3$1(0.5, -0.5, -0.5),
  35338. new Vector3$1(-0.5, -0.5, -0.5),
  35339. new Vector3$1(-0.5, -0.5, -0.5),
  35340. new Vector3$1(-0.5, -0.5, 0.5),
  35341. // top
  35342. new Vector3$1(-0.5, 0.5, 0.5),
  35343. new Vector3$1(0.5, 0.5, 0.5),
  35344. new Vector3$1(0.5, 0.5, 0.5),
  35345. new Vector3$1(0.5, 0.5, -0.5),
  35346. new Vector3$1(0.5, 0.5, -0.5),
  35347. new Vector3$1(-0.5, 0.5, -0.5),
  35348. new Vector3$1(-0.5, 0.5, -0.5),
  35349. new Vector3$1(-0.5, 0.5, 0.5),
  35350. // sides
  35351. new Vector3$1(-0.5, -0.5, 0.5),
  35352. new Vector3$1(-0.5, 0.5, 0.5),
  35353. new Vector3$1(0.5, -0.5, 0.5),
  35354. new Vector3$1(0.5, 0.5, 0.5),
  35355. new Vector3$1(0.5, -0.5, -0.5),
  35356. new Vector3$1(0.5, 0.5, -0.5),
  35357. new Vector3$1(-0.5, -0.5, -0.5),
  35358. new Vector3$1(-0.5, 0.5, -0.5),
  35359. );
  35360. }
  35361. this.material = new MeshBasicMaterial({
  35362. color: 0x00ff00,
  35363. transparent: true,
  35364. opacity: 0.3,
  35365. depthTest: true,
  35366. depthWrite: false});
  35367. this.box = new Mesh(boxGeometry, this.material);
  35368. this.box.geometry.computeBoundingBox();
  35369. this.boundingBox = this.box.geometry.boundingBox;
  35370. this.add(this.box);
  35371. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  35372. // this.frame.mode = THREE.Lines;
  35373. this.add(this.frame);
  35374. viewer.setObjectLayers(this, 'volume' );
  35375. this.update();
  35376. }
  35377. update(){
  35378. this.boundingBox = this.box.geometry.boundingBox;
  35379. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35380. if (this._clip) {
  35381. this.box.visible = false;
  35382. } else {
  35383. this.box.visible = true;
  35384. }
  35385. }
  35386. raycast (raycaster, intersects) {
  35387. let is = [];
  35388. this.box.raycast(raycaster, is);
  35389. if (is.length > 0) {
  35390. let I = is[0];
  35391. intersects.push({
  35392. distance: I.distance,
  35393. object: this,
  35394. point: I.point.clone()
  35395. });
  35396. }
  35397. }
  35398. getVolume(){
  35399. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  35400. }
  35401. };
  35402. class SphereVolume extends Volume{
  35403. constructor(args = {}){
  35404. super(args);
  35405. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35406. this.name = 'sphere_' + this.constructor.counter;
  35407. let sphereGeometry = new SphereGeometry(1, 32, 32);
  35408. sphereGeometry.computeBoundingBox();
  35409. this.material = new MeshBasicMaterial({
  35410. color: 0x00ff00,
  35411. transparent: true,
  35412. opacity: 0.3,
  35413. depthTest: true,
  35414. depthWrite: false});
  35415. this.sphere = new Mesh(sphereGeometry, this.material);
  35416. this.sphere.visible = false;
  35417. this.sphere.geometry.computeBoundingBox();
  35418. this.boundingBox = this.sphere.geometry.boundingBox;
  35419. this.add(this.sphere);
  35420. let frameGeometry = new Geometry();
  35421. {
  35422. let steps = 64;
  35423. let uSegments = 8;
  35424. let vSegments = 5;
  35425. let r = 1;
  35426. for(let uSegment = 0; uSegment < uSegments; uSegment++){
  35427. let alpha = (uSegment / uSegments) * Math.PI * 2;
  35428. let dirx = Math.cos(alpha);
  35429. let diry = Math.sin(alpha);
  35430. for(let i = 0; i <= steps; i++){
  35431. let v = (i / steps) * Math.PI * 2;
  35432. let vNext = v + 2 * Math.PI / steps;
  35433. let height = Math.sin(v);
  35434. let xyAmount = Math.cos(v);
  35435. let heightNext = Math.sin(vNext);
  35436. let xyAmountNext = Math.cos(vNext);
  35437. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  35438. frameGeometry.vertices.push(vertex);
  35439. let vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  35440. frameGeometry.vertices.push(vertexNext);
  35441. }
  35442. }
  35443. // creates rings at poles, just because it's easier to implement
  35444. for(let vSegment = 0; vSegment <= vSegments + 1; vSegment++){
  35445. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  35446. let uh = (vSegment / (vSegments + 1)); // -1 to 1
  35447. uh = (1 - uh) * (-Math.PI / 2) + uh *(Math.PI / 2);
  35448. let height = Math.sin(uh);
  35449. console.log(uh, height);
  35450. for(let i = 0; i <= steps; i++){
  35451. let u = (i / steps) * Math.PI * 2;
  35452. let uNext = u + 2 * Math.PI / steps;
  35453. let dirx = Math.cos(u);
  35454. let diry = Math.sin(u);
  35455. let dirxNext = Math.cos(uNext);
  35456. let diryNext = Math.sin(uNext);
  35457. let xyAmount = Math.sqrt(1 - height * height);
  35458. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  35459. frameGeometry.vertices.push(vertex);
  35460. let vertexNext = new Vector3(dirxNext * xyAmount, diryNext * xyAmount, height);
  35461. frameGeometry.vertices.push(vertexNext);
  35462. }
  35463. }
  35464. }
  35465. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({color: 0x000000}));
  35466. this.add(this.frame);
  35467. let frameMaterial = new MeshBasicMaterial({wireframe: true, color: 0x000000});
  35468. this.frame = new Mesh(sphereGeometry, frameMaterial);
  35469. //this.add(this.frame);
  35470. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  35471. // this.frame.mode = THREE.Lines;
  35472. //this.add(this.frame);
  35473. this.update();
  35474. }
  35475. update(){
  35476. this.boundingBox = this.sphere.geometry.boundingBox;
  35477. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35478. }
  35479. raycast (raycaster, intersects) {
  35480. let is = [];
  35481. this.sphere.raycast(raycaster, is);
  35482. if (is.length > 0) {
  35483. let I = is[0];
  35484. intersects.push({
  35485. distance: I.distance,
  35486. object: this,
  35487. point: I.point.clone()
  35488. });
  35489. }
  35490. }
  35491. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  35492. getVolume(){
  35493. return (4 / 3) * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  35494. }
  35495. };
  35496. class Profile extends Object3D{
  35497. constructor () {
  35498. super();
  35499. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35500. this.name = 'Profile_' + this.constructor.counter;
  35501. this.points = [];
  35502. this.spheres = [];
  35503. this.edges = [];
  35504. this.boxes = [];
  35505. this.width = 1;
  35506. this.height = 20;
  35507. this._modifiable = true;
  35508. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  35509. this.color = new Color(0xff0000);
  35510. this.lineColor = new Color(0xff0000);
  35511. }
  35512. createSphereMaterial () {
  35513. let sphereMaterial = new MeshLambertMaterial({
  35514. //shading: THREE.SmoothShading,
  35515. color: 0xff0000,
  35516. depthTest: false,
  35517. depthWrite: false}
  35518. );
  35519. return sphereMaterial;
  35520. };
  35521. getSegments () {
  35522. let segments = [];
  35523. for (let i = 0; i < this.points.length - 1; i++) {
  35524. let start = this.points[i].clone();
  35525. let end = this.points[i + 1].clone();
  35526. segments.push({start: start, end: end});
  35527. }
  35528. return segments;
  35529. }
  35530. getSegmentMatrices () {
  35531. let segments = this.getSegments();
  35532. let matrices = [];
  35533. for (let segment of segments) {
  35534. let {start, end} = segment;
  35535. let box = new Object3D();
  35536. let length;
  35537. if(window.axisYup){
  35538. length = start.clone().setY(0).distanceTo(end.clone().setY(0));
  35539. box.scale.set(length, 10000, this.width); //???
  35540. }else {
  35541. length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35542. box.scale.set(length, 10000, this.width);
  35543. box.up.set(0, 0, 1);
  35544. }
  35545. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35546. let diff = new Vector3().subVectors(end, start);
  35547. let target = new Vector3(diff.y, -diff.x, 0);
  35548. box.position.set(0, 0, 0);
  35549. box.lookAt(target);
  35550. box.position.copy(center);
  35551. box.updateMatrixWorld();
  35552. matrices.push(box.matrixWorld);
  35553. }
  35554. return matrices;
  35555. }
  35556. addMarker (point) {
  35557. this.points.push(point);
  35558. let sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  35559. this.add(sphere);
  35560. this.spheres.push(sphere);
  35561. // edges & boxes
  35562. if (this.points.length > 1) {
  35563. let lineGeometry = new Geometry();
  35564. lineGeometry.vertices.push(new Vector3(), new Vector3());
  35565. lineGeometry.colors.push(this.lineColor, this.lineColor, this.lineColor);
  35566. let lineMaterial = new LineBasicMaterial({
  35567. vertexColors: VertexColors,
  35568. lineWidth: 2,
  35569. transparent: true,
  35570. opacity: 0.4
  35571. });
  35572. lineMaterial.depthTest = false;
  35573. let edge = new Line(lineGeometry, lineMaterial);
  35574. edge.visible = false;
  35575. this.add(edge);
  35576. this.edges.push(edge);
  35577. let boxGeometry = new BoxGeometry(1, 1, 1);
  35578. let boxMaterial = new MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: 0.2});
  35579. let box = new Mesh(boxGeometry, boxMaterial);
  35580. box.visible = false;
  35581. this.add(box);
  35582. this.boxes.push(box);
  35583. }
  35584. { // event listeners
  35585. let drag = (e) => {
  35586. let I = Utils.getMousePointCloudIntersection(
  35587. e.drag.end,
  35588. e.viewer.scene.getActiveCamera(),
  35589. e.viewer,
  35590. e.viewer.scene.pointclouds);
  35591. if (I) {
  35592. let i = this.spheres.indexOf(e.drag.object);
  35593. if (i !== -1) {
  35594. this.setPosition(i, I.location);
  35595. //this.dispatchEvent({
  35596. // 'type': 'marker_moved',
  35597. // 'profile': this,
  35598. // 'index': i
  35599. //});
  35600. }
  35601. }
  35602. };
  35603. let drop = e => {
  35604. let i = this.spheres.indexOf(e.drag.object);
  35605. if (i !== -1) {
  35606. this.dispatchEvent({
  35607. 'type': 'marker_dropped',
  35608. 'profile': this,
  35609. 'index': i
  35610. });
  35611. }
  35612. };
  35613. let mouseover = (e) => e.object.material.emissive.setHex(0x888888);
  35614. let mouseleave = (e) => e.object.material.emissive.setHex(0x000000);
  35615. sphere.addEventListener('drag', drag);
  35616. sphere.addEventListener('drop', drop);
  35617. sphere.addEventListener('mouseover', mouseover);
  35618. sphere.addEventListener('mouseleave', mouseleave);
  35619. }
  35620. let event = {
  35621. type: 'marker_added',
  35622. profile: this,
  35623. sphere: sphere
  35624. };
  35625. this.dispatchEvent(event);
  35626. this.setPosition(this.points.length - 1, point);
  35627. }
  35628. removeMarker (index) {
  35629. this.points.splice(index, 1);
  35630. this.remove(this.spheres[index]);
  35631. let edgeIndex = (index === 0) ? 0 : (index - 1);
  35632. this.remove(this.edges[edgeIndex]);
  35633. this.edges.splice(edgeIndex, 1);
  35634. this.remove(this.boxes[edgeIndex]);
  35635. this.boxes.splice(edgeIndex, 1);
  35636. this.spheres.splice(index, 1);
  35637. this.update();
  35638. this.dispatchEvent({
  35639. 'type': 'marker_removed',
  35640. 'profile': this
  35641. });
  35642. }
  35643. setPosition (index, position) {
  35644. let point = this.points[index];
  35645. point.copy(position);
  35646. let event = {
  35647. type: 'marker_moved',
  35648. profile: this,
  35649. index: index,
  35650. position: point.clone()
  35651. };
  35652. this.dispatchEvent(event);
  35653. this.update();
  35654. }
  35655. setWidth (width) {
  35656. this.width = width;
  35657. let event = {
  35658. type: 'width_changed',
  35659. profile: this,
  35660. width: width
  35661. };
  35662. this.dispatchEvent(event);
  35663. this.update();
  35664. }
  35665. getWidth () {
  35666. return this.width;
  35667. }
  35668. update () {
  35669. if (this.points.length === 0) {
  35670. return;
  35671. } else if (this.points.length === 1) {
  35672. let point = this.points[0];
  35673. this.spheres[0].position.copy(point);
  35674. return;
  35675. }
  35676. let min = this.points[0].clone();
  35677. let max = this.points[0].clone();
  35678. let centroid = new Vector3();
  35679. let lastIndex = this.points.length - 1;
  35680. for (let i = 0; i <= lastIndex; i++) {
  35681. let point = this.points[i];
  35682. let sphere = this.spheres[i];
  35683. let leftIndex = (i === 0) ? lastIndex : i - 1;
  35684. // let rightIndex = (i === lastIndex) ? 0 : i + 1;
  35685. let leftVertex = this.points[leftIndex];
  35686. // let rightVertex = this.points[rightIndex];
  35687. let leftEdge = this.edges[leftIndex];
  35688. let rightEdge = this.edges[i];
  35689. let leftBox = this.boxes[leftIndex];
  35690. // rightBox = this.boxes[i];
  35691. // let leftEdgeLength = point.distanceTo(leftVertex);
  35692. // let rightEdgeLength = point.distanceTo(rightVertex);
  35693. // let leftEdgeCenter = new THREE.Vector3().addVectors(leftVertex, point).multiplyScalar(0.5);
  35694. // let rightEdgeCenter = new THREE.Vector3().addVectors(point, rightVertex).multiplyScalar(0.5);
  35695. sphere.position.copy(point);
  35696. if (this._modifiable) {
  35697. sphere.visible = true;
  35698. } else {
  35699. sphere.visible = false;
  35700. }
  35701. if (leftEdge) {
  35702. leftEdge.geometry.vertices[1].copy(point);
  35703. leftEdge.geometry.verticesNeedUpdate = true;
  35704. leftEdge.geometry.computeBoundingSphere();
  35705. }
  35706. if (rightEdge) {
  35707. rightEdge.geometry.vertices[0].copy(point);
  35708. rightEdge.geometry.verticesNeedUpdate = true;
  35709. rightEdge.geometry.computeBoundingSphere();
  35710. }
  35711. if (leftBox) {
  35712. let start = leftVertex;
  35713. let end = point;
  35714. let length;
  35715. if(window.axisYup){
  35716. length = start.clone().setY(0).distanceTo(end.clone().setY(0));
  35717. }else {
  35718. length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35719. leftBox.up.set(0, 0, 1);
  35720. }
  35721. leftBox.scale.set(length, 1000000, this.width);
  35722. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35723. let diff = new Vector3().subVectors(end, start);
  35724. let target = new Vector3(diff.y, -diff.x, 0);
  35725. leftBox.position.set(0, 0, 0);
  35726. leftBox.lookAt(target);
  35727. leftBox.position.copy(center);
  35728. }
  35729. centroid.add(point);
  35730. min.min(point);
  35731. max.max(point);
  35732. }
  35733. centroid.multiplyScalar(1 / this.points.length);
  35734. for (let i = 0; i < this.boxes.length; i++) {
  35735. let box = this.boxes[i];
  35736. box.position.z = min.z + (max.z - min.z) / 2;
  35737. }
  35738. }
  35739. raycast (raycaster, intersects) {
  35740. for (let i = 0; i < this.points.length; i++) {
  35741. let sphere = this.spheres[i];
  35742. sphere.raycast(raycaster, intersects);
  35743. }
  35744. // recalculate distances because they are not necessarely correct
  35745. // for scaled objects.
  35746. // see https://github.com/mrdoob/three.js/issues/5827
  35747. // TODO: remove this once the bug has been fixed
  35748. for (let i = 0; i < intersects.length; i++) {
  35749. let I = intersects[i];
  35750. I.distance = raycaster.ray.origin.distanceTo(I.point);
  35751. }
  35752. intersects.sort(function (a, b) { return a.distance - b.distance; });
  35753. };
  35754. get modifiable () {
  35755. return this._modifiable;
  35756. }
  35757. set modifiable (value) {
  35758. this._modifiable = value;
  35759. this.update();
  35760. }
  35761. }
  35762. class Label extends EventDispatcher{
  35763. constructor(o={}){
  35764. super();
  35765. this.position = o.pos;
  35766. this.text = o.text || '';
  35767. this.elem = $('<div class="hide"><a></a></div>');
  35768. o.className && this.elem.addClass(o.className);
  35769. this.elem.find('a').html(this.text);
  35770. $("#potree_labels").append(this.elem);
  35771. this.pos2d = new Vector3;
  35772. this.dom = o.dom || viewer.renderArea;
  35773. this.camera = o.camera || viewer.scene.getActiveCamera();
  35774. let update = (e)=>{
  35775. this.update(e);
  35776. };
  35777. viewer.addEventListener('camera_changed', update);
  35778. this.addEventListener('dispose', ()=>{
  35779. viewer.removeEventListener('camera_changed', update);
  35780. this.dispose();
  35781. });
  35782. }
  35783. update(){
  35784. if(!this.position || this.elem.hasClass('unvisible'))return
  35785. var p = Utils.getPos2d(this.position,this.camera,this.dom, viewer.mainViewport);
  35786. if(!p.trueSide){
  35787. this.elem.addClass("hide"); return;
  35788. }
  35789. this.elem.css({
  35790. left: p.pos.x +'px',
  35791. top: p.pos.y +'px'
  35792. });
  35793. this.elem.removeClass("hide");
  35794. this.pos2d = p.vector;
  35795. }
  35796. setVisible(visi){
  35797. if(!visi){
  35798. this.elem.addClass("unvisible");
  35799. }else {
  35800. this.elem.removeClass("unvisible");
  35801. this.update();
  35802. }
  35803. }
  35804. setText(text){
  35805. this.text = text || '';
  35806. this.elem.find('a').html(this.text);
  35807. }
  35808. setPos(pos){
  35809. this.position = pos;
  35810. }
  35811. dispose(){
  35812. this.elem.remove();
  35813. this.removeAllListeners();
  35814. }
  35815. }
  35816. const _box$4 = new Box3();
  35817. const _vector$d = new Vector3();
  35818. class LineSegmentsGeometry extends InstancedBufferGeometry {
  35819. constructor() {
  35820. super();
  35821. this.isLineSegmentsGeometry = true;
  35822. this.type = 'LineSegmentsGeometry';
  35823. const positions = [ - 1, 2, 0, 1, 2, 0, - 1, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 0, - 1, - 1, 0, 1, - 1, 0 ];
  35824. const uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ];
  35825. const index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ];
  35826. this.setIndex( index );
  35827. this.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  35828. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  35829. }
  35830. applyMatrix4( matrix ) {
  35831. const start = this.attributes.instanceStart;
  35832. const end = this.attributes.instanceEnd;
  35833. if ( start !== undefined ) {
  35834. start.applyMatrix4( matrix );
  35835. end.applyMatrix4( matrix );
  35836. start.needsUpdate = true;
  35837. }
  35838. if ( this.boundingBox !== null ) {
  35839. this.computeBoundingBox();
  35840. }
  35841. if ( this.boundingSphere !== null ) {
  35842. this.computeBoundingSphere();
  35843. }
  35844. return this;
  35845. }
  35846. setPositions( array ) {
  35847. let lineSegments;
  35848. if ( array instanceof Float32Array ) {
  35849. lineSegments = array;
  35850. } else if ( Array.isArray( array ) ) {
  35851. lineSegments = new Float32Array( array );
  35852. }
  35853. const instanceBuffer = new InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz
  35854. this.setAttribute( 'instanceStart', new InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz
  35855. this.setAttribute( 'instanceEnd', new InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz
  35856. //
  35857. this.computeBoundingBox();
  35858. this.computeBoundingSphere();
  35859. return this;
  35860. }
  35861. setColors( array ) {
  35862. let colors;
  35863. if ( array instanceof Float32Array ) {
  35864. colors = array;
  35865. } else if ( Array.isArray( array ) ) {
  35866. colors = new Float32Array( array );
  35867. }
  35868. const instanceColorBuffer = new InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb
  35869. this.setAttribute( 'instanceColorStart', new InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb
  35870. this.setAttribute( 'instanceColorEnd', new InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb
  35871. return this;
  35872. }
  35873. fromWireframeGeometry( geometry ) {
  35874. this.setPositions( geometry.attributes.position.array );
  35875. return this;
  35876. }
  35877. fromEdgesGeometry( geometry ) {
  35878. this.setPositions( geometry.attributes.position.array );
  35879. return this;
  35880. }
  35881. fromMesh( mesh ) {
  35882. this.fromWireframeGeometry( new WireframeGeometry( mesh.geometry ) );
  35883. // set colors, maybe
  35884. return this;
  35885. }
  35886. fromLineSegments( lineSegments ) {
  35887. const geometry = lineSegments.geometry;
  35888. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  35889. // set colors, maybe
  35890. return this;
  35891. }
  35892. computeBoundingBox() {
  35893. if ( this.boundingBox === null ) {
  35894. this.boundingBox = new Box3();
  35895. }
  35896. const start = this.attributes.instanceStart;
  35897. const end = this.attributes.instanceEnd;
  35898. if ( start !== undefined && end !== undefined ) {
  35899. this.boundingBox.setFromBufferAttribute( start );
  35900. _box$4.setFromBufferAttribute( end );
  35901. this.boundingBox.union( _box$4 );
  35902. }
  35903. }
  35904. computeBoundingSphere() {
  35905. if ( this.boundingSphere === null ) {
  35906. this.boundingSphere = new Sphere();
  35907. }
  35908. if ( this.boundingBox === null ) {
  35909. this.computeBoundingBox();
  35910. }
  35911. const start = this.attributes.instanceStart;
  35912. const end = this.attributes.instanceEnd;
  35913. if ( start !== undefined && end !== undefined ) {
  35914. const center = this.boundingSphere.center;
  35915. this.boundingBox.getCenter( center );
  35916. let maxRadiusSq = 0;
  35917. for ( let i = 0, il = start.count; i < il; i ++ ) {
  35918. _vector$d.fromBufferAttribute( start, i );
  35919. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35920. _vector$d.fromBufferAttribute( end, i );
  35921. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35922. }
  35923. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  35924. if ( isNaN( this.boundingSphere.radius ) ) {
  35925. console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this );
  35926. }
  35927. }
  35928. }
  35929. toJSON() {
  35930. // todo
  35931. }
  35932. applyMatrix( matrix ) {
  35933. console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' );
  35934. return this.applyMatrix4( matrix );
  35935. }
  35936. }
  35937. /**
  35938. * parameters = {
  35939. * color: <hex>,
  35940. * lineWidth: <float>,
  35941. * dashed: <boolean>,
  35942. * dashScale: <float>,
  35943. * dashSize: <float>,
  35944. * dashOffset: <float>,
  35945. * gapSize: <float>,
  35946. * resolution: <Vector2>, // to be set by renderer
  35947. * }
  35948. */
  35949. UniformsLib.line = {
  35950. /*
  35951. worldUnits: { value: 1 },
  35952. lineWidth: { value: 1 },
  35953. resolution: { value: new Vector2( 1, 1 ) },
  35954. dashOffset: { value: 0 },
  35955. dashScale: { value: 1 },
  35956. dashSize: { value: 1 },
  35957. gapSize: { value: 1 } // todo FIX - maybe change to totalSize
  35958. */
  35959. worldUnits: { value: 1 },
  35960. lineWidth: { value: 1 },
  35961. resolution: { value: new Vector2$1( 1, 1 ) },
  35962. viewportOffset: { value: new Vector2$1(0, 0 ) }, //left, top
  35963. dashScale: { value: 1 },
  35964. dashSize: { value: 1 },
  35965. dashOffset: { value: 0 },
  35966. gapSize: { value: 1 },
  35967. opacity: { value: 1 },
  35968. backColor: {type:'v3', value: new Color("#ddd")},
  35969. clipDistance : { type: 'f', value: 4}, //消失距离
  35970. occlusionDistance : { type: 'f', value: 1 }, //变为backColor距离
  35971. maxClipFactor : { type: 'f', value: 1 }, //0-1
  35972. depthTexture:{ value: null },
  35973. nearPlane:{value: 0.1},
  35974. farPlane:{value: 100000},
  35975. };
  35976. ShaderLib[ 'line' ] = {
  35977. uniforms: UniformsUtils.merge( [
  35978. UniformsLib.common,
  35979. UniformsLib.fog,
  35980. UniformsLib.line
  35981. ] ),
  35982. vertexShader:
  35983. /* glsl */`
  35984. #include <common>
  35985. #include <color_pars_vertex>
  35986. #include <fog_pars_vertex>
  35987. #include <logdepthbuf_pars_vertex>
  35988. #include <clipping_planes_pars_vertex>
  35989. uniform float lineWidth;
  35990. uniform vec2 resolution;
  35991. attribute vec3 instanceStart;
  35992. attribute vec3 instanceEnd;
  35993. attribute vec3 instanceColorStart;
  35994. attribute vec3 instanceColorEnd;
  35995. #ifdef WORLD_UNITS
  35996. varying vec4 worldPos;
  35997. varying vec3 worldStart;
  35998. varying vec3 worldEnd;
  35999. #ifdef USE_DASH
  36000. varying vec2 vUv;
  36001. #endif
  36002. #else
  36003. varying vec2 vUv;
  36004. #endif
  36005. #ifdef USE_DASH
  36006. uniform float dashScale;
  36007. attribute float instanceDistanceStart;
  36008. attribute float instanceDistanceEnd;
  36009. varying float vLineDistance;
  36010. #endif
  36011. void trimSegment( const in vec4 start, inout vec4 end ) {
  36012. // trim end segment so it terminates between the camera plane and the near plane
  36013. // conservative estimate of the near plane
  36014. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  36015. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  36016. float nearEstimate = - 0.5 * b / a;
  36017. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  36018. end.xyz = mix( start.xyz, end.xyz, alpha );
  36019. }
  36020. void main() {
  36021. #ifdef USE_COLOR
  36022. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  36023. #endif
  36024. #ifdef USE_DASH
  36025. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  36026. vUv = uv;
  36027. #endif
  36028. float aspect = resolution.x / resolution.y;
  36029. // camera space
  36030. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  36031. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  36032. #ifdef WORLD_UNITS
  36033. worldStart = start.xyz;
  36034. worldEnd = end.xyz;
  36035. #else
  36036. vUv = uv;
  36037. #endif
  36038. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  36039. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  36040. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  36041. // perhaps there is a more elegant solution -- WestLangley
  36042. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  36043. if ( perspective ) {
  36044. if ( start.z < 0.0 && end.z >= 0.0 ) {
  36045. trimSegment( start, end );
  36046. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  36047. trimSegment( end, start );
  36048. }
  36049. }
  36050. // clip space
  36051. vec4 clipStart = projectionMatrix * start;
  36052. vec4 clipEnd = projectionMatrix * end;
  36053. // ndc space
  36054. vec3 ndcStart = clipStart.xyz / clipStart.w;
  36055. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  36056. // direction
  36057. vec2 dir = ndcEnd.xy - ndcStart.xy;
  36058. // account for clip-space aspect ratio
  36059. dir.x *= aspect;
  36060. dir = normalize( dir );
  36061. #ifdef WORLD_UNITS
  36062. // get the offset direction as perpendicular to the view vector
  36063. vec3 worldDir = normalize( end.xyz - start.xyz );
  36064. vec3 offset;
  36065. if ( position.y < 0.5 ) {
  36066. offset = normalize( cross( start.xyz, worldDir ) );
  36067. } else {
  36068. offset = normalize( cross( end.xyz, worldDir ) );
  36069. }
  36070. // sign flip
  36071. if ( position.x < 0.0 ) offset *= - 1.0;
  36072. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  36073. // don't extend the line if we're rendering dashes because we
  36074. // won't be rendering the endcaps
  36075. #ifndef USE_DASH
  36076. // extend the line bounds to encompass endcaps
  36077. start.xyz += - worldDir * lineWidth * 0.5;
  36078. end.xyz += worldDir * lineWidth * 0.5;
  36079. // shift the position of the quad so it hugs the forward edge of the line
  36080. offset.xy -= dir * forwardOffset;
  36081. offset.z += 0.5;
  36082. #endif
  36083. // endcaps
  36084. if ( position.y > 1.0 || position.y < 0.0 ) {
  36085. offset.xy += dir * 2.0 * forwardOffset;
  36086. }
  36087. // adjust for lineWidth
  36088. offset *= lineWidth * 0.5;
  36089. // set the world position
  36090. worldPos = ( position.y < 0.5 ) ? start : end;
  36091. worldPos.xyz += offset;
  36092. // project the worldpos
  36093. vec4 clip = projectionMatrix * worldPos;
  36094. // shift the depth of the projected points so the line
  36095. // segments overlap neatly
  36096. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  36097. clip.z = clipPose.z * clip.w;
  36098. #else
  36099. vec2 offset = vec2( dir.y, - dir.x );
  36100. // undo aspect ratio adjustment
  36101. dir.x /= aspect;
  36102. offset.x /= aspect;
  36103. // sign flip
  36104. if ( position.x < 0.0 ) offset *= - 1.0;
  36105. // endcaps
  36106. if ( position.y < 0.0 ) {
  36107. offset += - dir;
  36108. } else if ( position.y > 1.0 ) {
  36109. offset += dir;
  36110. }
  36111. // adjust for lineWidth
  36112. offset *= lineWidth;
  36113. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  36114. offset /= resolution.y;
  36115. // select end
  36116. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  36117. // back to clip space
  36118. offset *= clip.w;
  36119. clip.xy += offset;
  36120. #endif
  36121. gl_Position = clip;
  36122. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  36123. #include <logdepthbuf_vertex>
  36124. #include <clipping_planes_vertex>
  36125. #include <fog_vertex>
  36126. }
  36127. `,
  36128. fragmentShader:
  36129. /* glsl */`
  36130. uniform vec3 diffuse;
  36131. uniform float opacity;
  36132. uniform float lineWidth;
  36133. uniform vec3 backColor;
  36134. uniform float occlusionDistance;
  36135. uniform float clipDistance;
  36136. uniform float maxClipFactor;
  36137. #ifdef USE_DASH
  36138. uniform float dashOffset;
  36139. uniform float dashSize;
  36140. uniform float gapSize;
  36141. #endif
  36142. //加
  36143. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36144. uniform sampler2D depthTexture;
  36145. uniform float nearPlane;
  36146. uniform float farPlane;
  36147. uniform vec2 resolution;
  36148. uniform vec2 viewportOffset;
  36149. #endif
  36150. varying float vLineDistance;
  36151. #ifdef WORLD_UNITS
  36152. varying vec4 worldPos;
  36153. varying vec3 worldStart;
  36154. varying vec3 worldEnd;
  36155. #ifdef USE_DASH
  36156. varying vec2 vUv;
  36157. #endif
  36158. #else
  36159. varying vec2 vUv;
  36160. #endif
  36161. #include <common>
  36162. #include <color_pars_fragment>
  36163. #include <fog_pars_fragment>
  36164. #include <logdepthbuf_pars_fragment>
  36165. #include <clipping_planes_pars_fragment>
  36166. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36167. float convertToLinear(float zValue)
  36168. {
  36169. float z = zValue * 2.0 - 1.0;
  36170. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  36171. }
  36172. #endif
  36173. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  36174. float mua;
  36175. float mub;
  36176. vec3 p13 = p1 - p3;
  36177. vec3 p43 = p4 - p3;
  36178. vec3 p21 = p2 - p1;
  36179. float d1343 = dot( p13, p43 );
  36180. float d4321 = dot( p43, p21 );
  36181. float d1321 = dot( p13, p21 );
  36182. float d4343 = dot( p43, p43 );
  36183. float d2121 = dot( p21, p21 );
  36184. float denom = d2121 * d4343 - d4321 * d4321;
  36185. float numer = d1343 * d4321 - d1321 * d4343;
  36186. mua = numer / denom;
  36187. mua = clamp( mua, 0.0, 1.0 );
  36188. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  36189. mub = clamp( mub, 0.0, 1.0 );
  36190. return vec2( mua, mub );
  36191. }
  36192. void main() {
  36193. #include <clipping_planes_fragment>
  36194. /*#ifdef USE_DASH
  36195. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  36196. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  36197. #endif*/
  36198. #ifdef USE_DASH
  36199. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  36200. bool unvisible = mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize;
  36201. //加
  36202. #ifdef DASH_with_depth
  36203. #else
  36204. if (unvisible) discard; // todo - FIX
  36205. #endif
  36206. #endif
  36207. float alpha = opacity;
  36208. #ifdef WORLD_UNITS
  36209. // Find the closest points on the view ray and the line segment
  36210. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  36211. vec3 lineDir = worldEnd - worldStart;
  36212. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  36213. vec3 p1 = worldStart + lineDir * params.x;
  36214. vec3 p2 = rayEnd * params.y;
  36215. vec3 delta = p1 - p2;
  36216. float len = length( delta );
  36217. float norm = len / lineWidth;
  36218. #ifndef USE_DASH
  36219. #ifdef USE_ALPHA_TO_COVERAGE
  36220. float dnorm = fwidth( norm );
  36221. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  36222. #else
  36223. if ( norm > 0.5 ) {
  36224. discard;
  36225. }
  36226. #endif
  36227. #endif
  36228. #else
  36229. #ifdef USE_ALPHA_TO_COVERAGE
  36230. // artifacts appear on some hardware if a derivative is taken within a conditional
  36231. float a = vUv.x;
  36232. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  36233. float len2 = a * a + b * b;
  36234. float dlen = fwidth( len2 );
  36235. if ( abs( vUv.y ) > 1.0 ) {
  36236. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  36237. }
  36238. #else
  36239. if ( abs( vUv.y ) > 1.0 ) {
  36240. float a = vUv.x;
  36241. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  36242. float len2 = a * a + b * b;
  36243. if ( len2 > 1.0 ) discard;
  36244. }
  36245. #endif
  36246. #endif
  36247. vec4 diffuseColor = vec4( diffuse, alpha );
  36248. //加
  36249. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36250. float mixFactor = 0.0;
  36251. float clipFactor = 0.0;
  36252. float fragDepth = convertToLinear(gl_FragCoord.z);
  36253. vec2 depthTxtCoords = vec2(gl_FragCoord.x - viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  36254. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  36255. float delta = fragDepth - textureDepth;
  36256. if (delta > 0.0)
  36257. {
  36258. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  36259. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  36260. }
  36261. if (clipFactor == 1.0)
  36262. {
  36263. discard;
  36264. }
  36265. vec4 backColor_ = vec4(backColor, opacity); //vec4(0.8,0.8,0.8, 0.8*opacity);
  36266. #ifdef DASH_with_depth
  36267. // 只在被遮住的部分显示虚线, 所以若同时是虚线不可见部分和被遮住时, a为0
  36268. if(unvisible) backColor_.a = 0.0;
  36269. #endif
  36270. //vec4 diffuseColor = vec4(mix(diffuse, backColor_, mixFactor), opacity*(1.0 - clipFactor));
  36271. diffuseColor = mix(diffuseColor, backColor_ , mixFactor);
  36272. diffuseColor.a *= (1.0 - clipFactor);
  36273. #endif
  36274. #include <logdepthbuf_fragment>
  36275. #include <color_fragment>
  36276. //gl_FragColor = vec4( diffuseColor.rgb, alpha );
  36277. gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
  36278. #include <tonemapping_fragment>
  36279. #include <encodings_fragment>
  36280. #include <fog_fragment>
  36281. #include <premultiplied_alpha_fragment>
  36282. }
  36283. `
  36284. };
  36285. class LineMaterial extends ShaderMaterial {
  36286. constructor( parameters ) {
  36287. super( {
  36288. type: 'LineMaterial',
  36289. uniforms: UniformsUtils.clone( ShaderLib[ 'line' ].uniforms ),
  36290. vertexShader: ShaderLib[ 'line' ].vertexShader,
  36291. fragmentShader: ShaderLib[ 'line' ].fragmentShader,
  36292. clipping: true // required for clipping support
  36293. } );
  36294. this.isLineMaterial = true;
  36295. this.lineWidth_ = 0;
  36296. this.supportExtDepth = parameters.supportExtDepth;
  36297. this.depthTestWhenPick = false; //pick时是否识别点云等
  36298. if(parameters.color){
  36299. this.color = new Color(parameters.color);
  36300. }
  36301. if(parameters.backColor){
  36302. this.uniforms.backColor.value = new Color(parameters.backColor);
  36303. }
  36304. if(parameters.clipDistance){
  36305. this.uniforms.clipDistance.value = parameters.clipDistance;
  36306. }
  36307. if(parameters.occlusionDistance){
  36308. this.uniforms.occlusionDistance.value = parameters.occlusionDistance;
  36309. }
  36310. if(parameters.maxClipFactor){
  36311. this.uniforms.maxClipFactor.value = parameters.maxClipFactor;
  36312. }
  36313. Object.defineProperties( this, {
  36314. color: {
  36315. enumerable: true,
  36316. get: function () {
  36317. return this.uniforms.diffuse.value;
  36318. },
  36319. set: function ( value ) {
  36320. this.uniforms.diffuse.value = value;
  36321. }
  36322. },
  36323. worldUnits: {
  36324. enumerable: true,
  36325. get: function () {
  36326. return 'WORLD_UNITS' in this.defines;
  36327. },
  36328. set: function ( value ) {
  36329. if ( value === true ) {
  36330. this.defines.WORLD_UNITS = '';
  36331. } else {
  36332. delete this.defines.WORLD_UNITS;
  36333. }
  36334. }
  36335. },
  36336. lineWidth: {
  36337. enumerable: true,
  36338. get: function () {
  36339. return this.lineWidth_;//this.uniforms.lineWidth.value;
  36340. },
  36341. set: function ( value ) {
  36342. this.uniforms.lineWidth.value = value * window.devicePixelRatio;
  36343. this.lineWidth_ = value;
  36344. }
  36345. },
  36346. dashed: {
  36347. enumerable: true,
  36348. get: function () {
  36349. return Boolean( 'USE_DASH' in this.defines );
  36350. },
  36351. set( value ) {
  36352. if ( Boolean( value ) !== Boolean( 'USE_DASH' in this.defines ) ) {
  36353. this.needsUpdate = true;
  36354. }
  36355. if ( value === true ) {
  36356. this.defines.USE_DASH = '';
  36357. } else {
  36358. delete this.defines.USE_DASH;
  36359. }
  36360. }
  36361. },
  36362. dashScale: {
  36363. enumerable: true,
  36364. get: function () {
  36365. return this.uniforms.dashScale.value;
  36366. },
  36367. set: function ( value ) {
  36368. this.uniforms.dashScale.value = value;
  36369. }
  36370. },
  36371. dashSize: {
  36372. enumerable: true,
  36373. get: function () {
  36374. return this.uniforms.dashSize.value;
  36375. },
  36376. set: function ( value ) {
  36377. this.uniforms.dashSize.value = value;
  36378. }
  36379. },
  36380. dashOffset: {
  36381. enumerable: true,
  36382. get: function () {
  36383. return this.uniforms.dashOffset.value;
  36384. },
  36385. set: function ( value ) {
  36386. this.uniforms.dashOffset.value = value;
  36387. }
  36388. },
  36389. gapSize: {
  36390. enumerable: true,
  36391. get: function () {
  36392. return this.uniforms.gapSize.value;
  36393. },
  36394. set: function ( value ) {
  36395. this.uniforms.gapSize.value = value;
  36396. }
  36397. },
  36398. opacity: {
  36399. enumerable: true,
  36400. get: function () {
  36401. return this.uniforms.opacity.value;
  36402. },
  36403. set: function ( value ) {
  36404. this.uniforms.opacity.value = value;
  36405. }
  36406. },
  36407. resolution: {
  36408. enumerable: true,
  36409. get: function () {
  36410. return this.uniforms.resolution.value;
  36411. },
  36412. set: function ( value ) {
  36413. this.uniforms.resolution.value.copy( value );
  36414. }
  36415. },
  36416. alphaToCoverage: {
  36417. enumerable: true,
  36418. get: function () {
  36419. return Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines );
  36420. },
  36421. set: function ( value ) {
  36422. if ( Boolean( value ) !== Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines ) ) {
  36423. this.needsUpdate = true;
  36424. }
  36425. if ( value === true ) {
  36426. this.defines.USE_ALPHA_TO_COVERAGE = '';
  36427. this.extensions.derivatives = true;
  36428. } else {
  36429. delete this.defines.USE_ALPHA_TO_COVERAGE;
  36430. this.extensions.derivatives = false;
  36431. }
  36432. }
  36433. }
  36434. ,
  36435. useDepth:{//add
  36436. enumerable: true,
  36437. get: function () {
  36438. return 'useDepth' in this.defines
  36439. },
  36440. set: function ( value ) {
  36441. value = value && !!this.supportExtDepth;
  36442. if(value != this.useDepth){
  36443. if(value){
  36444. this.defines.useDepth = '';
  36445. this.updateDepthParams();
  36446. }else {
  36447. delete this.defines.useDepth;
  36448. }
  36449. this.needsUpdate = true;
  36450. }
  36451. }
  36452. },
  36453. dashWithDepth:{//add
  36454. enumerable: true,
  36455. get: function () {
  36456. return 'DASH_with_depth' in this.defines
  36457. },
  36458. set: function ( value ) {
  36459. value = value && !!this.supportExtDepth;
  36460. if(value != this.dashWithDepth){
  36461. if(value){
  36462. this.defines.DASH_with_depth = '';
  36463. }else {
  36464. delete this.defines.DASH_with_depth;
  36465. }
  36466. this.needsUpdate = true;
  36467. }
  36468. }
  36469. },
  36470. } );
  36471. this.setValues( parameters );
  36472. let setSize = (e)=>{
  36473. let viewport = e.viewport;
  36474. let viewportOffset = viewport.offset || new Vector2$1();
  36475. this.uniforms.resolution.value.copy(viewport.resolution2);
  36476. this.uniforms.viewportOffset.value.copy(viewportOffset);
  36477. this.lineWidth = this.lineWidth_;
  36478. };
  36479. let viewport = viewer.mainViewport;
  36480. setSize({viewport});
  36481. viewer.addEventListener('resize',(e)=>{
  36482. setSize(e);
  36483. });
  36484. if(this.supportExtDepth){
  36485. //add
  36486. this.updateDepthParams();
  36487. /* viewer.addEventListener('camera_changed', (e)=>{
  36488. if(e.viewport.name != 'mapViewport') this.updateDepthParams(e)
  36489. }) */
  36490. viewer.addEventListener("render.begin", (e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  36491. if(e.viewport.camera.isPerspectiveCamera) this.updateDepthParams(e);
  36492. });
  36493. }
  36494. }
  36495. updateDepthParams(e={}){
  36496. if(this.useDepth){
  36497. var viewport = e.viewport || viewer.mainViewport;
  36498. var camera = viewport.camera;
  36499. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //viewer.getPRenderer().rtEDL.depthTexture
  36500. this.uniforms.nearPlane.value = camera.near; //似乎因为这个所以对OrthographicCamera 无效
  36501. this.uniforms.farPlane.value = camera.far;
  36502. }
  36503. }
  36504. }
  36505. const _start$2 = new Vector3();
  36506. const _end$2 = new Vector3();
  36507. const _start4 = new Vector4();
  36508. const _end4 = new Vector4();
  36509. const _ssOrigin = new Vector4();
  36510. const _ssOrigin3 = new Vector3();
  36511. const _mvMatrix = new Matrix4();
  36512. const _line = new Line3();
  36513. const _closestPoint = new Vector3();
  36514. const _box$5 = new Box3();
  36515. const _sphere$4 = new Sphere();
  36516. const _clipToWorldVector = new Vector4();
  36517. let _ray$3, _instanceStart, _instanceEnd, _lineWidth;
  36518. // Returns the margin required to expand by in world space given the distance from the camera,
  36519. // line width, resolution, and camera projection
  36520. function getWorldSpaceHalfWidth( camera, distance, resolution ) {
  36521. // transform into clip space, adjust the x and y values by the pixel width offset, then
  36522. // transform back into world space to get world offset. Note clip space is [-1, 1] so full
  36523. // width does not need to be halved.
  36524. _clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
  36525. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  36526. _clipToWorldVector.x = _lineWidth / resolution.width;
  36527. _clipToWorldVector.y = _lineWidth / resolution.height;
  36528. _clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
  36529. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  36530. return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
  36531. }
  36532. function raycastWorldUnits( lineSegments, intersects ) {
  36533. for ( let i = 0, l = _instanceStart.count; i < l; i ++ ) {
  36534. _line.start.fromBufferAttribute( _instanceStart, i );
  36535. _line.end.fromBufferAttribute( _instanceEnd, i );
  36536. const pointOnLine = new Vector3();
  36537. const point = new Vector3();
  36538. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  36539. const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
  36540. if ( isInside ) {
  36541. intersects.push( {
  36542. point,
  36543. pointOnLine,
  36544. distance: _ray$3.origin.distanceTo( point ),
  36545. object: lineSegments,
  36546. face: null,
  36547. faceIndex: i,
  36548. uv: null,
  36549. uv2: null,
  36550. } );
  36551. }
  36552. }
  36553. }
  36554. function raycastScreenSpace( lineSegments, camera, intersects ) {
  36555. const projectionMatrix = camera.projectionMatrix;
  36556. const material = lineSegments.material;
  36557. const resolution = material.resolution;
  36558. const matrixWorld = lineSegments.matrixWorld;
  36559. const geometry = lineSegments.geometry;
  36560. const instanceStart = geometry.attributes.instanceStart;
  36561. const instanceEnd = geometry.attributes.instanceEnd;
  36562. const near = - camera.near;
  36563. //
  36564. // pick a point 1 unit out along the ray to avoid the ray origin
  36565. // sitting at the camera origin which will cause "w" to be 0 when
  36566. // applying the projection matrix.
  36567. _ray$3.at( 1, _ssOrigin );
  36568. // ndc space [ - 1.0, 1.0 ]
  36569. _ssOrigin.w = 1;
  36570. _ssOrigin.applyMatrix4( camera.matrixWorldInverse );
  36571. _ssOrigin.applyMatrix4( projectionMatrix );
  36572. _ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
  36573. // screen space
  36574. _ssOrigin.x *= resolution.x / 2;
  36575. _ssOrigin.y *= resolution.y / 2;
  36576. _ssOrigin.z = 0;
  36577. _ssOrigin3.copy( _ssOrigin );
  36578. _mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
  36579. for ( let i = 0, l = instanceStart.count; i < l; i ++ ) {
  36580. _start4.fromBufferAttribute( instanceStart, i );
  36581. _end4.fromBufferAttribute( instanceEnd, i );
  36582. _start4.w = 1;
  36583. _end4.w = 1;
  36584. // camera space
  36585. _start4.applyMatrix4( _mvMatrix );
  36586. _end4.applyMatrix4( _mvMatrix );
  36587. // skip the segment if it's entirely behind the camera
  36588. const isBehindCameraNear = _start4.z > near && _end4.z > near;
  36589. if ( isBehindCameraNear ) {
  36590. continue;
  36591. }
  36592. // trim the segment if it extends behind camera near
  36593. if ( _start4.z > near ) {
  36594. const deltaDist = _start4.z - _end4.z;
  36595. const t = ( _start4.z - near ) / deltaDist;
  36596. _start4.lerp( _end4, t );
  36597. } else if ( _end4.z > near ) {
  36598. const deltaDist = _end4.z - _start4.z;
  36599. const t = ( _end4.z - near ) / deltaDist;
  36600. _end4.lerp( _start4, t );
  36601. }
  36602. // clip space
  36603. _start4.applyMatrix4( projectionMatrix );
  36604. _end4.applyMatrix4( projectionMatrix );
  36605. // ndc space [ - 1.0, 1.0 ]
  36606. _start4.multiplyScalar( 1 / _start4.w );
  36607. _end4.multiplyScalar( 1 / _end4.w );
  36608. // screen space
  36609. _start4.x *= resolution.x / 2;
  36610. _start4.y *= resolution.y / 2;
  36611. _end4.x *= resolution.x / 2;
  36612. _end4.y *= resolution.y / 2;
  36613. // create 2d segment
  36614. _line.start.copy( _start4 );
  36615. _line.start.z = 0;
  36616. _line.end.copy( _end4 );
  36617. _line.end.z = 0;
  36618. // get closest point on ray to segment
  36619. const param = _line.closestPointToPointParameter( _ssOrigin3, true );
  36620. _line.at( param, _closestPoint );
  36621. // check if the intersection point is within clip space
  36622. const zPos = MathUtils.lerp( _start4.z, _end4.z, param );
  36623. const isInClipSpace = zPos >= - 1 && zPos <= 1;
  36624. const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
  36625. if ( isInClipSpace && isInside ) {
  36626. _line.start.fromBufferAttribute( instanceStart, i );
  36627. _line.end.fromBufferAttribute( instanceEnd, i );
  36628. _line.start.applyMatrix4( matrixWorld );
  36629. _line.end.applyMatrix4( matrixWorld );
  36630. const pointOnLine = new Vector3();
  36631. const point = new Vector3();
  36632. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  36633. intersects.push( {
  36634. point: point,
  36635. pointOnLine: pointOnLine,
  36636. distance: _ray$3.origin.distanceTo( point ),
  36637. object: lineSegments,
  36638. face: null,
  36639. faceIndex: i,
  36640. uv: null,
  36641. uv2: null,
  36642. } );
  36643. }
  36644. }
  36645. }
  36646. class LineSegments2 extends Mesh {
  36647. constructor( geometry = new LineSegmentsGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36648. super( geometry, material );
  36649. this.isLineSegments2 = true;
  36650. this.type = 'LineSegments2';
  36651. }
  36652. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  36653. computeLineDistances() {
  36654. const geometry = this.geometry;
  36655. const instanceStart = geometry.attributes.instanceStart;
  36656. const instanceEnd = geometry.attributes.instanceEnd;
  36657. const lineDistances = new Float32Array( 2 * instanceStart.count );
  36658. for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
  36659. _start$2.fromBufferAttribute( instanceStart, i );
  36660. _end$2.fromBufferAttribute( instanceEnd, i );
  36661. lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
  36662. lineDistances[ j + 1 ] = lineDistances[ j ] + _start$2.distanceTo( _end$2 );
  36663. }
  36664. const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
  36665. geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
  36666. geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
  36667. return this;
  36668. }
  36669. raycast( raycaster, intersects ) {
  36670. const worldUnits = this.material.worldUnits;
  36671. const camera = raycaster.camera;
  36672. if ( camera === null && ! worldUnits ) {
  36673. console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
  36674. }
  36675. const threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
  36676. _ray$3 = raycaster.ray;
  36677. const matrixWorld = this.matrixWorld;
  36678. const geometry = this.geometry;
  36679. const material = this.material;
  36680. _lineWidth = material.lineWidth + threshold;
  36681. _instanceStart = geometry.attributes.instanceStart;
  36682. _instanceEnd = geometry.attributes.instanceEnd;
  36683. // check if we intersect the sphere bounds
  36684. if ( geometry.boundingSphere === null ) {
  36685. geometry.computeBoundingSphere();
  36686. }
  36687. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
  36688. // increase the sphere bounds by the worst case line screen space width
  36689. let sphereMargin;
  36690. if ( worldUnits ) {
  36691. sphereMargin = _lineWidth * 0.5;
  36692. } else {
  36693. const distanceToSphere = Math.max( camera.near, _sphere$4.distanceToPoint( _ray$3.origin ) );
  36694. sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, material.resolution );
  36695. }
  36696. _sphere$4.radius += sphereMargin;
  36697. if ( _ray$3.intersectsSphere( _sphere$4 ) === false ) {
  36698. return;
  36699. }
  36700. // check if we intersect the box bounds
  36701. if ( geometry.boundingBox === null ) {
  36702. geometry.computeBoundingBox();
  36703. }
  36704. _box$5.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
  36705. // increase the box bounds by the worst case line width
  36706. let boxMargin;
  36707. if ( worldUnits ) {
  36708. boxMargin = _lineWidth * 0.5;
  36709. } else {
  36710. const distanceToBox = Math.max( camera.near, _box$5.distanceToPoint( _ray$3.origin ) );
  36711. boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, material.resolution );
  36712. }
  36713. _box$5.expandByScalar( boxMargin );
  36714. if ( _ray$3.intersectsBox( _box$5 ) === false ) {
  36715. return;
  36716. }
  36717. if ( worldUnits ) {
  36718. raycastWorldUnits( this, intersects );
  36719. } else {
  36720. raycastScreenSpace( this, camera, intersects );
  36721. }
  36722. }
  36723. }
  36724. class LineGeometry extends LineSegmentsGeometry {
  36725. constructor() {
  36726. super();
  36727. this.isLineGeometry = true;
  36728. this.type = 'LineGeometry';
  36729. }
  36730. setPositions( array ) {
  36731. // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
  36732. const length = array.length - 3;
  36733. const points = new Float32Array( 2 * length );
  36734. for ( let i = 0; i < length; i += 3 ) {
  36735. points[ 2 * i ] = array[ i ];
  36736. points[ 2 * i + 1 ] = array[ i + 1 ];
  36737. points[ 2 * i + 2 ] = array[ i + 2 ];
  36738. points[ 2 * i + 3 ] = array[ i + 3 ];
  36739. points[ 2 * i + 4 ] = array[ i + 4 ];
  36740. points[ 2 * i + 5 ] = array[ i + 5 ];
  36741. }
  36742. super.setPositions( points );
  36743. return this;
  36744. }
  36745. setColors( array ) {
  36746. // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
  36747. const length = array.length - 3;
  36748. const colors = new Float32Array( 2 * length );
  36749. for ( let i = 0; i < length; i += 3 ) {
  36750. colors[ 2 * i ] = array[ i ];
  36751. colors[ 2 * i + 1 ] = array[ i + 1 ];
  36752. colors[ 2 * i + 2 ] = array[ i + 2 ];
  36753. colors[ 2 * i + 3 ] = array[ i + 3 ];
  36754. colors[ 2 * i + 4 ] = array[ i + 4 ];
  36755. colors[ 2 * i + 5 ] = array[ i + 5 ];
  36756. }
  36757. super.setColors( colors );
  36758. return this;
  36759. }
  36760. fromLine( line ) {
  36761. const geometry = line.geometry;
  36762. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  36763. // set colors, maybe
  36764. return this;
  36765. }
  36766. }
  36767. class Line2 extends LineSegments2 {
  36768. constructor( geometry = new LineGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36769. super( geometry, material );
  36770. this.isLine2 = true;
  36771. this.type = 'Line2';
  36772. }
  36773. }
  36774. var defaultColor = new Color(1,1,1);//config.applicationName == "zhiHouse" ? Colors.zhiBlue : Colors.lightGreen;
  36775. var LineDraw = {
  36776. createLine: function (posArr, o={}) {
  36777. //多段普通线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  36778. var mat;
  36779. if(o.mat){
  36780. mat = o.mat;
  36781. }else {
  36782. let prop = {
  36783. lineWidth: o.lineWidth || 1,
  36784. //windows无效。 似乎mac/ios上粗细有效 ?
  36785. color: o.color || defaultColor,
  36786. transparent: o.dontAlwaysSeen ? false : true,
  36787. depthTest: o.dontAlwaysSeen ? true : false,
  36788. };
  36789. if(o.deshed ){
  36790. prop.dashSize = o.dashSize || 0.1,
  36791. prop.gapSize = o.gapSize || 0.1;
  36792. }
  36793. mat = new THREE$1[o.deshed ? "LineDashedMaterial" : "LineBasicMaterial"](prop);
  36794. }
  36795. var line = new LineSegments(new BufferGeometry, mat);
  36796. line.renderOrder = o.renderOrder || 4;
  36797. this.moveLine(line, posArr);
  36798. return line;
  36799. },
  36800. moveLine: function (line, posArr) {
  36801. if(posArr.length == 0)return
  36802. let position = [];
  36803. posArr.forEach(e=>position.push(e.x,e.y,e.z));
  36804. line.geometry.setAttribute('position', new Float32BufferAttribute(/* new Float32Array( */position/* ) */, 3));
  36805. line.geometry.attributes.position.needsUpdate = true;
  36806. line.geometry.computeBoundingSphere();
  36807. if(line.material instanceof LineDashedMaterial){
  36808. line.computeLineDistances();
  36809. //line.geometry.attributes.lineDistance.needsUpdate = true;
  36810. line.geometry.verticesNeedUpdate = true; //没用
  36811. }
  36812. }
  36813. ,
  36814. createFatLineMat : function(o){
  36815. var supportExtDepth = !!Features.EXT_DEPTH.isSupported();
  36816. let params = $.extend({}, {
  36817. //默认
  36818. lineWidth : 5,
  36819. color:0xffffff,
  36820. transparent : true, depthWrite:false, depthTest:false,
  36821. dashSize : 0.1, gapSize:0.1,
  36822. }, o, {
  36823. //修正覆盖:
  36824. dashed: o.dashWithDepth ? supportExtDepth && !!o.dashed : !!o.dashed ,
  36825. dashWithDepth:!!o.dashWithDepth,//只在被遮住的部分显示虚线
  36826. useDepth: !!o.useDepth,
  36827. supportExtDepth,
  36828. });
  36829. var mat = new LineMaterial(params);
  36830. //if(o.dashed)(mat.defines.USE_DASH = "")
  36831. return mat;
  36832. },
  36833. /*
  36834. 创建可以改变粗细的线。
  36835. */
  36836. createFatLine : function(posArr, o){
  36837. var geometry = new LineGeometry();
  36838. geometry.setColors( o.color || [1,1,1]);
  36839. var matLine = o.material || this.createFatLineMat(o);
  36840. var line = new Line2( geometry, matLine );
  36841. //line.computeLineDistances();
  36842. line.scale.set( 1, 1, 1 );
  36843. line.renderOrder = 2;
  36844. this.moveFatLine(line, posArr);
  36845. return line;
  36846. },
  36847. moveFatLine: function(line, posArr){
  36848. var geometry = line.geometry;
  36849. var positions = [];
  36850. posArr.forEach(e=>{positions.push(...e.toArray());});
  36851. if(positions.length > 0){
  36852. if(!geometry){
  36853. geometry = line.geometry = new LineGeometry();
  36854. }
  36855. if(geometry.attributes.instanceEnd && geometry.attributes.instanceEnd.data.array.length != positions.length){//positions个数改变会有部分显示不出来,所以重建
  36856. geometry.dispose();
  36857. geometry = new LineGeometry();
  36858. line.geometry = geometry;
  36859. }
  36860. geometry.setPositions( positions );
  36861. if(line.material.defines.USE_DASH != void 0){
  36862. //line.geometry.verticesNeedUpdate = true; //没用
  36863. line.geometry.computeBoundingSphere(); //for raycaster
  36864. line.computeLineDistances();
  36865. }
  36866. }else {
  36867. geometry.dispose();
  36868. line.geometry = new LineGeometry();
  36869. }
  36870. },
  36871. updateLine: function(line, posArr){
  36872. if(line instanceof Line2){
  36873. LineDraw.moveFatLine(line,posArr);
  36874. }else {
  36875. LineDraw.moveLine(line,posArr);
  36876. }
  36877. },
  36878. /*
  36879. 为line创建用于检测鼠标的透明mesh,实际是个1-2段圆台。
  36880. 由于近大远小的原因,假设没有透视畸变、创建的是等粗的圆柱的话, 所看到的线上每个位置的粗细应该和距离成反比。所以将圆柱改为根据距离线性渐变其截面半径的圆台,在最近点(相机到线的垂足)最细。如果最近点在线段上,则分成两段圆台,否则一段。
  36881. */
  36882. createBoldLine:function(points, o){
  36883. o = o || {};
  36884. var cylinder = o && o.cylinder;
  36885. var CD = points[1].clone().sub(points[0]);
  36886. var rotate = function(){//根据端点旋转好模型
  36887. cylinder.lastVector = CD;//记录本次的端点向量
  36888. var AB = new Vector3(0,-1,0);
  36889. var axisVec = AB.clone().cross(CD).normalize(); //得到垂直于它们的向量,也就是旋转轴
  36890. var rotationAngle = AB.angleTo(CD);
  36891. cylinder.quaternion.setFromAxisAngle( axisVec, rotationAngle );
  36892. };
  36893. if(o && o.type == "init"){
  36894. cylinder = new Mesh();
  36895. cylinder.material = o.mat;
  36896. if(CD.length() == 0)return cylinder;
  36897. rotate();
  36898. }
  36899. if(CD.length() == 0)return cylinder;
  36900. if(o.type != "update"){
  36901. var CDcenter = points[0].clone().add(points[1]).multiplyScalar(.5);
  36902. cylinder.position.copy(CDcenter);
  36903. if(!cylinder.lastVector || o.type == "moveAndRotate")rotate();
  36904. else if(cylinder.lastVector && CD.angleTo(cylinder.lastVector)>0) rotate();//线方向改了or线反向了 重新旋转一下模型
  36905. if(config.isEdit && !objects.mainDesign.editing )return cylinder;//节省初始加载时间?
  36906. }
  36907. //为了保证线段任何地方的可检测点击范围看起来一样大,更新圆台的结构(但是在镜头边缘会比中心看起来大)
  36908. var height = points[0].distanceTo(points[1]);
  36909. var standPos = o && o.standPos || objects.player.position;
  36910. var k = config.isMobile ? 20 : 40;
  36911. var dis1 = points[0].distanceTo(standPos);
  36912. var dis2 = points[1].distanceTo(standPos);
  36913. var foot = math.getFootPoint(standPos, points[0], points[1]);//垂足
  36914. if(o.constantBold || objects.player.mode != "panorama"){
  36915. var width = 0.1;//0.08;
  36916. var pts = [new Vector2$1(width ,height/2),new Vector2$1(width ,-height/2)];
  36917. }else if(foot.clone().sub(points[0]).dot( foot.clone().sub(points[1]) ) > 0){//foot不在线段上
  36918. var pts = [new Vector2$1(dis1 / k,height/2),new Vector2$1(dis2 / k,-height/2)];
  36919. }else {//在线段上的话,要在垂足这加一个节点,因它距离站位最近,而两端较远
  36920. var dis3 = foot.distanceTo(standPos);
  36921. var len = foot.distanceTo(points[0]);
  36922. var pts = [new Vector2$1(dis1 / k,height/2), new Vector2$1(dis3 / k,height/2-len), new Vector2$1(dis2 / k,-height/2)];
  36923. }
  36924. cylinder.geometry && cylinder.geometry.dispose();//若不删除会占用内存
  36925. cylinder.geometry = new LatheBufferGeometry( pts, 4/* Math.min(dis1,dis2)<10?4:3 */ );
  36926. cylinder.renderOrder = 2;
  36927. return cylinder;
  36928. },
  36929. updateBoldLine:function(cylinder, points, type, standPos, constantBold){
  36930. this.createBoldLine(points,{type:type, cylinder : cylinder, standPos:standPos, constantBold}); //type:move:平移 会改长短 , type:update根据距离和角度更新 不改长短
  36931. },
  36932. };
  36933. var MeshDraw = {
  36934. getShape:function(points, holes){
  36935. var shape = new Shape();
  36936. shape.moveTo( points[0].x, points[0].y );
  36937. for(var i=1,len=points.length; i<len; i++){
  36938. shape.lineTo(points[i].x, points[i].y );
  36939. }
  36940. /* var holePath = new THREE.Path()
  36941. .moveTo( 20, 10 )
  36942. .absarc( 10, 10, 10, 0, Math.PI * 2, true )
  36943. arcShape.holes.push( holePath );
  36944. */
  36945. if(holes){//挖空
  36946. holes.forEach((points)=>{
  36947. var holePath = new Path();
  36948. holePath.moveTo( points[0].x, points[0].y );
  36949. for(var i=1,len=points.length; i<len; i++){
  36950. holePath.lineTo(points[i].x, points[i].y );
  36951. }
  36952. shape.holes.push( holePath );
  36953. });
  36954. }
  36955. return shape
  36956. },
  36957. getShapeGeo: function(points, holes){//获取任意形状(多边形或弧形)的形状面 //quadraticCurveTo() 这是弧形的含函数
  36958. var geometry = new ShapeBufferGeometry( this.getShape(points, holes) ); //ShapeGeometry
  36959. /* var matrix = new THREE.Matrix4();//将竖直的面变为水平
  36960. matrix.set(//z = y
  36961. 1, 0, 0, 0,
  36962. 0, 0, 0, 0,
  36963. 0, 1, 0, 0,
  36964. 0, 0, 0, 1
  36965. )
  36966. geometry.applyMatrix(matrix) */
  36967. //geometry.computeVertexNormals();//对于光照需要的是点法线
  36968. return geometry;
  36969. },
  36970. getExtrudeGeo: function(points, holes, options={}){//获得挤出棱柱,可以选择传递height,或者extrudePath
  36971. var shape = this.getShape(points, holes); //points是横截面 [vector2,...]
  36972. if(options.extrudePath ){// 路径 :[vector3,...]
  36973. var length = extrudePath.reduce((total, currentValue, currentIndex, arr)=>{
  36974. if(currentIndex == 0)return 0
  36975. return total + currentValue.distanceTo(arr[currentIndex-1]);
  36976. },0);
  36977. options.extrudePath = new CatmullRomCurve3(extrudePath, options.closed , 'catmullrom' /* 'centripetal' */ , options.tension);
  36978. }
  36979. var extrudeSettings = $.extend(options,{
  36980. steps: options.steps != void 0 ? options.steps : ( options.extrudePath ? Math.round(length/0.3) : 1),
  36981. bevelEnabled: false, //不加的话,height为0时会有圆弧高度
  36982. //depth
  36983. });
  36984. var geometry = new ExtrudeBufferGeometry( shape, extrudeSettings );
  36985. return geometry;
  36986. },
  36987. getUnPosPlaneGeo : function(){//获取还没有赋值位置的plane geometry
  36988. var e = new Uint16Array([0, 1, 2, 0, 2, 3])
  36989. // , t = new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0])
  36990. , i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])
  36991. , g = new BufferGeometry;
  36992. g.setIndex(new BufferAttribute(e, 1)),
  36993. //g.addAttribute("position", new n.BufferAttribute(t, 3)),
  36994. g.setAttribute("uv", new BufferAttribute(i, 2));
  36995. return function(){
  36996. return g
  36997. }
  36998. }(),
  36999. getPlaneGeo : function(A,B,C,D){
  37000. var geo = this.getUnPosPlaneGeo().clone();
  37001. var pos = [
  37002. A.x, A.y, A.z,
  37003. B.x, B.y, B.z,
  37004. C.x, C.y, C.z,
  37005. D.x, D.y, D.z
  37006. ];
  37007. //geo.addAttribute("position", new THREE.BufferAttribute(pos, 3))
  37008. geo.setAttribute('position', new Float32BufferAttribute(pos, 3));
  37009. geo.computeVertexNormals();
  37010. geo.computeBoundingSphere(); //for raycaster
  37011. return geo;
  37012. },
  37013. drawPlane : function(A,B,C,D, material){
  37014. var wall = new Mesh(this.getPlaneGeo(A,B,C,D), material);
  37015. return wall;
  37016. },
  37017. movePlane: function(mesh, A,B,C,D){
  37018. var pos = new Float32Array([
  37019. A.x, A.y, A.z,
  37020. B.x, B.y, B.z,
  37021. C.x, C.y, C.z,
  37022. D.x, D.y, D.z
  37023. ]);
  37024. mesh.geometry.addAttribute("position", new BufferAttribute(pos, 3));
  37025. mesh.geometry.computeBoundingSphere();//for checkIntersect
  37026. }
  37027. ,
  37028. createGeometry:function(posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  37029. let geo = new BufferGeometry;
  37030. let positions = [];
  37031. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  37032. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  37033. if(faceArr){
  37034. let indice = [];
  37035. faceArr.forEach(f=>indice.push(...f));
  37036. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  37037. }
  37038. if(uvArr){
  37039. let uvs = [];
  37040. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  37041. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  37042. }
  37043. if(normalArr){
  37044. let normals = [];
  37045. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  37046. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  37047. }
  37048. /*
  37049. geo.computeVertexNormals()
  37050. geo.computeBoundingSphere() //for raycaster
  37051. */
  37052. return geo
  37053. },
  37054. updateGeometry:function(geo, posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  37055. let positions = [];
  37056. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  37057. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  37058. geo.attributes.position.needsUpdate = true;
  37059. if(faceArr){
  37060. let indice = [];
  37061. faceArr.forEach(f=>indice.push(...f));
  37062. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  37063. }
  37064. if(uvArr){
  37065. let uvs = [];
  37066. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  37067. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  37068. }
  37069. if(normalArr){
  37070. let normals = [];
  37071. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  37072. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  37073. }
  37074. /*
  37075. geo.computeVertexNormals()
  37076. */
  37077. geo.computeBoundingSphere(); //for raycaster and visi
  37078. return geo
  37079. }
  37080. };
  37081. const verticalLine = new Line3();
  37082. //控制点和边的合集。具有可以拖拽修改的功能,拖拽时能防止线相交。
  37083. class ctrlPolygon extends Object3D {
  37084. constructor (type, prop) {
  37085. super();
  37086. this.type = type;
  37087. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  37088. this.transformData(prop);
  37089. for(let i in prop){
  37090. this[i] = prop[i];
  37091. }
  37092. if(this.closed && this.dimension == '2d'){
  37093. this.areaPlane = this.createAreaPlane();
  37094. this.add(this.areaPlane);
  37095. }
  37096. //数据--刚开始一定是空的
  37097. this.points = [];
  37098. //mesh 不一定有
  37099. this.markers = [];
  37100. this.edges = [];
  37101. this.center;
  37102. }
  37103. initData(prop){
  37104. //开始加数据
  37105. if(Potree.settings.editType == 'merge'){ //融合页面没有地图,measure的不需要指定datasetId,每个点都有各自的datasetId,跟着各自的模型走
  37106. if(this.dataset_points){
  37107. this.dataset_points = this.dataset_points.map(e=>{
  37108. return e && new Vector3().copy(e)
  37109. });
  37110. prop.points = this.dataset_points.map((p,i)=>{
  37111. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.points_datasets[i], position: p})
  37112. });
  37113. if(prop.points.some(e=>e == void 0)){
  37114. return false
  37115. }
  37116. }else {
  37117. this.dataset_points = [];
  37118. }
  37119. }
  37120. if(prop.points){
  37121. for(const p of prop.points){
  37122. const pos = new Vector3().copy(p);
  37123. this.addMarker({point:pos});
  37124. }
  37125. if(Potree.settings.editType != 'merge'){
  37126. if(this.datasetId != void 0){//初始化位置
  37127. if(this.dataset_points){
  37128. this.dataset_points = this.dataset_points.map(e=>{
  37129. return e && new Vector3().copy(e)
  37130. });
  37131. this.transformByPointcloud(); //根据dataset_points生成points
  37132. }
  37133. }else {
  37134. if(prop.dataset_points && prop.dataset_points.some(e=>e != void 0)){
  37135. console.error('存在测量线的datasetId为空而dataset_points有值,请检查并删除:'+this.sid);//存在过的bug,原因未知,可能是后台处理dataset时替换的错误:http://192.168.0.21/index.php?m=bug&f=view&bugID=23601
  37136. console.log(this);
  37137. }
  37138. }
  37139. }
  37140. this.getFacePlane();
  37141. this.getPoint2dInfo(this.points);
  37142. this.update({ifUpdateMarkers:true});
  37143. //this.dragChange(new THREE.Vector3().copy(prop.points[prop.points.length-1]), prop.points.length-1);
  37144. this.setSelected(false );
  37145. this.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  37146. return true
  37147. }
  37148. }
  37149. addMarker(o={}){
  37150. var index = o.index == void 0 ? this.points.length : o.index; //要当第几个
  37151. this.points = [...this.points.slice(0,index), o.point, ...this.points.slice(index,this.points.length)];
  37152. //this.points.push(o.point);
  37153. if(o.marker){
  37154. this.add(o.marker);
  37155. this.markers = [...this.markers.slice(0,index), o.marker, ...this.markers.slice(index,this.markers.length)];
  37156. this.updateMarker(o.marker, o.point);
  37157. o.marker.addEventListener('drag', this.dragMarker.bind(this));
  37158. o.marker.addEventListener('drop', this.dropMarker.bind(this));
  37159. let addHoverEvent = (e)=>{
  37160. let mouseover = (e) => {
  37161. this.setMarkerSelected(e.object, 'hover', 'single');
  37162. viewer.dispatchEvent({
  37163. type : "CursorChange", action : "add", name:"markerMove"
  37164. });
  37165. };
  37166. let mouseleave = (e) => {
  37167. this.setMarkerSelected(e.object, 'unhover', 'single');
  37168. viewer.dispatchEvent({
  37169. type : "CursorChange", action : "remove", name:"markerMove"
  37170. });
  37171. };
  37172. o.marker.addEventListener('mouseover', mouseover);
  37173. o.marker.addEventListener('mouseleave', mouseleave);
  37174. o.marker.removeEventListener('addHoverEvent',addHoverEvent);
  37175. };
  37176. o.marker.addEventListener('addHoverEvent',addHoverEvent);//当非isNew时才添加事件
  37177. if(!this.isNew){
  37178. o.marker.dispatchEvent('addHoverEvent');
  37179. }
  37180. }
  37181. if(o.edge){
  37182. this.add(o.edge);
  37183. this.edges = [...this.edges.slice(0,index), o.edge, ...this.edges.slice(index,this.edges.length)];
  37184. }
  37185. }
  37186. dragMarker(e){
  37187. var I, atMap;
  37188. if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  37189. viewer.dispatchEvent({
  37190. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  37191. });
  37192. return
  37193. }
  37194. viewer.dispatchEvent({
  37195. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37196. });
  37197. atMap = e.drag.dragViewport.name == 'mapViewport';
  37198. if(atMap && this.unableDragAtMap){
  37199. e.drag.object = null; //取消拖拽
  37200. return
  37201. }
  37202. e.drag.object.isDragging = true;
  37203. I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  37204. //记录数据集
  37205. //在三维中脱离点云(在map中拉到周围都没有点云的地方)的顶点,无法拖拽怎么办
  37206. if (I) {
  37207. let i = this.markers.indexOf(e.drag.object);
  37208. if (i !== -1) {
  37209. this.dragChange(I.clone(), i, atMap);
  37210. /* if(this.points_datasets){
  37211. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id
  37212. else this.points_datasets[i] = null
  37213. } */
  37214. if(this.points_datasets){
  37215. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id;
  37216. else if(e.intersect.object) this.points_datasets[i] = e.intersect.object.dataset_id;
  37217. else this.points_datasets[i] = null;
  37218. }
  37219. }
  37220. this.editStateChange(true);
  37221. return true
  37222. }
  37223. };
  37224. dragChange(intersectPos, i, atMap){
  37225. let len = this.markers.length;
  37226. let oldPoint = this.points[i];
  37227. if(atMap){
  37228. intersectPos.setZ(oldPoint.z); //在地图上拖拽,不改变其高度。
  37229. }
  37230. let location = intersectPos.clone();
  37231. if(this.faceDirection && this.maxMarkers == 2 && len == 2){//add 固定方向的点不直接拖拽
  37232. var p1 = this.markers[0].position;
  37233. if(this.faceDirection == 'horizontal'){
  37234. var projectPos = location.clone().setZ(p1.z);
  37235. }else {
  37236. var projectPos = p1.clone().setZ(location.z);
  37237. }
  37238. //var p2 = p1.clone().add(this.direction)
  37239. //var projectPos = math.getFootPoint(location, p1, p2)
  37240. LineDraw.updateLine(this.guideLine, [location, projectPos]);
  37241. location = projectPos;
  37242. this.guideLine.visible = true;
  37243. }else if( len > 1){
  37244. var points = this.points.map(e=>e.clone());
  37245. points[i].copy(location); //算normal需要提前确认point
  37246. //若为定义了面朝向的矩形
  37247. if(this.faceDirection == 'horizontal'){
  37248. if(len == 2){
  37249. location.setZ(points[0].z);
  37250. }
  37251. if(!this.facePlane){//一个点就能确定面
  37252. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( new Vector3(0,0,1), this.points[0] );
  37253. }
  37254. }else if(this.faceDirection == 'vertical'){//当有两个点时, 有两个方向的可能
  37255. if(len == 2){
  37256. if(this.isRect){
  37257. let vec = points[0].clone().sub(location);
  37258. if(Math.sqrt(vec.x*vec.x+vec.y*vec.y) > Math.abs(vec.z) ){//水平(高度差小于水平距离时)
  37259. location.setZ(points[0].z);
  37260. //this.cannotConfirmNormal = false;//能确定面为水平方向
  37261. }else {//垂直 (当两点一样时也属于这种)
  37262. location.setX(points[0].x);
  37263. location.setY(points[0].y);
  37264. //this.cannotConfirmNormal = true; //不能确定面,因第三点可绕着纵轴线自由移动
  37265. }
  37266. }
  37267. }else {
  37268. {//判断cannotConfirmNormal. 如果前几段都在竖直线上,就不能固定出面方向。
  37269. this.cannotConfirmNormal = true;
  37270. let max = this.isRect ? 1 : len-2;
  37271. for(let i=0;i<max;i++){
  37272. let p1 = points[i].clone();
  37273. let p2 = points[i+1].clone();
  37274. let vec = p1.sub(p2);
  37275. if(vec.x != 0 || vec.y != 0){
  37276. this.cannotConfirmNormal = false;
  37277. break;
  37278. }
  37279. }
  37280. }
  37281. if(!this.facePlane || this.cannotConfirmNormal){//三个点且为水平方向时,计算面
  37282. var points_ = points.map(e=>new Vector2$1(e.x,e.y));
  37283. var points2 = getDifferentPoint(points_, 2);
  37284. if(points2){
  37285. let normal = math.getNormal2d({p1:points2[0], p2:points2[1]});
  37286. normal = new Vector3(normal.x, normal.y, 0);
  37287. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] );
  37288. }
  37289. }
  37290. }
  37291. }
  37292. if(len > 2){//area
  37293. if(!this.faceDirection){
  37294. if(len == 3 || this.isRect) this.cannotConfirmNormal = true; //当第三个点固定后(有四个点时)才能固定面
  37295. if(!this.facePlane || this.cannotConfirmNormal){
  37296. var points3 = getDifferentPoint(points, 3);//只有找到三个不同的点算拥有面和area
  37297. if(points3){
  37298. this.facePlane = new Plane().setFromCoplanarPoints(...points3 );
  37299. }
  37300. }
  37301. }
  37302. if( this.facePlane && !this.cannotConfirmNormal ){//之后加的点一定要在面上
  37303. if(atMap){
  37304. //地图上用垂直线,得到和面的交点。
  37305. verticalLine.set(location.clone().setZ(100000), location.clone().setZ(-100000));//确保长度范围覆盖所有测量面
  37306. location = this.facePlane.intersectLine(verticalLine, new Vector3() );
  37307. if(!location) return;
  37308. }else {
  37309. location = this.facePlane.projectPoint(intersectPos, new Vector3() );
  37310. }
  37311. }
  37312. points[i].copy(location);//再copy确认一次
  37313. if(this.isRect){ //是矩形 (即使没有faceDirection也能执行)
  37314. //根据前两个点计算当前和下一个点
  37315. var p1 = points[(i-2+len)%len];
  37316. var p2 = points[(i-1+len)%len];
  37317. if(p1.equals(p2)){//意外情况:重复点两次 ( bug点,改了好多遍)
  37318. if(this.faceDirection == 'vertical'){
  37319. p2.add(new Vector3(0,0,0.0001));
  37320. }else {
  37321. p2.add(new Vector3(0,0.0001,0));
  37322. }
  37323. }
  37324. //p3 : location
  37325. var foot = math.getFootPoint(location, p1, p2);//p2 修改p2到垂足的位置
  37326. var vec = foot.clone().sub(location);
  37327. var p4 = p1.clone().sub(vec);
  37328. points[(i-1+len)%len].copy(foot);
  37329. points[(i+1)%len].copy(p4);
  37330. this.setPosition((i-1+len)%len, foot);//p2
  37331. this.setPosition((i+1)%len, p4);
  37332. }
  37333. /* let points2d;
  37334. if(this.facePlane){
  37335. var originPoint0 = points[0].clone()
  37336. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,1));
  37337. points2d = points.map(e=>e.clone().applyQuaternion(qua))
  37338. } */
  37339. this.getPoint2dInfo(points);
  37340. var isIntersectSelf = !this.isRect && len > 3 && this.intersectSelf(this.point2dInfo.points2d);//检测相交
  37341. if(isIntersectSelf){
  37342. //not-allowed
  37343. viewer.dispatchEvent({
  37344. type : "CursorChange", action : "add", name:"polygon_isIntersectSelf"
  37345. });
  37346. this.isIntersectSelf = true;
  37347. return
  37348. }else {
  37349. this.isIntersectSelf = false;
  37350. viewer.dispatchEvent({
  37351. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  37352. });
  37353. /* this.facePlane && (this.point2dInfo = {
  37354. originPoint0 ,
  37355. points2d,
  37356. quaInverse : qua.clone().invert()
  37357. }) */
  37358. }
  37359. }
  37360. var showGuideLine = len>1 && (this.faceDirection || len > 3);
  37361. if(showGuideLine && this.guideLine){
  37362. LineDraw.updateLine(this.guideLine, [intersectPos, location]);
  37363. this.guideLine.visible = true;
  37364. }
  37365. //console.log(this.points.map(e=>e.toArray()))
  37366. }
  37367. if(this.restrictArea){
  37368. let holes = this.restrictArea.holes.concat(this.restrictArea.parentHoles);
  37369. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  37370. if(!math.isPointInArea(this.restrictArea.points, holesPoints, location)){
  37371. viewer.dispatchEvent({
  37372. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  37373. });
  37374. this.isAtWrongPlace = true;
  37375. return
  37376. }
  37377. //就不处理相交线了。 有个缺点:floor上的hole可以限制room,但hole不受room限制,会导致room的marker被框在hole里而动不了。只能去调整hole了
  37378. }
  37379. viewer.dispatchEvent({
  37380. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37381. });
  37382. this.isAtWrongPlace = false;
  37383. this.setPosition(i, location);
  37384. this.update();
  37385. this.dispatchEvent({type:'dragChange', index:i});
  37386. }
  37387. dropMarker(e){
  37388. //console.log('dropMarker')
  37389. if (this.isNew && e.pressDistance>Potree.config.clickMaxDragDis){//拖拽的话返回
  37390. return this.continueDrag(null,e)
  37391. }
  37392. if(e.isTouch){
  37393. if(e.hoverViewport != viewer.mainViewport && this.unableDragAtMap){
  37394. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  37395. //console.log('reticule_forbit',true)
  37396. return this.continueDrag(null,e)
  37397. }else {
  37398. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  37399. //console.log('reticule_forbit',false)
  37400. }
  37401. this.dragMarker(e); //触屏时必须先更新下点
  37402. }
  37403. if (e.button != MOUSE.RIGHT && (//右键click的话继续执行,因为会停止
  37404. this.isIntersectSelf && this.isNew //有线相交了
  37405. || this.isAtWrongPlace && this.isNew
  37406. || !e.isAtDomElement && this.isNew//如果是刚添加时在其他dom点击, 不要响应
  37407. || e.hoverViewport != viewer.mainViewport && this.unableDragAtMap //垂直的测量线不允许在地图上放点
  37408. || this.isNew && !getDifferentPoint(this.points, this.points.length ) //不允许和之前的点相同, 但这句在点云稀疏时会导致难结束
  37409. )
  37410. ){
  37411. return this.continueDrag(null,e)
  37412. }
  37413. //console.log('drop marker' )
  37414. let i = this.markers.indexOf(e.drag.object);
  37415. if (i !== -1) {
  37416. this.dispatchEvent({
  37417. 'type': 'marker_dropped',
  37418. 'index': i
  37419. });
  37420. if(this.markers.length>2 && this.facePlane)this.cannotConfirmNormal = false;
  37421. this.guideLine &&(this.guideLine.visible = false);
  37422. }
  37423. this.setMarkerSelected(e.drag.object, 'unhover', 'single');
  37424. this.editStateChange(false);
  37425. e.drag.endDragFun && e.drag.endDragFun(e);// addmarker
  37426. //if(this.changeCallBack)this.changeCallBack()
  37427. return true
  37428. };
  37429. getFacePlane(){//最普通一种get方法,根据顶点。且假设所有点已经共面,且不重合
  37430. if(this.points.length<3) return
  37431. this.facePlane = new Plane().setFromCoplanarPoints(...this.points.slice(0,3) );
  37432. }
  37433. getPoint2dInfo(points){ //在更新areaplane之前必须更新过point2dInfo
  37434. if(this.facePlane){
  37435. var originPoint0 = points[0].clone();
  37436. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  37437. let points2d = points.map(e=>e.clone().applyQuaternion(qua));
  37438. this.point2dInfo = {
  37439. originPoint0 ,
  37440. points2d,
  37441. quaInverse : qua.clone().invert()
  37442. };
  37443. }
  37444. }
  37445. setPosition (index, position) {//拖拽后设置位置
  37446. let point = this.points[index];
  37447. point.copy(position);
  37448. /* if(this.datasetId){
  37449. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.datasetId, position:point.clone()})
  37450. } */
  37451. /* if(Potree.settings.editType == 'merge'){
  37452. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true,this.points_datasets[i], position:point.clone()})
  37453. } */
  37454. let marker = this.markers[index];
  37455. this.updateMarker(marker, point);
  37456. }
  37457. updateMarker(marker, pos){
  37458. marker.position.copy(pos);
  37459. marker.update();
  37460. }
  37461. intersectSelf(points2d){//add
  37462. var len = points2d.length;
  37463. for(var i=0;i<len;i++){
  37464. for(var j=i+2;j<len;j++){
  37465. if(Math.abs(j-len-i)<2)continue;//不和邻边比
  37466. var p1 = points2d[i];
  37467. var p2 = points2d[i+1];
  37468. var p3 = points2d[j];
  37469. var p4 = points2d[(j+1)%len];
  37470. if(p1.equals(p2) || p3.equals(p4) || p1.equals(p3) || p2.equals(p3) || p1.equals(p4) || p2.equals(p4))continue
  37471. var line1 = [p1,p2];
  37472. var line2 = [p3,p4];
  37473. var intersect = math.isLineIntersect(line1, line2, false, 0.001);
  37474. if(intersect){
  37475. return true
  37476. break
  37477. }
  37478. }
  37479. }
  37480. }
  37481. removeMarker (index) {
  37482. this.points.splice(index, 1);
  37483. const marker = this.markers[index];
  37484. //this.remove(marker);
  37485. this.markers.splice(index, 1);
  37486. marker.dispatchEvent({type:'dispose'});
  37487. let edgeIndex = index; //(index === 0) ? 0 : (index - 1);
  37488. const edge = this.edges[edgeIndex];
  37489. if(edge){
  37490. this.remove(edge);
  37491. this.edges.splice(edgeIndex, 1);
  37492. edge.dispatchEvent({type:'dispose'});
  37493. }
  37494. this.point2dInfo && this.point2dInfo.points2d.splice(index, 1); //add
  37495. this.dispatchEvent({type:'removeMarker',index,marker});
  37496. }
  37497. createAreaPlane(mat){
  37498. var geometry = new Geometry();
  37499. var mesh = new Mesh(geometry, mat);
  37500. return mesh
  37501. }
  37502. updateAreaPlane(){
  37503. if(!this.point2dInfo)return
  37504. this.areaPlane.geometry.dispose();
  37505. if(this.points.length>2){
  37506. this.areaPlane.geometry = MeshDraw.getShapeGeo(this.point2dInfo.points2d);
  37507. var center = math.getCenterOfGravityPoint(this.point2dInfo.points2d); //重心
  37508. var firstPos = this.point2dInfo.points2d[0].clone();
  37509. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  37510. firstPos.applyQuaternion(this.point2dInfo.quaInverse);
  37511. var vec = this.point2dInfo.originPoint0.clone().sub(firstPos);
  37512. center = new Vector3(center.x, center.y, 0);
  37513. center.applyQuaternion(this.point2dInfo.quaInverse);
  37514. this.areaPlane.quaternion.copy(this.point2dInfo.quaInverse);
  37515. this.areaPlane.position.copy(vec);
  37516. center.add(vec);
  37517. this.center = center;
  37518. }else {
  37519. this.areaPlane.geometry = new Geometry();
  37520. }
  37521. }
  37522. update(options={}){
  37523. if(this.points.length === 0){
  37524. return;
  37525. }
  37526. let lastIndex = this.points.length - 1;
  37527. for (let index = 0; index <= lastIndex; index++) {
  37528. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  37529. let previousIndex = (index === 0) ? lastIndex : index - 1;
  37530. let point = this.points[index];
  37531. let nextPoint = this.points[nextIndex];
  37532. let previousPoint = this.points[previousIndex];
  37533. if(options.ifUpdateMarkers){
  37534. this.updateMarker(this.markers[index], point);
  37535. }
  37536. { // edges
  37537. let edge = this.edges[index];
  37538. if(edge){
  37539. LineDraw.updateLine(edge, [point, nextPoint]);
  37540. //edge.visible = index < lastIndex || this.isRect || (this.closed && !this.isNew);
  37541. }
  37542. }
  37543. }
  37544. if(this.areaPlane){
  37545. this.updateAreaPlane();
  37546. }
  37547. //this.dispatchEvent({type:'update'})
  37548. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); //暂时先这么都通知
  37549. }
  37550. dispose(){//add
  37551. this.parent.remove(this);
  37552. this.markers.concat(this.edges).forEach(e=>e.dispatchEvent({type:'dispose'}));
  37553. }
  37554. reDraw(restMarkerCount=0){//重新开始画
  37555. let pointCount = this.points.length - restMarkerCount; // restMarkerCount为需要留下的marker数量
  37556. while(pointCount > 0){
  37557. this.removeMarker(--pointCount);
  37558. }
  37559. this.point2dInfo = null;
  37560. this.facePlane = null;
  37561. }
  37562. setMarkerSelected(){}
  37563. editStateChange(state){
  37564. if(!state){
  37565. viewer.dispatchEvent({
  37566. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  37567. });
  37568. viewer.dispatchEvent({
  37569. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37570. });
  37571. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  37572. this.markers.forEach(e=>e.isDragging = false );
  37573. }
  37574. }
  37575. transformData(){}
  37576. setSelected(){}
  37577. continueDrag(marker, e){
  37578. let object = marker || e.drag.object;
  37579. object.isDragging = true;
  37580. var timer = setTimeout(()=>{//等 drag=null之后 //右键拖拽结束后需要重新得到drag
  37581. if(this.parent && object.isDragging){
  37582. //console.log('continueDrag')
  37583. viewer.inputHandler.startDragging( object ,
  37584. {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport}
  37585. );
  37586. }
  37587. },1);
  37588. return timer
  37589. }
  37590. }
  37591. function getDifferentPoint(points, count){//for facePlane
  37592. var result = [];
  37593. for(let i=0;i<points.length;i++){
  37594. var p = points[i];
  37595. if(result.find(e=>e.equals(p)))continue;
  37596. else result.push(p);
  37597. if(result.length == count)break
  37598. }
  37599. if(result.length == count)return result
  37600. }
  37601. let texLoader = new TextureLoader();
  37602. let defaultColor$1 = new Color(config$1.measure.default.color);
  37603. let highlightColor = new Color(config$1.measure.highlight.color);
  37604. let color = new Color(config$1.measure.color);
  37605. let textColor = new Color(config$1.measure.textColor);
  37606. var markerMats;
  37607. var lineMats;
  37608. var planeMats;
  37609. const lineDepthInfo = {
  37610. clipDistance : 4,//消失距离
  37611. occlusionDistance: 1,//变为backColor距离
  37612. };
  37613. const LabelDepthInfo = {
  37614. clipDistance : 6,//消失距离
  37615. occlusionDistance: 2,//变为backColor距离
  37616. };
  37617. /* const LabelDepthInfo = {
  37618. clipDistance : 0.1,//消失距离
  37619. occlusionDistance: 0.1,//变为backColor距离
  37620. } */
  37621. const markerSizeInfo = {
  37622. minSize : 25 , maxSize : 65, nearBound : 0.2, farBound : 4,
  37623. };
  37624. const labelSizeInfo = {width2d:200};
  37625. const mainLabelProp = {
  37626. backgroundColor: {r: defaultColor$1.r*255, g: defaultColor$1.g*255, b: defaultColor$1.b*255, a:config$1.measure.default.opacity},
  37627. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  37628. fontsize:16,
  37629. useDepth : true ,
  37630. renderOrder : 5, pickOrder:5,
  37631. };
  37632. const subLabelProp = {
  37633. backgroundColor: {r: 255, g: 255, b: 255, a:1},
  37634. textColor: {r: 0, g: 0, b:0, a: 1.0},
  37635. fontsize:14,
  37636. renderOrder : 4, pickOrder:4,
  37637. };
  37638. const angle = MathUtils.degToRad(5);//显示水平垂直辅助线的最小角度
  37639. const guideShowMinAngle = {min: angle, max: Math.PI/2 - angle};
  37640. class Measure extends ctrlPolygon{
  37641. constructor (prop) {
  37642. prop.dimension = '2d';
  37643. super('measure',prop);
  37644. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  37645. this.name = this.measureType + this.constructor.counter; //'Measure_' + this.constructor.counter;
  37646. this.markerLabels = [];
  37647. this.edgeLabels = [];
  37648. this.angleLabels = [];
  37649. this.coordinateLabels = [];
  37650. this.area = {value:0,string:''};
  37651. if(this.closed/* this.showArea */){
  37652. this.areaLabel = this.createAreaLabel();
  37653. this.add(this.areaLabel);
  37654. }
  37655. //add:
  37656. if(this.maxMarkers > 2 || this.faceDirection){
  37657. this.createGuideLine();
  37658. }
  37659. if(this.measureType == 'Distance'){
  37660. this.createHorVerGuideLine();
  37661. }
  37662. this.selectStates = {};
  37663. this.setUnitSystem(prop.unit || viewer.unitConvert.UnitService.defaultSystem);
  37664. viewer.setObjectLayers(this, 'measure' );
  37665. //addMarkers:
  37666. this.initData(prop);
  37667. this.points_datasets || (this.points_datasets = []); //存每个点是哪个数据集
  37668. this.addEventListener('marker_dropped',(e)=>{
  37669. this.updateDatasetBelong(e.index);
  37670. });
  37671. this.addEventListener('isVisible', ()=>{
  37672. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  37673. });
  37674. }
  37675. initData(prop){
  37676. let makeIt = super.initData(prop);
  37677. if(makeIt){
  37678. this.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  37679. }else {
  37680. this.failBuilded = true;
  37681. }
  37682. }
  37683. updateDatasetBelong(changeIndex){//更新所属数据集
  37684. if(Potree.settings.editType == "merge"){//无地图
  37685. /* this.dataset_points = this.points.map((e,i)=>{
  37686. return Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[i], position:e.clone()})
  37687. }) */
  37688. this.dataset_points[changeIndex] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[changeIndex], position:this.points[changeIndex].clone()});
  37689. return
  37690. }
  37691. let old = this.datasetId;
  37692. let maxCount = {id:null,count:0};
  37693. let datasets = {};
  37694. this.points_datasets.forEach(e=>{
  37695. if(e == void 0)return
  37696. if(datasets[e]){
  37697. datasets[e] ++;
  37698. }else {
  37699. datasets[e] = 1;
  37700. }
  37701. });
  37702. for(let i in datasets) {
  37703. if(datasets[i]>maxCount.count){
  37704. maxCount = {id:i, count:datasets[i]};
  37705. }
  37706. }
  37707. this.datasetId = maxCount.count > 0 ? maxCount.id : null;
  37708. //if(this.datasetId != old){
  37709. //this.dispatchEvent({type:'changeDatasetId'})
  37710. if(this.datasetId == void 0){
  37711. this.dataset_points = null; //可能为空或[null,null...]
  37712. }else {
  37713. this.dataset_points = this.points.map(e=>{
  37714. return Potree.Utils.datasetPosTransform({toDataset:true,datasetId:this.datasetId, position:e.clone()})
  37715. });
  37716. }
  37717. //}
  37718. }
  37719. transformByPointcloud(){//每次移动点云 or 加载测量线时要获取一下当前position //有地图时
  37720. if(this.datasetId == void 0)return
  37721. this.points = this.dataset_points.map(e=>{
  37722. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.datasetId, position:e.clone()})
  37723. });
  37724. this.getPoint2dInfo(this.points);
  37725. this.update({ifUpdateMarkers:true});
  37726. this.setSelected(false);//隐藏edgelabel
  37727. }
  37728. update(options={}) {
  37729. super.update(options);
  37730. if(this.showCoordinates && this.points.length>0){
  37731. let position = this.points[0];
  37732. this.markers[0].position.copy(position);
  37733. { // coordinate labels
  37734. let coordinateLabel = this.coordinateLabels[0];
  37735. let lonlat = viewer.transform.lonlatToLocal.inverse(position.toArray());
  37736. let EPSG4550 = viewer.transform.lonlatTo4550.forward(lonlat);
  37737. let pos = [
  37738. position.toArray(),
  37739. lonlat,
  37740. EPSG4550
  37741. ];
  37742. //let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  37743. let msg = pos.map(a=>
  37744. a.map(p => Utils.addCommas(p.toFixed(10))).join(", ")
  37745. ).join("<br>");
  37746. coordinateLabel.setText(msg);
  37747. coordinateLabel.setPos(position);
  37748. coordinateLabel.setVisible(true);//this.showCoordinates;
  37749. }
  37750. return
  37751. }
  37752. let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字
  37753. let center = new Vector3().addVectors(p1,p2).multiplyScalar(0.5);
  37754. label.setPos(center);
  37755. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  37756. var text = viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision, this.unitSystem, 0.1 , true);//distance要传0.1 这个factor
  37757. label.setText(text);
  37758. return distance
  37759. };
  37760. let lastIndex = this.points.length - 1;
  37761. for (let index = 0; index <= lastIndex; index++) {
  37762. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  37763. let previousIndex = (index === 0) ? lastIndex : index - 1;
  37764. let point = this.points[index];
  37765. let nextPoint = this.points[nextIndex];
  37766. let previousPoint = this.points[previousIndex];
  37767. if(this.showDistances){ // edge labels
  37768. let edgeLabel = this.edgeLabels[index];
  37769. let distance = point.distanceTo(nextPoint);
  37770. edgeLabel.shouldVisi = (index < lastIndex || this.isRect || this.closed && !this.isNew /* && this.points.length > 2 */) && distance>0;
  37771. /* this.closed || */edgeLabel.setVisible(edgeLabel.shouldVisi);
  37772. if(edgeLabel.visible){
  37773. setEdgeLabel(edgeLabel,point,nextPoint,distance);
  37774. }
  37775. }
  37776. }
  37777. if(this.measureType == 'Distance' && this.points.length>1){//设置水平垂直辅助线
  37778. var pTop, pBtm;
  37779. if(this.points[0].z > this.points[1].z ){
  37780. pTop = this.points[0];
  37781. pBtm = this.points[1];
  37782. }else {
  37783. pTop = this.points[1];
  37784. pBtm = this.points[0];
  37785. }
  37786. let projectPos = new Vector3(pTop.x, pTop.y, pBtm.z);//两条guideline的交点
  37787. {//倾斜角度太小的时候不显示
  37788. let tan = pTop.distanceTo(projectPos) / pBtm.distanceTo(projectPos);
  37789. let angle = Math.atan(tan);
  37790. this.shouldShowHorVerGuide = angle > guideShowMinAngle.min && angle < guideShowMinAngle.max;
  37791. }
  37792. LineDraw.updateLine(this.verGuideEdge, [pTop, projectPos]);
  37793. LineDraw.updateLine(this.horGuideEdge, [pBtm, projectPos]);
  37794. setEdgeLabel(this.verEdgeLabel,pTop,projectPos);
  37795. setEdgeLabel(this.horEdgeLabel,pBtm,projectPos);
  37796. this.verGuideEdge.visible = this.horGuideEdge.visible = this.shouldShowHorVerGuide;
  37797. this.verEdgeLabel.visible = this.horEdgeLabel.visible = this.shouldShowHorVerGuide;
  37798. }
  37799. if(this.showArea && this.point2dInfo){ // update area
  37800. /* if(this.points.length>2){
  37801. this.area = {value:0};
  37802. this.areaLabel.setVisible(false)
  37803. }else{ */
  37804. let area = Math.abs(math.getArea(this.point2dInfo.points2d));//this.getArea();
  37805. let msg = viewer.unitConvert.convert(area, 'area', Potree.settings.precision, this.unitSystem/* , 0.1 */ );
  37806. this.area = {value:area, string:msg};
  37807. this.areaLabel.setPos(this.center);
  37808. this.areaLabel.setText(msg);
  37809. this.areaLabel.setVisible(true);
  37810. //}
  37811. }
  37812. };
  37813. addMarker (o={}) {
  37814. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo, name:"measure_point"} );
  37815. viewer.setObjectLayers(marker, 'measure' );
  37816. marker.pickOrder = marker.renderOrder = 3;
  37817. marker.markerSelectStates = {};
  37818. marker.addEventListener('startDragging',(e)=>{
  37819. if(e.drag.dragViewport.name == 'MainView')viewer.inputHandler.dispatchEvent( {type: 'isMeasuring',v:true, cause:'startDragging'});
  37820. });
  37821. marker.addEventListener('drop',(e)=>{
  37822. viewer.inputHandler.dispatchEvent({type: 'isMeasuring', v:false, cause:'stopDragging'} );
  37823. });
  37824. let edge;
  37825. { // edges
  37826. edge = LineDraw.createFatLine( [ ],{material:this.getLineMat('edgeDefault')} );
  37827. edge.pickOrder = 0;
  37828. viewer.setObjectLayers(edge, 'measure' );
  37829. let addHoverEvent = ()=>{ //当非isNew时才添加事件
  37830. let mouseover = (e) => {this.setSelected(true, 'edge');};
  37831. let mouseleave = (e) => {this.setSelected(false, 'edge');};
  37832. edge.addEventListener('mouseover', mouseover);
  37833. edge.addEventListener('mouseleave', mouseleave);
  37834. edge.removeEventListener('addHoverEvent', addHoverEvent);
  37835. };
  37836. edge.addEventListener('addHoverEvent', addHoverEvent);
  37837. }
  37838. super.addMarker({point:o.point, marker:marker, edge});
  37839. if(this.showEdges){ // edge labels
  37840. const edgeLabel = this.createEdgeLabel('edgeLabel', !this.closed);
  37841. this.edgeLabels.push(edgeLabel);
  37842. }
  37843. if(this.showCoordinates){ // coordinate labels
  37844. let coordinateLabel = new Label({
  37845. className:'measure_pointPos',
  37846. camera: viewer.scene.getActiveCamera()
  37847. });
  37848. coordinateLabel.setVisible(false);
  37849. this.coordinateLabels.push(coordinateLabel);
  37850. }
  37851. let event = {
  37852. type: 'marker_added',
  37853. measurement: this,
  37854. marker: marker
  37855. };
  37856. this.dispatchEvent(event);
  37857. //this.setMarker(this.points.length - 1, point);
  37858. this.update();//更新一下倒数第二条线
  37859. return marker;//add
  37860. };
  37861. editStateChange(state){ //主要针对edgeLabels显示切换,编辑时显示
  37862. super.editStateChange(state);
  37863. if(!state){
  37864. this.editStateTimer = setTimeout(()=>{
  37865. if(!this.isEditing){
  37866. this.dispatchEvent({type:'editStateChange',state:false});
  37867. this.setEdgesDisplay(false);
  37868. }
  37869. },100);
  37870. }else {
  37871. if(!this.isEditing){
  37872. this.dispatchEvent({type:'editStateChange',state:true});
  37873. this.setEdgesDisplay(true);
  37874. clearTimeout(this.editStateTimer);
  37875. }
  37876. }
  37877. this.isEditing = state;
  37878. }
  37879. setMarkerSelected(marker, state, hoverObject){
  37880. //console.warn(marker.id , state, hoverObject)
  37881. marker.markerSelectStates[hoverObject] = state;
  37882. let absoluteState = false;
  37883. for(var i in marker.markerSelectStates){
  37884. if(marker.markerSelectStates[i] == 'hover'){
  37885. absoluteState = true; break;
  37886. }
  37887. }
  37888. if(absoluteState){
  37889. marker.material = this.getMarkerMaterial('select');
  37890. }else {
  37891. marker.material = this.getMarkerMaterial('default');
  37892. }
  37893. marker.selected = absoluteState;
  37894. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  37895. }
  37896. setEdgesDisplay(state, ignoreGuideLine){
  37897. this.closed && this.edgeLabels.forEach(e=>e.setVisible(!!(state && e.shouldVisi)) );
  37898. if(!ignoreGuideLine && this.measureType == 'Distance'){
  37899. this.horEdgeLabel.visible = this.verEdgeLabel.visible = this.horGuideEdge.visible = this.verGuideEdge.visible = !!(state && this.shouldShowHorVerGuide);
  37900. }
  37901. }
  37902. setSelected(state, hoverObject){//add
  37903. //console.log('setSelected',state, hoverObject)
  37904. hoverObject && (this.selectStates[hoverObject] = state);
  37905. let absoluteState = false;
  37906. for(var i in this.selectStates){
  37907. if(this.selectStates[i]){
  37908. absoluteState = true; break;
  37909. }
  37910. }
  37911. if(absoluteState){
  37912. this.markers.forEach(e=>this.setMarkerSelected(e, 'hover', 'selectAll' ) );
  37913. this.edges.forEach(e=>e.material = this.getLineMat('edgeSelect') );
  37914. this.areaPlane && (this.areaPlane.material = planeMats.selected);
  37915. //this.areaLabel && this.areaLabel.elem.addClass('highLight')
  37916. //this.closed || this.edgeLabels.forEach(e=>e.elem.addClass('highLight') )
  37917. this.setEdgesDisplay(true, hoverObject=="screenshot");
  37918. this.areaLabel && setLabelHightState(this.areaLabel, true);
  37919. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, true) );
  37920. }else {
  37921. this.markers.forEach(e=>this.setMarkerSelected(e, 'unhover', 'selectAll' ));
  37922. this.edges.forEach(e=>e.material = this.getLineMat('edgeDefault') );
  37923. this.areaPlane && (this.areaPlane.material = planeMats.default);
  37924. this.setEdgesDisplay(false, hoverObject=="screenshot");
  37925. //this.areaLabel && this.areaLabel.elem.removeClass('highLight')
  37926. //this.closed || this.edgeLabels.forEach(e=>e.elem.removeClass('highLight') )
  37927. this.areaLabel && setLabelHightState(this.areaLabel, false);
  37928. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, false) );
  37929. }
  37930. this.selected = absoluteState;
  37931. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  37932. if(hoverObject != 'byList'){
  37933. //this.bus && this.bus.emit('highlight', this.selected)
  37934. this.dispatchEvent({type:'highlight',state:this.selected});//列表高亮
  37935. }
  37936. }
  37937. removeMarker(index ){
  37938. super.removeMarker(index);
  37939. this.points_datasets.splice(index, 1);
  37940. this.dataset_points && this.dataset_points.splice(index, 1);
  37941. this.coordinateLabels.splice(index, 1);
  37942. let edgeIndex = index;//(index === 0) ? 0 : (index - 1);
  37943. if(this.edgeLabels[edgeIndex]){
  37944. this.edgeLabels[edgeIndex].dispose();
  37945. this.edgeLabels.splice(edgeIndex, 1);
  37946. }
  37947. this.update();
  37948. this.dispatchEvent({type: 'marker_removed', measurement: this});
  37949. }
  37950. setPosition(index, position) {
  37951. super.setPosition(index, position);
  37952. let event = {
  37953. type: 'marker_moved',
  37954. measure: this,
  37955. index: index,
  37956. position: position.clone()
  37957. };
  37958. this.dispatchEvent(event);
  37959. }
  37960. dispose(){//add
  37961. var labels = this.edgeLabels.concat(this.coordinateLabels);
  37962. this.areaLabel && labels.push(this.areaLabel);
  37963. labels.forEach(e=>e.dispatchEvent({type:'dispose'}));
  37964. super.dispose();
  37965. }
  37966. getTotalDistance () {
  37967. if (this.points.length === 0) {
  37968. return 0;
  37969. }
  37970. let distance = 0;
  37971. for (let i = 1; i < this.points.length; i++) {
  37972. let prev = this.points[i - 1];
  37973. let curr = this.points[i];
  37974. let d = prev.distanceTo(curr);
  37975. distance += d;
  37976. }
  37977. if (this.closed && this.points.length > 1) {
  37978. let first = this.points[0];
  37979. let last = this.points[this.points.length - 1];
  37980. let d = last.distanceTo(first);
  37981. distance += d;
  37982. }
  37983. return distance;
  37984. }
  37985. getAngleBetweenLines (cornerPoint, point1, point2) {
  37986. let v1 = new Vector3().subVectors(point1, cornerPoint);
  37987. let v2 = new Vector3().subVectors(point2, cornerPoint);
  37988. // avoid the error printed by threejs if denominator is 0
  37989. const denominator = Math.sqrt( v1.lengthSq() * v2.lengthSq() );
  37990. if(denominator === 0){
  37991. return 0;
  37992. }else {
  37993. return v1.angleTo(v2);
  37994. }
  37995. };
  37996. getAngle (index) {
  37997. if (this.points.length < 3 || index >= this.points.length) {
  37998. return 0;
  37999. }
  38000. let previous = (index === 0) ? this.points[this.points.length - 1] : this.points[index - 1];
  38001. let point = this.points[index];
  38002. let next = this.points[(index + 1) % (this.points.length)];
  38003. return this.getAngleBetweenLines(point, previous, next);
  38004. }
  38005. getCenter(/* update */){
  38006. if(this.points.length>=3){
  38007. return this.center.clone()
  38008. }else if(this.points.length == 2){
  38009. return this.points[0].clone().add((this.points[1])).multiplyScalar(0.5)
  38010. }else return this.points[0].clone()
  38011. }
  38012. // updateAzimuth(){
  38013. // // if(this.points.length !== 2){
  38014. // // return;
  38015. // // }
  38016. // // const azimuth = this.azimuth;
  38017. // // const [p0, p1] = this.points;
  38018. // // const r = p0.distanceTo(p1);
  38019. // }
  38020. createGuideLine(){//add 辅助线
  38021. var guideLine = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38022. guideLine.visible = false;
  38023. this.guideLine = guideLine;
  38024. this.add(guideLine);
  38025. }
  38026. createHorVerGuideLine(){//创建水平与垂直辅助线,仅距离测量有。
  38027. var verGuideEdge = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38028. verGuideEdge.visible = false;
  38029. this.verGuideEdge = verGuideEdge;
  38030. var horGuideEdge = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38031. horGuideEdge.visible = false;
  38032. this.horGuideEdge = horGuideEdge;
  38033. this.add(this.verGuideEdge);
  38034. this.add(this.horGuideEdge);
  38035. //label:
  38036. this.verEdgeLabel = this.createEdgeLabel('verGuideEdge');
  38037. this.horEdgeLabel = this.createEdgeLabel('horGuideEdge');
  38038. }
  38039. createEdgeLabel(name, hasHoverEvent){
  38040. const edgeLabel = new TextSprite(
  38041. $.extend(hasHoverEvent ? mainLabelProp : subLabelProp,{sizeInfo: labelSizeInfo, name:name||'edgeLabel'})
  38042. );
  38043. if(hasHoverEvent){
  38044. edgeLabel.addEventListener('mouseover',()=>{
  38045. this.setSelected(true, 'edgeLabel');
  38046. });
  38047. edgeLabel.addEventListener('mouseleave',()=>{
  38048. this.setSelected(false, 'edgeLabel');
  38049. });
  38050. edgeLabel.addEventListener('click',()=>{
  38051. viewer.focusOnObject(this, 'measure');
  38052. });
  38053. }
  38054. edgeLabel.visible = false;
  38055. edgeLabel.sprite.material.depthTestWhenPick = true;
  38056. viewer.setObjectLayers(edgeLabel, 'measure' );
  38057. this.add(edgeLabel);
  38058. return edgeLabel
  38059. }
  38060. createAreaLabel(){
  38061. /* const areaLabel = new Label({
  38062. className:'measure_area',
  38063. })
  38064. areaLabel.elem.on('mouseover',()=>{
  38065. this.setSelected(true, 'areaLabel')
  38066. })
  38067. areaLabel.elem.on('mouseout',()=>{
  38068. this.setSelected(false, 'areaLabel')
  38069. }) */
  38070. const areaLabel = new TextSprite(
  38071. $.extend(mainLabelProp,{sizeInfo: labelSizeInfo, name:'areaLabel_'} )
  38072. );
  38073. areaLabel.addEventListener('mouseover',()=>{
  38074. this.setSelected(true, 'areaLabel');
  38075. });
  38076. areaLabel.addEventListener('mouseleave',()=>{
  38077. this.setSelected(false, 'areaLabel');
  38078. });
  38079. areaLabel.addEventListener('click',()=>{
  38080. viewer.focusOnObject(this, 'measure');
  38081. });
  38082. viewer.setObjectLayers(areaLabel, 'measure' );
  38083. areaLabel.visible = false;
  38084. return areaLabel;
  38085. }
  38086. getMarkerMaterial(type) {
  38087. if(!markerMats){
  38088. markerMats = {
  38089. default: new DepthBasicMaterial($.extend({},lineDepthInfo,{
  38090. transparent: !0,
  38091. opacity: 1,
  38092. map: texLoader.load(Potree.resourcePath+'/textures/pic_point_s32.png' ),
  38093. useDepth:true
  38094. })),
  38095. select: new MeshBasicMaterial({
  38096. transparent: !0,
  38097. opacity: 1,
  38098. depthTest:false,
  38099. map: texLoader.load(Potree.resourcePath+'/textures/pic_point32.png'/* , null, null, { antialias: false } */),
  38100. }),
  38101. };
  38102. Measure.markerMats = markerMats;
  38103. }
  38104. return markerMats[type]
  38105. }
  38106. getLineMat(type) {
  38107. if(!Measure.lineMats){
  38108. Measure.lineMats = {
  38109. edgeDefault: LineDraw.createFatLineMat({
  38110. color: config$1.measure.default.color,
  38111. lineWidth: config$1.measure.lineWidth,
  38112. useDepth :true,
  38113. dashWithDepth :true, // 只在被遮住的部分显示虚线,因为实线容易挡住label
  38114. dashed :true,
  38115. dashSize : 0.04,
  38116. gapSize: 0.04,
  38117. transparent: true,
  38118. opacity: config$1.measure.default.opacity,
  38119. depthTestWhenPick:true,
  38120. }),
  38121. edgeSelect: LineDraw.createFatLineMat({
  38122. color: config$1.measure.highlight.color,//'#f0ff00',
  38123. dashSize: 0.5,
  38124. gapSize: 0.2,
  38125. lineWidth: config$1.measure.lineWidth ,
  38126. transparent: true,
  38127. opacity: config$1.measure.highlight.opacity
  38128. }),
  38129. guide: LineDraw.createFatLineMat({
  38130. color:config$1.measure.guide.color,
  38131. dashSize: 0.1,
  38132. gapSize: 0.02,
  38133. dashed: true,
  38134. lineWidth: config$1.measure.lineWidth
  38135. })
  38136. };
  38137. }
  38138. return Measure.lineMats[type]
  38139. }
  38140. createAreaPlane(){
  38141. planeMats || (planeMats = {
  38142. default: new DepthBasicMaterial( $.extend({},LabelDepthInfo,{
  38143. color:color,
  38144. side:DoubleSide,
  38145. opacity:0.2,
  38146. transparent:true,
  38147. useDepth:true
  38148. })),
  38149. selected: new MeshBasicMaterial({
  38150. color: color ,
  38151. side:DoubleSide,
  38152. opacity:0.3,
  38153. transparent:true,
  38154. })
  38155. },Measure.planeMats = planeMats);
  38156. return super.createAreaPlane(planeMats.default)
  38157. }
  38158. raycast (raycaster, intersects) {
  38159. for (let i = 0; i < this.points.length; i++) {
  38160. let marker = this.markers[i];
  38161. marker.raycast(raycaster, intersects);
  38162. }
  38163. // recalculate distances because they are not necessarely correct
  38164. // for scaled objects.
  38165. // see https://github.com/mrdoob/three.js/issues/5827
  38166. // TODO: remove this once the bug has been fixed
  38167. for (let i = 0; i < intersects.length; i++) {
  38168. let I = intersects[i];
  38169. I.distance = raycaster.ray.origin.distanceTo(I.point);
  38170. }
  38171. intersects.sort(function (a, b) { return a.distance - b.distance; });
  38172. };
  38173. transformData(prop){
  38174. if(prop.measureType == 'Point'){
  38175. prop.showCoordinates = true,
  38176. prop.closed = true,
  38177. prop.maxMarkers = 1,
  38178. prop.minMarkers = 1;
  38179. }else if(prop.measureType == 'Distance'){
  38180. prop.showDistances = true,
  38181. prop.closed = false,
  38182. prop.showEdges = true,
  38183. prop.maxMarkers = 2,
  38184. prop.minMarkers = 2;
  38185. }else if(prop.measureType == 'Ver Distance'){
  38186. prop.showDistances = true,
  38187. prop.closed = false,
  38188. prop.showEdges = true,
  38189. prop.maxMarkers = 2,
  38190. prop.minMarkers = 2,
  38191. prop.faceDirection = "vertical";
  38192. prop.unableDragAtMap = true;
  38193. }else if(prop.measureType == 'Hor Distance'){
  38194. prop.showDistances = true,
  38195. prop.closed = false,
  38196. prop.showEdges = true,
  38197. prop.maxMarkers = 2,
  38198. prop.minMarkers = 2,
  38199. prop.faceDirection = "horizontal";
  38200. }else if(prop.measureType == 'Area'){
  38201. prop.showDistances = true,
  38202. prop.showArea = true,
  38203. prop.showEdges = true,
  38204. prop.closed = true,
  38205. prop.minMarkers = 3;
  38206. }else if(prop.measureType == 'Hor Area'){
  38207. prop.showDistances = true,
  38208. prop.showArea = true,
  38209. prop.showEdges = true,
  38210. prop.closed = true,
  38211. prop.minMarkers = 3;
  38212. prop.faceDirection = "horizontal";
  38213. }else if(prop.measureType == 'Ver Area'){
  38214. prop.showDistances = true,
  38215. prop.showArea = true,
  38216. prop.showEdges = true,
  38217. prop.closed = true,
  38218. prop.minMarkers = 3;
  38219. prop.faceDirection = "vertical";
  38220. prop.unableDragAtMap = true;
  38221. }else if(prop.measureType == 'Rect Area'){
  38222. prop.showDistances = true,
  38223. prop.showArea = true,
  38224. prop.showEdges = true,
  38225. prop.closed = true,
  38226. prop.minMarkers = 4;
  38227. prop.maxMarkers = 4;
  38228. }else if(prop.measureType == 'Hor Rect Area'){
  38229. prop.showDistances = true,
  38230. prop.showArea = true,
  38231. prop.showEdges = true,
  38232. prop.closed = true,
  38233. prop.minMarkers = 4;
  38234. prop.maxMarkers = 4;
  38235. prop.isRect = true;
  38236. prop.faceDirection = "horizontal";
  38237. }else if(prop.measureType == 'Ver Rect Area'){
  38238. prop.showDistances = true,
  38239. prop.showArea = true,
  38240. prop.showEdges = true,
  38241. prop.closed = true,
  38242. prop.minMarkers = 4;
  38243. prop.maxMarkers = 4;
  38244. prop.isRect = true;
  38245. prop.faceDirection = "vertical";
  38246. prop.unableDragAtMap = true;
  38247. }
  38248. }
  38249. setUnitSystem(unitSystem){
  38250. //console.log(this.name +':' +this.unitSystem)
  38251. if(unitSystem != this.unitSystem){
  38252. if(unitSystem == "metric"){
  38253. }else if(unitSystem == 'imperial'){
  38254. }
  38255. this.unitSystem = unitSystem;
  38256. this.update();
  38257. }
  38258. }
  38259. reDraw(restMarkerCount=0){//重新开始画
  38260. super.reDraw(restMarkerCount);
  38261. if(this.measureType == 'Distance'){
  38262. this.shouldShowHorVerGuide = false;
  38263. this.setEdgesDisplay(false);
  38264. }
  38265. if(this.showArea){
  38266. this.area = {value:0};
  38267. this.areaLabel && this.areaLabel.setVisible(false);
  38268. }
  38269. viewer.inputHandler.dispatchEvent( {type:'isMeasuring', v:true, cause:'reDraw'} );
  38270. }
  38271. /* get showCoordinates () {
  38272. return this._showCoordinates;
  38273. }
  38274. set showCoordinates (value) {
  38275. this._showCoordinates = value;
  38276. this.update();
  38277. }
  38278. get showAngles () {
  38279. return this._showAngles;
  38280. }
  38281. set showAngles (value) {
  38282. this._showAngles = value;
  38283. this.update();
  38284. }
  38285. get showCircle () {
  38286. return this._showCircle;
  38287. }
  38288. set showCircle (value) {
  38289. this._showCircle = value;
  38290. this.update();
  38291. }
  38292. get showAzimuth(){
  38293. return this._showAzimuth;
  38294. }
  38295. set showAzimuth(value){
  38296. this._showAzimuth = value;
  38297. this.update();
  38298. }
  38299. get showEdges () {
  38300. return this._showEdges;
  38301. }
  38302. set showEdges (value) {
  38303. this._showEdges = value;
  38304. this.update();
  38305. }
  38306. get showHeight () {
  38307. return this._showHeight;
  38308. }
  38309. set showHeight (value) {
  38310. this._showHeight = value;
  38311. this.update();
  38312. }
  38313. get showArea () {
  38314. return this._showArea;
  38315. }
  38316. set showArea (value) {
  38317. this._showArea = value;
  38318. this.update();
  38319. }
  38320. get closed () {
  38321. return this._closed;
  38322. }
  38323. set closed (value) {
  38324. this._closed = value;
  38325. this.update();
  38326. }
  38327. get showDistances () {
  38328. return this._showDistances;
  38329. }
  38330. set showDistances (value) {
  38331. this._showDistances = value;
  38332. this.update();
  38333. } */
  38334. }
  38335. function setLabelHightState(label, state){
  38336. if(state){
  38337. label.backgroundColor = {r: highlightColor.r*255, g: highlightColor.g*255, b: highlightColor.b*255, a:config$1.measure.highlight.opacity},
  38338. label.backgroundColor.a = config$1.measure.highlight.opacity;
  38339. label.sprite.material.useDepth = false;
  38340. }else {
  38341. label.backgroundColor = mainLabelProp.backgroundColor;
  38342. label.backgroundColor.a = config$1.measure.default.opacity;
  38343. label.sprite.material.useDepth = true;
  38344. }
  38345. label.updateTexture();
  38346. //label.sprite.material.needsUpdate = true
  38347. }
  38348. function createCircleRadiusLabel(){
  38349. const circleRadiusLabel = new TextSprite("");
  38350. circleRadiusLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  38351. circleRadiusLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  38352. circleRadiusLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  38353. circleRadiusLabel.fontsize = 16;
  38354. circleRadiusLabel.material.depthTest = false;
  38355. circleRadiusLabel.material.opacity = 1;
  38356. circleRadiusLabel.visible = false;
  38357. return circleRadiusLabel;
  38358. }
  38359. function createCircleRadiusLine(){
  38360. /* const lineGeometry = new LineGeometry();
  38361. lineGeometry.setPositions([
  38362. 0, 0, 0,
  38363. 0, 0, 0,
  38364. ]);
  38365. const lineMaterial = new LineMaterial({
  38366. color: 0xff0000,
  38367. lineWidth: 2,
  38368. resolution: new THREE.Vector2(1000, 1000),
  38369. gapSize: 1,
  38370. dashed: true,
  38371. });
  38372. lineMaterial.depthTest = false;
  38373. const circleRadiusLine = new Line2(lineGeometry, lineMaterial);*/
  38374. var circleRadiusLine = LineDraw.createFatLine([ ],{
  38375. color:0xff0000,
  38376. dashSize: 0.5,
  38377. gapSize: 0.2,
  38378. lineWidth: config$1.measure.lineWidth
  38379. });
  38380. circleRadiusLine.visible = false;
  38381. return circleRadiusLine;
  38382. }
  38383. function createCircleLine(){
  38384. const coordinates = [];
  38385. let n = 128;
  38386. for(let i = 0; i <= n; i++){
  38387. let u0 = 2 * Math.PI * (i / n);
  38388. let u1 = 2 * Math.PI * (i + 1) / n;
  38389. let p0 = new Vector3(
  38390. Math.cos(u0),
  38391. Math.sin(u0),
  38392. 0
  38393. );
  38394. let p1 = new Vector3(
  38395. Math.cos(u1),
  38396. Math.sin(u1),
  38397. 0
  38398. );
  38399. coordinates.push(
  38400. p0,
  38401. p1
  38402. );
  38403. }
  38404. /* const geometry = new LineGeometry();
  38405. geometry.setPositions(coordinates);
  38406. const material = new LineMaterial({
  38407. color: 0xff0000,
  38408. dashSize: 5,
  38409. gapSize: 2,
  38410. lineWidth: 2,
  38411. resolution: new THREE.Vector2(1000, 1000),
  38412. });
  38413. material.depthTest = false;
  38414. const circleLine = new Line2(geometry, material);
  38415. circleLine.visible = false;
  38416. circleLine.computeLineDistances();*/
  38417. var circleLine = LineDraw.createFatLine(coordinates,{
  38418. color: 0xff0000,
  38419. dashSize: 0.5,
  38420. gapSize: 0.2,
  38421. lineWidth: config$1.measure.lineWidth
  38422. });
  38423. return circleLine;
  38424. }
  38425. /* function createCircleCenter(){
  38426. const sg = new THREE.markerGeometry(1, 32, 32);
  38427. const sm = new THREE.MeshNormalMaterial();
  38428. const circleCenter = new THREE.Mesh(sg, sm);
  38429. circleCenter.visible = false;
  38430. return circleCenter;
  38431. } */
  38432. function createLine(){
  38433. const line = LineDraw.createFatLine([ ],{
  38434. color: 0xff0000,
  38435. dashSize: 0.5,
  38436. gapSize: 0.2,
  38437. lineWidth: config$1.measure.lineWidth
  38438. });
  38439. return line;
  38440. }
  38441. function createCircle(){
  38442. const coordinates = [];
  38443. let n = 128;
  38444. for(let i = 0; i <= n; i++){
  38445. let u0 = 2 * Math.PI * (i / n);
  38446. let u1 = 2 * Math.PI * (i + 1) / n;
  38447. let p0 = new Vector3(
  38448. Math.cos(u0),
  38449. Math.sin(u0),
  38450. 0
  38451. );
  38452. let p1 = new Vector3(
  38453. Math.cos(u1),
  38454. Math.sin(u1),
  38455. 0
  38456. );
  38457. coordinates.push(
  38458. p0,
  38459. p1
  38460. );
  38461. }
  38462. var line = LineDraw.createFatLine(coordinates,{
  38463. color: 0xff0000,
  38464. dashSize: 0.5,
  38465. gapSize: 0.2,
  38466. lineWidth: config$1.measure.lineWidth
  38467. });
  38468. return line;
  38469. }
  38470. /* function createAzimuth(){
  38471. const azimuth = {
  38472. label: null,
  38473. center: null,
  38474. target: null,
  38475. north: null,
  38476. centerToNorth: null,
  38477. centerToTarget: null,
  38478. centerToTargetground: null,
  38479. targetgroundToTarget: null,
  38480. circle: null,
  38481. node: null,
  38482. };
  38483. const sg = new THREE.markerGeometry(1, 32, 32);
  38484. const sm = new THREE.MeshNormalMaterial();
  38485. {
  38486. const label = new TextSprite("");
  38487. label.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  38488. label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  38489. label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  38490. label.fontsize = 16;
  38491. label.material.depthTest = false;
  38492. label.material.opacity = 1;
  38493. azimuth.label = label;
  38494. }
  38495. azimuth.center = new THREE.Mesh(sg, sm);
  38496. azimuth.target = new THREE.Mesh(sg, sm);
  38497. azimuth.north = new THREE.Mesh(sg, sm);
  38498. azimuth.centerToNorth = createLine();
  38499. azimuth.centerToTarget = createLine();
  38500. azimuth.centerToTargetground = createLine();
  38501. azimuth.targetgroundToTarget = createLine();
  38502. azimuth.circle = createCircle();
  38503. azimuth.node = new THREE.Object3D();
  38504. azimuth.node.add(
  38505. azimuth.centerToNorth,
  38506. azimuth.centerToTarget,
  38507. azimuth.centerToTargetground,
  38508. azimuth.targetgroundToTarget,
  38509. azimuth.circle,
  38510. azimuth.label,
  38511. azimuth.center,
  38512. azimuth.target,
  38513. azimuth.north,
  38514. );
  38515. return azimuth;
  38516. } */
  38517. /*
  38518. */
  38519. class PolygonClipVolume extends Object3D{
  38520. constructor(camera){
  38521. super();
  38522. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  38523. this.name = "polygon_clip_volume_" + this.constructor.counter;
  38524. this.camera = camera.clone();
  38525. this.camera.rotation.set(...camera.rotation.toArray()); // [r85] workaround because camera.clone() doesn't work on rotation
  38526. this.camera.rotation.order = camera.rotation.order;
  38527. this.camera.updateMatrixWorld();
  38528. this.camera.updateProjectionMatrix();
  38529. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  38530. this.viewMatrix = this.camera.matrixWorldInverse.clone();
  38531. this.projMatrix = this.camera.projectionMatrix.clone();
  38532. // projected markers
  38533. this.markers = [];
  38534. this.initialized = false;
  38535. }
  38536. addMarker() {
  38537. let marker = new Mesh();
  38538. let cancel;
  38539. let drag = e => {
  38540. let size = e.viewer.renderer.getSize(new Vector2$1());
  38541. let projectedPos = new Vector3(
  38542. 2.0 * (e.drag.end.x / size.width) - 1.0,
  38543. -2.0 * (e.drag.end.y / size.height) + 1.0,
  38544. 0
  38545. );
  38546. marker.position.copy(projectedPos);
  38547. };
  38548. let drop = e => {
  38549. cancel();
  38550. };
  38551. cancel = e => {
  38552. marker.removeEventListener("drag", drag);
  38553. marker.removeEventListener("drop", drop);
  38554. };
  38555. marker.addEventListener("drag", drag);
  38556. marker.addEventListener("drop", drop);
  38557. this.markers.push(marker);
  38558. }
  38559. removeLastMarker() {
  38560. if(this.markers.length > 0) {
  38561. this.markers.splice(this.markers.length - 1, 1);
  38562. }
  38563. }
  38564. };
  38565. class Utils {
  38566. static async loadShapefileFeatures (file, callback) {
  38567. let features = [];
  38568. let handleFinish = () => {
  38569. callback(features);
  38570. };
  38571. let source = await shapefile.open(file);
  38572. while(true){
  38573. let result = await source.read();
  38574. if (result.done) {
  38575. handleFinish();
  38576. break;
  38577. }
  38578. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  38579. features.push(result.value);
  38580. }
  38581. }
  38582. }
  38583. static toString (value) {
  38584. if (value.x != null) {
  38585. return value.x.toFixed(2) + ', ' + value.y.toFixed(2) + ', ' + value.z.toFixed(2);
  38586. } else {
  38587. return '' + value + '';
  38588. }
  38589. }
  38590. static normalizeURL (url) {
  38591. let u = new URL(url);
  38592. return u.protocol + '//' + u.hostname + u.pathname.replace(/\/+/g, '/');
  38593. };
  38594. static pathExists (url) {
  38595. let req = XHRFactory.createXMLHttpRequest();
  38596. req.open('GET', url, false);
  38597. req.send(null);
  38598. if (req.status !== 200) {
  38599. return false;
  38600. }
  38601. return true;
  38602. };
  38603. static debugSphere(parent, position, scale, color){
  38604. let geometry = new SphereGeometry(1, 8, 8);
  38605. let material;
  38606. if(color !== undefined){
  38607. material = new MeshBasicMaterial({color: color});
  38608. }else {
  38609. material = new MeshNormalMaterial();
  38610. }
  38611. let sphere = new Mesh(geometry, material);
  38612. sphere.position.copy(position);
  38613. sphere.scale.set(scale, scale, scale);
  38614. parent.add(sphere);
  38615. return sphere;
  38616. }
  38617. static debugLine(parent, start, end, color){
  38618. let material = new LineBasicMaterial({ color: color });
  38619. let geometry = new Geometry();
  38620. const p1 = new Vector3(0, 0, 0);
  38621. const p2 = end.clone().sub(start);
  38622. geometry.vertices.push(p1, p2);
  38623. let tl = new Line( geometry, material );
  38624. tl.position.copy(start);
  38625. parent.add(tl);
  38626. let line = {
  38627. node: tl,
  38628. set: (start, end) => {
  38629. geometry.vertices[0].copy(start);
  38630. geometry.vertices[1].copy(end);
  38631. geometry.verticesNeedUpdate = true;
  38632. },
  38633. };
  38634. return line;
  38635. }
  38636. static debugCircle(parent, center, radius, normal, color){
  38637. let material = new LineBasicMaterial({ color: color });
  38638. let geometry = new Geometry();
  38639. let n = 32;
  38640. for(let i = 0; i <= n; i++){
  38641. let u0 = 2 * Math.PI * (i / n);
  38642. let u1 = 2 * Math.PI * (i + 1) / n;
  38643. let p0 = new Vector3(
  38644. Math.cos(u0),
  38645. Math.sin(u0),
  38646. 0
  38647. );
  38648. let p1 = new Vector3(
  38649. Math.cos(u1),
  38650. Math.sin(u1),
  38651. 0
  38652. );
  38653. geometry.vertices.push(p0, p1);
  38654. }
  38655. let tl = new Line( geometry, material );
  38656. tl.position.copy(center);
  38657. tl.scale.set(radius, radius, radius);
  38658. parent.add(tl);
  38659. }
  38660. static debugBox(parent, box, transform = new Matrix4(), color = 0xFFFF00){
  38661. let vertices = [
  38662. [box.min.x, box.min.y, box.min.z],
  38663. [box.min.x, box.min.y, box.max.z],
  38664. [box.min.x, box.max.y, box.min.z],
  38665. [box.min.x, box.max.y, box.max.z],
  38666. [box.max.x, box.min.y, box.min.z],
  38667. [box.max.x, box.min.y, box.max.z],
  38668. [box.max.x, box.max.y, box.min.z],
  38669. [box.max.x, box.max.y, box.max.z],
  38670. ].map(v => new Vector3(...v));
  38671. let edges = [
  38672. [0, 4], [4, 5], [5, 1], [1, 0],
  38673. [2, 6], [6, 7], [7, 3], [3, 2],
  38674. [0, 2], [4, 6], [5, 7], [1, 3]
  38675. ];
  38676. let center = box.getCenter(new Vector3());
  38677. let centroids = [
  38678. {position: [box.min.x, center.y, center.z], color: 0xFF0000},
  38679. {position: [box.max.x, center.y, center.z], color: 0x880000},
  38680. {position: [center.x, box.min.y, center.z], color: 0x00FF00},
  38681. {position: [center.x, box.max.y, center.z], color: 0x008800},
  38682. {position: [center.x, center.y, box.min.z], color: 0x0000FF},
  38683. {position: [center.x, center.y, box.max.z], color: 0x000088},
  38684. ];
  38685. for(let vertex of vertices){
  38686. let pos = vertex.clone().applyMatrix4(transform);
  38687. Utils.debugSphere(parent, pos, 0.1, 0xFF0000);
  38688. }
  38689. for(let edge of edges){
  38690. let start = vertices[edge[0]].clone().applyMatrix4(transform);
  38691. let end = vertices[edge[1]].clone().applyMatrix4(transform);
  38692. Utils.debugLine(parent, start, end, color);
  38693. }
  38694. for(let centroid of centroids){
  38695. let pos = new Vector3(...centroid.position).applyMatrix4(transform);
  38696. Utils.debugSphere(parent, pos, 0.1, centroid.color);
  38697. }
  38698. }
  38699. static debugPlane(parent, plane, size = 1, color = 0x0000FF){
  38700. let planehelper = new PlaneHelper(plane, size, color);
  38701. parent.add(planehelper);
  38702. }
  38703. /**
  38704. * adapted from mhluska at https://github.com/mrdoob/three.js/issues/1561
  38705. */
  38706. static computeTransformedBoundingBox (box, transform) {
  38707. let vertices = [
  38708. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  38709. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  38710. new Vector3(box.max.x, box.min.y, box.min.z).applyMatrix4(transform),
  38711. new Vector3(box.min.x, box.max.y, box.min.z).applyMatrix4(transform),
  38712. new Vector3(box.min.x, box.min.y, box.max.z).applyMatrix4(transform),
  38713. new Vector3(box.min.x, box.max.y, box.max.z).applyMatrix4(transform),
  38714. new Vector3(box.max.x, box.max.y, box.min.z).applyMatrix4(transform),
  38715. new Vector3(box.max.x, box.min.y, box.max.z).applyMatrix4(transform),
  38716. new Vector3(box.max.x, box.max.y, box.max.z).applyMatrix4(transform)
  38717. ];
  38718. let boundingBox = new Box3();
  38719. boundingBox.setFromPoints(vertices);
  38720. return boundingBox;
  38721. };
  38722. /**
  38723. * add separators to large numbers
  38724. *
  38725. * @param nStr
  38726. * @returns
  38727. */
  38728. static addCommas (nStr) {
  38729. nStr += '';
  38730. let x = nStr.split('.');
  38731. let x1 = x[0];
  38732. let x2 = x.length > 1 ? '.' + x[1] : '';
  38733. let rgx = /(\d+)(\d{3})/;
  38734. while (rgx.test(x1)) {
  38735. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  38736. }
  38737. return x1 + x2;
  38738. };
  38739. static removeCommas (str) {
  38740. return str.replace(/,/g, '');
  38741. }
  38742. /**
  38743. * create worker from a string
  38744. *
  38745. * code from http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
  38746. */
  38747. static createWorker (code) {
  38748. let blob = new Blob([code], {type: 'application/javascript'});
  38749. let worker = new Worker(URL.createObjectURL(blob));
  38750. return worker;
  38751. };
  38752. static moveTo(scene, endPosition, endTarget){
  38753. let view = scene.view;
  38754. let camera = scene.getActiveCamera();
  38755. let animationDuration = 500;
  38756. let easing = TWEEN.Easing.Quartic.Out;
  38757. { // animate camera position
  38758. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  38759. tween.easing(easing);
  38760. tween.start();
  38761. }
  38762. { // animate camera target
  38763. let camTargetDistance = camera.position.distanceTo(endTarget);
  38764. let target = new Vector3().addVectors(
  38765. camera.position,
  38766. camera.getWorldDirection(new Vector3()).clone().multiplyScalar(camTargetDistance)
  38767. );
  38768. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  38769. tween.easing(easing);
  38770. tween.onUpdate(() => {
  38771. view.lookAt(target);
  38772. });
  38773. tween.onComplete(() => {
  38774. view.lookAt(target);
  38775. });
  38776. tween.start();
  38777. }
  38778. }
  38779. static loadSkybox (path) {
  38780. let parent = new Object3D("skybox_root");
  38781. let camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  38782. if(!window.axisYup) camera.up.set(0, 0, 1);
  38783. let scene = new Scene();
  38784. let format = '.jpg';
  38785. let urls = [
  38786. path + 'px' + format, path + 'nx' + format,
  38787. path + 'py' + format, path + 'ny' + format,
  38788. path + 'pz' + format, path + 'nz' + format
  38789. ];
  38790. let materialArray = [];
  38791. {
  38792. for (let i = 0; i < 6; i++) {
  38793. let material = new MeshBasicMaterial({
  38794. map: null,
  38795. side: BackSide,
  38796. depthTest: false,
  38797. depthWrite: false,
  38798. color: 0x424556
  38799. });
  38800. materialArray.push(material);
  38801. let loader = new TextureLoader();
  38802. loader.load(urls[i],
  38803. function loaded (texture) {
  38804. material.map = texture;
  38805. material.needsUpdate = true;
  38806. material.color.setHex(0xffffff);
  38807. }, function progress (xhr) {
  38808. // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
  38809. }, function error (xhr) {
  38810. console.log('An error happened', xhr);
  38811. }
  38812. );
  38813. }
  38814. }
  38815. let skyGeometry = new BoxGeometry(700, 700, 700);
  38816. let skybox = new Mesh(skyGeometry, materialArray);
  38817. scene.add(skybox);
  38818. scene.traverse(n => n.frustumCulled = false);
  38819. // z up
  38820. scene.rotation.x = Math.PI / 2;
  38821. parent.children.push(camera);
  38822. camera.parent = parent;
  38823. return {camera, scene, parent};
  38824. };
  38825. static createGrid (width, length, spacing, color) {
  38826. let material = new LineBasicMaterial({
  38827. color: color || 0x888888
  38828. });
  38829. let geometry = new Geometry();
  38830. for (let i = 0; i <= length; i++) {
  38831. geometry.vertices.push(new Vector3(-(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  38832. geometry.vertices.push(new Vector3(+(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  38833. }
  38834. for (let i = 0; i <= width; i++) {
  38835. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, -(spacing * length) / 2, 0));
  38836. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, +(spacing * length) / 2, 0));
  38837. }
  38838. let line = new LineSegments(geometry, material, LinePieces);
  38839. line.receiveShadow = true;
  38840. return line;
  38841. }
  38842. static createBackgroundTexture (width, height) {
  38843. function gauss (x, y) {
  38844. return (1 / (2 * Math.PI)) * Math.exp(-(x * x + y * y) / 2);
  38845. };
  38846. // map.magFilter = THREE.NearestFilter;
  38847. let size = width * height;
  38848. let data = new Uint8Array(3 * size);
  38849. let chroma = [1, 1.5, 1.7];
  38850. let max = gauss(0, 0);
  38851. for (let x = 0; x < width; x++) {
  38852. for (let y = 0; y < height; y++) {
  38853. let u = 2 * (x / width) - 1;
  38854. let v = 2 * (y / height) - 1;
  38855. let i = x + width * y;
  38856. let d = gauss(2 * u, 2 * v) / max;
  38857. let r = (Math.random() + Math.random() + Math.random()) / 3;
  38858. r = (d * 0.5 + 0.5) * r * 0.03;
  38859. r = r * 0.4;
  38860. // d = Math.pow(d, 0.6);
  38861. data[3 * i + 0] = 255 * (d / 15 + 0.05 + r) * chroma[0];
  38862. data[3 * i + 1] = 255 * (d / 15 + 0.05 + r) * chroma[1];
  38863. data[3 * i + 2] = 255 * (d / 15 + 0.05 + r) * chroma[2];
  38864. }
  38865. }
  38866. let texture = new DataTexture(data, width, height, RGBFormat);
  38867. texture.needsUpdate = true;
  38868. return texture;
  38869. }
  38870. static getMousePointCloudIntersection (viewport, mouse, pointer, camera, viewer, pointclouds, pickParams = {} ) {
  38871. if(!pointclouds || pointclouds.length == 0)return
  38872. let renderer = viewer.renderer;
  38873. if(viewport){ //转换到类似整个画面时
  38874. /*let mouseInViewport = Utils.convertNDCToScreenPosition(pointer, null, viewport.resolution.x, viewport.resolution.y)
  38875. pickParams.x = mouseInViewport.x //mouse.x / viewport.width;
  38876. pickParams.y = mouseInViewport.y //renderer.domElement.clientHeight - mouse.y / viewport.height; */
  38877. pickParams.x = mouse.x;
  38878. pickParams.y = viewport.resolution.y - mouse.y;
  38879. }else {
  38880. pickParams.x = mouse.x;
  38881. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  38882. }
  38883. //console.log('getMousePointCloudIntersection')
  38884. /* if(!raycaster){
  38885. raycaster = new THREE.Raycaster();
  38886. raycaster.setFromCamera(pointer, camera);
  38887. } */
  38888. let raycaster = new Raycaster();
  38889. raycaster.setFromCamera(pointer, camera);
  38890. let ray = raycaster.ray;
  38891. let selectedPointcloud = null;
  38892. let closestDistance = Infinity;
  38893. let closestIntersection = null;
  38894. let closestPoint = null;
  38895. let density;
  38896. let sizeType;
  38897. let size = new Map();
  38898. if(pickParams.isMeasuring || Potree.settings.displayMode == 'showPanos'){ //测量或全景模式提高精准度
  38899. density = Potree.settings.pointDensity;
  38900. Potree.settings.pointDensity = 'magnifier';
  38901. pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  38902. size.set(e, e.temp.pointSize);
  38903. sizeType = e.material.pointSizeType;
  38904. e.material.pointSizeType = Potree.config.material.pointSizeType;
  38905. e.changePointSize(Potree.config.material.realPointSize*2, true);//更改点云大小到能铺满为止,否则容易识别不到
  38906. });
  38907. Potree.updatePointClouds(pointclouds, camera, viewport.resolution );
  38908. }else {
  38909. if(viewer.viewports.filter(e=>!e.noPointcloud && e.active).length>1 || pickParams.cameraChanged){
  38910. viewport.beforeRender && viewport.beforeRender();
  38911. Potree.updatePointClouds(pointclouds, camera, viewport.resolution ); //不加这句的话hover久了会不准 因node是错的
  38912. //但依旧需要camera真的移动到那个位置才能加载出点云
  38913. }
  38914. }
  38915. let allPointclouds = [];
  38916. for(let pointcloud of pointclouds){
  38917. let point = pointcloud.pick(viewer, viewport, camera, ray, pickParams );
  38918. if(!point){
  38919. continue;
  38920. }
  38921. allPointclouds.push(pointcloud);
  38922. let distance = camera.position.distanceTo(point.position);
  38923. if (distance < closestDistance) {
  38924. closestDistance = distance;
  38925. selectedPointcloud = pointcloud;
  38926. closestIntersection = point.position;
  38927. closestPoint = point;
  38928. }
  38929. }
  38930. if(pickParams.isMeasuring || Potree.settings.displayMode == 'showPanos'){
  38931. Potree.settings.pointDensity = density;
  38932. pointclouds.forEach(e=>{
  38933. e.material.pointSizeType = sizeType;
  38934. e.changePointSize(size.get(e));
  38935. });
  38936. }else {
  38937. /* if(viewer.viewports.filter(e=>!e.noPointcloud).length>1){
  38938. viewport.afterRender && viewport.afterRender()
  38939. } */
  38940. }
  38941. if (selectedPointcloud) {
  38942. return {
  38943. location: closestIntersection,
  38944. distance: closestDistance,
  38945. pointcloud: selectedPointcloud,
  38946. point: closestPoint,
  38947. pointclouds: allPointclouds, //add
  38948. normal: new Vector3().fromArray(closestPoint.normal )//add
  38949. };
  38950. } else {
  38951. return null;
  38952. }
  38953. }
  38954. static renderTargetToDataUrl(renderTarget, width, height, renderer, compressRatio = 0.7){
  38955. let pixelCount = width * height;
  38956. let buffer = new Uint8Array(4 * pixelCount);
  38957. renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer);
  38958. var dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio);
  38959. return dataUrl
  38960. }
  38961. static pixelsArrayToDataUrl(pixels, width, height, compressRatio = 0.7) {
  38962. let canvas = document.createElement('canvas');
  38963. canvas.width = width;
  38964. canvas.height = height;
  38965. let context = canvas.getContext('2d');
  38966. pixels = new pixels.constructor(pixels);
  38967. /* for (let i = 0; i < pixels.length; i++) {
  38968. pixels[i * 4 + 3] = 255;
  38969. } */
  38970. // flip vertically
  38971. let bytesPerLine = width * 4;
  38972. for(let i = 0; i < parseInt(height / 2); i++){
  38973. let j = height - i - 1;
  38974. let lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  38975. let lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  38976. pixels.set(lineJ, i * bytesPerLine);
  38977. pixels.set(lineI, j * bytesPerLine);
  38978. }
  38979. let imageData = context.createImageData(width, height);
  38980. imageData.data.set(pixels);
  38981. context.putImageData(imageData, 0, 0);
  38982. let dataURL = canvas.toDataURL(compressRatio);
  38983. return dataURL;
  38984. }
  38985. static removeListeners(dispatcher, type){
  38986. if (dispatcher._listeners === undefined) {
  38987. return;
  38988. }
  38989. if (dispatcher._listeners[ type ]) {
  38990. delete dispatcher._listeners[ type ];
  38991. }
  38992. }
  38993. /* static mouseToRay(mouse, camera, width, height){
  38994. let normalizedMouse = {
  38995. x: (mouse.x / width) * 2 - 1,
  38996. y: -(mouse.y / height) * 2 + 1
  38997. };
  38998. let vector = new THREE.Vector3(normalizedMouse.x, normalizedMouse.y, 0.5);
  38999. let origin = camera.position.clone();
  39000. vector.unproject(camera);
  39001. let direction = new THREE.Vector3().subVectors(vector, origin).normalize();
  39002. let ray = new THREE.Ray(origin, direction);
  39003. return ray;
  39004. } */
  39005. static mouseToRay(pointer, camera ){
  39006. let vector = new Vector3(pointer.x, pointer.y, 1);
  39007. let origin = new Vector3(pointer.x, pointer.y, -1); //不能用camera.position,在orbitCamera时不准
  39008. vector.unproject(camera);
  39009. origin.unproject(camera);
  39010. let direction = new Vector3().subVectors(vector, origin).normalize();
  39011. let ray = new Ray(origin, direction);
  39012. return ray;
  39013. }
  39014. static getPos2d(point, camera, dom, viewport){//获取一个三维坐标对应屏幕中的二维坐标
  39015. var pos;
  39016. if(math.closeTo(camera.position, point, 1e-5) ){ //和相机位置重合时显示会四处飘,看是要改成一直显示中间还是隐藏?
  39017. pos = new Vector3(0,0,1.5); //1.5是为了不可见
  39018. }else {
  39019. pos = point.clone().project(camera); //比之前hotspot的计算方式写得简单 project用于3转2(求法同shader); unproject用于2转3 :new r.Vector3(e.x, e.y, -1).unproject(this.camera);
  39020. }
  39021. var x,y,left,top;
  39022. x = (pos.x + 1) / 2 * dom.clientWidth * viewport.width;
  39023. y = (1 - (pos.y + 1) / 2) * dom.clientHeight * viewport.height;
  39024. left = viewport.left * dom.clientWidth;
  39025. top = (1- viewport.bottom - viewport.height) * dom.clientHeight;
  39026. var inSight = pos.x <= 1 && pos.x >= -1 //是否在屏幕中
  39027. && pos.x <= 1 && pos.y >= -1;
  39028. return {
  39029. pos: new Vector2$1(left+x,top+y) ,// 屏幕像素坐标
  39030. vector: pos, //(范围 -1 ~ 1)
  39031. trueSide : pos.z<1, //trueSide为false时,即使在屏幕范围内可见,也是反方向的另一个不可以被渲染的点 参见Tag.update
  39032. inSight : inSight, //在屏幕范围内可见,
  39033. posInViewport: new Vector2$1(x,y)
  39034. };
  39035. }
  39036. static projectedRadius(radius, camera, distance, screenWidth, screenHeight){
  39037. if(camera instanceof OrthographicCamera){
  39038. return Utils.projectedRadiusOrtho(radius, camera.projectionMatrix, screenWidth, screenHeight);
  39039. }else if(camera instanceof PerspectiveCamera){
  39040. return Utils.projectedRadiusPerspective(radius, camera.fov * Math.PI / 180, distance, screenHeight);
  39041. }else {
  39042. throw new Error("invalid parameters");
  39043. }
  39044. }
  39045. static projectedRadiusPerspective(radius, fov, distance, screenHeight) {
  39046. let projFactor = (1 / Math.tan(fov / 2)) / distance;
  39047. projFactor = projFactor * screenHeight / 2;
  39048. return radius * projFactor;
  39049. }
  39050. static projectedRadiusOrtho(radius, proj, screenWidth, screenHeight) {
  39051. let p1 = new Vector4(0);
  39052. let p2 = new Vector4(radius);
  39053. p1.applyMatrix4(proj);
  39054. p2.applyMatrix4(proj);
  39055. p1 = new Vector3(p1.x, p1.y, p1.z);
  39056. p2 = new Vector3(p2.x, p2.y, p2.z);
  39057. p1.x = (p1.x + 1.0) * 0.5 * screenWidth;
  39058. p1.y = (p1.y + 1.0) * 0.5 * screenHeight;
  39059. p2.x = (p2.x + 1.0) * 0.5 * screenWidth;
  39060. p2.y = (p2.y + 1.0) * 0.5 * screenHeight;
  39061. return p1.distanceTo(p2);
  39062. }
  39063. static topView(camera, node){
  39064. camera.position.set(0, 1, 0);
  39065. camera.rotation.set(-Math.PI / 2, 0, 0);
  39066. camera.zoomTo(node, 1);
  39067. }
  39068. static frontView (camera, node) {
  39069. camera.position.set(0, 0, 1);
  39070. camera.rotation.set(0, 0, 0);
  39071. camera.zoomTo(node, 1);
  39072. }
  39073. static leftView (camera, node) {
  39074. camera.position.set(-1, 0, 0);
  39075. camera.rotation.set(0, -Math.PI / 2, 0);
  39076. camera.zoomTo(node, 1);
  39077. }
  39078. static rightView (camera, node) {
  39079. camera.position.set(1, 0, 0);
  39080. camera.rotation.set(0, Math.PI / 2, 0);
  39081. camera.zoomTo(node, 1);
  39082. }
  39083. static findClosestGpsTime(target, viewer){
  39084. const start = performance.now();
  39085. const nodes = [];
  39086. for(const pc of viewer.scene.pointclouds){
  39087. nodes.push(pc.root);
  39088. for(const child of pc.root.children){
  39089. if(child){
  39090. nodes.push(child);
  39091. }
  39092. }
  39093. }
  39094. let closestNode = null;
  39095. let closestIndex = Infinity;
  39096. let closestDistance = Infinity;
  39097. let closestValue = 0;
  39098. for(const node of nodes){
  39099. const isOkay = node.geometryNode != null
  39100. && node.geometryNode.geometry != null
  39101. && node.sceneNode != null;
  39102. if(!isOkay){
  39103. continue;
  39104. }
  39105. let geometry = node.geometryNode.geometry;
  39106. let gpsTime = geometry.attributes["gps-time"];
  39107. let range = gpsTime.potree.range;
  39108. for(let i = 0; i < gpsTime.array.length; i++){
  39109. let value = gpsTime.array[i];
  39110. value = value * (range[1] - range[0]) + range[0];
  39111. const distance = Math.abs(target - value);
  39112. if(distance < closestDistance){
  39113. closestIndex = i;
  39114. closestDistance = distance;
  39115. closestValue = value;
  39116. closestNode = node;
  39117. //console.log("found a closer one: " + value);
  39118. }
  39119. }
  39120. }
  39121. const geometry = closestNode.geometryNode.geometry;
  39122. const position = new Vector3(
  39123. geometry.attributes.position.array[3 * closestIndex + 0],
  39124. geometry.attributes.position.array[3 * closestIndex + 1],
  39125. geometry.attributes.position.array[3 * closestIndex + 2],
  39126. );
  39127. position.applyMatrix4(closestNode.sceneNode.matrixWorld);
  39128. const end = performance.now();
  39129. const duration = (end - start);
  39130. console.log(`duration: ${duration.toFixed(3)}ms`);
  39131. return {
  39132. node: closestNode,
  39133. index: closestIndex,
  39134. position: position,
  39135. };
  39136. }
  39137. /**
  39138. *
  39139. * 0: no intersection
  39140. * 1: intersection
  39141. * 2: fully inside
  39142. */
  39143. static frustumSphereIntersection (frustum, sphere) {
  39144. let planes = frustum.planes;
  39145. let center = sphere.center;
  39146. let negRadius = -sphere.radius;
  39147. let minDistance = Number.MAX_VALUE;
  39148. for (let i = 0; i < 6; i++) {
  39149. let distance = planes[ i ].distanceToPoint(center);
  39150. if (distance < negRadius) {
  39151. return 0;
  39152. }
  39153. minDistance = Math.min(minDistance, distance);
  39154. }
  39155. return (minDistance >= sphere.radius) ? 2 : 1;
  39156. }
  39157. // code taken from three.js
  39158. // ImageUtils - generateDataTexture()
  39159. static generateDataTexture (width, height, color) {
  39160. let size = width * height;
  39161. let data = new Uint8Array(4 * width * height);
  39162. let r = Math.floor(color.r * 255);
  39163. let g = Math.floor(color.g * 255);
  39164. let b = Math.floor(color.b * 255);
  39165. for (let i = 0; i < size; i++) {
  39166. data[ i * 3 ] = r;
  39167. data[ i * 3 + 1 ] = g;
  39168. data[ i * 3 + 2 ] = b;
  39169. }
  39170. let texture = new DataTexture(data, width, height, RGBAFormat);
  39171. texture.needsUpdate = true;
  39172. texture.magFilter = NearestFilter;
  39173. return texture;
  39174. }
  39175. // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
  39176. static getParameterByName (name) {
  39177. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  39178. let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  39179. let results = regex.exec(document.location.search);
  39180. return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
  39181. }
  39182. static setParameter (name, value) {
  39183. // value = encodeURIComponent(value);
  39184. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  39185. let regex = new RegExp('([\\?&])(' + name + '=([^&#]*))');
  39186. let results = regex.exec(document.location.search);
  39187. let url = window.location.href;
  39188. if (results === null) {
  39189. if (window.location.search.length === 0) {
  39190. url = url + '?';
  39191. } else {
  39192. url = url + '&';
  39193. }
  39194. url = url + name + '=' + value;
  39195. } else {
  39196. let newValue = name + '=' + value;
  39197. url = url.replace(results[2], newValue);
  39198. }
  39199. window.history.replaceState({}, '', url);
  39200. }
  39201. static createChildAABB(aabb, index){
  39202. let min = aabb.min.clone();
  39203. let max = aabb.max.clone();
  39204. let size = new Vector3().subVectors(max, min);
  39205. if ((index & 0b0001) > 0) {
  39206. min.z += size.z / 2;
  39207. } else {
  39208. max.z -= size.z / 2;
  39209. }
  39210. if ((index & 0b0010) > 0) {
  39211. min.y += size.y / 2;
  39212. } else {
  39213. max.y -= size.y / 2;
  39214. }
  39215. if ((index & 0b0100) > 0) {
  39216. min.x += size.x / 2;
  39217. } else {
  39218. max.x -= size.x / 2;
  39219. }
  39220. return new Box3(min, max);
  39221. }
  39222. // see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
  39223. static clipboardCopy(text){
  39224. let textArea = document.createElement("textarea");
  39225. textArea.style.position = 'fixed';
  39226. textArea.style.top = 0;
  39227. textArea.style.left = 0;
  39228. textArea.style.width = '2em';
  39229. textArea.style.height = '2em';
  39230. textArea.style.padding = 0;
  39231. textArea.style.border = 'none';
  39232. textArea.style.outline = 'none';
  39233. textArea.style.boxShadow = 'none';
  39234. textArea.style.background = 'transparent';
  39235. textArea.value = text;
  39236. document.body.appendChild(textArea);
  39237. textArea.select();
  39238. try {
  39239. let success = document.execCommand('copy');
  39240. if(success){
  39241. console.log("copied text to clipboard");
  39242. }else {
  39243. console.log("copy to clipboard failed");
  39244. }
  39245. } catch (err) {
  39246. console.log("error while trying to copy to clipboard");
  39247. }
  39248. document.body.removeChild(textArea);
  39249. }
  39250. static getMeasurementIcon(measurement){
  39251. if (measurement instanceof Measure) {
  39252. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  39253. return `${Potree.resourcePath}/icons/distance.svg`;
  39254. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  39255. return `${Potree.resourcePath}/icons/area.svg`;
  39256. } else if (measurement.maxMarkers === 1) {
  39257. return `${Potree.resourcePath}/icons/point.svg`;
  39258. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  39259. return `${Potree.resourcePath}/icons/angle.png`;
  39260. } else if (measurement.showHeight) {
  39261. return `${Potree.resourcePath}/icons/height.svg`;
  39262. } else {
  39263. return `${Potree.resourcePath}/icons/distance.svg`;
  39264. }
  39265. } else if (measurement instanceof Profile) {
  39266. return `${Potree.resourcePath}/icons/profile.svg`;
  39267. } else if (measurement instanceof Volume) {
  39268. return `${Potree.resourcePath}/icons/volume.svg`;
  39269. } else if (measurement instanceof PolygonClipVolume) {
  39270. return `${Potree.resourcePath}/icons/clip-polygon.svg`;
  39271. }
  39272. }
  39273. static lineToLineIntersection(P0, P1, P2, P3){
  39274. const P = [P0, P1, P2, P3];
  39275. const d = (m, n, o, p) => {
  39276. let result =
  39277. (P[m].x - P[n].x) * (P[o].x - P[p].x)
  39278. + (P[m].y - P[n].y) * (P[o].y - P[p].y)
  39279. + (P[m].z - P[n].z) * (P[o].z - P[p].z);
  39280. return result;
  39281. };
  39282. const mua = (d(0, 2, 3, 2) * d(3, 2, 1, 0) - d(0, 2, 1, 0) * d(3, 2, 3, 2))
  39283. /**-----------------------------------------------------------------**/ /
  39284. (d(1, 0, 1, 0) * d(3, 2, 3, 2) - d(3, 2, 1, 0) * d(3, 2, 1, 0));
  39285. const mub = (d(0, 2, 3, 2) + mua * d(3, 2, 1, 0))
  39286. /**--------------------------------------**/ /
  39287. d(3, 2, 3, 2);
  39288. const P01 = P1.clone().sub(P0);
  39289. const P23 = P3.clone().sub(P2);
  39290. const Pa = P0.clone().add(P01.multiplyScalar(mua));
  39291. const Pb = P2.clone().add(P23.multiplyScalar(mub));
  39292. const center = Pa.clone().add(Pb).multiplyScalar(0.5);
  39293. return center;
  39294. }
  39295. static computeCircleCenter(A, B, C){
  39296. const AB = B.clone().sub(A);
  39297. const AC = C.clone().sub(A);
  39298. const N = AC.clone().cross(AB).normalize();
  39299. const ab_dir = AB.clone().cross(N).normalize();
  39300. const ac_dir = AC.clone().cross(N).normalize();
  39301. const ab_origin = A.clone().add(B).multiplyScalar(0.5);
  39302. const ac_origin = A.clone().add(C).multiplyScalar(0.5);
  39303. const P0 = ab_origin;
  39304. const P1 = ab_origin.clone().add(ab_dir);
  39305. const P2 = ac_origin;
  39306. const P3 = ac_origin.clone().add(ac_dir);
  39307. const center = Utils.lineToLineIntersection(P0, P1, P2, P3);
  39308. return center;
  39309. // Potree.Utils.debugLine(viewer.scene.scene, P0, P1, 0x00ff00);
  39310. // Potree.Utils.debugLine(viewer.scene.scene, P2, P3, 0x0000ff);
  39311. // Potree.Utils.debugSphere(viewer.scene.scene, center, 0.03, 0xff00ff);
  39312. // const radius = center.distanceTo(A);
  39313. // Potree.Utils.debugCircle(viewer.scene.scene, center, radius, new THREE.Vector3(0, 0, 1), 0xff00ff);
  39314. }
  39315. static getNorthVec(p1, distance, projection){
  39316. if(projection){
  39317. // if there is a projection, transform coordinates to WGS84
  39318. // and compute angle to north there
  39319. proj4.defs("pointcloud", projection);
  39320. const transform = proj4("pointcloud", "WGS84");
  39321. const llP1 = transform.forward(p1.toArray());
  39322. let llP2 = transform.forward([p1.x, p1.y + distance]);
  39323. const polarRadius = Math.sqrt((llP2[0] - llP1[0]) ** 2 + (llP2[1] - llP1[1]) ** 2);
  39324. llP2 = [llP1[0], llP1[1] + polarRadius];
  39325. const northVec = transform.inverse(llP2);
  39326. return new Vector3(...northVec, p1.z).sub(p1);
  39327. }else {
  39328. // if there is no projection, assume [0, 1, 0] as north direction
  39329. const vec = new Vector3(0, 1, 0).multiplyScalar(distance);
  39330. return vec;
  39331. }
  39332. }
  39333. static computeAzimuth(p1, p2, projection){
  39334. let azimuth = 0;
  39335. if(projection){
  39336. // if there is a projection, transform coordinates to WGS84
  39337. // and compute angle to north there
  39338. let transform;
  39339. if (projection.includes('EPSG')) {
  39340. transform = proj4(projection, "WGS84");
  39341. } else {
  39342. proj4.defs("pointcloud", projection);
  39343. transform = proj4("pointcloud", "WGS84");
  39344. }
  39345. const llP1 = transform.forward(p1.toArray());
  39346. const llP2 = transform.forward(p2.toArray());
  39347. const dir = [
  39348. llP2[0] - llP1[0],
  39349. llP2[1] - llP1[1],
  39350. ];
  39351. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  39352. }else {
  39353. // if there is no projection, assume [0, 1, 0] as north direction
  39354. const dir = [p2.x - p1.x, p2.y - p1.y];
  39355. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  39356. }
  39357. // make clockwise
  39358. azimuth = -azimuth;
  39359. return azimuth;
  39360. }
  39361. static async loadScript(url){
  39362. return new Promise( resolve => {
  39363. const element = document.getElementById(url);
  39364. if(element){
  39365. resolve();
  39366. }else {
  39367. const script = document.createElement("script");
  39368. script.id = url;
  39369. script.onload = () => {
  39370. resolve();
  39371. };
  39372. script.src = url;
  39373. document.body.appendChild(script);
  39374. }
  39375. });
  39376. }
  39377. static createSvgGradient(scheme){
  39378. // this is what we are creating:
  39379. //
  39380. //<svg width="1em" height="3em" xmlns="http://www.w3.org/2000/svg">
  39381. // <defs>
  39382. // <linearGradient id="gradientID" gradientTransform="rotate(90)">
  39383. // <stop offset="0%" stop-color="rgb(93, 78, 162)" />
  39384. // ...
  39385. // <stop offset="100%" stop-color="rgb(157, 0, 65)" />
  39386. // </linearGradient>
  39387. // </defs>
  39388. //
  39389. // <rect width="100%" height="100%" fill="url('#myGradient')" stroke="black" stroke-width="0.1em"/>
  39390. //</svg>
  39391. const gradientId = `${Math.random()}_${Date.now()}`;
  39392. const svgn = "http://www.w3.org/2000/svg";
  39393. const svg = document.createElementNS(svgn, "svg");
  39394. svg.setAttributeNS(null, "width", "2em");
  39395. svg.setAttributeNS(null, "height", "3em");
  39396. { // <defs>
  39397. const defs = document.createElementNS(svgn, "defs");
  39398. const linearGradient = document.createElementNS(svgn, "linearGradient");
  39399. linearGradient.setAttributeNS(null, "id", gradientId);
  39400. linearGradient.setAttributeNS(null, "gradientTransform", "rotate(90)");
  39401. for(let i = scheme.length - 1; i >= 0; i--){
  39402. const stopVal = scheme[i];
  39403. const percent = parseInt(100 - stopVal[0] * 100);
  39404. const [r, g, b] = stopVal[1].toArray().map(v => parseInt(v * 255));
  39405. const stop = document.createElementNS(svgn, "stop");
  39406. stop.setAttributeNS(null, "offset", `${percent}%`);
  39407. stop.setAttributeNS(null, "stop-color", `rgb(${r}, ${g}, ${b})`);
  39408. linearGradient.appendChild(stop);
  39409. }
  39410. defs.appendChild(linearGradient);
  39411. svg.appendChild(defs);
  39412. }
  39413. const rect = document.createElementNS(svgn, "rect");
  39414. rect.setAttributeNS(null, "width", `100%`);
  39415. rect.setAttributeNS(null, "height", `100%`);
  39416. rect.setAttributeNS(null, "fill", `url("#${gradientId}")`);
  39417. rect.setAttributeNS(null, "stroke", `black`);
  39418. rect.setAttributeNS(null, "stroke-width", `0.1em`);
  39419. svg.appendChild(rect);
  39420. return svg;
  39421. }
  39422. static async waitAny(promises){
  39423. return new Promise( (resolve) => {
  39424. promises.map( promise => {
  39425. promise.then( () => {
  39426. resolve();
  39427. });
  39428. });
  39429. });
  39430. }
  39431. }
  39432. Utils.screenPass = new function () {
  39433. this.screenScene = new Scene();
  39434. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  39435. this.screenQuad.material.depthTest = true;
  39436. this.screenQuad.material.depthWrite = true;
  39437. this.screenQuad.material.transparent = true;
  39438. this.screenScene.add(this.screenQuad);
  39439. this.camera = new Camera();
  39440. this.render = function (renderer, material, target) {
  39441. this.screenQuad.material = material;
  39442. if (typeof target === 'undefined') {
  39443. renderer.render(this.screenScene, this.camera);
  39444. } else {
  39445. renderer.setRenderTarget(target);
  39446. renderer.render(this.screenScene, this.camera);
  39447. }
  39448. };
  39449. }();
  39450. //add
  39451. Utils.computePointcloudsBound = function(pointclouds){
  39452. var boundingBox = new Box3();
  39453. pointclouds.forEach(pointcloud=>{
  39454. pointcloud.updateBound();
  39455. boundingBox.union(pointcloud.bound);
  39456. });
  39457. var boundSize = boundingBox.getSize(new Vector3);
  39458. var center = boundingBox.getCenter(new Vector3);
  39459. return {boundSize, center, boundingBox}
  39460. };
  39461. Utils.convertScreenPositionToNDC = function(pointer, mouse, width, height) {
  39462. return pointer = pointer || new Vector2$1,
  39463. pointer.x = mouse.x / width * 2 - 1,
  39464. pointer.y = 2 * -(mouse.y / height) + 1,
  39465. pointer
  39466. };
  39467. Utils.convertNDCToScreenPosition = function(pointer, mouse, width, height) {
  39468. return mouse = mouse || new Vector2$1,
  39469. mouse.x = Math.round((pointer.x + 1 ) / 2 * width),
  39470. mouse.y = Math.round(-(pointer.y - 1 ) / 2 * height),
  39471. mouse
  39472. };
  39473. Utils.getOrthoCameraMoveVec = function(pointerDelta, camera ){//获取当camera为Ortho型时 屏幕点1 到 屏幕点2 的三维距离
  39474. let cameraViewWidth = camera.right / camera.zoom;
  39475. let cameraViewHeight = camera.top / camera.zoom;
  39476. let moveVec = new Vector3;
  39477. moveVec.set( pointerDelta.x * cameraViewWidth , pointerDelta.y * cameraViewHeight , 0).applyQuaternion(camera.quaternion);
  39478. return moveVec
  39479. };
  39480. Utils.VectorFactory = {
  39481. fromArray : function(t) {
  39482. if (t) {
  39483. if (t.length < 2 || t.length > 3)
  39484. console.error("Wrong number of ordinates for a point!");
  39485. return 3 === t.length ? (new Vector3).fromArray(t) : (new Vector2$1).fromArray(t)
  39486. }
  39487. },
  39488. fromArray3 : function(t) {
  39489. if (t) {
  39490. if (3 !== t.length)
  39491. console.error("Wrong number of ordinates for a point!");
  39492. return (new Vector3).fromArray(t)
  39493. }
  39494. },
  39495. fromArray2 : function(t) {
  39496. if (t) {
  39497. if (2 !== t.length)
  39498. console.error("Wrong number of ordinates for a point!");
  39499. return (new Vector2$1).fromArray(t)
  39500. }
  39501. },
  39502. toString : function(t) {
  39503. return t.x.toFixed(8) + "," + t.y.toFixed(8) + "," + t.z.toFixed(3)
  39504. }
  39505. };
  39506. Utils.QuaternionFactory = {
  39507. rot90 : (new Quaternion).setFromAxisAngle(new Vector3(0,0,1), MathUtils.degToRad(-90)),
  39508. fromArray : function(t) {
  39509. if (t) {
  39510. if (4 !== t.length)
  39511. console.error("Wrong number of ordinates for a quaternion!");
  39512. return new Quaternion(t[1],t[2],t[3],t[0]).multiply(this.rot90)
  39513. }
  39514. }
  39515. ,
  39516. toArray : function(t) {
  39517. if (t) {
  39518. var e = t.clone().multiply(a).toArray();
  39519. return [e[3], e[0], e[1], e[2]]
  39520. }
  39521. }
  39522. ,
  39523. fromLonLat : function(t) {
  39524. if (t)
  39525. return (new Quaternion).setFromEuler(new Euler(t.lon,t.lat,0))
  39526. }
  39527. ,
  39528. toLonLat : function(t) {
  39529. if (t) {
  39530. var e = (new Euler).setFromQuaternion(t);
  39531. return {
  39532. lon: e.x,
  39533. lat: e.y
  39534. }
  39535. }
  39536. }
  39537. };
  39538. Utils.datasetPosTransform = function(o={}){
  39539. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  39540. let tranMatrix;
  39541. if(pointcloud){
  39542. if(Potree.settings.editType == 'merge'){
  39543. tranMatrix = o.fromDataset ? pointcloud.matrixWorld : new Matrix4().copy(pointcloud.matrixWorld).invert();
  39544. }else {
  39545. tranMatrix = o.fromDataset ? pointcloud.transformMatrix : pointcloud.transformInvMatrix;
  39546. }
  39547. }else {
  39548. if(Potree.settings.intersectOnObjs){
  39549. let object = o.object || viewer.objs.children.find(e=>e.dataset_id == o.datasetId);
  39550. if(object){
  39551. tranMatrix = o.fromDataset ? object.matrixWorld : new Matrix4().copy(object.matrixWorld).invert();
  39552. }
  39553. }
  39554. }
  39555. if(tranMatrix){
  39556. return (new Vector3).copy(o.position).applyMatrix4(tranMatrix)
  39557. }else {
  39558. if(o.datasetId != void 0){
  39559. console.error(`datasetPosTransform找不到datasetId为${o.datasetId}的数据集或模型,请检查数据, 模型未创建或删除`);
  39560. //很可能是旧的热点,需要删除
  39561. }
  39562. }
  39563. };
  39564. Utils.datasetRotTransform = function(o={}){
  39565. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  39566. if(pointcloud){
  39567. var matrix, newMatrix, result;
  39568. if(o.rotation){
  39569. matrix = new Matrix4().makeRotationFromEuler(o.rotation);
  39570. }else if(o.quaternion){
  39571. matrix = new Matrix4().makeRotationFromQuaternion(o.quaternion);
  39572. }else if(o.matrix){
  39573. matrix = o.matrix.clone();
  39574. }else {
  39575. return
  39576. }
  39577. let rotateMatrix = o.fromDataset ? pointcloud.rotateMatrix : pointcloud.rotateInvMatrix;
  39578. newMatrix = new Matrix4().multiplyMatrices(rotateMatrix, matrix );
  39579. if(o.getRotation){
  39580. result = new Euler().setFromRotationMatrix(newMatrix);
  39581. }else if(o.getQuaternion){
  39582. result = new Quaternion().setFromRotationMatrix(newMatrix);
  39583. }else if(o.getMatrix){
  39584. result = newMatrix;
  39585. }
  39586. return result
  39587. }
  39588. };
  39589. Utils.isInsideFrustum = function(bounding, camera){// boundingBox在视野范围内有可见部分
  39590. let frustumMatrix = new Matrix4;
  39591. frustumMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  39592. let frustum = new Frustum();
  39593. frustum.setFromProjectionMatrix(frustumMatrix);
  39594. if(bounding instanceof Sphere){
  39595. return frustum.intersectsSphere(bounding)
  39596. }else {
  39597. return frustum.intersectsBox(bounding)
  39598. }
  39599. };
  39600. Utils.isInsideBox = function(object, boxMatrixInverse){//object可以是点或者bounding, box原为1*1*1,但可能形变
  39601. let frustum = new Frustum();
  39602. frustum.setFromProjectionMatrix(boxMatrixInverse);
  39603. if(object instanceof Box3){
  39604. return frustum.intersectsSphere(object)
  39605. }else if(object instanceof Array){//点合集,先求Sphere setFromPoints
  39606. let sphere = new Sphere();
  39607. sphere.setFromPoints(object);
  39608. return this.isInsideBox(sphere, boxMatrixInverse)
  39609. }else if(object instanceof Sphere){
  39610. return frustum.intersectsSphere(object)
  39611. }else if(object instanceof Vector3){
  39612. return frustum.containsPoint(object)
  39613. }
  39614. /* containsPoint: ƒ containsPoint( point )
  39615. intersectsBox: ƒ intersectsBox( box )
  39616. intersectsObject: ƒ intersectsObject( object )//geo
  39617. intersectsSphere: ƒ intersectsSphere( sphere )
  39618. intersectsSprite: ƒ intersectsSprite( sprite )
  39619. */
  39620. };
  39621. Utils.getIntersect = function (camera, meshes, pointer, raycaster) {
  39622. //获取鼠标和meshes交点
  39623. camera.updateMatrixWorld();
  39624. if(!raycaster){//getMouseIntersect
  39625. raycaster = new Raycaster();
  39626. var origin = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  39627. end = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  39628. var dir = end.sub(origin).normalize();
  39629. raycaster.set(origin, dir);
  39630. }
  39631. meshes.forEach(e=>{
  39632. raycaster.layers.enable(math.getBaseLog(e.layers.mask,2));
  39633. });
  39634. var n = raycaster.intersectObjects(meshes);
  39635. if (0 === n.length) return null
  39636. return n[0]
  39637. };
  39638. var start = function(dom, mapDom, number ){ //t-Zvd3w0m
  39639. /* {
  39640. let obj = JSON.parse(localStorage.getItem('setting'))
  39641. for(let i in obj){
  39642. console.log(i + ': ' + obj[i])
  39643. }
  39644. }
  39645. */
  39646. Potree.settings.number = number || 't-o5YMR13';// 't-iksBApb'// 写在viewer前
  39647. let viewer = new Potree.Viewer(dom , mapDom);
  39648. let Alignment = viewer.modules.Alignment;
  39649. //let pointDensity = config.pointDensity.middle
  39650. viewer.setEDLEnabled(false);
  39651. viewer.setFOV(config$1.view.fov);
  39652. //viewer.setPointBudget(pointDensity.pointBudget);
  39653. viewer.loadSettingsFromURL();
  39654. if(!Potree.settings.isOfficial){
  39655. viewer.loadGUI(() => {
  39656. viewer.setLanguage('en');
  39657. //$("#menu_appearance").next().show();
  39658. $("#menu_tools").next().show();
  39659. $("#menu_scene").next().show();
  39660. $("#siteModel").show();
  39661. //$("#alignment").show();
  39662. viewer.toggleSidebar();
  39663. });
  39664. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  39665. }
  39666. Potree.loadDatasetsCallback = function(data, ifReload){
  39667. if(!data || data.length == 0)return console.error('getDataSet加载的数据为空')
  39668. Potree.datasetData = data;
  39669. viewer.transform = null;
  39670. var datasetLength = data.length;
  39671. var pointcloudLoaded = 0;
  39672. var panosLoaded = 0;
  39673. var pointcloudLoadDone = function(){//点云cloud.js加载完毕后
  39674. viewer.updateModelBound();
  39675. let {boundSize, center} = viewer.bound;
  39676. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , null, 12);
  39677. if(!Potree.settings.isOfficial){
  39678. Potree.loadMapEntity('all'); //加载floorplan
  39679. }
  39680. if(!ifReload){
  39681. viewer.scene.view.setView({
  39682. position: center.clone().add(new Vector3(10,5,10)),
  39683. target: center
  39684. });
  39685. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39686. if(!Potree.settings.UserPointDensity){
  39687. Potree.settings.UserPointDensity = 'high';//'middle'
  39688. }
  39689. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39690. }
  39691. };
  39692. var panosLoadDone = function(){
  39693. viewer.images360.loadDone();
  39694. viewer.scene.add360Images(viewer.images360);
  39695. viewer.mapViewer.addListener(viewer.images360);
  39696. {//初始位置
  39697. var urlFirstView = false;
  39698. var panoId = browser.urlHasValue('pano',true);
  39699. if(panoId !== ''){
  39700. var pos;
  39701. var pano = viewer.images360.panos.find(e=>e.id==panoId);
  39702. if(pano){
  39703. viewer.images360.focusPano({
  39704. pano,
  39705. duration:0,
  39706. callback:()=>{/* Potree.settings.displayMode = 'showPanos' */}
  39707. });
  39708. }
  39709. }else {//考虑到多数据集距离很远,或者像隧道那种场景,要使视野范围内一定能看到点云,最好初始点设置在漫游点上
  39710. let {boundSize, center} = viewer.bound;
  39711. let pano = viewer.images360.findNearestPano(center);
  39712. /* pano && viewer.scene.view.setView({
  39713. position: pano.position.clone().add(new THREE.Vector3(10,10,10)),
  39714. target: pano.position
  39715. }) */
  39716. pano && viewer.images360.flyToPano({
  39717. pano, duration:0,
  39718. target : viewer.images360.bound.center
  39719. });
  39720. }
  39721. }
  39722. viewer.addVideo();//addFire()
  39723. console.log('allLoaded');
  39724. viewer.dispatchEvent('allLoaded');
  39725. };
  39726. var transformPointcloud = (pointcloud, dataset)=>{
  39727. var locationLonLat = dataset.location.slice(0,2);
  39728. //当只有一个dataset时,无论如何transform 点云和漫游点都能对应上。
  39729. var location = viewer.transform.lonlatToLocal.forward(locationLonLat); //transform.inverse()
  39730. //初始化位置
  39731. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  39732. //dataset.orientation = 0
  39733. Alignment.rotate(pointcloud, null, dataset.orientation);
  39734. Alignment.translate(pointcloud, new Vector3(location[0], location[1], dataset.location[2]));
  39735. pointcloud.updateMatrixWorld();
  39736. Potree.Log(`点云${pointcloud.dataset_id}旋转值:${pointcloud.orientationUser}, 位置${math.toPrecision(pointcloud.translateUser.toArray(),3)}, 经纬度 ${locationLonLat}, spacing ${pointcloud.material.spacing}`, null, 17 );
  39737. //-------------------
  39738. //viewer.mapView.showSources(false);
  39739. };
  39740. if(!Potree.settings.originDatasetId)Potree.settings.originDatasetId = data[0].id;
  39741. var originDataset = data.find(e=>e.id == Potree.settings.originDatasetId);
  39742. {//拿初始数据集作为基准。它的位置是000
  39743. var locationLonLat = originDataset.location.slice(0,2);
  39744. proj4.defs("NAVVIS:TMERC", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  39745. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  39746. let transform1 = proj4("WGS84", "NAVVIS:TMERC"); //这个ok TMERC是展开的平面投影
  39747. let transform2 = proj4("+proj=tmerc +lat_0=0 +lon_0=123 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs;");
  39748. viewer.transform = {
  39749. lonlatToLocal : transform1,
  39750. lonlatTo4550 : transform2 // 转大地坐标EPSG:4550
  39751. };
  39752. viewer.mapViewer && viewer.mapViewer.mapLayer.maps[0].updateProjection();
  39753. }
  39754. data.forEach((dataset,index)=>{
  39755. if(!ifReload){
  39756. var datasetCode = dataset.sceneCode || dataset.name; //对应4dkk的场景码
  39757. var cloudPath = `${Potree.settings.urls.prefix}/${Potree.settings.webSite}/${datasetCode}/data/${datasetCode}/webcloud/cloud.js`;
  39758. var timeStamp = dataset.createTime ? dataset.createTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随createTime更新一次
  39759. //console.warn(dataset.name, 'timeStamp', timeStamp)
  39760. Potree.loadPointCloud(cloudPath, dataset.name ,datasetCode, timeStamp, e => {
  39761. let scene = viewer.scene;
  39762. let pointcloud = e.pointcloud;
  39763. let config = Potree.config.material;
  39764. let material = pointcloud.material;
  39765. pointcloud.hasDepthTex = Potree.settings.useDepthTex && (!!dataset.has_depth || Potree.settings.isLocalhost && Potree.settings.number == 'SS-t-7DUfWAUZ3V'); //test
  39766. material.minSize = config.minSize;
  39767. material.maxSize = config.maxSize;
  39768. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39769. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  39770. pointcloud.changePointOpacity(1);
  39771. material.shape = Potree.PointShape.SQUARE;
  39772. pointcloud.color = pointcloud.material.color = dataset.color;
  39773. pointcloud.dataset_id = dataset.id;//供漫游点找到属于的dataset点云
  39774. pointcloud.timeStamp = timeStamp;
  39775. transformPointcloud(pointcloud,dataset);
  39776. scene.addPointCloud(pointcloud);
  39777. pointcloudLoaded ++;
  39778. if(pointcloudLoaded == datasetLength)pointcloudLoadDone();
  39779. Potree.loadPanos(dataset.id, (data) => {
  39780. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  39781. viewer.images360.addPanoData(data, dataset.id );
  39782. panosLoaded ++;
  39783. if(panosLoaded == datasetLength){
  39784. panosLoadDone();
  39785. }
  39786. });
  39787. });
  39788. }else {
  39789. let pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == dataset.id);
  39790. if(!pointcloud){
  39791. Potree.Log('数据集id变了,自动使用第一个','#500');
  39792. pointcloud = viewer.scene.pointclouds[0];
  39793. }
  39794. //先归零
  39795. Alignment.translate(pointcloud, pointcloud.translateUser.clone().negate());
  39796. Alignment.rotate(pointcloud, null, - pointcloud.orientationUser);
  39797. transformPointcloud(pointcloud, dataset);
  39798. }
  39799. });
  39800. if(ifReload){
  39801. //loadDone()
  39802. }
  39803. };
  39804. Potree.loadDatasets(Potree.loadDatasetsCallback);
  39805. window.testTransform = function(locationLonLat, location1, location2){
  39806. proj4.defs("NAVVIS:test", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  39807. let transform = proj4("WGS84", "NAVVIS:test"); //这个ok navvis里也是这两种转换 见proj4Factory
  39808. if(location1){//经纬度
  39809. return transform.forward(location1)
  39810. }else {
  39811. return transform.inverse(location2)
  39812. }
  39813. };
  39814. window.THREE = THREE$1;
  39815. window.buttonFunction = function(){
  39816. viewer.scene.pointclouds.forEach(e=>e.predictNodeMaxLevel());
  39817. /*
  39818. viewer.startScreenshot({type:'measure', measurement:viewer.scene.measurements[0]})
  39819. viewer.modules.RouteGuider.routeStart = new THREE.Vector3(0,0,-1.3)
  39820. viewer.modules.RouteGuider.routeEnd = new THREE.Vector3(-10,0,-1.3)
  39821. */
  39822. };
  39823. if(Potree.settings.isLocalhost){
  39824. let before = {};
  39825. viewer.inputHandler.addEventListener('keydown',e=>{ //测试的代码
  39826. if(e.event.key == 't'){
  39827. viewer.images360.cube.visible = true;
  39828. viewer.images360.cube.material.wireframe = true;
  39829. }else if(e.event.key == 'y'){
  39830. viewer.images360.cube.material.wireframe = false;
  39831. viewer.images360.cube.visible = Potree.settings.displayMode == 'showPanos';
  39832. }
  39833. });
  39834. }
  39835. };
  39836. //=======================================================================
  39837. /*
  39838. 漫游点编辑
  39839. */
  39840. //=======================================================================
  39841. var panoEditStart = function(dom, number, fileServer){
  39842. Potree.settings.editType = 'pano';
  39843. Potree.settings.number = number;
  39844. Potree.settings.unableNavigate = true;
  39845. let viewer = new Potree.Viewer(dom);
  39846. let Alignment = viewer.modules.Alignment;
  39847. viewer.setEDLEnabled(false);
  39848. viewer.setFOV(config$1.view.fov);
  39849. viewer.loadSettingsFromURL();
  39850. let datasetLoaded = 0;
  39851. if(!Potree.settings.isOfficial){
  39852. viewer.loadGUI(() => {
  39853. viewer.setLanguage('en');
  39854. $("#menu_tools").next().show();
  39855. $("#panos").show();
  39856. $("#alignment").show();
  39857. viewer.toggleSidebar();
  39858. });
  39859. Potree.settings.sizeFitToLevel = true;
  39860. }
  39861. var pointcloudLoadDone = function( ){//所有点云cloud.js加载完毕后
  39862. viewer.scene.pointclouds.forEach(c=>{
  39863. transformPointcloud(c);
  39864. });
  39865. viewer.images360.loadDone();
  39866. viewer.scene.add360Images(viewer.images360);
  39867. viewer.updateModelBound();
  39868. let {boundSize, center} = viewer.bound;
  39869. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , null, 12);
  39870. viewer.scene.view.setView({
  39871. position: center.clone().add(new Vector3(10,5,10)),
  39872. target: center
  39873. });
  39874. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39875. if(!Potree.settings.UserPointDensity){
  39876. Potree.settings.UserPointDensity = 'panoEdit';//'middle'
  39877. }
  39878. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39879. viewer.dispatchEvent('allLoaded');
  39880. };
  39881. var transformPointcloud = (pointcloud )=>{ //初始化位置
  39882. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  39883. let orientation = pointcloud.panos[0].dataRotation.z + Math.PI;
  39884. let location = pointcloud.panos[0].dataPosition.clone();//.negate()
  39885. Alignment.rotate(pointcloud, null, orientation );
  39886. Alignment.translate(pointcloud, location );
  39887. pointcloud.updateMatrixWorld();
  39888. };
  39889. let loadPanosDone = Potree.loadPanosDone = (datasetId, panoData )=>{ //一个数据集获取到它的panos后
  39890. Potree.settings.datasetsPanos[datasetId] = {panoData, panos:[]};
  39891. console.log('panoData', datasetId, panoData);
  39892. let panoCount = panoData.length;
  39893. let pointcloudLoaded = 0;
  39894. let datasetsCount = Object.keys(Potree.settings.datasetsPanos).length;
  39895. panoData.forEach((pano, index)=>{
  39896. //let cloudPath = `${Potree.scriptPath}/data/panoEdit/uuidcloud/${pano.uuid}/cloud.js`
  39897. let cloudPath = `https://laser-oss.4dkankan.com/${Potree.settings.webSite}/${Potree.settings.number}/data/bundle_${Potree.settings.number}/building/uuidcloud/${pano.uuid}/cloud.js`;
  39898. let name = datasetId + '-'+pano.uuid;
  39899. let timeStamp = 0;
  39900. pano.index = index; //注意:index不等于uuid,因为有的uuid缺失。但是visibles中存的是下标!
  39901. Potree.loadPointCloud(cloudPath, name , name, timeStamp, e => { //开始加载点云
  39902. let scene = viewer.scene;
  39903. let pointcloud = e.pointcloud;
  39904. let config = Potree.config.material;
  39905. let material = pointcloud.material;
  39906. material.minSize = config.minSize;
  39907. material.maxSize = config.maxSize;
  39908. material.pointSizeType = /* 'ADAPTIVE'// */config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39909. pointcloud.changePointSize( 0.1 /* config.realPointSize */ ); //material.size = config.pointSize;
  39910. pointcloud.changePointOpacity(1);
  39911. material.shape = Potree.PointShape.SQUARE;
  39912. pointcloud.color = config.pointColor;
  39913. pointcloud.dataset_id = datasetId; //多个点云指向一个datasetId
  39914. pointcloud.panoUuid = pano.uuid;
  39915. pointcloud.timeStamp = timeStamp;
  39916. //transformPointcloud(pointcloud, pano)
  39917. scene.addPointCloud(pointcloud);
  39918. pointcloudLoaded ++;
  39919. if(pointcloudLoaded == panoCount ){
  39920. datasetLoaded ++;
  39921. viewer.images360.addPanoData(panoData , datasetId );
  39922. if(datasetLoaded == datasetsCount){
  39923. pointcloudLoadDone();
  39924. }
  39925. }
  39926. });
  39927. });
  39928. };
  39929. if(!Potree.settings.isOfficial){
  39930. Potree.settings.datasetsPano = {'testDataset':null};
  39931. Potree.loadPanosInfo( data=>{loadPanosDone('testDataset', data.sweepLocations);} );
  39932. }
  39933. };
  39934. var mergeEditStart = function(dom){
  39935. Potree.settings.editType = 'merge';
  39936. Potree.settings.intersectOnObjs = true;
  39937. Potree.settings.boundAddObjs = true;
  39938. Potree.settings.unableNavigate = true;
  39939. let viewer = new Potree.Viewer(dom );
  39940. let Alignment = viewer.modules.Alignment;
  39941. viewer.setEDLEnabled(false);
  39942. viewer.setFOV(config$1.view.fov);
  39943. viewer.loadSettingsFromURL();
  39944. {
  39945. viewer.mainViewport.view.position.set(30,30,30);
  39946. viewer.mainViewport.view.lookAt(0,0,0);
  39947. viewer.updateModelBound();//init
  39948. //this.bound = new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1))
  39949. viewer.transformationTool.setModeEnable('scale',false);
  39950. viewer.ssaaRenderPass.sampleLevel = 1; // sampleLevel为1 的话,ground就不会变黑
  39951. viewer.inputHandler.fixSelection = true; //不通过点击屏幕而切换transfrom选中状态
  39952. }
  39953. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  39954. Potree.loadPointCloudScene = function(sceneCode, type, id, done, onError){//对应4dkk的场景码
  39955. let loadCloud = (cloudPath, sceneName, sceneCode, timeStamp, color)=>{
  39956. Potree.loadPointCloud(cloudPath, sceneName , sceneCode, timeStamp, e => {
  39957. let scene = viewer.scene;
  39958. let pointcloud = e.pointcloud;
  39959. let config = Potree.config.material;
  39960. let material = pointcloud.material;
  39961. material.minSize = config.minSize;
  39962. material.maxSize = config.maxSize;
  39963. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39964. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  39965. pointcloud.changePointOpacity(1);
  39966. material.shape = Potree.PointShape.SQUARE;
  39967. color && (pointcloud.color = pointcloud.material.color = color);
  39968. pointcloud.timeStamp = timeStamp;
  39969. //transformPointcloud(pointcloud, originDataset)
  39970. scene.addPointCloud(pointcloud);
  39971. {
  39972. viewer.updateModelBound();
  39973. let {boundSize, center} = viewer.bound;
  39974. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39975. if(!Potree.settings.UserPointDensity){
  39976. Potree.settings.UserPointDensity = 'high';//'middle'
  39977. }
  39978. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39979. }
  39980. /* Potree.loadPanos(dataset.id, (data) => { //暂时不加载panos了,因为没有id
  39981. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  39982. viewer.images360.addPanoData(data, dataset.id )
  39983. viewer.images360.loadDone()
  39984. viewer.scene.add360Images(viewer.images360); */
  39985. viewer.dispatchEvent('allLoaded');
  39986. done(pointcloud);
  39987. },onError);
  39988. };
  39989. if(type == 'laser'){
  39990. Potree.loadDatasets((data)=>{
  39991. let originDataset = data.find(e=>e.sceneCode == sceneCode);//只加载初始数据集
  39992. let timeStamp = originDataset.createTime ? originDataset.createTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随createTime更新一次
  39993. let cloudPath = `${Potree.settings.urls.prefix}/${Potree.settings.webSite}/${sceneCode}/data/${sceneCode}/webcloud/cloud.js`;
  39994. loadCloud(cloudPath, originDataset.sceneName, sceneCode, timeStamp, originDataset.color);
  39995. }, sceneCode, onError);
  39996. }else {//las or ply
  39997. let name = type + '|' + id;
  39998. let cloudPath = sceneCode + '/cloud.js';
  39999. loadCloud(cloudPath, name, name, '' );
  40000. }
  40001. };
  40002. let setMatrix = (pointcloud)=>{//为了漫游点变换,要算一下 类似setMatrix
  40003. /* pointcloud.transformMatrix = new THREE.Matrix4().multiplyMatrices(pointcloud.matrix, pointcloud.pos1MatrixInvert)//还原一点位移
  40004. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert()
  40005. pointcloud.rotateMatrix = new THREE.Matrix4().makeRotationFromEuler(pointcloud.rotation);
  40006. pointcloud.rotateInvMatrix.copy(pointcloud.rotateMatrix).invert()
  40007. pointcloud.panos.forEach(e=>e.transformByPointcloud()) */
  40008. //pointcloud.updateBound()
  40009. //pointcloud.getPanosBound()
  40010. viewer.updateModelBound();
  40011. };
  40012. let moveModel = (e)=>{//根据鼠标移动的位置改变位置
  40013. let camera = viewer.mainViewport.camera;
  40014. var origin = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera),
  40015. end = new Vector3(e.pointer.x, e.pointer.y, 1).unproject(camera);
  40016. var dir = end.sub(origin);
  40017. let planeZ = 0;
  40018. let r = (planeZ - origin.z)/dir.z;
  40019. let x = r * dir.x + origin.x;
  40020. let y = r * dir.y + origin.y;
  40021. //过后改为根据intersect的点来设置底部高度;这样的话,需要发送高度
  40022. /*let pos = new THREE.Vector3(x,y, planeZ )
  40023. modelEditing.updateMatrixWorld()
  40024. let boundCenter = modelEditing.boundingBox.getCenter(new THREE.Vector3).applyMatrix4(modelEditing.matrixWorld);
  40025. */
  40026. MergeEditor.moveBoundCenterTo(modelEditing,new Vector3(x,y, modelEditing.boundCenter.z)); //使模型中心的xy在鼠标所在位置
  40027. modelEditing.dispatchEvent("position_changed");
  40028. };
  40029. let cancelMove = ()=>{
  40030. modelEditing = null;
  40031. viewer.removeEventListener('global_mousemove', moveModel);
  40032. viewer.removeEventListener('global_click', confirmPos);
  40033. };
  40034. let confirmPos = ()=>{
  40035. MergeEditor.focusOn(modelEditing);
  40036. cancelMove();
  40037. return {stopContinue:true}
  40038. };
  40039. let modelType, modelEditing, MergeEditor = viewer.modules.MergeEditor;
  40040. Potree.addModel = function(prop, done, onProgress, onError){ //加载模型
  40041. let loadDone = (model)=>{
  40042. model.dataset_id = prop.id; //唯一标识
  40043. if(prop.position){
  40044. model.position.copy(prop.position);
  40045. }
  40046. if(prop.rotation){
  40047. model.rotation.setFromVector3(prop.rotation);
  40048. }
  40049. if(prop.scale){
  40050. model.scale.set(prop.scale,prop.scale,prop.scale);
  40051. }
  40052. if(model.isPointcloud){
  40053. model.renderOrder = Potree.config.renderOrders.model; //same as glb
  40054. }
  40055. /* {//transform --------维持离地高度和中心点的版本
  40056. let updateBound = ()=>{
  40057. model.updateMatrixWorld()
  40058. viewer.updateModelBound()
  40059. }
  40060. let maintainBtmZAndCenter = ()=>{
  40061. MergeEditor.maintainBoundXY(model)
  40062. MergeEditor.setModelBtmHeight(model)
  40063. updateBound()
  40064. model.dispatchEvent('transformChanged')
  40065. }
  40066. model.addEventListener('position_changed', ()=>{
  40067. updateBound()
  40068. MergeEditor.getBoundCenter(model);//更新boundcenter
  40069. MergeEditor.computeBtmHeight(model)
  40070. if(prop.bottomRange && (model.btmHeight > prop.bottomRange.max || model.btmHeight < prop.bottomRange.min)){
  40071. model.btmHeight = THREE.Math.clamp(model.btmHeight, prop.bottomRange.min, prop.bottomRange.max)
  40072. MergeEditor.setModelBtmHeight(model)
  40073. updateBound()
  40074. }
  40075. model.dispatchEvent('transformChanged')
  40076. })
  40077. model.addEventListener("rotation_changed", maintainBtmZAndCenter )
  40078. model.addEventListener("scale_changed", maintainBtmZAndCenter )
  40079. model.addEventListener('transformChanged', ()=>{
  40080. MergeEditor.modelTransformCallback(model)
  40081. })
  40082. //离地高度只是boundingbox在transform后的最低点的高度,而非模型transform后的最低点的高度,所以旋转过后看起来不太准确
  40083. } */
  40084. {//transform --------维持中心点的版本
  40085. let updateBound = ()=>{
  40086. model.updateMatrixWorld();
  40087. viewer.updateModelBound();
  40088. };
  40089. let maintainCenter = ()=>{
  40090. //MergeEditor.maintainBoundXY(model)
  40091. MergeEditor.maintainBoundCenter(model);
  40092. updateBound();
  40093. model.dispatchEvent('transformChanged');
  40094. };
  40095. model.addEventListener('position_changed', ()=>{
  40096. updateBound();
  40097. MergeEditor.getBoundCenter(model);//更新boundcenter
  40098. model.dispatchEvent('transformChanged');
  40099. });
  40100. model.addEventListener("rotation_changed", maintainCenter );
  40101. model.addEventListener("scale_changed", maintainCenter );
  40102. model.addEventListener('transformChanged', ()=>{
  40103. MergeEditor.modelTransformCallback(model);
  40104. });
  40105. }
  40106. model.updateMatrixWorld();
  40107. viewer.updateModelBound();
  40108. MergeEditor.getBoundCenter(model); //初始化
  40109. model.lastMatrixWorld = model.matrixWorld.clone();
  40110. done(model); // 先发送成功,因为2d界面会随机执行changePosition等初始化,然后这边再将模型移到中心地面上
  40111. if(prop.isFirstLoad){
  40112. MergeEditor.moveBoundCenterTo(model, new Vector3(0,0,0));
  40113. MergeEditor.setModelBtmHeight(model, 0); //初始加载设置离地高度为0
  40114. if(prop.mode != 'single'){//如果不是模型展示页,模型会随着鼠标位置移动
  40115. viewer.addEventListener('global_mousemove', moveModel);
  40116. viewer.addEventListener('global_click', confirmPos, 3);
  40117. modelEditing = model;
  40118. }
  40119. model.dispatchEvent("position_changed");
  40120. }else {
  40121. //MergeEditor.setModelBtmHeight(model, prop.bottom || 0) //默认离地高度为0
  40122. modelEditing = null;
  40123. }
  40124. };
  40125. if(prop.type == 'glb'){
  40126. let callback = (object)=>{
  40127. //focusOnSelect(object, 1000)
  40128. object.isModel = true;
  40129. //object.dataset_id = Date.now() //暂时
  40130. object.traverse(e=>e.material && (e.material.transparent = true));
  40131. /* object.addEventListener('click',(e)=>{
  40132. //只是为了能得到hoverElement识别才加这个侦听
  40133. }) */
  40134. loadDone(object);
  40135. };
  40136. let info = {
  40137. name: prop.type,
  40138. id: prop.id,
  40139. unlit:true,
  40140. /* transform : {
  40141. position : prop.position,
  40142. rotation : new THREE.Euler().setFromVector3(prop.rotation),
  40143. scale: new THREE.Vector3(prop.scale,prop.scale,prop.scale),
  40144. } */
  40145. };
  40146. if(prop.type == 'glb'){
  40147. info.glburl = prop.url;
  40148. }
  40149. viewer.loadModel(info , callback, onProgress, onError);
  40150. }else {
  40151. //else if(prop.type == 'las' || prop.type == 'ply')
  40152. Potree.loadPointCloudScene(prop.url, prop.type, prop.modelId, (pointcloud)=>{
  40153. pointcloud.matrixAutoUpdate = true;
  40154. pointcloud.initialPosition = pointcloud.position.clone();
  40155. pointcloud.pos1MatrixInvert = new Matrix4().setPosition(pointcloud.initialPosition).invert();
  40156. /* let maintainBtmZ = ()=>{
  40157. MergeEditor.setModelBtmHeight(pointcloud)
  40158. updateMatrix()
  40159. }
  40160. let updateMatrix = ()=>{
  40161. setMatrix(pointcloud)
  40162. pointcloud.dispatchEvent('transformChanged')
  40163. }
  40164. pointcloud.addEventListener('position_changed', updateMatrix )
  40165. pointcloud.addEventListener("orientation_changed", maintainBtmZ )
  40166. pointcloud.addEventListener("scale_changed", maintainBtmZ ) */
  40167. loadDone(pointcloud);
  40168. /* pointcloud.addEventListener('select',(e)=>{
  40169. if(Potree.settings.displayMode == 'showPanos')return
  40170. console.log('select',e)
  40171. //viewer.setControls(viewer.orbitControls)
  40172. MergeEditor.focusOnSelect(pointcloud)
  40173. viewer.outlinePass.selectedObjects = [pointcloud]
  40174. return {stopContinue:true}
  40175. },1)
  40176. pointcloud.addEventListener('deselect',(e)=>{
  40177. console.log('deselect',e)
  40178. //viewer.setControls(viewer.fpControls)
  40179. viewer.outlinePass.selectedObjects = []
  40180. }) */
  40181. }, onError);
  40182. }
  40183. };
  40184. return {THREE: THREE$1}
  40185. };
  40186. /*
  40187. 坐标转换问题:
  40188. 由于控制点可以随便输入,所以本地和地理位置的转换也是可拉伸的。而navvis的转换是等比由中心展开,
  40189. 所以对比两种转化方式时误差较大。
  40190. 另外地理注册控制点是有参考数据集的,若参考数据集和我放置在0,0,0的数据集一致,就可直接使用,否则要转换。
  40191. */
  40192. class Action extends EventDispatcher {
  40193. constructor (args = {}) {
  40194. super();
  40195. this.icon = args.icon || '';
  40196. this.tooltip = args.tooltip;
  40197. if (args.onclick !== undefined) {
  40198. this.onclick = args.onclick;
  40199. }
  40200. }
  40201. onclick (event) {
  40202. }
  40203. pairWith (object) {
  40204. }
  40205. setIcon (newIcon) {
  40206. let oldIcon = this.icon;
  40207. if (newIcon === oldIcon) {
  40208. return;
  40209. }
  40210. this.icon = newIcon;
  40211. this.dispatchEvent({
  40212. type: 'icon_changed',
  40213. action: this,
  40214. icon: newIcon,
  40215. oldIcon: oldIcon
  40216. });
  40217. }
  40218. };
  40219. //Potree.Actions = {};
  40220. //
  40221. //Potree.Actions.ToggleAnnotationVisibility = class ToggleAnnotationVisibility extends Potree.Action {
  40222. // constructor (args = {}) {
  40223. // super(args);
  40224. //
  40225. // this.icon = Potree.resourcePath + '/icons/eye.svg';
  40226. // this.showIn = 'sidebar';
  40227. // this.tooltip = 'toggle visibility';
  40228. // }
  40229. //
  40230. // pairWith (annotation) {
  40231. // if (annotation.visible) {
  40232. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40233. // } else {
  40234. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40235. // }
  40236. //
  40237. // annotation.addEventListener('visibility_changed', e => {
  40238. // let annotation = e.annotation;
  40239. //
  40240. // if (annotation.visible) {
  40241. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40242. // } else {
  40243. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40244. // }
  40245. // });
  40246. // }
  40247. //
  40248. // onclick (event) {
  40249. // let annotation = event.annotation;
  40250. //
  40251. // annotation.visible = !annotation.visible;
  40252. //
  40253. // if (annotation.visible) {
  40254. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40255. // } else {
  40256. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40257. // }
  40258. // }
  40259. //};
  40260. class PathAnimation{
  40261. constructor(path, start, end, speed, callback){
  40262. this.path = path;
  40263. this.length = this.path.spline.getLength();
  40264. this.speed = speed;
  40265. this.callback = callback;
  40266. this.tween = null;
  40267. this.startPoint = Math.max(start, 0);
  40268. this.endPoint = Math.min(end, this.length);
  40269. this.t = 0.0;
  40270. }
  40271. start(resume = false){
  40272. if(this.tween){
  40273. this.tween.stop();
  40274. this.tween = null;
  40275. }
  40276. let tStart;
  40277. if(resume){
  40278. tStart = this.t;
  40279. }else {
  40280. tStart = this.startPoint / this.length;
  40281. }
  40282. let tEnd = this.endPoint / this.length;
  40283. let animationDuration = (tEnd - tStart) * this.length * 1000 / this.speed;
  40284. let progress = {t: tStart};
  40285. this.tween = new TWEEN.Tween(progress).to({t: tEnd}, animationDuration);
  40286. this.tween.easing(TWEEN.Easing.Linear.None);
  40287. this.tween.onUpdate((e) => {
  40288. this.t = progress.t;
  40289. this.callback(progress.t);
  40290. });
  40291. this.tween.onComplete(() => {
  40292. if(this.repeat){
  40293. this.start();
  40294. }
  40295. });
  40296. setTimeout(() => {
  40297. this.tween.start();
  40298. }, 0);
  40299. }
  40300. stop(){
  40301. if(!this.tween){
  40302. return;
  40303. }
  40304. this.tween.stop();
  40305. this.tween = null;
  40306. this.t = 0;
  40307. }
  40308. pause(){
  40309. if(!this.tween){
  40310. return;
  40311. }
  40312. this.tween.stop();
  40313. TWEEN.remove(this.tween);
  40314. this.tween = null;
  40315. }
  40316. resume(){
  40317. this.start(true);
  40318. }
  40319. getPoint(t){
  40320. return this.path.spline.getPoint(t);
  40321. }
  40322. }
  40323. class AnimationPath{
  40324. constructor (points = []) {
  40325. this.points = points;
  40326. this.spline = new CatmullRomCurve3(points);
  40327. //this.spline.reparametrizeByArcLength(1 / this.spline.getLength().total);
  40328. }
  40329. get (t) {
  40330. return this.spline.getPoint(t);
  40331. }
  40332. getLength () {
  40333. return this.spline.getLength();
  40334. }
  40335. animate (start, end, speed, callback) {
  40336. let animation = new PathAnimation(this, start, end, speed, callback);
  40337. animation.start();
  40338. return animation;
  40339. }
  40340. pause () {
  40341. if (this.tween) {
  40342. this.tween.stop();
  40343. }
  40344. }
  40345. resume () {
  40346. if (this.tween) {
  40347. this.tween.start();
  40348. }
  40349. }
  40350. getGeometry () {
  40351. let geometry = new Geometry();
  40352. let samples = 500;
  40353. let i = 0;
  40354. for (let u = 0; u <= 1; u += 1 / samples) {
  40355. let position = this.spline.getPoint(u);
  40356. geometry.vertices[i] = new Vector3(position.x, position.y, position.z);
  40357. i++;
  40358. }
  40359. if(this.closed){
  40360. let position = this.spline.getPoint(0);
  40361. geometry.vertices[i] = new Vector3(position.x, position.y, position.z);
  40362. }
  40363. return geometry;
  40364. }
  40365. get closed(){
  40366. return this.spline.closed;
  40367. }
  40368. set closed(value){
  40369. this.spline.closed = value;
  40370. }
  40371. }
  40372. class Annotation extends EventDispatcher {
  40373. constructor (args = {}) {
  40374. super();
  40375. this.scene = null;
  40376. this._title = args.title || 'No Title';
  40377. this._description = args.description || '';
  40378. this.offset = new Vector3();
  40379. this.uuid = MathUtils.generateUUID();
  40380. if (!args.position) {
  40381. this.position = null;
  40382. } else if (args.position.x != null) {
  40383. this.position = args.position;
  40384. } else {
  40385. this.position = new Vector3(...args.position);
  40386. }
  40387. this.cameraPosition = (args.cameraPosition instanceof Array)
  40388. ? new Vector3().fromArray(args.cameraPosition) : args.cameraPosition;
  40389. this.cameraTarget = (args.cameraTarget instanceof Array)
  40390. ? new Vector3().fromArray(args.cameraTarget) : args.cameraTarget;
  40391. if(!this.cameraTarget && this.position){//add
  40392. this.cameraTarget = this.position.clone();
  40393. }
  40394. this.radius = args.radius;
  40395. this.view = args.view || null;
  40396. this.keepOpen = false;
  40397. this.descriptionVisible = false;
  40398. this.showDescription = true;
  40399. this.actions = args.actions || [];
  40400. this.isHighlighted = false;
  40401. this._visible = true;
  40402. this.__visible = true;
  40403. this._display = true;
  40404. this._expand = false;
  40405. this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined);
  40406. this.children = [];
  40407. this.parent = null;
  40408. this.boundingBox = new Box3();
  40409. let iconClose = exports.resourcePath + '/icons/close.svg';
  40410. this.domElement = $(`
  40411. <div class="annotation" oncontextmenu="return false;">
  40412. <div class="annotation-titlebar">
  40413. <span class="annotation-label"></span>
  40414. </div>
  40415. <div class="annotation-description">
  40416. <span class="annotation-description-close">
  40417. <img src="${iconClose}" width="16px">
  40418. </span>
  40419. <span class="annotation-description-content">${this._description}</span>
  40420. </div>
  40421. </div>
  40422. `);
  40423. this.elTitlebar = this.domElement.find('.annotation-titlebar');
  40424. this.elTitle = this.elTitlebar.find('.annotation-label');
  40425. this.elTitle.append(this._title);
  40426. this.elDescription = this.domElement.find('.annotation-description');
  40427. this.elDescriptionClose = this.elDescription.find('.annotation-description-close');
  40428. // this.elDescriptionContent = this.elDescription.find(".annotation-description-content");
  40429. this.clickTitle = () => {
  40430. //if(this.hasView()){
  40431. this.moveHere(this.scene.getActiveCamera());
  40432. //}
  40433. this.dispatchEvent({type: 'click', target: this});
  40434. viewer.renderer.domElement.focus();//add 使得方向键可用
  40435. };
  40436. this.elTitle.click(this.clickTitle);
  40437. this.actions = this.actions.map(a => {
  40438. if (a instanceof Action) {
  40439. return a;
  40440. } else {
  40441. return new Action(a);
  40442. }
  40443. });
  40444. for (let action of this.actions) {
  40445. action.pairWith(this);
  40446. }
  40447. let actions = this.actions.filter(
  40448. a => a.showIn === undefined || a.showIn.includes('scene'));
  40449. for (let action of actions) {
  40450. let elButton = $(`<img src="${action.icon}" class="annotation-action-icon">`);
  40451. this.elTitlebar.append(elButton);
  40452. elButton.click(() => action.onclick({annotation: this}));
  40453. }
  40454. this.elDescriptionClose.hover(
  40455. e => this.elDescriptionClose.css('opacity', '1'),
  40456. e => this.elDescriptionClose.css('opacity', '0.5')
  40457. );
  40458. this.elDescriptionClose.click(e => this.setHighlighted(false));
  40459. // this.elDescriptionContent.html(this._description);
  40460. this.domElement.mouseenter(e => this.setHighlighted(true));
  40461. this.domElement.mouseleave(e => this.setHighlighted(false));
  40462. this.domElement.on('touchstart', e => {
  40463. this.setHighlighted(!this.isHighlighted);
  40464. });
  40465. this.display = false;
  40466. //this.display = true;
  40467. }
  40468. installHandles(viewer){
  40469. if(this.handles !== undefined){
  40470. return;
  40471. }
  40472. let domElement = $(`
  40473. <div style="position: absolute; left: 300; top: 200; pointer-events: none">
  40474. <svg width="300" height="600">
  40475. <line x1="0" y1="0" x2="1200" y2="200" style="stroke: black; stroke-width:2" />
  40476. <circle cx="50" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  40477. <circle cx="150" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  40478. </svg>
  40479. </div>
  40480. `);
  40481. let svg = domElement.find("svg")[0];
  40482. let elLine = domElement.find("line")[0];
  40483. let elStart = domElement.find("circle")[0];
  40484. let elEnd = domElement.find("circle")[1];
  40485. let setCoordinates = (start, end) => {
  40486. elStart.setAttribute("cx", `${start.x}`);
  40487. elStart.setAttribute("cy", `${start.y}`);
  40488. elEnd.setAttribute("cx", `${end.x}`);
  40489. elEnd.setAttribute("cy", `${end.y}`);
  40490. elLine.setAttribute("x1", start.x);
  40491. elLine.setAttribute("y1", start.y);
  40492. elLine.setAttribute("x2", end.x);
  40493. elLine.setAttribute("y2", end.y);
  40494. let box = svg.getBBox();
  40495. svg.setAttribute("width", `${box.width}`);
  40496. svg.setAttribute("height", `${box.height}`);
  40497. svg.setAttribute("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`);
  40498. let ya = start.y - end.y;
  40499. let xa = start.x - end.x;
  40500. if(ya > 0){
  40501. start.y = start.y - ya;
  40502. }
  40503. if(xa > 0){
  40504. start.x = start.x - xa;
  40505. }
  40506. domElement.css("left", `${start.x}px`);
  40507. domElement.css("top", `${start.y}px`);
  40508. };
  40509. $(viewer.renderArea).append(domElement);
  40510. let annotationStartPos = this.position.clone();
  40511. let annotationStartOffset = this.offset.clone();
  40512. $(this.domElement).draggable({
  40513. start: (event, ui) => {
  40514. annotationStartPos = this.position.clone();
  40515. annotationStartOffset = this.offset.clone();
  40516. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none");
  40517. console.log($(this.domElement).find(".annotation-titlebar"));
  40518. },
  40519. stop: () => {
  40520. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "");
  40521. },
  40522. drag: (event, ui ) => {
  40523. let renderAreaWidth = viewer.renderer.getSize(new Vector2$1()).width;
  40524. //let renderAreaHeight = viewer.renderer.getSize().height;
  40525. let diff = {
  40526. x: ui.originalPosition.left - ui.position.left,
  40527. y: ui.originalPosition.top - ui.position.top
  40528. };
  40529. let nDiff = {
  40530. x: -(diff.x / renderAreaWidth) * 2,
  40531. y: (diff.y / renderAreaWidth) * 2
  40532. };
  40533. let camera = viewer.scene.getActiveCamera();
  40534. let oldScreenPos = new Vector3()
  40535. .addVectors(annotationStartPos, annotationStartOffset)
  40536. .project(camera);
  40537. let newScreenPos = oldScreenPos.clone();
  40538. newScreenPos.x += nDiff.x;
  40539. newScreenPos.y += nDiff.y;
  40540. let newPos = newScreenPos.clone();
  40541. newPos.unproject(camera);
  40542. let newOffset = new Vector3().subVectors(newPos, this.position);
  40543. this.offset.copy(newOffset);
  40544. }
  40545. });
  40546. let updateCallback = () => {
  40547. let position = this.position;
  40548. let scene = viewer.scene;
  40549. const renderAreaSize = viewer.renderer.getSize(new Vector2$1());
  40550. let renderAreaWidth = renderAreaSize.width;
  40551. let renderAreaHeight = renderAreaSize.height;
  40552. let start = this.position.clone();
  40553. let end = new Vector3().addVectors(this.position, this.offset);
  40554. let toScreen = (position) => {
  40555. let camera = scene.getActiveCamera();
  40556. let screenPos = new Vector3();
  40557. let worldView = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  40558. let ndc = new Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView);
  40559. // limit w to small positive value, in case position is behind the camera
  40560. ndc.w = Math.max(ndc.w, 0.1);
  40561. ndc.divideScalar(ndc.w);
  40562. screenPos.copy(ndc);
  40563. screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2;
  40564. screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2);
  40565. return screenPos;
  40566. };
  40567. start = toScreen(start);
  40568. end = toScreen(end);
  40569. setCoordinates(start, end);
  40570. };
  40571. viewer.addEventListener("update", updateCallback);
  40572. this.handles = {
  40573. domElement: domElement,
  40574. setCoordinates: setCoordinates,
  40575. updateCallback: updateCallback
  40576. };
  40577. }
  40578. removeHandles(viewer){
  40579. if(this.handles === undefined){
  40580. return;
  40581. }
  40582. //$(viewer.renderArea).remove(this.handles.domElement);
  40583. this.handles.domElement.remove();
  40584. viewer.removeEventListener("update", this.handles.updateCallback);
  40585. delete this.handles;
  40586. }
  40587. get visible () {
  40588. return this._visible;
  40589. }
  40590. set visible (value) {
  40591. if (this._visible === value) {
  40592. return;
  40593. }
  40594. this._visible = value;
  40595. //this.traverse(node => {
  40596. // node.display = value;
  40597. //});
  40598. this.dispatchEvent({
  40599. type: 'visibility_changed',
  40600. annotation: this
  40601. });
  40602. }
  40603. get display () {
  40604. return this._display;
  40605. }
  40606. set display (display) {
  40607. if (this._display === display) {
  40608. return;
  40609. }
  40610. this._display = display;
  40611. if (display) {
  40612. // this.domElement.fadeIn(200);
  40613. this.domElement.show();
  40614. } else {
  40615. // this.domElement.fadeOut(200);
  40616. this.domElement.hide();
  40617. }
  40618. }
  40619. get expand () {
  40620. return this._expand;
  40621. }
  40622. set expand (expand) {
  40623. if (this._expand === expand) {
  40624. return;
  40625. }
  40626. if (expand) {
  40627. this.display = false;
  40628. } else {
  40629. this.display = true;
  40630. this.traverseDescendants(node => {
  40631. node.display = false;
  40632. });
  40633. }
  40634. this._expand = expand;
  40635. }
  40636. get title () {
  40637. return this._title;
  40638. }
  40639. set title (title) {
  40640. if (this._title === title) {
  40641. return;
  40642. }
  40643. this._title = title;
  40644. this.elTitle.empty();
  40645. this.elTitle.append(this._title);
  40646. this.dispatchEvent({
  40647. type: "annotation_changed",
  40648. annotation: this,
  40649. });
  40650. }
  40651. get description () {
  40652. return this._description;
  40653. }
  40654. set description (description) {
  40655. if (this._description === description) {
  40656. return;
  40657. }
  40658. this._description = description;
  40659. const elDescriptionContent = this.elDescription.find(".annotation-description-content");
  40660. elDescriptionContent.empty();
  40661. elDescriptionContent.append(this._description);
  40662. this.dispatchEvent({
  40663. type: "annotation_changed",
  40664. annotation: this,
  40665. });
  40666. }
  40667. add (annotation) {
  40668. if (!this.children.includes(annotation)) {
  40669. this.children.push(annotation);
  40670. annotation.parent = this;
  40671. let descendants = [];
  40672. annotation.traverse(a => { descendants.push(a); });
  40673. for (let descendant of descendants) {
  40674. let c = this;
  40675. while (c !== null) {
  40676. c.dispatchEvent({
  40677. 'type': 'annotation_added',
  40678. 'annotation': descendant
  40679. });
  40680. c = c.parent;
  40681. }
  40682. }
  40683. }
  40684. }
  40685. level () {
  40686. if (this.parent === null) {
  40687. return 0;
  40688. } else {
  40689. return this.parent.level() + 1;
  40690. }
  40691. }
  40692. hasChild(annotation) {
  40693. return this.children.includes(annotation);
  40694. }
  40695. remove (annotation) {
  40696. if (this.hasChild(annotation)) {
  40697. annotation.removeAllChildren();
  40698. annotation.dispose();
  40699. this.children = this.children.filter(e => e !== annotation);
  40700. annotation.parent = null;
  40701. }
  40702. }
  40703. removeAllChildren() {
  40704. this.children.forEach((child) => {
  40705. if (child.children.length > 0) {
  40706. child.removeAllChildren();
  40707. }
  40708. this.remove(child);
  40709. });
  40710. }
  40711. updateBounds () {
  40712. let box = new Box3();
  40713. if (this.position) {
  40714. box.expandByPoint(this.position);
  40715. }
  40716. for (let child of this.children) {
  40717. child.updateBounds();
  40718. box.union(child.boundingBox);
  40719. }
  40720. this.boundingBox.copy(box);
  40721. }
  40722. traverse (handler) {
  40723. let expand = handler(this);
  40724. if (expand === undefined || expand === true) {
  40725. for (let child of this.children) {
  40726. child.traverse(handler);
  40727. }
  40728. }
  40729. }
  40730. traverseDescendants (handler) {
  40731. for (let child of this.children) {
  40732. child.traverse(handler);
  40733. }
  40734. }
  40735. flatten () {
  40736. let annotations = [];
  40737. this.traverse(annotation => {
  40738. annotations.push(annotation);
  40739. });
  40740. return annotations;
  40741. }
  40742. descendants () {
  40743. let annotations = [];
  40744. this.traverse(annotation => {
  40745. if (annotation !== this) {
  40746. annotations.push(annotation);
  40747. }
  40748. });
  40749. return annotations;
  40750. }
  40751. setHighlighted (highlighted) {
  40752. if (highlighted) {
  40753. this.domElement.css('opacity', '0.8');
  40754. this.elTitlebar.css('box-shadow', '0 0 5px #fff');
  40755. this.domElement.css('z-index', '1000');
  40756. if (this._description) {
  40757. this.descriptionVisible = true;
  40758. this.elDescription.fadeIn(200);
  40759. this.elDescription.css('position', 'relative');
  40760. }
  40761. } else {
  40762. this.domElement.css('opacity', '0.5');
  40763. this.elTitlebar.css('box-shadow', '');
  40764. this.domElement.css('z-index', '100');
  40765. this.descriptionVisible = false;
  40766. this.elDescription.css('display', 'none');
  40767. }
  40768. this.isHighlighted = highlighted;
  40769. }
  40770. hasView () {
  40771. let hasPosTargetView = this.cameraTarget.x != null;
  40772. hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null;
  40773. let hasRadiusView = this.radius !== undefined;
  40774. let hasView = hasPosTargetView || hasRadiusView;
  40775. return hasView;
  40776. };
  40777. moveHere (camera) {
  40778. if (!this.hasView()) {
  40779. return;
  40780. }
  40781. let view = this.scene.view;
  40782. let animationDuration = 500;
  40783. let easing = TWEEN.Easing.Quartic.Out;
  40784. let endTarget;
  40785. if (this.cameraTarget) {
  40786. endTarget = this.cameraTarget;
  40787. } else if (this.position) {
  40788. endTarget = this.position;
  40789. } else {
  40790. endTarget = this.boundingBox.getCenter(new Vector3());
  40791. }
  40792. if (this.cameraPosition) {
  40793. let endPosition = this.cameraPosition;
  40794. Utils.moveTo(this.scene, endPosition, endTarget);
  40795. } else if (this.radius) {
  40796. let direction = view.direction;
  40797. let endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius));
  40798. let startRadius = view.radius;
  40799. let endRadius = this.radius;
  40800. { // animate camera position
  40801. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  40802. tween.easing(easing);
  40803. tween.start();
  40804. }
  40805. { // animate radius
  40806. let t = {x: 0};
  40807. let tween = new TWEEN.Tween(t)
  40808. .to({x: 1}, animationDuration)
  40809. .onUpdate(function () {
  40810. view.radius = this.x * endRadius + (1 - this.x) * startRadius;
  40811. });
  40812. tween.easing(easing);
  40813. tween.start();
  40814. }
  40815. }
  40816. };
  40817. dispose () {
  40818. if (this.domElement.parentElement) {
  40819. this.domElement.parentElement.removeChild(this.domElement);
  40820. }
  40821. };
  40822. toString () {
  40823. return 'Annotation: ' + this._title;
  40824. }
  40825. };
  40826. class EnumItem{
  40827. constructor(object){
  40828. for(let key of Object.keys(object)){
  40829. this[key] = object[key];
  40830. }
  40831. }
  40832. inspect(){
  40833. return `Enum(${this.name}: ${this.value})`;
  40834. }
  40835. };
  40836. class Enum{//??????做什么用的
  40837. constructor(object){
  40838. this.object = object;
  40839. for(let key of Object.keys(object)){
  40840. let value = object[key];
  40841. if(typeof value === "object"){
  40842. value.name = key;
  40843. }else {
  40844. value = {name: key, value: value};
  40845. }
  40846. this[key] = new EnumItem(value);
  40847. }
  40848. }
  40849. fromValue(value){
  40850. for(let key of Object.keys(this.object)){
  40851. if(this[key].value === value){
  40852. return this[key];
  40853. }
  40854. }
  40855. throw new Error(`No enum for value: ${value}`);
  40856. }
  40857. };
  40858. const CameraMode = {
  40859. ORTHOGRAPHIC: 0,
  40860. PERSPECTIVE: 1,
  40861. VR: 2,
  40862. };
  40863. const ClipTask = {
  40864. NONE: 0,
  40865. HIGHLIGHT: 1,
  40866. SHOW_INSIDE: 2,
  40867. SHOW_OUTSIDE: 3
  40868. };
  40869. const ClipMethod = {
  40870. INSIDE_ANY: 0,
  40871. INSIDE_ALL: 1
  40872. };
  40873. const ElevationGradientRepeat = {
  40874. CLAMP: 0,
  40875. REPEAT: 1,
  40876. MIRRORED_REPEAT: 2,
  40877. };
  40878. const Buttons = {// MouseEvent.buttons
  40879. //buttons,设置按下了鼠标哪些键,是一个3个比特位的二进制值,默认为0。1表示按下主键(通常是左键),2表示按下次要键(通常是右键),4表示按下辅助键(通常是中间的键)。
  40880. NONE:0,//add
  40881. LEFT: 0b0001,
  40882. RIGHT: 0b0010,
  40883. MIDDLE: 0b0100
  40884. };
  40885. /* 如果访问的是button, 用THREE.MOUSE来判断:
  40886. button,设置按下了哪一个鼠标按键,默认为0。-1表示没有按键,0表示按下主键(通常是左键),1表示按下辅助键(通常是中间的键),2表示按下次要键(通常是右键)
  40887. */
  40888. const PointSizeType = {
  40889. FIXED: 0,
  40890. ATTENUATED: 1,
  40891. ADAPTIVE: 2
  40892. };
  40893. const PointShape = {
  40894. SQUARE: 0,
  40895. CIRCLE: 1,
  40896. PARABOLOID: 2
  40897. };
  40898. const TreeType = {
  40899. OCTREE: 0,
  40900. KDTREE: 1
  40901. };
  40902. const LengthUnits = {
  40903. METER: {code: 'm', unitspermeter: 1.0},
  40904. FEET: {code: 'ft', unitspermeter: 3.28084},
  40905. INCH: {code: '\u2033', unitspermeter: 39.3701}
  40906. };
  40907. /////////// add //////////////////////////////////
  40908. var GLCubeFaces$1 = {
  40909. GL_TEXTURE_CUBE_MAP_POSITIVE_X: 0,
  40910. GL_TEXTURE_CUBE_MAP_NEGATIVE_X: 1,
  40911. GL_TEXTURE_CUBE_MAP_POSITIVE_Y: 2,
  40912. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: 3,
  40913. GL_TEXTURE_CUBE_MAP_POSITIVE_Z: 4,
  40914. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: 5
  40915. };
  40916. var PanoSizeClass = {
  40917. BASE: 1,
  40918. STANDARD: 2,
  40919. HIGH: 3,
  40920. ULTRAHIGH: 4
  40921. };
  40922. var PanoRendererEvents = {
  40923. PanoRenderComplete: "panorama.render.complete",
  40924. TileRenderFailure: "panorama.tile.render.failed",
  40925. TileRenderSuccess: "panorama.tile.render.success",
  40926. TileUploadAttempted: "panorama.tile.upload.attempted",
  40927. UploadAttemptedForAllTiles: "panorama.upload.attempted.all.tiles",
  40928. ZoomLevelRenderStarted: "panorama.zoom.render.started"
  40929. };
  40930. var SceneRendererEvents = {
  40931. ContextCreated: "scene-renderer-context-created",
  40932. AfterRender: "after-render",
  40933. MemoryUsageUpdated: "scene-renderer-memory-usage-updated"
  40934. };
  40935. var TileDownloaderEvents = {
  40936. TileDownloadSuccess: "tiledownloader.download.success",
  40937. TileDownloadFailure: "tiledownloader.download.failure",
  40938. PanoDownloadComplete: "tiledownloader.pano.download.complete"
  40939. };
  40940. var Vectors = {
  40941. UP: new Vector3(0,1,0),
  40942. DOWN: new Vector3(0,-1,0),
  40943. LEFT: new Vector3(-1,0,0),
  40944. RIGHT: new Vector3(1,0,0),
  40945. FORWARD: new Vector3(0,0,-1),
  40946. BACK: new Vector3(0,0,1)
  40947. };
  40948. var Vectors2 = {};
  40949. for(var i in Vectors){
  40950. Vectors2[i] = math.convertVector.YupToZup(Vectors[i]);
  40951. }
  40952. var DownloadStatus = Object.freeze({
  40953. None: 0,
  40954. Queued: 1,
  40955. ForceQueued: 2,
  40956. Downloading: 3,
  40957. Downloaded: 4,
  40958. DownloadFailed: 5
  40959. });
  40960. var ModelManagerEvents = {
  40961. ModelAdded: "model-added",
  40962. ActiveModelChanged: "active-model-changed"
  40963. };
  40964. var PanoramaEvents = {
  40965. Enter: 'panorama.enter',
  40966. Exit: 'panorama.exit',
  40967. LoadComplete: "panorama.load.complete",
  40968. LoadFailed: "panorama.load.failed",
  40969. TileLoaded: "panorama.tile.loaded",
  40970. VideoRendered: "panorama.video.rendered"
  40971. };
  40972. /**
  40973. * @author mrdoob / http://mrdoob.com/ https://github.com/mrdoob/eventdispatcher.js
  40974. *
  40975. * with slight modifications by mschuetz, http://potree.org
  40976. *
  40977. */
  40978. // The MIT License
  40979. //
  40980. // Copyright (c) 2011 Mr.doob
  40981. //
  40982. // Permission is hereby granted, free of charge, to any person obtaining a copy
  40983. // of this software and associated documentation files (the "Software"), to deal
  40984. // in the Software without restriction, including without limitation the rights
  40985. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40986. // copies of the Software, and to permit persons to whom the Software is
  40987. // furnished to do so, subject to the following conditions:
  40988. //
  40989. // The above copyright notice and this permission notice shall be included in
  40990. // all copies or substantial portions of the Software.
  40991. //
  40992. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40993. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40994. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40995. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40996. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40997. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40998. // THE SOFTWARE.
  40999. class EventDispatcher$1{
  41000. constructor(){
  41001. this._listeners = {};
  41002. }
  41003. addEventListener(type, listener, importance=0 ){//add importance
  41004. const listeners = this._listeners;
  41005. if(listeners[type] === undefined){
  41006. listeners[type] = [];
  41007. }
  41008. if(listeners[type].indexOf(listener) === - 1){
  41009. listeners[type].push({ listener, importance});
  41010. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  41011. }
  41012. }
  41013. hasEventListener(type, listener){
  41014. const listeners = this._listeners;
  41015. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== - 1;
  41016. }
  41017. removeEventListener(type, listener){
  41018. let listeners = this._listeners;
  41019. let listenerArray = listeners[type];
  41020. if (listenerArray !== undefined){
  41021. /* let index = listenerArray.indexOf(listener);
  41022. if(index !== - 1){
  41023. listenerArray.splice(index, 1);
  41024. } */
  41025. let item = listenerArray.find(e=>e.listener == listener);
  41026. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  41027. }
  41028. }
  41029. removeEventListeners(type){
  41030. if(this._listeners[type] !== undefined){
  41031. delete this._listeners[type];
  41032. }
  41033. };
  41034. dispatchEvent(event){
  41035. if(typeof event == 'string'){//add
  41036. event = {type:event};
  41037. }
  41038. let listeners = this._listeners;
  41039. let listenerArray = listeners[event.type];
  41040. if ( listenerArray !== undefined ) {
  41041. event.target = this;
  41042. for(let {listener} of listenerArray.slice(0)){
  41043. let result = listener.call(this, event); //add stopContinue
  41044. if(result && result.stopContinue){
  41045. break
  41046. }
  41047. }
  41048. }
  41049. }
  41050. //add
  41051. /* emit(type){
  41052. this.dispatchEvent({type, arguments: Array.from(arguments).slice(1, arguments.length) })
  41053. }
  41054. on(type, fun){
  41055. this.addEventListener(type,(ev)=>{
  41056. fun.apply(this, ev.arguments)
  41057. })
  41058. }
  41059. off(type, fun){
  41060. this.removeEventListener(type,)
  41061. }
  41062. once(type, fun) {
  41063. function callback() {
  41064. this.removeEventListener(type, callback),
  41065. n || (n = !0, fun.apply(this, arguments))
  41066. }
  41067. var n = !1;
  41068. return callback.listener = fun,
  41069. this.on(type, callback),
  41070. this
  41071. } */
  41072. removeAllListeners(){
  41073. this._listeners = {};
  41074. }
  41075. }
  41076. const KeyCodes = {
  41077. LEFT: 37,
  41078. UP: 38,
  41079. RIGHT: 39,
  41080. BOTTOM: 40,
  41081. DELETE: 46,
  41082. BACKSPACE:8,
  41083. A: 'A'.charCodeAt(0),
  41084. S: 'S'.charCodeAt(0),
  41085. D: 'D'.charCodeAt(0),
  41086. W: 'W'.charCodeAt(0),
  41087. Q: 'Q'.charCodeAt(0),
  41088. E: 'E'.charCodeAt(0),
  41089. R: 'R'.charCodeAt(0),
  41090. F: 'F'.charCodeAt(0)
  41091. };
  41092. class LRUItem{
  41093. constructor(node){
  41094. this.previous = null;
  41095. this.next = null;
  41096. this.node = node;
  41097. }
  41098. }
  41099. /**
  41100. *
  41101. * @class A doubly-linked-list of the least recently used elements.
  41102. */
  41103. class LRU{
  41104. constructor(){
  41105. // the least recently used item
  41106. this.first = null;
  41107. // the most recently used item
  41108. this.last = null;
  41109. // a list of all items in the lru list
  41110. this.items = {};
  41111. this.elements = 0;
  41112. this.numPoints = 0;
  41113. }
  41114. size(){
  41115. return this.elements;
  41116. }
  41117. contains(node){
  41118. return this.items[node.id] == null;
  41119. }
  41120. touch(node){
  41121. if (!node.loaded) {
  41122. return;
  41123. }
  41124. let item;
  41125. if (this.items[node.id] == null) {
  41126. // add to list
  41127. item = new LRUItem(node);
  41128. item.previous = this.last;
  41129. this.last = item;
  41130. if (item.previous !== null) {
  41131. item.previous.next = item;
  41132. }
  41133. this.items[node.id] = item;
  41134. this.elements++;
  41135. if (this.first === null) {
  41136. this.first = item;
  41137. }
  41138. this.numPoints += node.numPoints;
  41139. } else {
  41140. // update in list
  41141. item = this.items[node.id];
  41142. if (item.previous === null) {
  41143. // handle touch on first element
  41144. if (item.next !== null) {
  41145. this.first = item.next;
  41146. this.first.previous = null;
  41147. item.previous = this.last;
  41148. item.next = null;
  41149. this.last = item;
  41150. item.previous.next = item;
  41151. }
  41152. } else if (item.next === null) {
  41153. // handle touch on last element
  41154. } else {
  41155. // handle touch on any other element
  41156. item.previous.next = item.next;
  41157. item.next.previous = item.previous;
  41158. item.previous = this.last;
  41159. item.next = null;
  41160. this.last = item;
  41161. item.previous.next = item;
  41162. }
  41163. }
  41164. }
  41165. remove(node){
  41166. let lruItem = this.items[node.id];
  41167. if (lruItem) {
  41168. if (this.elements === 1) {
  41169. this.first = null;
  41170. this.last = null;
  41171. } else {
  41172. if (!lruItem.previous) {
  41173. this.first = lruItem.next;
  41174. this.first.previous = null;
  41175. }
  41176. if (!lruItem.next) {
  41177. this.last = lruItem.previous;
  41178. this.last.next = null;
  41179. }
  41180. if (lruItem.previous && lruItem.next) {
  41181. lruItem.previous.next = lruItem.next;
  41182. lruItem.next.previous = lruItem.previous;
  41183. }
  41184. }
  41185. delete this.items[node.id];
  41186. this.elements--;
  41187. this.numPoints -= node.numPoints;
  41188. }
  41189. }
  41190. getLRUItem(){
  41191. if (this.first === null) {
  41192. return null;
  41193. }
  41194. let lru = this.first;
  41195. return lru.node;
  41196. }
  41197. toString(){
  41198. let string = '{ ';
  41199. let curr = this.first;
  41200. while (curr !== null) {
  41201. string += curr.node.id;
  41202. if (curr.next !== null) {
  41203. string += ', ';
  41204. }
  41205. curr = curr.next;
  41206. }
  41207. string += '}';
  41208. string += '(' + this.size() + ')';
  41209. return string;
  41210. }
  41211. freeMemory(){
  41212. if (this.elements <= 1) {
  41213. return;
  41214. }
  41215. /* while (this.numPoints > Potree.pointLoadLimit) {
  41216. let element = this.first;
  41217. let node = element.node;
  41218. this.disposeDescendants(node);
  41219. } */
  41220. //改成navvis的,使用pointBudget,否则四屏点云闪烁。
  41221. let max = /* this.pageVisible ? */viewer.viewports.length * 2 * Potree.pointBudget;// : 1000
  41222. for (; this.numPoints > max; ) {//要根据屏幕数量来增加pointBudget
  41223. var node = this.getLRUItem();
  41224. node && this.disposeSubtree(node);
  41225. }
  41226. }
  41227. disposeSubtree(t) {//add from navvis 25.js
  41228. var e = [t];
  41229. t.traverse((function(t) {
  41230. t.loaded && e.push(t);
  41231. }
  41232. ));
  41233. for (var n = 0, i = e; n < i.length; n++) {
  41234. var o = i[n];
  41235. o.dispose(),
  41236. this.remove(o);
  41237. }
  41238. }
  41239. disposeDescendants(node){
  41240. let stack = [];
  41241. stack.push(node);
  41242. while (stack.length > 0) {
  41243. let current = stack.pop();
  41244. // console.log(current);
  41245. current.dispose();
  41246. this.remove(current);
  41247. for (let key in current.children) {
  41248. if (current.children.hasOwnProperty(key)) {
  41249. let child = current.children[key];
  41250. if (child.loaded) {
  41251. stack.push(current.children[key]);
  41252. }
  41253. }
  41254. }
  41255. }
  41256. }
  41257. }
  41258. class PointCloudTreeNode extends EventDispatcher{
  41259. constructor(){
  41260. super();
  41261. this.needsTransformUpdate = true;
  41262. }
  41263. getChildren () {
  41264. throw new Error('override function');
  41265. }
  41266. getBoundingBox () {
  41267. throw new Error('override function');
  41268. }
  41269. isLoaded () {
  41270. throw new Error('override function');
  41271. }
  41272. isGeometryNode () {
  41273. throw new Error('override function');
  41274. }
  41275. isTreeNode () {
  41276. throw new Error('override function');
  41277. }
  41278. getLevel () {
  41279. throw new Error('override function');
  41280. }
  41281. getBoundingSphere () {
  41282. throw new Error('override function');
  41283. }
  41284. };
  41285. class PointCloudTree extends Object3D {
  41286. constructor () {
  41287. super();
  41288. //this.spriteGroup = new THREE.Object3D //add
  41289. }
  41290. initialized () {
  41291. return this.root !== null;
  41292. }
  41293. };
  41294. /**
  41295. * Some types of possible point attribute data formats
  41296. *
  41297. * @class
  41298. */
  41299. const PointAttributeTypes = {
  41300. DATA_TYPE_DOUBLE: {ordinal: 0, name: "double", size: 8},
  41301. DATA_TYPE_FLOAT: {ordinal: 1, name: "float", size: 4},
  41302. DATA_TYPE_INT8: {ordinal: 2, name: "int8", size: 1},
  41303. DATA_TYPE_UINT8: {ordinal: 3, name: "uint8", size: 1},
  41304. DATA_TYPE_INT16: {ordinal: 4, name: "int16", size: 2},
  41305. DATA_TYPE_UINT16: {ordinal: 5, name: "uint16", size: 2},
  41306. DATA_TYPE_INT32: {ordinal: 6, name: "int32", size: 4},
  41307. DATA_TYPE_UINT32: {ordinal: 7, name: "uint32", size: 4},
  41308. DATA_TYPE_INT64: {ordinal: 8, name: "int64", size: 8},
  41309. DATA_TYPE_UINT64: {ordinal: 9, name: "uint64", size: 8}
  41310. };
  41311. let i$1 = 0;
  41312. for (let obj in PointAttributeTypes) {
  41313. PointAttributeTypes[i$1] = PointAttributeTypes[obj];
  41314. i$1++;
  41315. }
  41316. class PointAttribute{
  41317. constructor(name, type, numElements){
  41318. this.name = name;
  41319. this.type = type;
  41320. this.numElements = numElements;
  41321. this.byteSize = this.numElements * this.type.size;
  41322. this.description = "";
  41323. this.range = [Infinity, -Infinity];
  41324. }
  41325. };
  41326. //add
  41327. const replacements = {
  41328. "COLOR_PACKED": "rgba",
  41329. "RGBA": "rgba",
  41330. "INTENSITY": "intensity",
  41331. "CLASSIFICATION": "classification",
  41332. "GPS_TIME": "gps-time",
  41333. };
  41334. const replaceOldNames = (old) => {
  41335. if(replacements[old]){
  41336. return replacements[old];
  41337. }else {
  41338. return old;
  41339. }
  41340. };
  41341. PointAttribute.POSITION_CARTESIAN = new PointAttribute(
  41342. "POSITION_CARTESIAN", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41343. PointAttribute.RGBA_PACKED = new PointAttribute(
  41344. replaceOldNames("COLOR_PACKED"), PointAttributeTypes.DATA_TYPE_INT8, 4);
  41345. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  41346. PointAttribute.RGB_PACKED = new PointAttribute(
  41347. "COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 3);
  41348. PointAttribute.NORMAL_FLOATS = new PointAttribute(
  41349. "NORMAL_FLOATS", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41350. PointAttribute.INTENSITY = new PointAttribute(
  41351. replaceOldNames("INTENSITY"), PointAttributeTypes.DATA_TYPE_UINT16, 1);
  41352. PointAttribute.CLASSIFICATION = new PointAttribute(
  41353. replaceOldNames("CLASSIFICATION"), PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41354. PointAttribute.NORMAL_SPHEREMAPPED = new PointAttribute(
  41355. "NORMAL_SPHEREMAPPED", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  41356. PointAttribute.NORMAL_OCT16 = new PointAttribute(
  41357. "NORMAL_OCT16", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  41358. PointAttribute.NORMAL = new PointAttribute(
  41359. "NORMAL", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41360. PointAttribute.RETURN_NUMBER = new PointAttribute(
  41361. "RETURN_NUMBER", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41362. PointAttribute.NUMBER_OF_RETURNS = new PointAttribute(
  41363. "NUMBER_OF_RETURNS", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41364. PointAttribute.SOURCE_ID = new PointAttribute(
  41365. "SOURCE_ID", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  41366. PointAttribute.INDICES = new PointAttribute(
  41367. "INDICES", PointAttributeTypes.DATA_TYPE_UINT32, 1);
  41368. PointAttribute.SPACING = new PointAttribute(
  41369. "SPACING", PointAttributeTypes.DATA_TYPE_FLOAT, 1);
  41370. PointAttribute.GPS_TIME = new PointAttribute(
  41371. replaceOldNames("GPS_TIME"), PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  41372. class PointAttributes{
  41373. constructor(pointAttributes){
  41374. this.attributes = [];
  41375. this.byteSize = 0;
  41376. this.size = 0;
  41377. this.vectors = [];
  41378. if (pointAttributes != null) {
  41379. for (let i = 0; i < pointAttributes.length; i++) {
  41380. let pointAttributeName = pointAttributes[i];
  41381. let pointAttribute = PointAttribute[pointAttributeName];
  41382. this.attributes.push(pointAttribute);
  41383. this.byteSize += pointAttribute.byteSize;
  41384. this.size++;
  41385. }
  41386. }
  41387. }
  41388. add(pointAttribute){
  41389. this.attributes.push(pointAttribute);
  41390. this.byteSize += pointAttribute.byteSize;
  41391. this.size++;
  41392. };
  41393. addVector(vector){
  41394. this.vectors.push(vector);
  41395. }
  41396. hasNormals(){
  41397. for (let name in this.attributes) {
  41398. let pointAttribute = this.attributes[name];
  41399. if (
  41400. pointAttribute === PointAttribute.NORMAL_SPHEREMAPPED ||
  41401. pointAttribute === PointAttribute.NORMAL_FLOATS ||
  41402. pointAttribute === PointAttribute.NORMAL ||
  41403. pointAttribute === PointAttribute.NORMAL_OCT16) {
  41404. return true;
  41405. }
  41406. }
  41407. return false;
  41408. };
  41409. }
  41410. class U {
  41411. static toVector3(v, offset) {
  41412. return new Vector3().fromArray(v, offset || 0);
  41413. }
  41414. static toBox3(b) {
  41415. return new Box3(U.toVector3(b), U.toVector3(b, 3));
  41416. };
  41417. static findDim(schema, name) {
  41418. var dim = schema.find((dim) => dim.name == name);
  41419. if (!dim) throw new Error('Failed to find ' + name + ' in schema');
  41420. return dim;
  41421. }
  41422. static sphereFrom(b) {
  41423. return b.getBoundingSphere(new Sphere());
  41424. }
  41425. };
  41426. class PointCloudEptGeometry {
  41427. constructor(url, info) {
  41428. let version = info.version;
  41429. let schema = info.schema;
  41430. let bounds = info.bounds;
  41431. let boundsConforming = info.boundsConforming;
  41432. let xyz = [
  41433. U.findDim(schema, 'X'),
  41434. U.findDim(schema, 'Y'),
  41435. U.findDim(schema, 'Z')
  41436. ];
  41437. let scale = xyz.map((d) => d.scale || 1);
  41438. let offset = xyz.map((d) => d.offset || 0);
  41439. this.eptScale = U.toVector3(scale);
  41440. this.eptOffset = U.toVector3(offset);
  41441. this.url = url;
  41442. this.info = info;
  41443. this.type = 'ept';
  41444. this.schema = schema;
  41445. this.span = info.span || info.ticks;
  41446. this.boundingBox = U.toBox3(bounds);
  41447. this.tightBoundingBox = U.toBox3(boundsConforming);
  41448. this.offset = U.toVector3([0, 0, 0]);
  41449. this.boundingSphere = U.sphereFrom(this.boundingBox);
  41450. this.tightBoundingSphere = U.sphereFrom(this.tightBoundingBox);
  41451. this.version = new Potree.Version('1.7');
  41452. this.projection = null;
  41453. this.fallbackProjection = null;
  41454. if (info.srs && info.srs.horizontal) {
  41455. this.projection = info.srs.authority + ':' + info.srs.horizontal;
  41456. }
  41457. if (info.srs.wkt) {
  41458. if (!this.projection) this.projection = info.srs.wkt;
  41459. else this.fallbackProjection = info.srs.wkt;
  41460. }
  41461. {
  41462. // TODO [mschuetz]: named projections that proj4 can't handle seem to cause problems.
  41463. // remove them for now
  41464. try{
  41465. proj4(this.projection);
  41466. }catch(e){
  41467. this.projection = null;
  41468. }
  41469. }
  41470. {
  41471. const attributes = new PointAttributes();
  41472. attributes.add(PointAttribute.POSITION_CARTESIAN);
  41473. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  41474. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  41475. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41476. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  41477. attributes.add(new PointAttribute("returnNumber", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41478. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41479. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41480. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  41481. this.pointAttributes = attributes;
  41482. }
  41483. this.spacing =
  41484. (this.boundingBox.max.x - this.boundingBox.min.x) / this.span;
  41485. let hierarchyType = info.hierarchyType || 'json';
  41486. const dataType = info.dataType;
  41487. if (dataType == 'laszip') {
  41488. this.loader = new Potree.EptLaszipLoader();
  41489. }
  41490. else if (dataType == 'binary') {
  41491. this.loader = new Potree.EptBinaryLoader();
  41492. }
  41493. else if (dataType == 'zstandard') {
  41494. this.loader = new Potree.EptZstandardLoader();
  41495. }
  41496. else {
  41497. throw new Error('Could not read data type: ' + dataType);
  41498. }
  41499. }
  41500. };
  41501. class EptKey {
  41502. constructor(ept, b, d, x, y, z) {
  41503. this.ept = ept;
  41504. this.b = b;
  41505. this.d = d;
  41506. this.x = x || 0;
  41507. this.y = y || 0;
  41508. this.z = z || 0;
  41509. }
  41510. name() {
  41511. return this.d + '-' + this.x + '-' + this.y + '-' + this.z;
  41512. }
  41513. step(a, b, c) {
  41514. let min = this.b.min.clone();
  41515. let max = this.b.max.clone();
  41516. let dst = new Vector3().subVectors(max, min);
  41517. if (a) min.x += dst.x / 2;
  41518. else max.x -= dst.x / 2;
  41519. if (b) min.y += dst.y / 2;
  41520. else max.y -= dst.y / 2;
  41521. if (c) min.z += dst.z / 2;
  41522. else max.z -= dst.z / 2;
  41523. return new Potree.EptKey(
  41524. this.ept,
  41525. new Box3(min, max),
  41526. this.d + 1,
  41527. this.x * 2 + a,
  41528. this.y * 2 + b,
  41529. this.z * 2 + c);
  41530. }
  41531. children() {
  41532. var result = [];
  41533. for (var a = 0; a < 2; ++a) {
  41534. for (var b = 0; b < 2; ++b) {
  41535. for (var c = 0; c < 2; ++c) {
  41536. var add = this.step(a, b, c).name();
  41537. if (!result.includes(add)) result = result.concat(add);
  41538. }
  41539. }
  41540. }
  41541. return result;
  41542. }
  41543. }
  41544. class PointCloudEptGeometryNode extends PointCloudTreeNode {
  41545. constructor(ept, b, d, x, y, z) {
  41546. super();
  41547. this.ept = ept;
  41548. this.key = new Potree.EptKey(
  41549. this.ept,
  41550. b || this.ept.boundingBox,
  41551. d || 0,
  41552. x,
  41553. y,
  41554. z);
  41555. this.id = PointCloudEptGeometryNode.IDCount++;
  41556. this.geometry = null;
  41557. this.boundingBox = this.key.b;
  41558. this.tightBoundingBox = this.boundingBox;
  41559. this.spacing = this.ept.spacing / Math.pow(2, this.key.d);
  41560. this.boundingSphere = U.sphereFrom(this.boundingBox);
  41561. // These are set during hierarchy loading.
  41562. this.hasChildren = false;
  41563. this.children = { };
  41564. this.numPoints = -1;
  41565. this.level = this.key.d;
  41566. this.loaded = false;
  41567. this.loading = false;
  41568. this.oneTimeDisposeHandlers = [];
  41569. let k = this.key;
  41570. this.name = this.toPotreeName(k.d, k.x, k.y, k.z);
  41571. this.index = parseInt(this.name.charAt(this.name.length - 1));
  41572. }
  41573. isGeometryNode() { return true; }
  41574. getLevel() { return this.level; }
  41575. isTreeNode() { return false; }
  41576. isLoaded() { return this.loaded; }
  41577. getBoundingSphere() { return this.boundingSphere; }
  41578. getBoundingBox() { return this.boundingBox; }
  41579. url() { return this.ept.url + 'ept-data/' + this.filename(); }
  41580. getNumPoints() { return this.numPoints; }
  41581. filename() { return this.key.name(); }
  41582. getChildren() {
  41583. let children = [];
  41584. for (let i = 0; i < 8; i++) {
  41585. if (this.children[i]) {
  41586. children.push(this.children[i]);
  41587. }
  41588. }
  41589. return children;
  41590. }
  41591. addChild(child) {
  41592. this.children[child.index] = child;
  41593. child.parent = this;
  41594. }
  41595. load() {
  41596. if (this.loaded || this.loading) return;
  41597. if (Potree.numNodesLoading >= Potree.maxNodesLoading) return;
  41598. this.loading = true;
  41599. ++Potree.numNodesLoading;
  41600. if (this.numPoints == -1) this.loadHierarchy();
  41601. this.loadPoints();
  41602. }
  41603. loadPoints(){
  41604. this.ept.loader.load(this);
  41605. }
  41606. async loadHierarchy() {
  41607. let nodes = { };
  41608. nodes[this.filename()] = this;
  41609. this.hasChildren = false;
  41610. let eptHierarchyFile =
  41611. `${this.ept.url}ept-hierarchy/${this.filename()}.json`;
  41612. let response = await fetch(eptHierarchyFile);
  41613. let hier = await response.json();
  41614. // Since we want to traverse top-down, and 10 comes
  41615. // lexicographically before 9 (for example), do a deep sort.
  41616. var keys = Object.keys(hier).sort((a, b) => {
  41617. let [da, xa, ya, za] = a.split('-').map((n) => parseInt(n, 10));
  41618. let [db, xb, yb, zb] = b.split('-').map((n) => parseInt(n, 10));
  41619. if (da < db) return -1; if (da > db) return 1;
  41620. if (xa < xb) return -1; if (xa > xb) return 1;
  41621. if (ya < yb) return -1; if (ya > yb) return 1;
  41622. if (za < zb) return -1; if (za > zb) return 1;
  41623. return 0;
  41624. });
  41625. keys.forEach((v) => {
  41626. let [d, x, y, z] = v.split('-').map((n) => parseInt(n, 10));
  41627. let a = x & 1, b = y & 1, c = z & 1;
  41628. let parentName =
  41629. (d - 1) + '-' + (x >> 1) + '-' + (y >> 1) + '-' + (z >> 1);
  41630. let parentNode = nodes[parentName];
  41631. if (!parentNode) return;
  41632. parentNode.hasChildren = true;
  41633. let key = parentNode.key.step(a, b, c);
  41634. let node = new Potree.PointCloudEptGeometryNode(
  41635. this.ept,
  41636. key.b,
  41637. key.d,
  41638. key.x,
  41639. key.y,
  41640. key.z);
  41641. node.level = d;
  41642. node.numPoints = hier[v];
  41643. parentNode.addChild(node);
  41644. nodes[key.name()] = node;
  41645. });
  41646. }
  41647. doneLoading(bufferGeometry, tightBoundingBox, np, mean) {
  41648. bufferGeometry.boundingBox = this.boundingBox;
  41649. this.geometry = bufferGeometry;
  41650. this.tightBoundingBox = tightBoundingBox;
  41651. this.numPoints = np;
  41652. this.mean = mean;
  41653. this.loaded = true;
  41654. this.loading = false;
  41655. --Potree.numNodesLoading;
  41656. }
  41657. toPotreeName(d, x, y, z) {
  41658. var name = 'r';
  41659. for (var i = 0; i < d; ++i) {
  41660. var shift = d - i - 1;
  41661. var mask = 1 << shift;
  41662. var step = 0;
  41663. if (x & mask) step += 4;
  41664. if (y & mask) step += 2;
  41665. if (z & mask) step += 1;
  41666. name += step;
  41667. }
  41668. return name;
  41669. }
  41670. dispose() {
  41671. if (this.geometry && this.parent != null) {
  41672. this.geometry.dispose();
  41673. this.geometry = null;
  41674. this.loaded = false;
  41675. // this.dispatchEvent( { type: 'dispose' } );
  41676. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  41677. let handler = this.oneTimeDisposeHandlers[i];
  41678. handler();
  41679. }
  41680. this.oneTimeDisposeHandlers = [];
  41681. }
  41682. }
  41683. }
  41684. PointCloudEptGeometryNode.IDCount = 0;
  41685. class PointCloudOctreeGeometry extends EventDispatcher{
  41686. constructor(){
  41687. super();
  41688. this.url = null;
  41689. this.octreeDir = null;
  41690. this.spacing = 0;
  41691. this.boundingBox = null;
  41692. this.root = null;
  41693. this.nodes = null;
  41694. this.pointAttributes = null;
  41695. this.hierarchyStepSize = -1;
  41696. this.loader = null;
  41697. }
  41698. }
  41699. class PointCloudOctreeGeometryNode extends PointCloudTreeNode{
  41700. constructor(name, pcoGeometry, boundingBox){
  41701. super();
  41702. this.id = PointCloudOctreeGeometryNode.IDCount++;
  41703. this.name = name;
  41704. this.index = parseInt(name.charAt(name.length - 1));
  41705. this.pcoGeometry = pcoGeometry;
  41706. this.geometry = null;
  41707. this.boundingBox = boundingBox;
  41708. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  41709. this.children = {};
  41710. this.numPoints = 0;
  41711. this.level = null;
  41712. this.loaded = false;
  41713. this.oneTimeDisposeHandlers = [];
  41714. }
  41715. isGeometryNode(){
  41716. return true;
  41717. }
  41718. getLevel(){
  41719. return this.level;
  41720. }
  41721. isTreeNode(){
  41722. return false;
  41723. }
  41724. isLoaded(){
  41725. return this.loaded;
  41726. }
  41727. getBoundingSphere(){
  41728. return this.boundingSphere;
  41729. }
  41730. getBoundingBox(){
  41731. return this.boundingBox;
  41732. }
  41733. getChildren(){
  41734. let children = [];
  41735. for (let i = 0; i < 8; i++) {
  41736. if (this.children[i]) {
  41737. children.push(this.children[i]);
  41738. }
  41739. }
  41740. return children;
  41741. }
  41742. getBoundingBox(){
  41743. return this.boundingBox;
  41744. }
  41745. getURL(){
  41746. let url = '';
  41747. let version = this.pcoGeometry.loader.version;
  41748. if (version.equalOrHigher('1.5')) {
  41749. url = this.pcoGeometry.octreeDir + '/' + this.getHierarchyPath() + '/' + this.name;
  41750. } else if (version.equalOrHigher('1.4')) {
  41751. url = this.pcoGeometry.octreeDir + '/' + this.name;
  41752. } else if (version.upTo('1.3')) {
  41753. url = this.pcoGeometry.octreeDir + '/' + this.name;
  41754. }
  41755. return url;
  41756. }
  41757. getHierarchyPath(){
  41758. let path = 'r/';
  41759. let hierarchyStepSize = this.pcoGeometry.hierarchyStepSize;
  41760. let indices = this.name.substr(1);
  41761. let numParts = Math.floor(indices.length / hierarchyStepSize);
  41762. for (let i = 0; i < numParts; i++) {
  41763. path += indices.substr(i * hierarchyStepSize, hierarchyStepSize) + '/';
  41764. }
  41765. path = path.slice(0, -1);
  41766. return path;
  41767. }
  41768. addChild(child) {
  41769. this.children[child.index] = child;
  41770. child.parent = this;
  41771. }
  41772. load(){
  41773. if (this.loading === true || this.loaded === true || Potree.numNodesLoading >= Potree.maxNodesLoading) {
  41774. return;
  41775. }
  41776. this.loading = true;
  41777. Potree.numNodesLoading++;
  41778. if (this.pcoGeometry.loader.version.equalOrHigher('1.5')) {
  41779. if ((this.level % this.pcoGeometry.hierarchyStepSize) === 0 && this.hasChildren) {
  41780. this.loadHierachyThenPoints();
  41781. } else {
  41782. this.loadPoints();
  41783. }
  41784. } else {
  41785. this.loadPoints();
  41786. }
  41787. }
  41788. loadPoints(){
  41789. this.pcoGeometry.loader.load(this);
  41790. }
  41791. loadHierachyThenPoints(pointcloud){
  41792. let node = this;
  41793. // load hierarchy
  41794. let callback = function (node, hbuffer) {
  41795. let tStart = performance.now();
  41796. let view = new DataView(hbuffer);
  41797. let stack = [];
  41798. let children = view.getUint8(0);
  41799. let numPoints = view.getUint32(1, true);
  41800. node.numPoints = numPoints;
  41801. stack.push({children: children, numPoints: numPoints, name: node.name});
  41802. let decoded = [];
  41803. let offset = 5;
  41804. while (stack.length > 0) {
  41805. let snode = stack.shift();
  41806. let mask = 1;
  41807. for (let i = 0; i < 8; i++) {
  41808. if ((snode.children & mask) !== 0) {
  41809. let childName = snode.name + i;
  41810. let childChildren = view.getUint8(offset);
  41811. let childNumPoints = view.getUint32(offset + 1, true);
  41812. stack.push({children: childChildren, numPoints: childNumPoints, name: childName});
  41813. decoded.push({children: childChildren, numPoints: childNumPoints, name: childName});
  41814. offset += 5;
  41815. }
  41816. mask = mask * 2;
  41817. }
  41818. if (offset === hbuffer.byteLength) {
  41819. break;
  41820. }
  41821. }
  41822. // console.log(decoded);
  41823. let nodes = {};
  41824. nodes[node.name] = node;
  41825. let pco = node.pcoGeometry;
  41826. for (let i = 0; i < decoded.length; i++) {
  41827. let name = decoded[i].name;
  41828. let decodedNumPoints = decoded[i].numPoints;
  41829. let index = parseInt(name.charAt(name.length - 1));
  41830. let parentName = name.substring(0, name.length - 1);
  41831. let parentNode = nodes[parentName];
  41832. let level = name.length - 1;
  41833. pco.dispatchEvent({type:'updateNodeMaxLevel',level});//add
  41834. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  41835. let currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  41836. currentNode.level = level;
  41837. currentNode.numPoints = decodedNumPoints;
  41838. currentNode.hasChildren = decoded[i].children > 0;
  41839. currentNode.spacing = pco.spacing / Math.pow(2, level);
  41840. parentNode.addChild(currentNode);
  41841. nodes[name] = currentNode;
  41842. }
  41843. let duration = performance.now() - tStart;
  41844. if(duration > 5){
  41845. /* let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`;
  41846. console.log(msg); */
  41847. }
  41848. node.loadPoints();
  41849. };
  41850. if ((node.level % node.pcoGeometry.hierarchyStepSize) === 0) {
  41851. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  41852. let hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  41853. hurl += '?m='+node.pcoGeometry.timeStamp; //add
  41854. let xhr = XHRFactory.createXMLHttpRequest();
  41855. xhr.open('GET', hurl, true);
  41856. xhr.responseType = 'arraybuffer';
  41857. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  41858. xhr.onreadystatechange = () => {
  41859. if (xhr.readyState === 4) {
  41860. if (xhr.status === 200 || xhr.status === 0) {
  41861. let hbuffer = xhr.response;
  41862. callback(node, hbuffer);
  41863. } else {
  41864. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  41865. Potree.numNodesLoading--;
  41866. }
  41867. }
  41868. };
  41869. try {
  41870. xhr.send(null);
  41871. } catch (e) {
  41872. console.log('fehler beim laden der punktwolke: ' + e);
  41873. }
  41874. }
  41875. }
  41876. getNumPoints(){
  41877. return this.numPoints;
  41878. }
  41879. dispose(){
  41880. if (this.geometry && this.parent != null) {
  41881. this.geometry.dispose();
  41882. this.geometry = null;
  41883. this.loaded = false;
  41884. this.dispatchEvent( { type: 'dispose' } );
  41885. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  41886. let handler = this.oneTimeDisposeHandlers[i];
  41887. handler();
  41888. }
  41889. this.oneTimeDisposeHandlers = [];
  41890. }
  41891. }
  41892. traverse(t, e){//add from navvis 25.js
  41893. void 0 === e && (e = !0);
  41894. for (var n, i = e ? [this] : []; void 0 !== (n = i.pop()); ) {
  41895. t(n);
  41896. for (var o = 0, r = n.children; o < r.length; o++) {
  41897. var a = r[o];
  41898. null !== a && i.push(a);
  41899. }
  41900. }
  41901. }
  41902. }
  41903. PointCloudOctreeGeometryNode.IDCount = 0;
  41904. // -------------------------------------------
  41905. // to get a ready to use gradient array from a chroma.js gradient:
  41906. // http://gka.github.io/chroma.js/
  41907. // -------------------------------------------
  41908. //
  41909. // let stops = [];
  41910. // for(let i = 0; i <= 10; i++){
  41911. // let range = chroma.scale(['yellow', 'navy']).mode('lch').domain([10,0])(i)._rgb
  41912. // .slice(0, 3)
  41913. // .map(v => (v / 255).toFixed(4))
  41914. // .join(", ");
  41915. //
  41916. // let line = `[${i / 10}, new THREE.Color(${range})],`;
  41917. //
  41918. // stops.push(line);
  41919. // }
  41920. // stops.join("\n");
  41921. //
  41922. //
  41923. //
  41924. // -------------------------------------------
  41925. // to get a ready to use gradient array from matplotlib:
  41926. // -------------------------------------------
  41927. // import matplotlib.pyplot as plt
  41928. // import matplotlib.colors as colors
  41929. //
  41930. // norm = colors.Normalize(vmin=0,vmax=1)
  41931. // cmap = plt.cm.viridis
  41932. //
  41933. // for i in range(0,11):
  41934. // u = i / 10
  41935. // rgb = cmap(norm(u))[0:3]
  41936. // rgb = ["{0:.3f}".format(v) for v in rgb]
  41937. // rgb = "[" + str(u) + ", new THREE.Color(" + ", ".join(rgb) + ")],"
  41938. // print(rgb)
  41939. let Gradients = {
  41940. // From chroma spectral http://gka.github.io/chroma.js/
  41941. SPECTRAL: [
  41942. [0, new Color(0.3686, 0.3098, 0.6353)],
  41943. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  41944. [0.2, new Color(0.4000, 0.7608, 0.6471)],
  41945. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  41946. [0.4, new Color(0.9020, 0.9608, 0.5961)],
  41947. [0.5, new Color(1.0000, 1.0000, 0.7490)],
  41948. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  41949. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  41950. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  41951. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  41952. [1, new Color(0.6196, 0.0039, 0.2588)]
  41953. ],
  41954. PLASMA: [
  41955. [0.0, new Color(0.241, 0.015, 0.610)],
  41956. [0.1, new Color(0.387, 0.001, 0.654)],
  41957. [0.2, new Color(0.524, 0.025, 0.653)],
  41958. [0.3, new Color(0.651, 0.125, 0.596)],
  41959. [0.4, new Color(0.752, 0.227, 0.513)],
  41960. [0.5, new Color(0.837, 0.329, 0.431)],
  41961. [0.6, new Color(0.907, 0.435, 0.353)],
  41962. [0.7, new Color(0.963, 0.554, 0.272)],
  41963. [0.8, new Color(0.992, 0.681, 0.195)],
  41964. [0.9, new Color(0.987, 0.822, 0.144)],
  41965. [1.0, new Color(0.940, 0.975, 0.131)]
  41966. ],
  41967. YELLOW_GREEN: [
  41968. [0, new Color(0.1647, 0.2824, 0.3451)],
  41969. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  41970. [0.2, new Color(0.0610, 0.4319, 0.4864)],
  41971. [0.3, new Color(0.0000, 0.5099, 0.5319)],
  41972. [0.4, new Color(0.0000, 0.5881, 0.5569)],
  41973. [0.5, new Color(0.1370, 0.6650, 0.5614)],
  41974. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  41975. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  41976. [0.8, new Color(0.6102, 0.8748, 0.4850)],
  41977. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  41978. [1, new Color(0.9804, 0.9804, 0.4314)]
  41979. ],
  41980. VIRIDIS: [
  41981. [0.0, new Color(0.267, 0.005, 0.329)],
  41982. [0.1, new Color(0.283, 0.141, 0.458)],
  41983. [0.2, new Color(0.254, 0.265, 0.530)],
  41984. [0.3, new Color(0.207, 0.372, 0.553)],
  41985. [0.4, new Color(0.164, 0.471, 0.558)],
  41986. [0.5, new Color(0.128, 0.567, 0.551)],
  41987. [0.6, new Color(0.135, 0.659, 0.518)],
  41988. [0.7, new Color(0.267, 0.749, 0.441)],
  41989. [0.8, new Color(0.478, 0.821, 0.318)],
  41990. [0.9, new Color(0.741, 0.873, 0.150)],
  41991. [1.0, new Color(0.993, 0.906, 0.144)]
  41992. ],
  41993. INFERNO: [
  41994. [0.0, new Color(0.077, 0.042, 0.206)],
  41995. [0.1, new Color(0.225, 0.036, 0.388)],
  41996. [0.2, new Color(0.373, 0.074, 0.432)],
  41997. [0.3, new Color(0.522, 0.128, 0.420)],
  41998. [0.4, new Color(0.665, 0.182, 0.370)],
  41999. [0.5, new Color(0.797, 0.255, 0.287)],
  42000. [0.6, new Color(0.902, 0.364, 0.184)],
  42001. [0.7, new Color(0.969, 0.516, 0.063)],
  42002. [0.8, new Color(0.988, 0.683, 0.072)],
  42003. [0.9, new Color(0.961, 0.859, 0.298)],
  42004. [1.0, new Color(0.988, 0.998, 0.645)]
  42005. ],
  42006. GRAYSCALE: [
  42007. [0, new Color(0, 0, 0)],
  42008. [1, new Color(1, 1, 1)]
  42009. ],
  42010. // 16 samples of the TURBU color scheme
  42011. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  42012. // original file licensed under Apache-2.0
  42013. TURBO: [
  42014. [0.00, new Color(0.18995, 0.07176, 0.23217)],
  42015. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  42016. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  42017. [0.20, new Color(0.25862, 0.57958, 0.99876)],
  42018. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  42019. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  42020. [0.40, new Color(0.19659, 0.94901, 0.59466)],
  42021. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  42022. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  42023. [0.60, new Color(0.80473, 0.92452, 0.20459)],
  42024. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  42025. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  42026. [0.80, new Color(0.9836, 0.49291, 0.12849)],
  42027. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  42028. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  42029. [1.00, new Color(0.66449, 0.08436, 0.00424)],
  42030. ],
  42031. RAINBOW: [
  42032. [0, new Color(0.278, 0, 0.714)],
  42033. [1 / 6, new Color(0, 0, 1)],
  42034. [2 / 6, new Color(0, 1, 1)],
  42035. [3 / 6, new Color(0, 1, 0)],
  42036. [4 / 6, new Color(1, 1, 0)],
  42037. [5 / 6, new Color(1, 0.64, 0)],
  42038. [1, new Color(1, 0, 0)]
  42039. ],
  42040. CONTOUR: [
  42041. [0.00, new Color(0, 0, 0)],
  42042. [0.03, new Color(0, 0, 0)],
  42043. [0.04, new Color(1, 1, 1)],
  42044. [1.00, new Color(1, 1, 1)]
  42045. ],
  42046. };
  42047. const ClassificationScheme = {
  42048. DEFAULT: {
  42049. 0: { visible: true, name: 'never classified' , color: [0.5, 0.5, 0.5, 1.0] },
  42050. 1: { visible: true, name: 'unclassified' , color: [0.5, 0.5, 0.5, 1.0] },
  42051. 2: { visible: true, name: 'ground' , color: [0.63, 0.32, 0.18, 1.0] },
  42052. 3: { visible: true, name: 'low vegetation' , color: [0.0, 1.0, 0.0, 1.0] },
  42053. 4: { visible: true, name: 'medium vegetation' , color: [0.0, 0.8, 0.0, 1.0] },
  42054. 5: { visible: true, name: 'high vegetation' , color: [0.0, 0.6, 0.0, 1.0] },
  42055. 6: { visible: true, name: 'building' , color: [1.0, 0.66, 0.0, 1.0] },
  42056. 7: { visible: true, name: 'low point(noise)' , color: [1.0, 0.0, 1.0, 1.0] },
  42057. 8: { visible: true, name: 'key-point' , color: [1.0, 0.0, 0.0, 1.0] },
  42058. 9: { visible: true, name: 'water' , color: [0.0, 0.0, 1.0, 1.0] },
  42059. 12: { visible: true, name: 'overlap' , color: [1.0, 1.0, 0.0, 1.0] },
  42060. DEFAULT: { visible: true, name: 'default' , color: [0.3, 0.6, 0.6, 0.5] },
  42061. }
  42062. };
  42063. Object.defineProperty(ClassificationScheme, 'RANDOM', {
  42064. get: function() {
  42065. let scheme = {};
  42066. for(let i = 0; i <= 255; i++){
  42067. scheme[i] = new Vector4(Math.random(), Math.random(), Math.random());
  42068. }
  42069. scheme["DEFAULT"] = new Vector4(Math.random(), Math.random(), Math.random());
  42070. return scheme;
  42071. }
  42072. });
  42073. //
  42074. // how to calculate the radius of a projected sphere in screen space
  42075. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  42076. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  42077. //
  42078. class PointCloudMaterial$1 extends RawShaderMaterial {
  42079. constructor (parameters = {}) {
  42080. super();
  42081. this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new Color(0xffffff));
  42082. this.visibleNodesTexture.minFilter = NearestFilter;
  42083. this.visibleNodesTexture.magFilter = NearestFilter;
  42084. let getValid = (a, b) => {
  42085. if(a !== undefined){
  42086. return a;
  42087. }else {
  42088. return b;
  42089. }
  42090. };
  42091. let pointSize = getValid(parameters.size, 1.0);
  42092. let minSize = getValid(parameters.minSize, 2.0);
  42093. let maxSize = getValid(parameters.maxSize, 1550.0);
  42094. let treeType = getValid(parameters.treeType, TreeType.OCTREE);
  42095. this._pointSizeType = PointSizeType.FIXED;
  42096. this._shape = PointShape.SQUARE;
  42097. this._useClipBox = false;
  42098. this.clipBoxes = [];
  42099. this.clipPolygons = [];
  42100. this._weighted = false;
  42101. this._gradient = Gradients.RAINBOW;//Gradients.SPECTRAL;//海拔贴图种类
  42102. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  42103. this._matcap = "matcap.jpg";
  42104. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  42105. this.lights = false;
  42106. this.fog = false;
  42107. this._treeType = treeType;
  42108. this._useEDL = false;
  42109. this.defines = new Map();
  42110. this.ranges = new Map();
  42111. this._activeAttributeName = null;
  42112. this._defaultIntensityRangeChanged = false;
  42113. this._defaultElevationRangeChanged = false;
  42114. {
  42115. const [width, height] = [256, 1];
  42116. let data = new Uint8Array(width * 4);
  42117. let texture = new DataTexture(data, width, height, RGBAFormat);
  42118. texture.magFilter = NearestFilter;
  42119. texture.needsUpdate = true;
  42120. this.classificationTexture = texture;
  42121. }
  42122. this.attributes = {
  42123. position: { type: 'fv', value: [] },
  42124. color: { type: 'fv', value: [] },
  42125. normal: { type: 'fv', value: [] },
  42126. intensity: { type: 'f', value: [] },
  42127. classification: { type: 'f', value: [] },
  42128. returnNumber: { type: 'f', value: [] },
  42129. numberOfReturns: { type: 'f', value: [] },
  42130. pointSourceID: { type: 'f', value: [] },
  42131. indices: { type: 'fv', value: [] }
  42132. };
  42133. this.uniforms = {
  42134. level: { type: "f", value: 0.0 },
  42135. vnStart: { type: "f", value: 0.0 },
  42136. spacing: { type: "f", value: 1.0 },
  42137. blendHardness: { type: "f", value: 2.0 },
  42138. blendDepthSupplement: { type: "f", value: 0.0 },
  42139. fov: { type: "f", value: 1.0 },
  42140. /* screenWidth: { type: "f", value: 1.0 },
  42141. screenHeight: { type: "f", value: 1.0 }, */
  42142. resolution: { type: 'v2', value: new Vector2$1() },
  42143. near: { type: "f", value: 0.1 },
  42144. far: { type: "f", value: 1.0 },
  42145. uColor: { type: "c", value: new Color( 0xffffff ) },
  42146. uOpacity: { type: "f", value: 1.0 },
  42147. size: { type: "f", value: pointSize },
  42148. minSize: { type: "f", value: minSize },
  42149. maxSize: { type: "f", value: maxSize },
  42150. octreeSize: { type: "f", value: 0 },
  42151. bbSize: { type: "fv", value: [0, 0, 0] },
  42152. elevationRange: { type: "2fv", value: [0, 0] },
  42153. clipBoxCount: { type: "f", value: 0 },
  42154. //clipSphereCount: { type: "f", value: 0 },
  42155. clipPolygonCount: { type: "i", value: 0 },
  42156. clipBoxes: { type: "Matrix4fv", value: [] },
  42157. //clipSpheres: { type: "Matrix4fv", value: [] },
  42158. clipPolygons: { type: "3fv", value: [] },
  42159. clipPolygonVCount: { type: "iv", value: [] },
  42160. clipPolygonVP: { type: "Matrix4fv", value: [] },
  42161. visibleNodes: { type: "t", value: this.visibleNodesTexture },
  42162. pcIndex: { type: "f", value: 0 },
  42163. gradient: { type: "t", value: this.gradientTexture },
  42164. classificationLUT: { type: "t", value: this.classificationTexture },
  42165. uHQDepthMap: { type: "t", value: null },
  42166. toModel: { type: "Matrix4f", value: [] },
  42167. diffuse: { type: "fv", value: [1, 1, 1] },
  42168. transition: { type: "f", value: 0.5 },
  42169. intensityRange: { type: "fv", value: [Infinity, -Infinity] },
  42170. intensity_gbc: { type: "fv", value: [1, 0, 0]},
  42171. uRGB_gbc: { type: "fv", value: [1, 0, 0]},
  42172. // intensityGamma: { type: "f", value: 1 },
  42173. // intensityContrast: { type: "f", value: 0 },
  42174. // intensityBrightness:{ type: "f", value: 0 },
  42175. // rgbGamma: { type: "f", value: 1 },
  42176. // rgbContrast: { type: "f", value: 0 },
  42177. // rgbBrightness: { type: "f", value: 0 },
  42178. wRGB: { type: "f", value: 1 },
  42179. wIntensity: { type: "f", value: 0 },
  42180. wElevation: { type: "f", value: 0 },
  42181. wClassification: { type: "f", value: 0 },
  42182. wReturnNumber: { type: "f", value: 0 },
  42183. wSourceID: { type: "f", value: 0 },
  42184. useOrthographicCamera: { type: "b", value: false },
  42185. elevationGradientRepat: { type: "i", value: ElevationGradientRepeat.CLAMP },
  42186. clipTask: { type: "i", value: 1 },
  42187. clipMethod: { type: "i", value: 1 },
  42188. uShadowColor: { type: "3fv", value: [0, 0, 0] },
  42189. uExtraScale: { type: "f", value: 1},
  42190. uExtraOffset: { type: "f", value: 0},
  42191. uExtraRange: { type: "2fv", value: [0, 1] },
  42192. uExtraGammaBrightContr: { type: "3fv", value: [1, 0, 0] },
  42193. uFilterReturnNumberRange: { type: "fv", value: [0, 7]},
  42194. uFilterNumberOfReturnsRange: { type: "fv", value: [0, 7]},
  42195. uFilterGPSTimeClipRange: { type: "fv", value: [0, 7]},
  42196. uFilterPointSourceIDClipRange: { type: "fv", value: [0, 65535]},
  42197. matcapTextureUniform: { type: "t", value: this.matcapTexture },
  42198. backfaceCulling: { type: "b", value: false },
  42199. ////////////////add
  42200. //usePanoMap:{ type: "i", value: 0 },
  42201. progress: {
  42202. type: "f",
  42203. value: 0
  42204. },
  42205. easeInOutRatio:{
  42206. type: "f",
  42207. value: 0.3
  42208. },
  42209. pano0Map: {
  42210. type: "t",
  42211. value: null
  42212. },
  42213. pano0Position: {
  42214. type: "v3",
  42215. value: new Vector3
  42216. },
  42217. pano0Matrix: {
  42218. type: "m4",
  42219. value: new Matrix4
  42220. },
  42221. pano1Map: {
  42222. type: "t",
  42223. value: null
  42224. },
  42225. pano1Position: {
  42226. type: "v3",
  42227. value: new Vector3
  42228. },
  42229. pano1Matrix: {
  42230. type: "m4",
  42231. value: new Matrix4
  42232. },
  42233. };
  42234. this.classification = ClassificationScheme.DEFAULT;
  42235. this.defaultAttributeValues.normal = [0, 0, 0];
  42236. this.defaultAttributeValues.classification = [0, 0, 0];
  42237. this.defaultAttributeValues.indices = [0, 0, 0, 0];
  42238. this.vertexShader = Shaders['pointcloud.vs'];
  42239. this.fragmentShader = Shaders['pointcloud.fs'];
  42240. this.vertexColors = VertexColors;
  42241. this.updateShaderSource();
  42242. }
  42243. setDefine(key, value){
  42244. if(value !== undefined && value !== null){
  42245. if(this.defines.get(key) !== value){
  42246. this.defines.set(key, value);
  42247. this.updateShaderSource();
  42248. }
  42249. }else {
  42250. this.removeDefine(key);
  42251. }
  42252. }
  42253. removeDefine(key){
  42254. this.defines.delete(key);
  42255. }
  42256. updateShaderSource () {
  42257. let vs = Shaders['pointcloud.vs'];
  42258. let fs = Shaders['pointcloud.fs'];
  42259. let definesString = this.getDefines();
  42260. let vsVersionIndex = vs.indexOf("#version ");
  42261. let fsVersionIndex = fs.indexOf("#version ");
  42262. if(vsVersionIndex >= 0){
  42263. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  42264. }else {
  42265. vs = `${definesString}\n${vs}`;
  42266. }
  42267. if(fsVersionIndex >= 0){
  42268. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  42269. }else {
  42270. fs = `${definesString}\n${fs}`;
  42271. }
  42272. this.vertexShader = vs;
  42273. this.fragmentShader = fs;
  42274. if (this.opacity === 1.0 && !this.useFilterByNormal) {//add useFilterByNormal
  42275. this.blending = NoBlending;
  42276. this.transparent = false;
  42277. this.depthTest = true;
  42278. this.depthWrite = true;
  42279. this.depthFunc = LessEqualDepth;
  42280. } else if ( (this.opacity < 1.0 ||this.useFilterByNormal) && !this.useEDL) {//add useFilterByNormal
  42281. this.blending = AdditiveBlending;
  42282. this.transparent = true;
  42283. this.depthTest = false;
  42284. this.depthWrite = true;
  42285. this.depthFunc = AlwaysDepth;
  42286. }
  42287. if (this.weighted) {
  42288. this.blending = AdditiveBlending;
  42289. this.transparent = true;
  42290. this.depthTest = true;
  42291. this.depthWrite = false;
  42292. }
  42293. this.needsUpdate = true;
  42294. }
  42295. getDefines () {
  42296. let defines = [];
  42297. if (this.pointSizeType === PointSizeType.FIXED) {
  42298. defines.push('#define fixed_point_size');
  42299. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  42300. defines.push('#define attenuated_point_size');
  42301. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  42302. defines.push('#define adaptive_point_size');
  42303. }
  42304. if(!Features.EXT_DEPTH.isSupported() && this.shape === PointShape.PARABOLOID){
  42305. this.shape = PointShape.SQUARE ;//强行替换
  42306. }
  42307. if (this.shape === PointShape.SQUARE) {
  42308. defines.push('#define square_point_shape');
  42309. } else if (this.shape === PointShape.CIRCLE) {
  42310. defines.push('#define circle_point_shape');
  42311. } else if (this.shape === PointShape.PARABOLOID) {
  42312. defines.push('#define paraboloid_point_shape');
  42313. }
  42314. //console.log('this.shape PARABOLOID', this.shape, this.shape === PointShape.PARABOLOID)
  42315. if (this._useEDL || this.fakeEDL) {
  42316. defines.push('#define use_edl');
  42317. }
  42318. if(this.activeAttributeName){
  42319. let attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  42320. defines.push(`#define color_type_${attributeName}`);
  42321. }
  42322. if(this._treeType === TreeType.OCTREE){
  42323. defines.push('#define tree_type_octree');
  42324. }else if(this._treeType === TreeType.KDTREE){
  42325. defines.push('#define tree_type_kdtree');
  42326. }
  42327. if (this.weighted) {
  42328. defines.push('#define weighted_splats');
  42329. }
  42330. for(let [key, value] of this.defines){
  42331. defines.push(value);
  42332. }
  42333. return defines.join("\n");
  42334. }
  42335. setClipBoxes (clipBoxes) {
  42336. if (!clipBoxes) {
  42337. return;
  42338. }
  42339. let doUpdate = (this.clipBoxes.length !== clipBoxes.length) && (clipBoxes.length === 0 || this.clipBoxes.length === 0);
  42340. this.uniforms.clipBoxCount.value = this.clipBoxes.length;
  42341. this.clipBoxes = clipBoxes;
  42342. if (doUpdate) {
  42343. this.updateShaderSource();
  42344. }
  42345. this.uniforms.clipBoxes.value = new Float32Array(this.clipBoxes.length * 16);
  42346. for (let i = 0; i < this.clipBoxes.length; i++) {
  42347. let box = clipBoxes[i];
  42348. this.uniforms.clipBoxes.value.set(box.inverse.elements, 16 * i);
  42349. }
  42350. for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {
  42351. if (Number.isNaN(this.uniforms.clipBoxes.value[i])) {
  42352. this.uniforms.clipBoxes.value[i] = Infinity;
  42353. }
  42354. }
  42355. }
  42356. setClipPolygons(clipPolygons, maxPolygonVertices) {
  42357. if(!clipPolygons){
  42358. return;
  42359. }
  42360. this.clipPolygons = clipPolygons;
  42361. let doUpdate = (this.clipPolygons.length !== clipPolygons.length);
  42362. if(doUpdate){
  42363. this.updateShaderSource();
  42364. }
  42365. }
  42366. get gradient(){
  42367. return this._gradient;
  42368. }
  42369. set gradient (value) {//海拔贴图
  42370. if (this._gradient !== value) {
  42371. this._gradient = value;
  42372. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  42373. this.uniforms.gradient.value = this.gradientTexture;
  42374. }
  42375. }
  42376. get matcap(){
  42377. return this._matcap;
  42378. }
  42379. set matcap (value) {
  42380. if (this._matcap !== value) {
  42381. this._matcap = value;
  42382. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  42383. this.uniforms.matcapTextureUniform.value = this.matcapTexture;
  42384. }
  42385. }
  42386. get useOrthographicCamera() {
  42387. return this.uniforms.useOrthographicCamera.value;
  42388. }
  42389. set useOrthographicCamera(value) {
  42390. if(this.uniforms.useOrthographicCamera.value !== value){
  42391. this.uniforms.useOrthographicCamera.value = value;
  42392. }
  42393. }
  42394. get backfaceCulling() {
  42395. return this.uniforms.backfaceCulling.value;
  42396. }
  42397. set backfaceCulling(value) {
  42398. if(this.uniforms.backfaceCulling.value !== value){
  42399. this.uniforms.backfaceCulling.value = value;
  42400. this.dispatchEvent({type: 'backface_changed', target: this});
  42401. }
  42402. }
  42403. recomputeClassification () {
  42404. const classification = this.classification;
  42405. const data = this.classificationTexture.image.data;
  42406. let width = 256;
  42407. const black = [1, 1, 1, 1];
  42408. let valuesChanged = false;
  42409. for (let i = 0; i < width; i++) {
  42410. let color;
  42411. let visible = true;
  42412. if (classification[i]) {
  42413. color = classification[i].color;
  42414. visible = classification[i].visible;
  42415. } else if (classification[i % 32]) {
  42416. color = classification[i % 32].color;
  42417. visible = classification[i % 32].visible;
  42418. } else if(classification.DEFAULT) {
  42419. color = classification.DEFAULT.color;
  42420. visible = classification.DEFAULT.visible;
  42421. }else {
  42422. color = black;
  42423. }
  42424. const r = parseInt(255 * color[0]);
  42425. const g = parseInt(255 * color[1]);
  42426. const b = parseInt(255 * color[2]);
  42427. const a = visible ? parseInt(255 * color[3]) : 0;
  42428. if(data[4 * i + 0] !== r){
  42429. data[4 * i + 0] = r;
  42430. valuesChanged = true;
  42431. }
  42432. if(data[4 * i + 1] !== g){
  42433. data[4 * i + 1] = g;
  42434. valuesChanged = true;
  42435. }
  42436. if(data[4 * i + 2] !== b){
  42437. data[4 * i + 2] = b;
  42438. valuesChanged = true;
  42439. }
  42440. if(data[4 * i + 3] !== a){
  42441. data[4 * i + 3] = a;
  42442. valuesChanged = true;
  42443. }
  42444. }
  42445. if(valuesChanged){
  42446. this.classificationTexture.needsUpdate = true;
  42447. this.dispatchEvent({
  42448. type: 'material_property_changed',
  42449. target: this
  42450. });
  42451. }
  42452. }
  42453. get spacing () {
  42454. return this.uniforms.spacing.value;
  42455. }
  42456. set spacing (value) {
  42457. if (this.uniforms.spacing.value !== value) { // 即 uOctreeSpacing 来自cloud.js里
  42458. this.uniforms.spacing.value = value;
  42459. }
  42460. }
  42461. get useClipBox () {
  42462. return this._useClipBox;
  42463. }
  42464. set useClipBox (value) {
  42465. if (this._useClipBox !== value) {
  42466. this._useClipBox = value;
  42467. this.updateShaderSource();
  42468. }
  42469. }
  42470. get clipTask(){
  42471. return this.uniforms.clipTask.value;
  42472. }
  42473. set clipTask(mode){
  42474. this.uniforms.clipTask.value = mode;
  42475. }
  42476. get elevationGradientRepat(){
  42477. return this.uniforms.elevationGradientRepat.value;
  42478. }
  42479. set elevationGradientRepat(mode){
  42480. this.uniforms.elevationGradientRepat.value = mode;
  42481. }
  42482. get clipMethod(){
  42483. return this.uniforms.clipMethod.value;
  42484. }
  42485. set clipMethod(mode){
  42486. this.uniforms.clipMethod.value = mode;
  42487. }
  42488. get weighted(){
  42489. return this._weighted;
  42490. }
  42491. set weighted (value) {
  42492. if (this._weighted !== value) {
  42493. this._weighted = value;
  42494. this.updateShaderSource();
  42495. }
  42496. }
  42497. get fov () {
  42498. return this.uniforms.fov.value;
  42499. }
  42500. set fov (value) {
  42501. if (this.uniforms.fov.value !== value) {
  42502. this.uniforms.fov.value = value;
  42503. // this.updateShaderSource();
  42504. }
  42505. }
  42506. /* get screenWidth () {
  42507. return this.uniforms.screenWidth.value;
  42508. }
  42509. set screenWidth (value) {
  42510. if (this.uniforms.screenWidth.value !== value) {
  42511. this.uniforms.screenWidth.value = value;
  42512. // this.updateShaderSource();
  42513. }
  42514. }
  42515. get screenHeight () {
  42516. return this.uniforms.screenHeight.value;
  42517. }
  42518. set screenHeight (value) {
  42519. if (this.uniforms.screenHeight.value !== value) {
  42520. this.uniforms.screenHeight.value = value;
  42521. // this.updateShaderSource();
  42522. }
  42523. }*/
  42524. //add--------------
  42525. get resolution(){
  42526. return this.uniforms.resolution.value
  42527. }
  42528. set resolution(value){
  42529. this.uniforms.resolution.value.copy(value);
  42530. }
  42531. //--------------
  42532. get near () {
  42533. return this.uniforms.near.value;
  42534. }
  42535. set near (value) {
  42536. if (this.uniforms.near.value !== value) {
  42537. this.uniforms.near.value = value;
  42538. }
  42539. }
  42540. get far () {
  42541. return this.uniforms.far.value;
  42542. }
  42543. set far (value) {
  42544. if (this.uniforms.far.value !== value) {
  42545. this.uniforms.far.value = value;
  42546. }
  42547. }
  42548. get opacity(){
  42549. return this.uniforms.uOpacity.value;
  42550. }
  42551. set opacity (value) {
  42552. if (this.uniforms && this.uniforms.uOpacity) {
  42553. if (this.uniforms.uOpacity.value !== value) {
  42554. this.uniforms.uOpacity.value = value;
  42555. this.updateShaderSource();
  42556. this.dispatchEvent({
  42557. type: 'opacity_changed',
  42558. target: this
  42559. });
  42560. this.dispatchEvent({
  42561. type: 'material_property_changed',
  42562. target: this
  42563. });
  42564. }
  42565. }
  42566. }
  42567. get activeAttributeName(){
  42568. return this._activeAttributeName;
  42569. }
  42570. set activeAttributeName(value){
  42571. if (this._activeAttributeName !== value) {
  42572. this._activeAttributeName = value;
  42573. this.updateShaderSource();
  42574. this.dispatchEvent({
  42575. type: 'active_attribute_changed',
  42576. target: this
  42577. });
  42578. this.dispatchEvent({
  42579. type: 'material_property_changed',
  42580. target: this
  42581. });
  42582. }
  42583. }
  42584. get pointSizeType () {
  42585. return this._pointSizeType;
  42586. }
  42587. set pointSizeType (value) {
  42588. if(typeof value == 'string' )value = PointSizeType[value];
  42589. if (this._pointSizeType !== value) {
  42590. this._pointSizeType = value;
  42591. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  42592. this.dispatchEvent({
  42593. type: 'point_size_type_changed',
  42594. target: this
  42595. });
  42596. this.dispatchEvent({
  42597. type: 'material_property_changed',
  42598. target: this
  42599. });
  42600. }
  42601. }
  42602. get useEDL(){
  42603. return this._useEDL;
  42604. }
  42605. set useEDL (value) {
  42606. if (this._useEDL !== value) {
  42607. this._useEDL = value;
  42608. this.updateShaderSource();
  42609. }
  42610. }
  42611. get fakeEDL(){
  42612. return this._fakeEDL;
  42613. }
  42614. set fakeEDL (value) {//add
  42615. if (this._fakeEDL !== value) {
  42616. this._fakeEDL = value;
  42617. this.updateShaderSource();
  42618. }
  42619. }
  42620. get color () {
  42621. return this.uniforms.uColor.value;
  42622. }
  42623. set color (value) {//改
  42624. if(value == this.color_)return
  42625. let color = value;
  42626. //if (!this.uniforms.uColor.value.equals(value)) {
  42627. if(typeof value == 'string') {
  42628. var colorArr = Potree.config.colors[value];
  42629. if(!colorArr){
  42630. //console.warn('没找到该颜色值'+ value)
  42631. }else {
  42632. color = new Color().fromArray(colorArr).multiplyScalar(1/255);
  42633. }
  42634. }
  42635. this.uniforms.uColor.value.set(color);
  42636. //this.uniforms.uColor.value.copy(value);
  42637. this.dispatchEvent({
  42638. type: 'color_changed',
  42639. target: this
  42640. });
  42641. this.dispatchEvent({
  42642. type: 'material_property_changed',
  42643. target: this
  42644. });
  42645. //}
  42646. this.color_ = value; //记录下str
  42647. }
  42648. get shape () {
  42649. return this._shape;
  42650. }
  42651. set shape (value) {
  42652. if (this._shape !== value) {
  42653. this._shape = value;
  42654. this.updateShaderSource();
  42655. this.dispatchEvent({type: 'point_shape_changed', target: this});
  42656. this.dispatchEvent({
  42657. type: 'material_property_changed',
  42658. target: this
  42659. });
  42660. }
  42661. }
  42662. get treeType () {
  42663. return this._treeType;
  42664. }
  42665. set treeType (value) {
  42666. if (this._treeType !== value) {
  42667. this._treeType = value;
  42668. this.updateShaderSource();
  42669. }
  42670. }
  42671. get bbSize () {
  42672. return this.uniforms.bbSize.value;
  42673. }
  42674. set bbSize (value) {
  42675. this.uniforms.bbSize.value = value;
  42676. }
  42677. get size () {
  42678. return this.uniforms.size.value;
  42679. }
  42680. set size (value) {
  42681. if (this.uniforms.size.value !== value) {
  42682. this.uniforms.size.value = value;
  42683. this.dispatchEvent({
  42684. type: 'point_size_changed',
  42685. target: this
  42686. });
  42687. this.dispatchEvent({
  42688. type: 'material_property_changed',
  42689. target: this
  42690. });
  42691. }
  42692. }
  42693. get minSize(){
  42694. return this.uniforms.minSize.value;
  42695. }
  42696. set minSize(value){
  42697. if (this.uniforms.minSize.value !== value) {
  42698. this.uniforms.minSize.value = value;
  42699. this.dispatchEvent({
  42700. type: 'point_size_changed',
  42701. target: this
  42702. });
  42703. this.dispatchEvent({
  42704. type: 'material_property_changed',
  42705. target: this
  42706. });
  42707. }
  42708. }
  42709. get elevationRange () {
  42710. return this.uniforms.elevationRange.value;
  42711. }
  42712. set elevationRange (value) {
  42713. let changed = this.uniforms.elevationRange.value[0] !== value[0]
  42714. || this.uniforms.elevationRange.value[1] !== value[1];
  42715. if(changed){
  42716. this.uniforms.elevationRange.value = value;
  42717. this._defaultElevationRangeChanged = true;
  42718. this.dispatchEvent({
  42719. type: 'material_property_changed',
  42720. target: this
  42721. });
  42722. }
  42723. }
  42724. get heightMin () {
  42725. return this.uniforms.elevationRange.value[0];
  42726. }
  42727. set heightMin (value) {
  42728. this.elevationRange = [value, this.elevationRange[1]];
  42729. }
  42730. get heightMax () {
  42731. return this.uniforms.elevationRange.value[1];
  42732. }
  42733. set heightMax (value) {
  42734. this.elevationRange = [this.elevationRange[0], value];
  42735. }
  42736. get transition () {
  42737. return this.uniforms.transition.value;
  42738. }
  42739. set transition (value) {
  42740. this.uniforms.transition.value = value;
  42741. }
  42742. get intensityRange () {
  42743. return this.uniforms.intensityRange.value;
  42744. }
  42745. set intensityRange (value) {
  42746. if (!(value instanceof Array && value.length === 2)) {
  42747. return;
  42748. }
  42749. if (value[0] === this.uniforms.intensityRange.value[0] &&
  42750. value[1] === this.uniforms.intensityRange.value[1]) {
  42751. return;
  42752. }
  42753. this.uniforms.intensityRange.value = value;
  42754. this._defaultIntensityRangeChanged = true;
  42755. this.dispatchEvent({
  42756. type: 'material_property_changed',
  42757. target: this
  42758. });
  42759. }
  42760. get intensityGamma () {
  42761. return this.uniforms.intensity_gbc.value[0];
  42762. }
  42763. set intensityGamma (value) {
  42764. if (this.uniforms.intensity_gbc.value[0] !== value) {
  42765. this.uniforms.intensity_gbc.value[0] = value;
  42766. this.dispatchEvent({
  42767. type: 'material_property_changed',
  42768. target: this
  42769. });
  42770. }
  42771. }
  42772. get intensityContrast () {
  42773. return this.uniforms.intensity_gbc.value[2];
  42774. }
  42775. set intensityContrast (value) {
  42776. if (this.uniforms.intensity_gbc.value[2] !== value) {
  42777. this.uniforms.intensity_gbc.value[2] = value;
  42778. this.dispatchEvent({
  42779. type: 'material_property_changed',
  42780. target: this
  42781. });
  42782. }
  42783. }
  42784. get intensityBrightness () {
  42785. return this.uniforms.intensity_gbc.value[1];
  42786. }
  42787. set intensityBrightness (value) {
  42788. if (this.uniforms.intensity_gbc.value[1] !== value) {
  42789. this.uniforms.intensity_gbc.value[1] = value;
  42790. this.dispatchEvent({
  42791. type: 'material_property_changed',
  42792. target: this
  42793. });
  42794. }
  42795. }
  42796. get rgbGamma () {
  42797. return this.uniforms.uRGB_gbc.value[0];
  42798. }
  42799. set rgbGamma (value) {
  42800. if (this.uniforms.uRGB_gbc.value[0] !== value) {
  42801. this.uniforms.uRGB_gbc.value[0] = value;
  42802. this.dispatchEvent({
  42803. type: 'material_property_changed',
  42804. target: this
  42805. });
  42806. }
  42807. }
  42808. get rgbContrast () {
  42809. return this.uniforms.uRGB_gbc.value[2];
  42810. }
  42811. set rgbContrast (value) {
  42812. if (this.uniforms.uRGB_gbc.value[2] !== value) {
  42813. this.uniforms.uRGB_gbc.value[2] = value;
  42814. this.dispatchEvent({
  42815. type: 'material_property_changed',
  42816. target: this
  42817. });
  42818. }
  42819. }
  42820. get rgbBrightness () {
  42821. return this.uniforms.uRGB_gbc.value[1];
  42822. }
  42823. set rgbBrightness (value) {
  42824. if (this.uniforms.uRGB_gbc.value[1] !== value) {
  42825. this.uniforms.uRGB_gbc.value[1] = value;
  42826. this.dispatchEvent({
  42827. type: 'material_property_changed',
  42828. target: this
  42829. });
  42830. }
  42831. }
  42832. get extraGamma () {
  42833. return this.uniforms.uExtraGammaBrightContr.value[0];
  42834. }
  42835. set extraGamma (value) {
  42836. if (this.uniforms.uExtraGammaBrightContr.value[0] !== value) {
  42837. this.uniforms.uExtraGammaBrightContr.value[0] = value;
  42838. this.dispatchEvent({
  42839. type: 'material_property_changed',
  42840. target: this
  42841. });
  42842. }
  42843. }
  42844. get extraBrightness () {
  42845. return this.uniforms.uExtraGammaBrightContr.value[1];
  42846. }
  42847. set extraBrightness (value) {
  42848. if (this.uniforms.uExtraGammaBrightContr.value[1] !== value) {
  42849. this.uniforms.uExtraGammaBrightContr.value[1] = value;
  42850. this.dispatchEvent({
  42851. type: 'material_property_changed',
  42852. target: this
  42853. });
  42854. }
  42855. }
  42856. get extraContrast () {
  42857. return this.uniforms.uExtraGammaBrightContr.value[2];
  42858. }
  42859. set extraContrast (value) {
  42860. if (this.uniforms.uExtraGammaBrightContr.value[2] !== value) {
  42861. this.uniforms.uExtraGammaBrightContr.value[2] = value;
  42862. this.dispatchEvent({
  42863. type: 'material_property_changed',
  42864. target: this
  42865. });
  42866. }
  42867. }
  42868. getRange(attributeName){
  42869. return this.ranges.get(attributeName);
  42870. }
  42871. setRange(attributeName, newRange){
  42872. let rangeChanged = false;
  42873. let oldRange = this.ranges.get(attributeName);
  42874. if(oldRange != null && newRange != null){
  42875. rangeChanged = oldRange[0] !== newRange[0] || oldRange[1] !== newRange[1];
  42876. }else {
  42877. rangeChanged = true;
  42878. }
  42879. this.ranges.set(attributeName, newRange);
  42880. if(rangeChanged){
  42881. this.dispatchEvent({
  42882. type: 'material_property_changed',
  42883. target: this
  42884. });
  42885. }
  42886. }
  42887. get extraRange () {
  42888. return this.uniforms.uExtraRange.value;
  42889. }
  42890. set extraRange (value) {
  42891. if (!(value instanceof Array && value.length === 2)) {
  42892. return;
  42893. }
  42894. if (value[0] === this.uniforms.uExtraRange.value[0] &&
  42895. value[1] === this.uniforms.uExtraRange.value[1]) {
  42896. return;
  42897. }
  42898. this.uniforms.uExtraRange.value = value;
  42899. this._defaultExtraRangeChanged = true;
  42900. this.dispatchEvent({
  42901. type: 'material_property_changed',
  42902. target: this
  42903. });
  42904. }
  42905. get weightRGB () {
  42906. return this.uniforms.wRGB.value;
  42907. }
  42908. set weightRGB (value) {
  42909. if(this.uniforms.wRGB.value !== value){
  42910. this.uniforms.wRGB.value = value;
  42911. this.dispatchEvent({
  42912. type: 'material_property_changed',
  42913. target: this
  42914. });
  42915. }
  42916. }
  42917. get weightIntensity () {
  42918. return this.uniforms.wIntensity.value;
  42919. }
  42920. set weightIntensity (value) {
  42921. if(this.uniforms.wIntensity.value !== value){
  42922. this.uniforms.wIntensity.value = value;
  42923. this.dispatchEvent({
  42924. type: 'material_property_changed',
  42925. target: this
  42926. });
  42927. }
  42928. }
  42929. get weightElevation () {
  42930. return this.uniforms.wElevation.value;
  42931. }
  42932. set weightElevation (value) {
  42933. if(this.uniforms.wElevation.value !== value){
  42934. this.uniforms.wElevation.value = value;
  42935. this.dispatchEvent({
  42936. type: 'material_property_changed',
  42937. target: this
  42938. });
  42939. }
  42940. }
  42941. get weightClassification () {
  42942. return this.uniforms.wClassification.value;
  42943. }
  42944. set weightClassification (value) {
  42945. if(this.uniforms.wClassification.value !== value){
  42946. this.uniforms.wClassification.value = value;
  42947. this.dispatchEvent({
  42948. type: 'material_property_changed',
  42949. target: this
  42950. });
  42951. }
  42952. }
  42953. get weightReturnNumber () {
  42954. return this.uniforms.wReturnNumber.value;
  42955. }
  42956. set weightReturnNumber (value) {
  42957. if(this.uniforms.wReturnNumber.value !== value){
  42958. this.uniforms.wReturnNumber.value = value;
  42959. this.dispatchEvent({
  42960. type: 'material_property_changed',
  42961. target: this
  42962. });
  42963. }
  42964. }
  42965. get weightSourceID () {
  42966. return this.uniforms.wSourceID.value;
  42967. }
  42968. set weightSourceID (value) {
  42969. if(this.uniforms.wSourceID.value !== value){
  42970. this.uniforms.wSourceID.value = value;
  42971. this.dispatchEvent({
  42972. type: 'material_property_changed',
  42973. target: this
  42974. });
  42975. }
  42976. }
  42977. static generateGradientTexture (gradient) {
  42978. let size = 64;
  42979. // create canvas
  42980. let canvas = document.createElement('canvas');
  42981. canvas.width = size;
  42982. canvas.height = size;
  42983. // get context
  42984. let context = canvas.getContext('2d');
  42985. // draw gradient
  42986. context.rect(0, 0, size, size);
  42987. let ctxGradient = context.createLinearGradient(0, 0, size, size);
  42988. for (let i = 0; i < gradient.length; i++) {
  42989. let step = gradient[i];
  42990. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  42991. }
  42992. context.fillStyle = ctxGradient;
  42993. context.fill();
  42994. //let texture = new THREE.Texture(canvas);
  42995. let texture = new CanvasTexture(canvas);
  42996. texture.needsUpdate = true;
  42997. texture.minFilter = LinearFilter;
  42998. texture.wrap = RepeatWrapping;
  42999. texture.repeat = 2;
  43000. // textureImage = texture.image;
  43001. return texture;
  43002. }
  43003. static generateMatcapTexture (matcap) {
  43004. var url = new URL(Potree.resourcePath + "/textures/matcap/" + matcap).href;
  43005. let texture = new TextureLoader().load( url );
  43006. texture.magFilter = texture.minFilter = LinearFilter;
  43007. texture.needsUpdate = true;
  43008. // PotreeConverter_1.6_2018_07_29_windows_x64\PotreeConverter.exe autzen_xyzrgbXYZ_ascii.xyz -f xyzrgbXYZ -a RGB NORMAL -o autzen_xyzrgbXYZ_ascii_a -p index --overwrite
  43009. // Switch matcap texture on the fly : viewer.scene.pointclouds[0].material.matcap = 'matcap1.jpg';
  43010. // For non power of 2, use LinearFilter and dont generate mipmaps, For power of 2, use NearestFilter and generate mipmaps : matcap2.jpg 1 2 8 11 12 13
  43011. return texture;
  43012. }
  43013. disableEvents(){
  43014. if(this._hiddenListeners === undefined){
  43015. this._hiddenListeners = this._listeners;
  43016. this._listeners = {};
  43017. }
  43018. };
  43019. enableEvents(){
  43020. this._listeners = this._hiddenListeners;
  43021. this._hiddenListeners = undefined;
  43022. };
  43023. ////////////////////////add
  43024. setProjectedPanos(pano0, pano1, progressValue, easeInOutRatio){
  43025. //this.uniforms.usePanoMap.value = 1
  43026. this.usePanoMap = true;
  43027. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  43028. //pano0.ensureSkyboxReadyForRender();
  43029. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();
  43030. this.uniforms.pano0Position.value.copy(pano0.position);
  43031. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix );
  43032. //pano1.ensureSkyboxReadyForRender();
  43033. this.uniforms.easeInOutRatio.value = easeInOutRatio || 0; //之前做点云和全景混合时加的,为了让点云颜色柔和切换到全景颜色。如不混合就0
  43034. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();
  43035. this.uniforms.pano1Position.value.copy(pano1.position);
  43036. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix );
  43037. //this.updateShaderSource()
  43038. //this.needsUpdate = true;
  43039. }
  43040. stopProjectedPanos(){
  43041. //this.uniforms.usePanoMap.value = 0
  43042. this.usePanoMap = false;
  43043. }
  43044. // copyFrom(from){
  43045. // var a = 10;
  43046. // for(let name of Object.keys(this.uniforms)){
  43047. // this.uniforms[name].value = from.uniforms[name].value;
  43048. // }
  43049. // }
  43050. // copy(from){
  43051. // this.copyFrom(from);
  43052. // }
  43053. }
  43054. var Common = {
  43055. sortByScore: function(list, request, rank){
  43056. var i = request ? Common.filterAll(list, request) : list;
  43057. return 0 === i.length ? null : i = i.map(function(e) {
  43058. return {
  43059. item: e,
  43060. score: rank.reduce(function(t, i) {
  43061. return t + i(e)
  43062. }, 0)
  43063. }
  43064. }).sort(function(e, t) {
  43065. return t.score - e.score;
  43066. })
  43067. }
  43068. ,
  43069. filterAll: function(e, t) {
  43070. return e.filter(function (e) {
  43071. return t.every(function (t) {
  43072. return t(e)
  43073. })
  43074. })
  43075. },
  43076. //---------------
  43077. find : function(list, request, rank, sortByScore ) {
  43078. if(sortByScore){
  43079. var r = this.sortByScore(list, request, rank);
  43080. return r && r[0] && r[0].item
  43081. }else {
  43082. var i = request ? Common.filterAll(list, request) : list;
  43083. return 0 === i.length ? null : (rank && rank.forEach(function(e) {
  43084. i = Common.stableSort(i, e);
  43085. }),
  43086. i[0])
  43087. }
  43088. }
  43089. ,
  43090. stableSort: function(e, f) {//用到排序函数,涉及到两个item相减
  43091. return e.map(function(e, i) {
  43092. return {
  43093. value: e,
  43094. index: i
  43095. }
  43096. }).sort(function(e, u) {
  43097. var n = f(e.value, u.value);
  43098. return 0 !== n ? n : e.index - u.index //似乎就是加多了这一步:若差距为0,按照原顺序
  43099. }).map(function(e) {
  43100. return e.value
  43101. })
  43102. },
  43103. average: function (e, t) {
  43104. if (0 === e.length)
  43105. return null;
  43106. for (var i = 0, n = 0, r = 0; r < e.length; r++) {
  43107. var o = t ? e[r][t] : e[r];
  43108. i += o,
  43109. n++;
  43110. }
  43111. return i / n
  43112. },
  43113. //---------------------------
  43114. getMixedSet : function(arr1, arr2){//交集
  43115. return arr1.filter(item=>arr2.includes(item));
  43116. },
  43117. getUnionSet : function(arr1, arr2){//并集
  43118. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  43119. },
  43120. getDifferenceSet : function(arr1, arr2){//差集 不能识别重复的,如getDifferenceSet([1,2,2],[1,1,2]) 为空
  43121. var arr11 = arr1.filter(item=>!arr2.includes(item));
  43122. var arr22 = arr2.filter(item=>!arr1.includes(item));
  43123. return arr11.concat(arr22)
  43124. },
  43125. getDifferenceSetMuti : function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  43126. var set = [];
  43127. arr.forEach(arr1=>{
  43128. arr1.forEach(item=>{
  43129. var index = set.indexOf(item);
  43130. if(index>-1){
  43131. set.splice(index, 1);
  43132. }else {
  43133. set.push(item);
  43134. }
  43135. });
  43136. });
  43137. return set;
  43138. }
  43139. ,
  43140. CloneJson : function(data){
  43141. var str = JSON.stringify(data);
  43142. return JSON.parse(str)
  43143. }
  43144. ,
  43145. CloneObject : function(copyObj, result, isSimpleCopy, simpleCopyList=[]) {
  43146. //isSimpleCopy 只复制最外层
  43147. //复制json result的可能:普通数字或字符串、普通数组、复杂对象
  43148. simpleCopyList.push(Object3D); //遇到simpleCopyList中的类直接使用不拷贝
  43149. if(!copyObj || typeof copyObj == 'number' || typeof copyObj == 'string' || copyObj instanceof Function || simpleCopyList.some(className => copyObj instanceof className)){
  43150. return copyObj
  43151. }
  43152. result = result || {};
  43153. if (copyObj instanceof Array) {
  43154. return copyObj.map(e=>{
  43155. return this.CloneObject(e)
  43156. })
  43157. }else {
  43158. if(copyObj.clone instanceof Function ){ //解决一部分
  43159. return copyObj.clone()
  43160. }
  43161. }
  43162. for (var key in copyObj) {
  43163. if (copyObj[key] instanceof Object && !isSimpleCopy)
  43164. result[key] = this.CloneObject(copyObj[key]);
  43165. else
  43166. result[key] = copyObj[key];
  43167. //如果是函数类同基本数据,即复制引用
  43168. }
  43169. return result;
  43170. }
  43171. ,
  43172. CloneClassObject :function(copyObj ){//复杂类对象
  43173. var newobj = new copyObj.constructor();
  43174. this.CopyClassObject(newobj, copyObj);
  43175. return newobj
  43176. }
  43177. ,
  43178. CopyClassObject :function(targetObj, copyObj){//复杂类对象
  43179. for(let i in copyObj){
  43180. if(i in copyObj.__proto__)break; //到函数了跳出
  43181. targetObj[i] = this.CloneObject(copyObj[i], null );
  43182. /* else if(copyObj[i].clone instanceof Function ){
  43183. targetObj[i] = copyObj[i].clone()
  43184. }else{
  43185. targetObj[i] = copyObj[i];
  43186. } */
  43187. }
  43188. }
  43189. ,
  43190. ifSame : function(object1, object2){
  43191. if(object1 == object2 )return true // 0 != undefined , 0 == ''
  43192. else if(!object1 || !object2) return false
  43193. else if(object1.constructor != object2.constructor){
  43194. return false
  43195. }else if(object1 instanceof Array ) {
  43196. if(object1.length != object2.length)return false;
  43197. var _object2 = object2.slice(0);
  43198. for(let i=0;i<object1.length;i++){
  43199. var u = _object2.find(e=>ifSame(object1[i], e));
  43200. if(u == void 0 && !_object2.includes(u) && !object1.includes(u))return false;
  43201. else {
  43202. let index = _object2.indexOf(u);
  43203. _object2.splice(index,1);
  43204. }
  43205. }
  43206. return true
  43207. }else if(object1.equals instanceof Function ){//复杂数据仅支持这种,其他的可能卡住?
  43208. return object1.equals(object2)
  43209. }else if(typeof object1 == 'number' || typeof object1 == 'string'){
  43210. if(isNaN(object1) && isNaN(object2))return true
  43211. else return object1 == object2
  43212. }else if(typeof object1 == "object"){
  43213. var keys1 = Object.keys(object1);
  43214. var keys2 = Object.keys(object2);
  43215. if(!ifSame(keys1,keys2))return false;
  43216. for(let i in object1){
  43217. var same = ifSame(object1[i], object2[i]);
  43218. if(!same)return false
  43219. }
  43220. return true
  43221. }else {
  43222. console.log('isSame出现例外');
  43223. }
  43224. }
  43225. ,
  43226. replaceAll : function (str, f, e) {
  43227. //f全部替换成e
  43228. var reg = new RegExp(f, "g"); //创建正则RegExp对象
  43229. return str.replace(reg, e);
  43230. }
  43231. ,
  43232. downloadFile : function(data, filename, cb) {
  43233. var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  43234. save_link.href = data;
  43235. save_link.download = filename;
  43236. var event = document.createEvent('MouseEvents');
  43237. event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  43238. save_link.dispatchEvent(event);
  43239. cb && cb();
  43240. },
  43241. intervalTool:{ //延时update,防止卡顿
  43242. list:[],
  43243. isWaiting:function(name, func, delayTime){
  43244. if(!this.list.includes(name)){ //如果没有该项, 则开始判断
  43245. var needWait = func(); //触发了改变,则等待一段时间后再自动判断
  43246. if(needWait){
  43247. this.list.push(name);
  43248. setTimeout(()=>{
  43249. var a = this.list.indexOf(name);
  43250. this.list.splice(a,1);
  43251. this.isWaiting(name, func, delayTime); //循环
  43252. },delayTime);
  43253. }
  43254. }
  43255. },
  43256. /* wait:function(name, delayTime){
  43257. this.list.push(name);
  43258. setTimeout(()=>{
  43259. },delayTime)
  43260. }, */
  43261. }
  43262. ,
  43263. pushToGroupAuto : function(items, groups, recognizeFunction){//自动分组。 items是将分到一起的组合。items.length = 1 or 2.
  43264. recognizeFunction = recognizeFunction || function(){};
  43265. var atGroups = groups.filter(group=>group.find(
  43266. item => items[0] == item || recognizeFunction(item, items[0]) || items[1] == item || items[1] && recognizeFunction(item, items[1])
  43267. ));
  43268. if(atGroups.length){//在不同组
  43269. //因为items是一组的,所以先都放入组1
  43270. items.forEach(item=> {if(!atGroups[0].includes(item)) atGroups[0].push(item);});
  43271. if(atGroups.length>1){//如果在不同组,说明这两个组需要合并
  43272. var combineGroup = [];
  43273. atGroups.forEach(group=>{
  43274. combineGroup = Common.getUnionSet(combineGroup, group);
  43275. groups.splice(groups.indexOf(group),1);
  43276. });
  43277. groups.push(combineGroup);
  43278. }
  43279. }else {//直接加入为一组
  43280. groups.push(items);
  43281. }
  43282. },
  43283. addOrRemoveDefine(material, defineName, type, value=''){
  43284. let defines = material.defines;
  43285. if(type == 'add'){
  43286. if(defines[defineName] != void 0 && defines[defineName] == value)return
  43287. defines[defineName] = value;
  43288. }else {
  43289. if(defines[defineName] != void 0)return;
  43290. delete defines[defineName];
  43291. }
  43292. material.needsUpdate = true;
  43293. },
  43294. makeTexDontResize(map){//避免贴图因非2的次方而缩小。小心使用
  43295. if(!map || map.image && MathUtils.isPowerOfTwo(map.image.width ) && MathUtils.isPowerOfTwo(map.image.height ))return
  43296. map.wrapS = map.wrapT = ClampToEdgeWrapping; //原默认 RepeatWrapping
  43297. map.minFilter = LinearFilter; // or THREE.NearestFilter 原默认 LinearMipmapLinearFilter
  43298. }
  43299. };
  43300. const planeGeo = new PlaneBufferGeometry(1,1);
  43301. const planeMats$1 = new Map();
  43302. let getPlaneMat = (group, removed)=>{
  43303. let mat = planeMats$1.get(group);
  43304. if(mat)return mat
  43305. var planeMat = new MeshBasicMaterial({
  43306. //color: level == 'removed' ? "#f00" : new THREE.Color(1 - level*0.2, 1,1),
  43307. color: (new Color()).setHSL(Math.random(), 0.5, 0.9) ,
  43308. //color: (new THREE.Color()).setHSL(removed ? 0 : 0.6, Math.random(), 0.9/* Math.random() */) ,
  43309. transparent:true,
  43310. side:2,
  43311. opacity: removed ? 0.3 : 0.9,
  43312. });
  43313. planeMats$1.set(group, planeMat);
  43314. return planeMat
  43315. };
  43316. class PointCloudOctreeNode extends PointCloudTreeNode {
  43317. constructor () {
  43318. super();
  43319. //this.children = {};
  43320. this.children = [];
  43321. this.sceneNode = null;
  43322. this.octree = null;
  43323. }
  43324. getNumPoints () {
  43325. return this.geometryNode.numPoints;
  43326. }
  43327. isLoaded () {
  43328. return true;
  43329. }
  43330. isTreeNode () {
  43331. return true;
  43332. }
  43333. isGeometryNode () {
  43334. return false;
  43335. }
  43336. getLevel () {
  43337. return this.geometryNode.level;
  43338. }
  43339. getBoundingSphere () {
  43340. return this.geometryNode.boundingSphere;
  43341. }
  43342. getBoundingBox () {
  43343. return this.geometryNode.boundingBox;
  43344. }
  43345. getChildren () {
  43346. let children = [];
  43347. for (let i = 0; i < 8; i++) {
  43348. if (this.children[i]) {
  43349. children.push(this.children[i]);
  43350. }
  43351. }
  43352. return children;
  43353. }
  43354. getPointsInBox(boxNode){
  43355. if(!this.sceneNode){
  43356. return null;
  43357. }
  43358. let buffer = this.geometryNode.buffer;
  43359. let posOffset = buffer.offset("position");
  43360. let stride = buffer.stride;
  43361. let view = new DataView(buffer.data);
  43362. let worldToBox = boxNode.matrixWorld.clone().invert();
  43363. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  43364. let inBox = [];
  43365. let pos = new Vector4();
  43366. for(let i = 0; i < buffer.numElements; i++){
  43367. let x = view.getFloat32(i * stride + posOffset + 0, true);
  43368. let y = view.getFloat32(i * stride + posOffset + 4, true);
  43369. let z = view.getFloat32(i * stride + posOffset + 8, true);
  43370. pos.set(x, y, z, 1);
  43371. pos.applyMatrix4(objectToBox);
  43372. if(-0.5 < pos.x && pos.x < 0.5){
  43373. if(-0.5 < pos.y && pos.y < 0.5){
  43374. if(-0.5 < pos.z && pos.z < 0.5){
  43375. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  43376. inBox.push(new Vector3(pos.x, pos.y, pos.z));
  43377. }
  43378. }
  43379. }
  43380. }
  43381. return inBox;
  43382. }
  43383. get name () {
  43384. return this.geometryNode.name;
  43385. }
  43386. };
  43387. class PointCloudOctree extends PointCloudTree {
  43388. constructor (geometry, material) {
  43389. super();
  43390. //this.pointBudget = Infinity;
  43391. this.pcoGeometry = geometry;
  43392. this.boundingBox = this.pcoGeometry.tightBoundingBox;//this.pcoGeometry.boundingBox; //boundingBox是正方体,所以换掉
  43393. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  43394. this.material = material || new PointCloudMaterial$1();
  43395. this.visiblePointsTarget = 2 * 1000 * 1000;
  43396. this.minimumNodePixelSize = 150;
  43397. this.level = 0;
  43398. this.position.copy(geometry.offset);
  43399. this.updateMatrix();
  43400. this.nodeMaxLevel = 0;//add
  43401. this.maxLevel = Infinity;
  43402. this.temp = { sizeFitToLevel:{}, opacity:{}};//add
  43403. //add
  43404. this.panos = [];
  43405. this.matrixAutoUpdate = false; //最好禁止updateMatrix 直接使用matrixWorld
  43406. this.orientationUser = 0;
  43407. this.translateUser = new Vector3;
  43408. this.rotateMatrix = new Matrix4;
  43409. this.transformMatrix = new Matrix4;// 数据集的变化矩阵
  43410. this.transformInvMatrix = new Matrix4;
  43411. this.rotateInvMatrix = new Matrix4;
  43412. this.nodeMaxLevelPredict = this.predictNodeMaxLevel();//预测maxNodeLevel
  43413. this.testMaxNodeCount = this.testMaxNodeCount2 = 0;
  43414. this.material.spacing = this.pcoGeometry.spacing;//初始化一下 以便于设置pointsize
  43415. {
  43416. let priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  43417. let selected = "rgba";
  43418. for(let attributeName of priorityQueue){
  43419. let attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  43420. if(!attribute){
  43421. continue;
  43422. }
  43423. let min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  43424. let max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  43425. let range_min = new Vector3(...min);
  43426. let range_max = new Vector3(...max);
  43427. let range = range_min.distanceTo(range_max);
  43428. if(range === 0){
  43429. continue;
  43430. }
  43431. selected = attributeName;
  43432. break;
  43433. }
  43434. this.material.activeAttributeName = selected;
  43435. }
  43436. this.showBoundingBox = false;
  43437. this.boundingBoxNodes = [];
  43438. this.loadQueue = [];
  43439. this.visibleBounds = new Box3();
  43440. this.visibleNodes = [];
  43441. this.visibleGeometry = [];
  43442. this.generateDEM = false;
  43443. this.profileRequests = [];
  43444. this.name = '';
  43445. this._visible = true;
  43446. //this._isVisible = true//add
  43447. //this.unvisibleReasons = []
  43448. {
  43449. let box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()]
  43450. .find(v => v !== undefined);
  43451. this.updateMatrixWorld(true);
  43452. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  43453. let bMin = box.min.z;
  43454. let bMax = box.max.z;
  43455. this.material.heightMin = bMin;
  43456. this.material.heightMax = bMax;
  43457. }
  43458. // TODO read projection from file instead
  43459. this.projection = geometry.projection;
  43460. this.fallbackProjection = geometry.fallbackProjection;
  43461. this.root = this.pcoGeometry.root;
  43462. this.pcoGeometry.addEventListener('updateNodeMaxLevel', this.updateNodeMaxLevel.bind(this));
  43463. this.isPointcloud = true; //add
  43464. }
  43465. /*
  43466. 注释:node的level从最大的box 0开始。
  43467. 且加载任意一个node必定也会加载它的所有祖先。(如visibleNodes中有一个level为4,则一定有3,2,1,0)
  43468. visibleNodes就是所有可见的node,比如:
  43469. 如果相机在0这个位置朝下,这时候的visibleNodes中只有一个level为0的node;
  43470. 而如果朝上看,上方的几个node如果在视野中占据足够大的位置的话,就会加载。
  43471. 如果相机在2这个位置朝上,这时候的visibleNodes中所包含的level为: 0,1,2
  43472. ________________
  43473. | | | |
  43474. |__2| | |
  43475. | 1 | 1 |
  43476. |_______|_______|
  43477. | |
  43478. | |
  43479. | 0 |
  43480. |_______________|
  43481. 查看box可在potree中开启
  43482. */
  43483. updateNodeMaxLevel(e){//目前点云包含node的最高level
  43484. var level = Math.max(e.level, this.nodeMaxLevel);
  43485. if(level != this.nodeMaxLevel){
  43486. this.nodeMaxLevel = level;
  43487. //viewer.dispatchEvent({type:'updateNodeMaxLevel', pointcloud: this, nodeMaxLevel:level})
  43488. //console.log('updateNodeMaxLevel ' + this.dataset_id + " : "+ this.nodeMaxLevel)
  43489. this.setPointLevel();//重新计算
  43490. if(!Potree.settings.sizeFitToLevel){
  43491. this.changePointSize();
  43492. }
  43493. }
  43494. }//注:在没有加载到真实的 nodeMaxLevel之前,点云会显示得偏大
  43495. //panoEdit时比预测值小很多?
  43496. testMaxNodeLevel(){//手动使maxLevel达到最高,从而迫使updateNodeMaxLevel。 因为Potree.settings.pointDensity 不为 'high'时,maxLevel不是所加载的最高,就很容易加载不出下一个层级,导致无法知道nodeMaxLevel
  43497. if(this.testMaxNodeLevelDone ) return
  43498. //if(this.nodeMaxLevel > this.nodeMaxLevelPredict.min )return
  43499. if( this.nodeMaxLevel==0 )return true
  43500. if( !viewer.atDatasets.includes(this))return true //否则老远就count++
  43501. let levels = this.visibleNodes.map(e=>e.getLevel());
  43502. let actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  43503. if(actMaxLevel < this.maxLevel)return true// 还没加载到能加载到的最高。 但在细节设置较低时,排除作用微弱。
  43504. //尝试加载出更高级的level
  43505. let old = this.maxLevel;
  43506. this.maxLevel = 12;
  43507. //var visibleNodes1 = this.visibleNodes.map(e=>e.getLevel())
  43508. //console.log('visibleNodes1',visibleNodes1)
  43509. Potree.updatePointClouds([this], viewer.scene.getActiveCamera(), viewer.mainViewport.resolution );
  43510. //不在camera可视范围内还是加载不出来。即使临时修改位置
  43511. var visibleNodes2 = this.visibleNodes.map(e=>e.getLevel());
  43512. //console.log('visibleNodes2',visibleNodes2)
  43513. this.maxLevel = old;
  43514. this.testMaxNodeCount ++;
  43515. if(this.testMaxNodeCount > 500){
  43516. console.log('testMaxNodeLevel次数超出,强制结束:',this.dataset_id, this.nodeMaxLevel, this.nodeMaxLevelPredict.min);
  43517. this.testMaxNodeLevelDone = 'moreThanMaxCount';
  43518. return; //在可以看见点云的情况下,超时,有可能是预测的max是错的
  43519. }
  43520. if(this.nodeMaxLevel < this.nodeMaxLevelPredict.min) return true //仍需要继续testMaxNodeLevel
  43521. this.testMaxNodeCount2 ++; // 已经> this.nodeMaxLevelPredict.min 后,开始计数。因为min可能低于真实nodeMaxLevel所以要再试几次
  43522. /* if(this.name == 'SS-t-CWmVgzP4XU'){
  43523. console.log('SS-t-CWmVgzP4XU count++')
  43524. } */
  43525. if(this.testMaxNodeCount2 < 50) return true //再试几次 ( 主要是细节调得低时需要多测几次才加载到
  43526. this.testMaxNodeLevelDone = true;
  43527. }
  43528. setPointLevel(){
  43529. var pointDensity = Potree.settings.pointDensity;
  43530. var config = Potree.config.pointDensity[pointDensity];
  43531. if(!config)return
  43532. /* if(this.testingMaxLevel){
  43533. this.maxLevel = 12;//先加载到最大的直到测试完毕。由于5个level为一组来加载,所以如果写4最高能加载到5,如果写5最高能加载到下一个级别的最高也就是10
  43534. //console.log('maxLevel: '+e.maxLevel + ' testingMaxLevel中 ' )
  43535. }else{ */
  43536. let percent = config.percentByUser && Potree.settings.UserDensityPercent != void 0 ? Potree.settings.UserDensityPercent : config.maxLevelPercent;
  43537. this.maxLevel = Math.round( percent * this.nodeMaxLevel);
  43538. //console.log('maxLevel: '+e.maxLevel + ', density : '+Potree.settings.pointDensity, ", percent :"+percent);
  43539. if(Potree.settings.sizeFitToLevel){
  43540. this.changePointSize();
  43541. }
  43542. this.changePointOpacity();
  43543. //}
  43544. }
  43545. //预测可能的nodeMaxLevel:
  43546. predictNodeMaxLevel(){//预测maxNodeLevel。 可能只适用于我们相机拍的点云
  43547. let spacing = {min:0.005, max:0.014};//最小节的两点间的距离 ,获得方法:spacing / Math.pow(2, nodeMaxLevel)。 目前观测的我们自己拍的这个数值的范围大概是这样
  43548. let min = Math.log2(this.material.spacing / spacing.max); //有见过最大是0.01368
  43549. let max = Math.log2(this.material.spacing / spacing.min); //大部分是 0.006
  43550. //console.log('predictNodeMaxLevel:', this.name , min, max )
  43551. return {min, max}
  43552. }
  43553. getHighestNodeSpacing(){
  43554. return this.material.spacing / Math.pow(2, this.nodeMaxLevel) //前提是这个nodeMaxLevel是准确的
  43555. }
  43556. setName (name) {
  43557. if (this.name !== name) {
  43558. this.name = name;
  43559. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  43560. }
  43561. }
  43562. getName () {
  43563. return this.name;
  43564. }
  43565. getAttribute(name){
  43566. const attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  43567. if(attribute){
  43568. return attribute;
  43569. }else {
  43570. return null;
  43571. }
  43572. }
  43573. getAttributes(){
  43574. return this.pcoGeometry.pointAttributes;
  43575. }
  43576. toTreeNode (geometryNode, parent) {
  43577. let node = new PointCloudOctreeNode();
  43578. // if(geometryNode.name === "r40206"){
  43579. // console.log("creating node for r40206");
  43580. // }
  43581. let sceneNode = new Points(geometryNode.geometry, this.material); //好像没什么用
  43582. sceneNode.name = geometryNode.name;
  43583. sceneNode.position.copy(geometryNode.boundingBox.min);
  43584. sceneNode.frustumCulled = false;
  43585. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  43586. if (material.program) {
  43587. _this.getContext().useProgram(material.program.program);
  43588. if (material.program.getUniforms().map.level) {
  43589. let level = geometryNode.getLevel();
  43590. material.uniforms.level.value = level;
  43591. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  43592. }
  43593. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  43594. let vnStart = this.visibleNodeTextureOffsets.get(node);
  43595. material.uniforms.vnStart.value = vnStart;
  43596. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  43597. }
  43598. if (material.program.getUniforms().map.pcIndex) {
  43599. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  43600. material.uniforms.pcIndex.value = i;
  43601. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  43602. }
  43603. }
  43604. };
  43605. // { // DEBUG
  43606. // let sg = new THREE.SphereGeometry(1, 16, 16);
  43607. // let sm = new THREE.MeshNormalMaterial();
  43608. // let s = new THREE.Mesh(sg, sm);
  43609. // s.scale.set(5, 5, 5);
  43610. // s.position.copy(geometryNode.mean)
  43611. // .add(this.position)
  43612. // .add(geometryNode.boundingBox.min);
  43613. //
  43614. // viewer.scene.scene.add(s);
  43615. // }
  43616. node.geometryNode = geometryNode;
  43617. node.sceneNode = sceneNode;
  43618. node.pointcloud = this;
  43619. node.children = [];
  43620. //for (let key in geometryNode.children) {
  43621. // node.children[key] = geometryNode.children[key];
  43622. //}
  43623. for(let i = 0; i < 8; i++){
  43624. node.children[i] = geometryNode.children[i];
  43625. }
  43626. if (!parent) {
  43627. this.root = node;
  43628. this.add(sceneNode);
  43629. } else {
  43630. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  43631. parent.sceneNode.add(sceneNode);
  43632. parent.children[childIndex] = node;
  43633. }
  43634. let disposeListener = function () {
  43635. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  43636. parent.sceneNode.remove(node.sceneNode);
  43637. parent.children[childIndex] = geometryNode;
  43638. };
  43639. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  43640. //this.buildTexMesh(geometryNode,sceneNode)
  43641. return node;
  43642. }
  43643. buildTexMesh11(geometryNode,sceneNode){
  43644. // viewer.scene.pointclouds.forEach(a=>a.areaPlanes.forEach(e=>e.material = viewer.images360.cube.material))
  43645. //还是无法避免不在同一个平面的点被识别到同一个面上,然后法向都算错了。 另外还有就是破面太多。虽然能算出地板也不错。或者只去算水平面和垂直面。
  43646. let startTime = Date.now();
  43647. if(!this.splitSprites){
  43648. let splitSprites = new Object3D;
  43649. splitSprites.name = 'splitSprites_'+this.name;
  43650. splitSprites.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43651. splitSprites.matrix.copy(this.matrix);
  43652. splitSprites.matrixWorld.copy(this.matrixWorld);
  43653. this.splitSprites = splitSprites;
  43654. viewer.scene.scene.add(splitSprites);
  43655. this.areaPlanes = [];
  43656. }
  43657. if(this.texMeshUseLevel == void 0 || geometryNode.level == this.texMeshUseLevel){//只需要某一层level的点
  43658. let showPointLabel = true, showCenterLabel = false;
  43659. //let spritesGeo = new THREE.BufferGeometry();
  43660. let scaleRatio = 1.4; //稍微放大些,填满缝隙
  43661. let spriteWidth1 = this.material.spacing / Math.pow(2, geometryNode.level);
  43662. if(spriteWidth1 > 3)return
  43663. let spriteWidth = spriteWidth1 * scaleRatio;
  43664. if(this.texMeshUseLevel == void 0 ){
  43665. this.texMeshUseLevel = geometryNode.level;
  43666. console.log('texMeshUseLevel ',geometryNode.level);
  43667. }
  43668. let geometry = geometryNode.geometry;
  43669. let count = geometry.attributes.position.count;
  43670. let end = Math.min(count, 6000);
  43671. let start = Math.min(5000, end);
  43672. console.warn('check points count:', end-start);
  43673. let position = geometry.attributes.position.array;
  43674. let normal = geometry.attributes.normal.array;
  43675. let i;
  43676. let up = new Vector3(0,1,0) , zeroVec = new Vector3; //up写成z向上居然结果一样
  43677. let positions = [];
  43678. let normals = [];
  43679. let newPositions = [];
  43680. let newIndices = [];
  43681. let groupMaxPointCount = 1000 ;//太多找环会崩
  43682. let minDisSquare = Math.pow(spriteWidth1 * 1.8 , 2 ); //这个数太小就连不上啦 1.65太小
  43683. let minDot = Math.cos(MathUtils.degToRad(5));//括号内是最小偏差角度, 20太大。太大的话会将立方体的相邻两面视为一个面。
  43684. //根据相邻点位置和角度是否相近来分组。有风险:两大区域可能因为一个模棱两可中间点连接在一起。
  43685. let closeGroups = [];
  43686. let groupTolerateMaxPoint = 6;//组内点<=这个数的最后会被删除
  43687. let removedCount = 0;
  43688. let useGroupCount = 0;
  43689. let splitSprites = new Object3D;
  43690. splitSprites.name = 'sub_splitSprites_'+geometryNode.name;
  43691. splitSprites.position.copy(sceneNode.position);
  43692. splitSprites.rotation.copy(sceneNode.rotation);
  43693. this.splitSprites.add(splitSprites);
  43694. for(i=start;i<end;i++){
  43695. let pos = new Vector3(position[3*i], position[3*i+1], position[3*i+2] );
  43696. let nor = new Vector3(normal[3*i],normal[3*i+1],normal[3*i+2]);
  43697. pos.nor = nor;
  43698. pos.index = i;
  43699. positions.push(pos);
  43700. normals.push(nor);
  43701. let groups = closeGroups.filter(group=>{
  43702. if(group.length>groupMaxPointCount)return //满员了
  43703. var hasClosed = group.some(p=>{
  43704. var dis = p.distanceToSquared(pos);
  43705. var dot = p.nor.dot(nor);
  43706. if(dis<minDisSquare && dot>minDot){
  43707. //return dis / minDisSquare + (Math.abs(p.nor.x - nor.x) + Math.abs(p.nor.y - nor.y) + Math.abs(p.nor.z - nor.z)) < 1.7
  43708. return dis / minDisSquare - p.nor.dot(nor) < 0
  43709. }
  43710. });
  43711. return hasClosed
  43712. });
  43713. if(groups.length == 0){//创建一个新的
  43714. var newGroup = [];
  43715. closeGroups.push(newGroup);
  43716. groups = [newGroup];
  43717. }
  43718. if(groups.length == 1){//直接加入原有的
  43719. pos.belongTo = groups[0];
  43720. }else if(groups.length>1){ // comebine多个组成一个
  43721. let newBigGroup = [];
  43722. groups.forEach(e=>{
  43723. newBigGroup.push(...e);
  43724. let index = closeGroups.indexOf(e);
  43725. closeGroups.splice(index, 1);
  43726. });
  43727. closeGroups.push(newBigGroup);
  43728. pos.belongTo = newBigGroup;
  43729. newBigGroup.forEach(e=>{e.belongTo = newBigGroup;});
  43730. }
  43731. pos.belongTo.push(pos);
  43732. }
  43733. closeGroups.forEach((points,index)=>{//建造面
  43734. if(points.length <= groupTolerateMaxPoint ){
  43735. /* let sprite = new THREE.Mesh(planeGeo, getPlaneMat(pos.belongTo, true))
  43736. sprite.lookAt(nor);
  43737. sprite.position.copy(pos)
  43738. sprite.scale.set(spriteWidth,spriteWidth,spriteWidth)
  43739. sprite.name = geometryNode.name+'_index'+i
  43740. splitSprites.add(sprite)
  43741. removedCount ++; */
  43742. removedCount += points.length;
  43743. return
  43744. }
  43745. useGroupCount ++;
  43746. points.sort(function(a,b){
  43747. return a.index - b.index
  43748. });
  43749. console.log(`开始解析 ${geometryNode.name} - 第${index}组,总第${points[0].index}个点,组内有${points.length}个点`);
  43750. let planeMat = getPlaneMat(points, true);
  43751. if(showPointLabel){
  43752. points.forEach((p,i)=>{
  43753. var label = new TextSprite({
  43754. text : index+"-"+i+" ("+p.index+")"+geometryNode.name, dontFixOrient:true,
  43755. backgroundColor: {r: planeMat.color.r*255, g: planeMat.color.g*255, b: planeMat.color.b*255, a:0.6},
  43756. });
  43757. label.lookAt(p.nor);
  43758. label.position.copy(p);
  43759. label.scale.set(spriteWidth/3, spriteWidth/3, spriteWidth/3);
  43760. splitSprites.add(label);
  43761. /* let sprite = new THREE.Mesh(planeGeo,planeMat)
  43762. sprite.lookAt(p.nor);
  43763. sprite.position.copy(p)
  43764. sprite.scale.set(spriteWidth/3,spriteWidth/3,spriteWidth/3)
  43765. sprite.name = geometryNode.name+'_group'+index+"_"+ i
  43766. splitSprites.add(sprite) */
  43767. });
  43768. }
  43769. var avePos = points.reduce(function(total, currentValue){
  43770. return total.add(currentValue)
  43771. }, new Vector3).multiplyScalar(1/points.length);
  43772. let planeNormals = [];
  43773. {//获得planeNormals
  43774. //随机找两个距离远的点算normal。 按距离排序后, //抽取若干个点,然后算两两之间的法线,其中距离远的多抽取几个。
  43775. var sortPoints = points.slice(0).sort(function(a,b){
  43776. return a.distanceToSquared(avePos) - b.distanceToSquared(avePos)
  43777. });//从小到大
  43778. var pickPoints;
  43779. var length = sortPoints.length;
  43780. if(length>=7){
  43781. var ratio = [0.02,0.15,0.4,0.55,0.7,0.86,0.99];
  43782. var index = ratio.map(e=>Math.round(e * (length-1)));
  43783. //console.log('index ',index)
  43784. pickPoints = index.map(e=>sortPoints[e]);
  43785. }else {
  43786. pickPoints = sortPoints;
  43787. }
  43788. //console.log('pickPoints', pickPoints)
  43789. let num = pickPoints.length;
  43790. for(let i=0;i<num;i++){//任意一个三角形能算出一个normal
  43791. for(let j=i+1;j<num;j++){
  43792. for(let u=j+1;u<num;u++){
  43793. var p1 = pickPoints[i];
  43794. var p2 = pickPoints[j];
  43795. var p3 = pickPoints[u];
  43796. let vec1 = new Vector3().subVectors(p1,p3);
  43797. let vec2 = new Vector3().subVectors(p2,p3);
  43798. let nor = vec1.cross(vec2).normalize();
  43799. if(planeNormals[0]){
  43800. if(nor.dot(planeNormals[0])<0)nor.negate(); //反向下
  43801. }
  43802. console.log('nor',nor);
  43803. planeNormals.push(nor);
  43804. }
  43805. }
  43806. }
  43807. }
  43808. var aveNor = planeNormals.reduce(function(total, currentValue){
  43809. return total.add(currentValue)
  43810. }, new Vector3).normalize();
  43811. console.log('aveNor',aveNor, 'avePos' ,avePos, index);
  43812. if(showCenterLabel){
  43813. var label = new TextSprite({
  43814. //index+"-"+i+" ("+p.index+")"+geometryNode.name
  43815. text : `我是${index}组 ${geometryNode.name} 中心点`, dontFixOrient:true,
  43816. backgroundColor: {r: planeMat.color.r*255, g: planeMat.color.g*255, b: planeMat.color.b*255, a:0.6},
  43817. });
  43818. label.lookAt(aveNor);
  43819. label.position.copy(avePos);
  43820. label.scale.set(spriteWidth, spriteWidth, spriteWidth);
  43821. splitSprites.add(label);
  43822. }
  43823. var facePlane = new Plane().setFromNormalAndCoplanarPoint(aveNor, avePos );
  43824. var coplanarPoints = points.map(p=> facePlane.projectPoint(p, new Vector3() ));
  43825. var originPoint0 = coplanarPoints[0].clone();
  43826. var qua = math.getQuaBetween2Vector(facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  43827. let points2d = coplanarPoints.map(e=>e.clone().applyQuaternion(qua));
  43828. let quaInverse = qua.clone().invert();
  43829. //--------------------
  43830. let lines = [];
  43831. points2d.forEach((p,j)=>{
  43832. p.id = j;
  43833. for(let i=0;i<j;i++){
  43834. if(p.distanceToSquared(points2d[i])<minDisSquare*1.5){
  43835. lines.push({p1:i,p2:j});
  43836. }
  43837. }
  43838. });
  43839. console.log('points count:',points2d.length, 'lines:',lines);
  43840. var rings = searchRings({
  43841. points:points2d,
  43842. lines,
  43843. onlyGetOutRing:true,
  43844. precision: Math.max(spriteWidth1/10, 0.01)
  43845. });
  43846. console.log( 'rings:', rings );//mesh间可能重叠 但换上贴图材质应该看不出(但只要searchRings时getSliceLines就不会重叠)
  43847. if(!rings)return
  43848. let planeMat2 = planeMat.clone(); planeMat2.opacity = 0.5;
  43849. var firstPos = points2d[0].clone();
  43850. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  43851. firstPos.applyQuaternion(quaInverse);
  43852. var vec = originPoint0.clone().sub(firstPos);
  43853. rings.forEach(ring=>{
  43854. var shapeGeo = MeshDraw.getShapeGeo(ring.points);
  43855. var areaPlane = new Mesh(shapeGeo, planeMat2);
  43856. areaPlane.quaternion.copy(quaInverse);
  43857. areaPlane.position.copy(vec);
  43858. areaPlane.name = 'areaPlane_'+index;
  43859. splitSprites.add(areaPlane);
  43860. this.areaPlanes.push(areaPlane);
  43861. });
  43862. });
  43863. console.log(geometryNode.name, '中:');
  43864. console.log('removed point count: ', removedCount/* splitSprites.children.length */);
  43865. console.log(closeGroups);
  43866. console.log('comebine mesh Len:', useGroupCount);
  43867. /*
  43868. spritesGeo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(newPositions), 3));
  43869. spritesGeo.setIndex( newIndices );
  43870. let sprites = new THREE.Mesh(spritesGeo, getPlaneMat('use'))
  43871. sprites.name = geometryNode.name
  43872. sprites.position.copy(sceneNode.position)
  43873. sprites.rotation.copy(sceneNode.rotation)
  43874. sceneNode.sprites = sprites
  43875. sprites.pointsNode = sceneNode
  43876. if(geometryNode.level == 0){
  43877. let root = new THREE.Object3D;
  43878. root.name = 'spriteNodeRoot'
  43879. root.matrixAutoUpdate = false //同pointcloud一样不自动更新,直接使用
  43880. root.matrix.copy(this.matrix)
  43881. root.matrixWorld.copy(this.matrixWorld)
  43882. viewer.scene.scene.add(root)
  43883. this.spriteNodeRoot = root
  43884. }
  43885. this.spriteNodeRoot.add(sprites) */
  43886. console.log('computeTime: ' + (Date.now() - startTime));
  43887. }
  43888. //------------------
  43889. /*
  43890. viewer.scene.pointclouds[0].spriteNodeRoot.traverse(e=>e.material && (e.material = viewer.images360.cube.material))
  43891. viewer.scene.scene.children[12].visible = false
  43892. */
  43893. }
  43894. buildTexMesh(geometryNode,sceneNode){
  43895. if(geometryNode.level <= 0){
  43896. let startTime = Date.now();
  43897. let splitSprites = new Object3D;
  43898. splitSprites.name = 'splitSprites_'+geometryNode.name;
  43899. splitSprites.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43900. splitSprites.matrix.copy(this.matrix);
  43901. splitSprites.matrixWorld.copy(this.matrixWorld);
  43902. viewer.scene.scene.add(splitSprites);
  43903. let spritesGeo = new BufferGeometry();
  43904. let scaleRatio = 1.4; //稍微放大些,填满缝隙
  43905. let spriteWidth1 = this.material.spacing / Math.pow(2, geometryNode.level);
  43906. let spriteWidth = spriteWidth1 * scaleRatio;
  43907. console.log('spriteWidth:',spriteWidth);
  43908. const removeChip = false;
  43909. let geometry = geometryNode.geometry;
  43910. let count = geometry.attributes.position.count;
  43911. //count = 4000
  43912. let position = geometry.attributes.position.array;
  43913. let normal = geometry.attributes.normal.array;
  43914. let i;
  43915. let up = new Vector3(0,1,0) , zeroVec = new Vector3; //up写成z向上居然结果一样
  43916. let positions = [];
  43917. let normals = [];
  43918. let newPositions = [];
  43919. //let newNormals = [];
  43920. let newIndices = [];
  43921. let cornerPoints = [new Vector3(-1,1,0),new Vector3(1,1,0),new Vector3(-1,-1,0),new Vector3(1,-1,0) ];
  43922. let indices = [0, 2, 1, 2, 3, 1];
  43923. cornerPoints.forEach(e=>e.multiplyScalar(spriteWidth/2));
  43924. let minDisSquare = spriteWidth1 * spriteWidth1 * 1.5;
  43925. let closeGroups = [];
  43926. let groupTolerateMaxPoint = 4;//组内点<=这个数的最后会被删除
  43927. let removedCount = 0;
  43928. for(i=0;i<count;i++){
  43929. let pos = new Vector3(position[3*i], position[3*i+1], position[3*i+2] );
  43930. let nor = new Vector3(normal[3*i],normal[3*i+1],normal[3*i+2]);
  43931. pos.nor = nor;
  43932. positions.push(pos);
  43933. normals.push(nor);
  43934. if(removeChip){
  43935. let groups = closeGroups.filter(group=>{
  43936. var hasClosed = group.some(p=>{
  43937. var dis = p.distanceToSquared(pos);
  43938. if(dis<minDisSquare){
  43939. //return dis / minDisSquare + (Math.abs(p.nor.x - nor.x) + Math.abs(p.nor.y - nor.y) + Math.abs(p.nor.z - nor.z)) < 1.7
  43940. return dis / minDisSquare - p.nor.dot(nor) < 0
  43941. }
  43942. });
  43943. return hasClosed
  43944. });
  43945. if(groups.length == 0){//创建一个新的
  43946. var newGroup = [];
  43947. closeGroups.push(newGroup);
  43948. groups = [newGroup];
  43949. }
  43950. if(groups.length == 1){//直接加入原有的
  43951. pos.belongTo = groups[0];
  43952. }else if(groups.length>1){ // comebine多个组成一个
  43953. let newBigGroup = [];
  43954. groups.forEach(e=>{
  43955. newBigGroup.push(...e);
  43956. let index = closeGroups.indexOf(e);
  43957. closeGroups.splice(index, 1);
  43958. });
  43959. closeGroups.push(newBigGroup);
  43960. pos.belongTo = newBigGroup;
  43961. newBigGroup.forEach(e=>{e.belongTo = newBigGroup;});
  43962. }
  43963. pos.belongTo.push(pos);
  43964. }
  43965. }
  43966. for(i=0;i<count;i++){
  43967. let pos = positions[i];
  43968. let nor = normals[i];
  43969. if(Math.abs(nor.z)>0.2)continue
  43970. if(removeChip){
  43971. if(pos.belongTo.length <= groupTolerateMaxPoint){
  43972. let sprite = new Mesh(planeGeo, getPlaneMat(pos.belongTo, true));
  43973. sprite.lookAt(nor);
  43974. sprite.position.copy(pos);
  43975. sprite.scale.set(spriteWidth,spriteWidth,spriteWidth);
  43976. sprite.name = geometryNode.name+'_index'+i;
  43977. splitSprites.add(sprite);
  43978. removedCount ++;
  43979. continue
  43980. }else {
  43981. /*
  43982. let sprite = new THREE.Mesh(planeGeo, getPlaneMat(pos.belongTo))
  43983. sprite.lookAt(nor);
  43984. sprite.position.copy(pos)
  43985. sprite.scale.set(spriteWidth/3,spriteWidth/3,spriteWidth/3)
  43986. sprite.name = geometryNode.name+'_index'+i
  43987. splitSprites.add(sprite)
  43988. */
  43989. }
  43990. }
  43991. let matrix = (new Matrix4).lookAt( nor, zeroVec, up);
  43992. matrix.elements[12] = pos.x;
  43993. matrix.elements[13] = pos.y;
  43994. matrix.elements[14] = pos.z;
  43995. cornerPoints.forEach(p=>{
  43996. let point = p.clone();
  43997. point.applyMatrix4(matrix);
  43998. newPositions.push(...point.toArray());
  43999. //newNormals
  44000. });
  44001. indices.forEach(index=>{
  44002. newIndices.push(index + i*4);
  44003. });
  44004. }
  44005. /* closeGroups.forEach(e=>{
  44006. if(e.length <= groupTolerateMaxPoint )return
  44007. }) */
  44008. console.log('removed count: ', removedCount/* splitSprites.children.length */);
  44009. console.log(closeGroups);
  44010. console.log('computeTime: ' + (Date.now() - startTime));
  44011. spritesGeo.setAttribute('position', new Float32BufferAttribute(new Float32Array(newPositions), 3));
  44012. spritesGeo.setIndex( newIndices );
  44013. let sprites = new Mesh(spritesGeo, getPlaneMat('use'));
  44014. sprites.name = geometryNode.name;
  44015. sprites.position.copy(sceneNode.position);
  44016. sprites.rotation.copy(sceneNode.rotation);
  44017. sceneNode.sprites = sprites;
  44018. sprites.pointsNode = sceneNode;
  44019. if(geometryNode.level == 0){
  44020. let root = new Object3D;
  44021. root.name = 'spriteNodeRoot';
  44022. root.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  44023. root.matrix.copy(this.matrix);
  44024. root.matrixWorld.copy(this.matrixWorld);
  44025. viewer.scene.scene.add(root);
  44026. this.spriteNodeRoot = root;
  44027. }
  44028. this.spriteNodeRoot.add(sprites);
  44029. viewer.setObjectLayers(sprites,'sceneObjects');
  44030. }
  44031. }
  44032. updateVisibleBounds () {
  44033. let leafNodes = [];
  44034. for (let i = 0; i < this.visibleNodes.length; i++) {
  44035. let node = this.visibleNodes[i];
  44036. let isLeaf = true;
  44037. for (let j = 0; j < node.children.length; j++) {
  44038. let child = node.children[j];
  44039. if (child instanceof PointCloudOctreeNode) {
  44040. isLeaf = isLeaf && !child.sceneNode.visible;
  44041. } else if (child instanceof PointCloudOctreeGeometryNode) {
  44042. isLeaf = true;
  44043. }
  44044. }
  44045. if (isLeaf) {
  44046. leafNodes.push(node);
  44047. }
  44048. }
  44049. this.visibleBounds.min = new Vector3(Infinity, Infinity, Infinity);
  44050. this.visibleBounds.max = new Vector3(-Infinity, -Infinity, -Infinity);
  44051. for (let i = 0; i < leafNodes.length; i++) {
  44052. let node = leafNodes[i];
  44053. this.visibleBounds.expandByPoint(node.getBoundingBox().min);
  44054. this.visibleBounds.expandByPoint(node.getBoundingBox().max);
  44055. }
  44056. }
  44057. updateMaterial (material, visibleNodes, camera, renderer, resolution) {
  44058. material.fov = camera.fov * (Math.PI / 180);
  44059. /* material.screenWidth = renderer.domElement.clientWidth;
  44060. material.screenHeight = renderer.domElement.clientHeight; */
  44061. material.resolution = resolution;
  44062. //material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z); //应该不需要
  44063. material.near = camera.near;
  44064. material.far = camera.far;
  44065. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  44066. }
  44067. computeVisibilityTextureData(nodes, camera){
  44068. if(Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  44069. let data = new Uint8Array(nodes.length * 4);
  44070. let visibleNodeTextureOffsets = new Map();
  44071. // copy array
  44072. nodes = nodes.slice();
  44073. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  44074. let sort = function (a, b) {
  44075. let na = a.geometryNode.name;
  44076. let nb = b.geometryNode.name;
  44077. if (na.length !== nb.length) return na.length - nb.length;
  44078. if (na < nb) return -1;
  44079. if (na > nb) return 1;
  44080. return 0;
  44081. };
  44082. nodes.sort(sort);
  44083. let worldDir = new Vector3();
  44084. let nodeMap = new Map();
  44085. let offsetsToChild = new Array(nodes.length).fill(Infinity);
  44086. for(let i = 0; i < nodes.length; i++){
  44087. let node = nodes[i];
  44088. nodeMap.set(node.name, node);
  44089. visibleNodeTextureOffsets.set(node, i);
  44090. if(i > 0){
  44091. let index = parseInt(node.name.slice(-1));
  44092. let parentName = node.name.slice(0, -1);
  44093. let parent = nodeMap.get(parentName);
  44094. let parentOffset = visibleNodeTextureOffsets.get(parent);
  44095. let parentOffsetToChild = (i - parentOffset);
  44096. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  44097. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | (1 << index);
  44098. data[parentOffset * 4 + 1] = (offsetsToChild[parentOffset] >> 8);
  44099. data[parentOffset * 4 + 2] = (offsetsToChild[parentOffset] % 256);
  44100. }
  44101. let density = node.geometryNode.density;
  44102. if(typeof density === "number"){
  44103. let lodOffset = Math.log2(density) / 2 - 1.5;
  44104. let offsetUint8 = (lodOffset + 10) * 10;
  44105. data[i * 4 + 3] = offsetUint8;
  44106. }else {
  44107. data[i * 4 + 3] = 100;
  44108. }
  44109. }
  44110. if(Potree.measureTimings){
  44111. performance.mark("computeVisibilityTextureData-end");
  44112. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  44113. }
  44114. return {
  44115. data: data,
  44116. offsets: visibleNodeTextureOffsets
  44117. };
  44118. }
  44119. nodeIntersectsProfile (node, profile) {
  44120. let bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  44121. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  44122. let intersects = false;
  44123. for (let i = 0; i < profile.points.length - 1; i++) {
  44124. let start = new Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  44125. let end = new Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  44126. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  44127. let distance = closest.distanceTo(bsWorld.center);
  44128. intersects = intersects || (distance < (bsWorld.radius + profile.width));
  44129. }
  44130. //console.log(`${node.name}: ${intersects}`);
  44131. return intersects;
  44132. }
  44133. deepestNodeAt(position){
  44134. const toObjectSpace = this.matrixWorld.clone().invert();
  44135. const objPos = position.clone().applyMatrix4(toObjectSpace);
  44136. let current = this.root;
  44137. while(true){
  44138. let containingChild = null;
  44139. for(const child of current.children){
  44140. if(child !== undefined){
  44141. if(child.getBoundingBox().containsPoint(objPos)){
  44142. containingChild = child;
  44143. }
  44144. }
  44145. }
  44146. if(containingChild !== null && containingChild instanceof PointCloudOctreeNode){
  44147. current = containingChild;
  44148. }else {
  44149. break;
  44150. }
  44151. }
  44152. const deepest = current;
  44153. return deepest;
  44154. }
  44155. nodesOnRay (nodes, ray) {
  44156. let nodesOnRay = [];
  44157. let _ray = ray.clone();
  44158. for (let i = 0; i < nodes.length; i++) {
  44159. let node = nodes[i];
  44160. let sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  44161. if (_ray.intersectsSphere(sphere)) {
  44162. nodesOnRay.push(node);
  44163. }
  44164. }
  44165. return nodesOnRay;
  44166. }
  44167. updateMatrixWorld (force) {
  44168. if (this.matrixAutoUpdate === true) this.updateMatrix();
  44169. if (this.matrixWorldNeedsUpdate === true || force === true) {
  44170. if (!this.parent) {
  44171. this.matrixWorld.copy(this.matrix);
  44172. } else {
  44173. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  44174. }
  44175. this.matrixWorldNeedsUpdate = false;
  44176. force = true;
  44177. }
  44178. }
  44179. hideDescendants (object) {
  44180. let stack = [];
  44181. for (let i = 0; i < object.children.length; i++) {
  44182. let child = object.children[i];
  44183. if (child.visible) {
  44184. stack.push(child);
  44185. }
  44186. }
  44187. while (stack.length > 0) {
  44188. let object = stack.shift();
  44189. object.visible = false;
  44190. for (let i = 0; i < object.children.length; i++) {
  44191. let child = object.children[i];
  44192. if (child.visible) {
  44193. stack.push(child);
  44194. }
  44195. }
  44196. }
  44197. }
  44198. moveToOrigin () {
  44199. this.position.set(0, 0, 0);
  44200. this.updateMatrixWorld(true);
  44201. let box = this.boundingBox;
  44202. let transform = this.matrixWorld;
  44203. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44204. this.position.set(0, 0, 0).sub(tBox.getCenter(new Vector3()));
  44205. };
  44206. moveToGroundPlane () {
  44207. this.updateMatrixWorld(true);
  44208. let box = this.boundingBox;
  44209. let transform = this.matrixWorld;
  44210. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44211. this.position.y += -tBox.min.y;
  44212. };
  44213. getBoundingBoxWorld () {
  44214. this.updateMatrixWorld(true);
  44215. let box = this.boundingBox;
  44216. let transform = this.matrixWorld;
  44217. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44218. return tBox;
  44219. };
  44220. /**
  44221. * returns points inside the profile points
  44222. *
  44223. * maxDepth: search points up to the given octree depth
  44224. *
  44225. *
  44226. * The return value is an array with all segments of the profile path
  44227. * let segment = {
  44228. * start: THREE.Vector3,
  44229. * end: THREE.Vector3,
  44230. * points: {}
  44231. * project: function()
  44232. * };
  44233. *
  44234. * The project() function inside each segment can be used to transform
  44235. * that segments point coordinates to line up along the x-axis.
  44236. *
  44237. *
  44238. */
  44239. getPointsInProfile (profile, maxDepth, callback) {
  44240. if (callback) {
  44241. let request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  44242. this.profileRequests.push(request);
  44243. return request;
  44244. }
  44245. let points = {
  44246. segments: [],
  44247. boundingBox: new Box3(),
  44248. projectedBoundingBox: new Box2()
  44249. };
  44250. // evaluate segments
  44251. for (let i = 0; i < profile.points.length - 1; i++) {
  44252. let start = profile.points[i];
  44253. let end = profile.points[i + 1];
  44254. let ps = this.getProfile(start, end, profile.width, maxDepth);
  44255. let segment = {
  44256. start: start,
  44257. end: end,
  44258. points: ps,
  44259. project: null
  44260. };
  44261. points.segments.push(segment);
  44262. points.boundingBox.expandByPoint(ps.boundingBox.min);
  44263. points.boundingBox.expandByPoint(ps.boundingBox.max);
  44264. }
  44265. // add projection functions to the segments
  44266. let mileage = new Vector3();
  44267. for (let i = 0; i < points.segments.length; i++) {
  44268. let segment = points.segments[i];
  44269. let start = segment.start;
  44270. let end = segment.end;
  44271. let project = (function (_start, _end, _mileage, _boundingBox) {
  44272. let start = _start;
  44273. let end = _end;
  44274. let mileage = _mileage;
  44275. let boundingBox = _boundingBox;
  44276. let xAxis = new Vector3(1, 0, 0);
  44277. let dir = new Vector3().subVectors(end, start);
  44278. dir.y = 0;
  44279. dir.normalize();
  44280. let alpha = Math.acos(xAxis.dot(dir));
  44281. if (dir.z > 0) {
  44282. alpha = -alpha;
  44283. }
  44284. return function (position) {
  44285. let toOrigin = new Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  44286. let alignWithX = new Matrix4().makeRotationY(-alpha);
  44287. let applyMileage = new Matrix4().makeTranslation(mileage.x, 0, 0);
  44288. let pos = position.clone();
  44289. pos.applyMatrix4(toOrigin);
  44290. pos.applyMatrix4(alignWithX);
  44291. pos.applyMatrix4(applyMileage);
  44292. return pos;
  44293. };
  44294. }(start, end, mileage.clone(), points.boundingBox.clone()));
  44295. segment.project = project;
  44296. mileage.x += new Vector3(start.x, 0, start.z).distanceTo(new Vector3(end.x, 0, end.z));
  44297. mileage.y += end.y - start.y;
  44298. }
  44299. points.projectedBoundingBox.min.x = 0;
  44300. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  44301. points.projectedBoundingBox.max.x = mileage.x;
  44302. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  44303. return points;
  44304. }
  44305. /**
  44306. * returns points inside the given profile bounds.
  44307. *
  44308. * start:
  44309. * end:
  44310. * width:
  44311. * depth: search points up to the given octree depth
  44312. * callback: if specified, points are loaded before searching
  44313. *
  44314. *
  44315. */
  44316. getProfile (start, end, width, depth, callback) {
  44317. let request = new Potree.ProfileRequest(start, end, width, depth, callback);
  44318. this.profileRequests.push(request);
  44319. };
  44320. getVisibleExtent () {
  44321. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  44322. };
  44323. intersectsPoint(position){
  44324. let rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  44325. if(!rootAvailable){
  44326. return false;
  44327. }
  44328. if(typeof this.signedDistanceField === "undefined"){
  44329. const resolution = 32;
  44330. const field = new Float32Array(resolution ** 3).fill(Infinity);
  44331. const positions = this.pcoGeometry.root.geometry.attributes.position;
  44332. const boundingBox = this.boundingBox;
  44333. const n = positions.count;
  44334. for(let i = 0; i < n; i = i + 3){
  44335. const x = positions.array[3 * i + 0];
  44336. const y = positions.array[3 * i + 1];
  44337. const z = positions.array[3 * i + 2];
  44338. const ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  44339. const iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  44340. const iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  44341. const index = ix + iy * resolution + iz * resolution * resolution;
  44342. field[index] = 0;
  44343. }
  44344. const sdf = {
  44345. resolution: resolution,
  44346. field: field,
  44347. };
  44348. this.signedDistanceField = sdf;
  44349. }
  44350. {
  44351. const sdf = this.signedDistanceField;
  44352. const boundingBox = this.boundingBox;
  44353. const toObjectSpace = this.matrixWorld.clone().invert();
  44354. const objPos = position.clone().applyMatrix4(toObjectSpace);
  44355. const resolution = sdf.resolution;
  44356. const ix = parseInt(resolution * (objPos.x / boundingBox.max.x));
  44357. const iy = parseInt(resolution * (objPos.y / boundingBox.max.y));
  44358. const iz = parseInt(resolution * (objPos.z / boundingBox.max.z));
  44359. if(ix < 0 || iy < 0 || iz < 0){
  44360. return false;
  44361. }
  44362. if(ix >= resolution || iy >= resolution || iz >= resolution){
  44363. return false;
  44364. }
  44365. const index = ix + iy * resolution + iz * resolution * resolution;
  44366. const value = sdf.field[index];
  44367. if(value === 0){
  44368. return true;
  44369. }
  44370. }
  44371. return false;
  44372. }
  44373. /**
  44374. *
  44375. *
  44376. *
  44377. * params.pickWindowSize: Look for points inside a pixel window of this size.
  44378. * Use odd values: 1, 3, 5, ...
  44379. *
  44380. *
  44381. * TODO: only draw pixels that are actually read with readPixels().
  44382. *
  44383. */
  44384. pick(viewer, viewport, camera, ray, params = {}){
  44385. let renderer = viewer.renderer;
  44386. let pRenderer = viewer.pRenderer;
  44387. performance.mark("pick-start");
  44388. let getVal = (a, b) => a != void 0 ? a : b;
  44389. let pickWindowSize_ = MathUtils.clamp( Math.round((1.1-this.maxLevel/this.nodeMaxLevel)*80), 5, 100);
  44390. let pickWindowSize = getVal(params.pickWindowSize, pickWindowSize_ ); /* 65 */ //拾取像素边长,越小越精准,但点云稀疏的话可能容易出现识别不到的情况。 另外左下侧会有缝隙无法识别到,缝隙大小和这个值有关
  44391. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  44392. let size = viewport ? viewport.resolution : renderer.getSize(new Vector2$1());
  44393. let width = Math.ceil(getVal(params.width, size.width)); //renderTarget大小。影响识别精度
  44394. let height = Math.ceil(getVal(params.height, size.height));
  44395. let screenshot = ()=>{
  44396. if(window.testScreen){
  44397. let dataUrl = Potree.Utils.renderTargetToDataUrl(pickState.renderTarget, width, height, renderer);
  44398. Common.downloadFile(dataUrl, 'screenshot.jpg'); //为什么图片上不是只有pickWindowSize区域有颜色??
  44399. window.testScreen = 0;
  44400. }
  44401. };
  44402. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  44403. let pointSize = getVal(params.pointSize, this.material.size);
  44404. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  44405. if (nodes.length === 0) {
  44406. return null;
  44407. }
  44408. //console.log('nodes.length != 0', this.name)
  44409. if (!this.pickState) {
  44410. let scene = new Scene();
  44411. let material = new Potree.PointCloudMaterial();
  44412. material.activeAttributeName = "indices";
  44413. let renderTarget = new WebGLRenderTarget(
  44414. 1, 1,
  44415. { minFilter: LinearFilter,
  44416. magFilter: NearestFilter,
  44417. format: RGBAFormat }
  44418. );
  44419. this.pickState = {
  44420. renderTarget: renderTarget,
  44421. material: material,
  44422. scene: scene
  44423. };
  44424. };
  44425. let pickState = this.pickState;
  44426. let pickMaterial = pickState.material;
  44427. { // update pick material
  44428. pickMaterial.pointSizeType = pointSizeType;
  44429. //pickMaterial.shape = this.material.shape;
  44430. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  44431. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  44432. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  44433. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  44434. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  44435. pickMaterial.activeAttributeName = "indices";
  44436. pickMaterial.size = pointSize;
  44437. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  44438. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  44439. pickMaterial.classification = this.material.classification;
  44440. pickMaterial.recomputeClassification();
  44441. if(params.pickClipped){
  44442. pickMaterial.clipBoxes = this.material.clipBoxes;
  44443. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  44444. if(this.material.clipTask === Potree.ClipTask.HIGHLIGHT){
  44445. pickMaterial.clipTask = Potree.ClipTask.NONE;
  44446. }else {
  44447. pickMaterial.clipTask = this.material.clipTask;
  44448. }
  44449. pickMaterial.clipMethod = this.material.clipMethod;
  44450. }else {
  44451. pickMaterial.clipBoxes = [];
  44452. }
  44453. this.updateMaterial(pickMaterial, nodes, camera, renderer, new Vector2$1(width, height));
  44454. }
  44455. pickState.renderTarget.setSize(width, height); //仅绘制屏幕大小的,而不乘以devicePixelRatio
  44456. let pixelPos = new Vector2$1(params.x, params.y);
  44457. let gl = renderer.getContext();
  44458. gl.enable(gl.SCISSOR_TEST);
  44459. gl.scissor( //规定渲染范围,只渲染一小块
  44460. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  44461. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  44462. parseInt(pickWindowSize), parseInt(pickWindowSize));
  44463. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  44464. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  44465. renderer.state.setBlending(NoBlending);
  44466. { // RENDER
  44467. renderer.setRenderTarget(pickState.renderTarget);
  44468. gl.clearColor(0, 0, 0, 0);
  44469. renderer.clear(true, true, true);
  44470. let tmp = this.material;
  44471. this.material = pickMaterial;
  44472. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  44473. screenshot();
  44474. this.material = tmp;
  44475. }
  44476. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  44477. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  44478. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  44479. /* let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  44480. let h = parseInt(Math.min(y + pickWindowSize, height) - y); */
  44481. let pixelCount = pickWindowSize * pickWindowSize;//w * h;
  44482. let buffer = new Uint8Array(4 * pixelCount);
  44483. //w<pickWindowSize会报错
  44484. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  44485. renderer.setRenderTarget(null);
  44486. renderer.state.reset();
  44487. renderer.setScissorTest(false);
  44488. gl.disable(gl.SCISSOR_TEST);
  44489. let pixels = buffer;
  44490. let ibuffer = new Uint32Array(buffer.buffer); //四个数整合成一个
  44491. // find closest hit inside pixelWindow boundaries
  44492. let min = Number.MAX_VALUE;
  44493. let hits = [];
  44494. for (let u = 0; u < pickWindowSize; u++) {
  44495. for (let v = 0; v < pickWindowSize; v++) {
  44496. let offset = (u + v * pickWindowSize);
  44497. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  44498. let pcIndex = pixels[4 * offset + 3];//nodes index(第四位)
  44499. pixels[4 * offset + 3] = 0; //去除nodes index后剩下的是index(前三位)
  44500. let pIndex = ibuffer[offset]; //index
  44501. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  44502. let hit = {
  44503. pIndex: pIndex,
  44504. pcIndex: pcIndex,
  44505. distanceToCenter: distance
  44506. };
  44507. if(params.all){
  44508. hits.push(hit);
  44509. }else {
  44510. if(hits.length > 0){
  44511. if(distance < hits[0].distanceToCenter){
  44512. hits[0] = hit;
  44513. }
  44514. }else {
  44515. hits.push(hit);
  44516. }
  44517. }
  44518. }
  44519. }
  44520. }
  44521. // { // DEBUG: show panel with pick image
  44522. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  44523. // let screenshot = img.src;
  44524. // if(!this.debugDIV){
  44525. // this.debugDIV = $(`
  44526. // <div id="pickDebug"
  44527. // style="position: absolute;
  44528. // right: 400px; width: 300px;
  44529. // bottom: 44px; width: 300px;
  44530. // z-index: 1000;
  44531. // "></div>`);
  44532. // $(document.body).append(this.debugDIV);
  44533. // }
  44534. // this.debugDIV.empty();
  44535. // this.debugDIV.append($(`<img src="${screenshot}"
  44536. // style="transform: scaleY(-1); width: 300px"/>`));
  44537. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  44538. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  44539. // }
  44540. for(let hit of hits){
  44541. let point = {};
  44542. if (!nodes[hit.pcIndex]) {
  44543. return null;
  44544. }
  44545. let node = nodes[hit.pcIndex];
  44546. let pc = node.sceneNode;
  44547. let geometry = node.geometryNode.geometry;
  44548. for(let attributeName in geometry.attributes){
  44549. let attribute = geometry.attributes[attributeName];
  44550. if (attributeName === 'position') {
  44551. let x = attribute.array[3 * hit.pIndex + 0];
  44552. let y = attribute.array[3 * hit.pIndex + 1];
  44553. let z = attribute.array[3 * hit.pIndex + 2];
  44554. let position = new Vector3(x, y, z);
  44555. position.applyMatrix4( pc.matrixWorld );
  44556. point[attributeName] = position;
  44557. } else if (attributeName === 'indices') {
  44558. } else {
  44559. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  44560. if(attribute.potree){
  44561. const {scale, offset} = attribute.potree;
  44562. values = values.map(v => v / scale + offset);
  44563. }
  44564. point[attributeName] = values;
  44565. //debugger;
  44566. //if (values.itemSize === 1) {
  44567. // point[attribute.name] = values.array[hit.pIndex];
  44568. //} else {
  44569. // let value = [];
  44570. // for (let j = 0; j < values.itemSize; j++) {
  44571. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  44572. // }
  44573. // point[attribute.name] = value;
  44574. //}
  44575. }
  44576. }
  44577. hit.point = point;
  44578. }
  44579. performance.mark("pick-end");
  44580. performance.measure("pick", "pick-start", "pick-end");
  44581. if(params.all){
  44582. return hits.map(hit => hit.point);
  44583. }else {
  44584. if(hits.length === 0){
  44585. return null;
  44586. }else {
  44587. return hits[0].point;
  44588. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  44589. //return sorted[0].point;
  44590. }
  44591. }
  44592. };
  44593. * getFittedBoxGen(boxNode){//???
  44594. let start = performance.now();
  44595. let shrinkedLocalBounds = new Box3();
  44596. let worldToBox = boxNode.matrixWorld.clone().invert();
  44597. for(let node of this.visibleNodes){
  44598. if(!node.sceneNode){
  44599. continue;
  44600. }
  44601. let buffer = node.geometryNode.buffer;
  44602. let posOffset = buffer.offset("position");
  44603. let stride = buffer.stride;
  44604. let view = new DataView(buffer.data);
  44605. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  44606. let pos = new Vector4();
  44607. for(let i = 0; i < buffer.numElements; i++){
  44608. let x = view.getFloat32(i * stride + posOffset + 0, true);
  44609. let y = view.getFloat32(i * stride + posOffset + 4, true);
  44610. let z = view.getFloat32(i * stride + posOffset + 8, true);
  44611. pos.set(x, y, z, 1);
  44612. pos.applyMatrix4(objectToBox);
  44613. if(-0.5 < pos.x && pos.x < 0.5){
  44614. if(-0.5 < pos.y && pos.y < 0.5){
  44615. if(-0.5 < pos.z && pos.z < 0.5){
  44616. shrinkedLocalBounds.expandByPoint(pos);
  44617. }
  44618. }
  44619. }
  44620. }
  44621. yield;
  44622. }
  44623. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  44624. let fitted = new Object3D();
  44625. fitted.position.copy(fittedPosition);
  44626. fitted.scale.copy(boxNode.scale);
  44627. fitted.rotation.copy(boxNode.rotation);
  44628. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  44629. fitted.scale.multiply(ds);
  44630. let duration = performance.now() - start;
  44631. console.log("duration: ", duration);
  44632. yield fitted;
  44633. }
  44634. getFittedBox(boxNode, maxLevel = Infinity){
  44635. maxLevel = Infinity;
  44636. let start = performance.now();
  44637. let shrinkedLocalBounds = new Box3();
  44638. let worldToBox = boxNode.matrixWorld.clone().invert();
  44639. for(let node of this.visibleNodes){
  44640. if(!node.sceneNode || node.getLevel() > maxLevel){
  44641. continue;
  44642. }
  44643. let buffer = node.geometryNode.buffer;
  44644. let posOffset = buffer.offset("position");
  44645. let stride = buffer.stride;
  44646. let view = new DataView(buffer.data);
  44647. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  44648. let pos = new Vector4();
  44649. for(let i = 0; i < buffer.numElements; i++){
  44650. let x = view.getFloat32(i * stride + posOffset + 0, true);
  44651. let y = view.getFloat32(i * stride + posOffset + 4, true);
  44652. let z = view.getFloat32(i * stride + posOffset + 8, true);
  44653. pos.set(x, y, z, 1);
  44654. pos.applyMatrix4(objectToBox);
  44655. if(-0.5 < pos.x && pos.x < 0.5){
  44656. if(-0.5 < pos.y && pos.y < 0.5){
  44657. if(-0.5 < pos.z && pos.z < 0.5){
  44658. shrinkedLocalBounds.expandByPoint(pos);
  44659. }
  44660. }
  44661. }
  44662. }
  44663. }
  44664. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  44665. let fitted = new Object3D();
  44666. fitted.position.copy(fittedPosition);
  44667. fitted.scale.copy(boxNode.scale);
  44668. fitted.rotation.copy(boxNode.rotation);
  44669. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  44670. fitted.scale.multiply(ds);
  44671. let duration = performance.now() - start;
  44672. console.log("duration: ", duration);
  44673. return fitted;
  44674. }
  44675. get progress () {
  44676. return this.visibleNodes.length / this.visibleGeometry.length;
  44677. }
  44678. find(name){
  44679. let node = null;
  44680. for(let char of name){
  44681. if(char === "r"){
  44682. node = this.root;
  44683. }else {
  44684. node = node.children[char];
  44685. }
  44686. }
  44687. return node;
  44688. }
  44689. get visible(){
  44690. return this._visible;
  44691. }
  44692. set visible(value){
  44693. if(value !== this._visible){
  44694. this._visible = value;
  44695. this.dispatchEvent({type: 'visibility_changed', pointcloud: this});
  44696. }
  44697. }
  44698. // 设置点大小
  44699. changePointSize(num, sizeFitToLevel) {
  44700. if(this.material.pointSizeType != PointSizeType.ATTENUATED){
  44701. return num && (this.material.size = num)
  44702. }
  44703. if (num == void 0) {
  44704. num = this.temp.pointSize;
  44705. } else {
  44706. this.temp.pointSize = num;
  44707. }
  44708. num /= (Potree.config.material.realPointSize / Potree.config.material.pointSize); //兼容
  44709. num = Math.pow(num, 1.05) * 6;
  44710. if(sizeFitToLevel || Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本: 近似将pointSizeType换成ADAPTIVE
  44711. let str = this.temp.pointSize+':'+this.maxLevel+':'+this.nodeMaxLevel;
  44712. let value = this.temp.sizeFitToLevel[str]; //储存。防止每次渲染(反复切换density)都要算。
  44713. if(value){
  44714. this.material.size = value;
  44715. }else {
  44716. let base = this.material.spacing / Math.pow(2, this.maxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  44717. base *= this.nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(this.maxLevel / this.nodeMaxLevel, 1.3)) : 0.1; //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙
  44718. this.material.size = base * 3 * num;/* * window.devicePixelRatio */
  44719. //在t-8BCqxQAr93 会议室 和 t-e2Kb2iU 隧道 两个场景里调节,因为它们的spacing相差较大,观察会议室墙壁的龟裂程度
  44720. this.temp.sizeFitToLevel[str] = this.material.size;
  44721. }
  44722. }else {
  44723. let base = 0.007; //let base = this.material.spacing / Math.pow(2, this.nodeMaxLevel) //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  44724. //base的数值理论上应该是右侧算出来的,但发现有的场景nodeMaxLevel和nodeMaxLevelPredict差别较大的点云显示也过大,而直接换成固定值反而可以适应所有场景。该固定值来源于 getHighestNodeSpacing 最小值,修改了下。(会不会是我们的相机其实该值是固定的,根据该值算出的spacing才是有误差的? 如果换了相机是否要改值?)
  44725. this.material.size = base * 5 * num; /* * window.devicePixelRatio */
  44726. }
  44727. //console.log('changePointSize ' + this.dataset_id + ' , num : ' + num + ' , size : ' + this.material.size, this.material.spacing)
  44728. }
  44729. // 设置点透明度
  44730. changePointOpacity(num, canMoreThanOne) {
  44731. //num:0-1 navvis用的是亮度
  44732. if (num == void 0) {
  44733. num = this.temp.pointOpacity;
  44734. } else {
  44735. this.temp.pointOpacity = num;
  44736. }
  44737. if(Potree.settings.editType == 'merge'){ //not AdditiveBlending
  44738. return this.material.opacity = num
  44739. }
  44740. if (num == 1) {
  44741. this.material.opacity = 1;
  44742. } else {
  44743. let str = (Potree.settings.sizeFitToLevel?'sizeFit:':'')+ (canMoreThanOne ? 'canMoreThanOne:':'') +this.temp.pointOpacity+':'+this.maxLevel+':'+this.nodeMaxLevel;
  44744. let value = this.temp.opacity[str]; //储存。防止每次渲染(反复切换density)都要算。
  44745. if(value){
  44746. this.material.opacity = value;
  44747. }else {
  44748. if(Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本:
  44749. let base = this.material.spacing / Math.pow(1.4, this.maxLevel); //随着level提高,点云重叠几率增多
  44750. let minBase = this.material.spacing / Math.pow(1.4, this.nodeMaxLevel);
  44751. let ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  44752. this.material.opacity = base * ratio * num;
  44753. if(!canMoreThanOne){
  44754. this.material.opacity = MathUtils.clamp(this.material.opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  44755. }
  44756. }else {
  44757. let base = this.material.spacing / Math.pow(1.8, this.maxLevel);
  44758. let minBase = this.material.spacing / Math.pow(1.8, this.nodeMaxLevel);
  44759. //console.log(1 / base, 1 / minBase / 6)
  44760. let ratio = Math.min(1 / base, 1 / minBase / 6); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  44761. this.material.opacity = base * ratio * num;
  44762. if(!canMoreThanOne){
  44763. this.material.opacity = MathUtils.clamp(this.material.opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  44764. }
  44765. }
  44766. this.temp.opacity[str] = this.material.opacity;
  44767. }
  44768. //缺点:防止颜色过亮主要是相机离远时,当在漫游点处由于离点云太近,可能会导致高质量点云看起来很暗。
  44769. }
  44770. //console.log('changePointOpacity ' + this.dataset_id + ', num : ' + num + ' , opacity : ' + this.material.opacity) //检查是否做到了低质量时num==opacity,中质量opacity稍小于num,高质量更小
  44771. }
  44772. updateBound(){
  44773. var boundingBox_ = this.pcoGeometry.tightBoundingBox.clone().applyMatrix4(this.matrixWorld);
  44774. this.bound = boundingBox_;
  44775. }
  44776. getPanosBound(){
  44777. if(this.panos.length > 0){
  44778. let minSize = new Vector3(1,1,1);
  44779. this.panosBound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  44780. }else {
  44781. this.panosBound = null;
  44782. }
  44783. }
  44784. getUnrotBoundPoint(type){//获取没有旋转的tightBounding的水平四个点
  44785. //如果alighment支持任意轴旋转,水平面上看到的可能就是六边形了,失去意义,到时候不能用这个。也可以若只绕z旋转, 使用tightBoundingBox,否则bound
  44786. let bound = this.pcoGeometry.tightBoundingBox;
  44787. if(type == 'all'){
  44788. return [new Vector3(bound.min.x, bound.min.y, bound.min.z),
  44789. new Vector3(bound.max.x, bound.min.y, bound.min.z),
  44790. new Vector3(bound.max.x, bound.max.y,bound.min.z),
  44791. new Vector3(bound.min.x, bound.max.y,bound.min.z),
  44792. new Vector3(bound.min.x, bound.min.y, bound.max.z),
  44793. new Vector3(bound.max.x, bound.min.y, bound.max.z),
  44794. new Vector3(bound.max.x, bound.max.y,bound.max.z),
  44795. new Vector3(bound.min.x, bound.max.y,bound.max.z),
  44796. ].map(e=>e.applyMatrix4(this.matrixWorld))
  44797. }else
  44798. return [new Vector3(bound.min.x, bound.min.y,0),
  44799. new Vector3(bound.max.x, bound.min.y,0),
  44800. new Vector3(bound.max.x, bound.max.y,0),
  44801. new Vector3(bound.min.x, bound.max.y,0),
  44802. ].map(e=>e.applyMatrix4(this.matrixWorld))
  44803. }
  44804. ifContainsPoint(pos){
  44805. if(!this.bound || !this.bound.containsPoint(pos))return
  44806. var points = this.getUnrotBoundPoint();
  44807. return math.isPointInArea(points, null, pos)
  44808. }
  44809. getVolume(){
  44810. var points = this.getUnrotBoundPoint();
  44811. var area = Math.abs(math.getArea(points));
  44812. return area * (this.bound.max.z - this.bound.min.z)
  44813. }
  44814. //数据集的显示影响到其下的:点云、marker .不会影响地图上的显示
  44815. /*
  44816. updateVisible(reason, ifShow){//当所有加入的条件都不为false时才显示
  44817. if(ifShow){
  44818. var index = this.unvisibleReasons.indexOf(reason);
  44819. index > -1 && this.unvisibleReasons.splice(index, 1);
  44820. if(this.unvisibleReasons.length == 0){
  44821. this.visible = true;
  44822. this.dispatchEvent({
  44823. type: 'isVisible'
  44824. visible:true
  44825. })
  44826. }
  44827. }else {
  44828. if(!this.unvisibleReasons.includes(reason)) this.unvisibleReasons.push(reason);
  44829. this.visible = false;
  44830. this.dispatchEvent({
  44831. type: 'isVisible'
  44832. visible:false
  44833. })
  44834. }
  44835. }
  44836. getVisible(reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  44837. if(this.visible)return true
  44838. else{
  44839. return !this.unvisibleReasons.includes(reason)
  44840. }
  44841. } */
  44842. /* get isVisible(){//add 手动在数据集选择是否显示(和是否全景图、隐藏点云无关)
  44843. return this._isVisible
  44844. }
  44845. set isVisible(visi){
  44846. if(!visi)this.visible = false
  44847. this._isVisible = visi
  44848. } */
  44849. }
  44850. /*
  44851. window.searchOutRing = function(points){
  44852. var points = [{x:0,y:0},{x:1,y:1},{x:0,y:1},{x:1,y:0},{x:2,y:1},{x:1,y:2},{x:1,y:3},{x:2,y:3},
  44853. {x:3,y:1},{x:3,y:2},{x:0,y:2},{x:0,y:3},{x:2,y:0},{x:-1,y:0},{x:-1,y:1},{x:-2,y:1},{x:3,y:3},
  44854. {x:3,y:0},{x:2,y:-1},{x:0,y:-1},{x:1,y:0.5},{x:2,y:0.5}, ].map((e,index)=>{
  44855. var a = new THREE.Vector2().copy(e)
  44856. a.id = index;
  44857. return a
  44858. })
  44859. var lines = []
  44860. var minDis = 2*2
  44861. points.forEach((p,j)=>{
  44862. for(let i=0;i<j;i++){
  44863. if(p.distanceToSquared(points[i])<minDis){
  44864. lines.push({p1:i,p2:j})
  44865. }
  44866. }
  44867. })
  44868. searchRings({
  44869. points,
  44870. lines,
  44871. onlyGetOutRing:true
  44872. })
  44873. }
  44874. */
  44875. class Points$1 {
  44876. constructor () {
  44877. this.boundingBox = new Box3();
  44878. this.numPoints = 0;
  44879. this.data = {};
  44880. }
  44881. add (points) {
  44882. let currentSize = this.numPoints;
  44883. let additionalSize = points.numPoints;
  44884. let newSize = currentSize + additionalSize;
  44885. let thisAttributes = Object.keys(this.data);
  44886. let otherAttributes = Object.keys(points.data);
  44887. let attributes = new Set([...thisAttributes, ...otherAttributes]);
  44888. for (let attribute of attributes) {
  44889. if (thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  44890. // attribute in both, merge
  44891. let Type = this.data[attribute].constructor;
  44892. let merged = new Type(this.data[attribute].length + points.data[attribute].length);
  44893. merged.set(this.data[attribute], 0);
  44894. merged.set(points.data[attribute], this.data[attribute].length);
  44895. this.data[attribute] = merged;
  44896. } else if (thisAttributes.includes(attribute) && !otherAttributes.includes(attribute)) {
  44897. // attribute only in this; take over this and expand to new size
  44898. let elementsPerPoint = this.data[attribute].length / this.numPoints;
  44899. let Type = this.data[attribute].constructor;
  44900. let expanded = new Type(elementsPerPoint * newSize);
  44901. expanded.set(this.data[attribute], 0);
  44902. this.data[attribute] = expanded;
  44903. } else if (!thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  44904. // attribute only in points to be added; take over new points and expand to new size
  44905. let elementsPerPoint = points.data[attribute].length / points.numPoints;
  44906. let Type = points.data[attribute].constructor;
  44907. let expanded = new Type(elementsPerPoint * newSize);
  44908. expanded.set(points.data[attribute], elementsPerPoint * currentSize);
  44909. this.data[attribute] = expanded;
  44910. }
  44911. }
  44912. this.numPoints = newSize;
  44913. this.boundingBox.union(points.boundingBox);
  44914. }
  44915. }
  44916. /**
  44917. *
  44918. * code adapted from three.js BoxHelper.js
  44919. * https://github.com/mrdoob/three.js/blob/dev/src/helpers/BoxHelper.js
  44920. *
  44921. * @author mrdoob / http://mrdoob.com/
  44922. * @author Mugen87 / http://github.com/Mugen87
  44923. * @author mschuetz / http://potree.org
  44924. */
  44925. class Box3Helper$1 extends LineSegments {
  44926. constructor (box, color) {
  44927. if (color === undefined) color = 0xffff00;
  44928. let 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 ]);
  44929. let positions = new Float32Array([
  44930. box.min.x, box.min.y, box.min.z,
  44931. box.max.x, box.min.y, box.min.z,
  44932. box.max.x, box.min.y, box.max.z,
  44933. box.min.x, box.min.y, box.max.z,
  44934. box.min.x, box.max.y, box.min.z,
  44935. box.max.x, box.max.y, box.min.z,
  44936. box.max.x, box.max.y, box.max.z,
  44937. box.min.x, box.max.y, box.max.z
  44938. ]);
  44939. let geometry = new BufferGeometry();
  44940. geometry.setIndex(new BufferAttribute(indices, 1));
  44941. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  44942. let material = new LineBasicMaterial({ color: color });
  44943. super(geometry, material);
  44944. }
  44945. }
  44946. function updatePointClouds(pointclouds,camera, areaSize /* renderer */){
  44947. for (let pointcloud of pointclouds) {
  44948. let start = performance.now();
  44949. for (let profileRequest of pointcloud.profileRequests) {
  44950. profileRequest.update();
  44951. let duration = performance.now() - start;
  44952. if(duration > 5){
  44953. break;
  44954. }
  44955. }
  44956. let duration = performance.now() - start;
  44957. }
  44958. let result = updateVisibility(pointclouds, camera, areaSize );
  44959. for (let pointcloud of pointclouds) {
  44960. //pointcloud.updateMaterial(pointcloud.material, pointcloud.visibleNodes, camera, renderer);//转移到渲染时
  44961. pointcloud.updateVisibleBounds();
  44962. }
  44963. exports.lru.freeMemory();//即Potree.lru 能看到所有在加载的node
  44964. return result;
  44965. };
  44966. function updateVisibilityStructures(pointclouds, camera, areaSize) {
  44967. let frustums = [];
  44968. let camObjPositions = [];
  44969. let priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  44970. for (let i = 0; i < pointclouds.length; i++) {
  44971. let pointcloud = pointclouds[i];
  44972. if (!pointcloud.initialized()) {
  44973. continue;
  44974. }
  44975. pointcloud.numVisibleNodes = 0;
  44976. pointcloud.numVisiblePoints = 0;
  44977. pointcloud.deepestVisibleLevel = 0;
  44978. pointcloud.visibleNodes = [];
  44979. pointcloud.visibleGeometry = [];
  44980. // frustum in object space
  44981. camera.updateMatrixWorld();
  44982. let frustum = new Frustum();
  44983. let viewI = camera.matrixWorldInverse;
  44984. let world = pointcloud.matrixWorld;
  44985. // use close near plane for frustum intersection
  44986. let frustumCam = camera.clone();
  44987. frustumCam.near = Math.min(camera.near, 0.1);
  44988. frustumCam.updateProjectionMatrix();
  44989. let proj = camera.projectionMatrix;
  44990. let fm = new Matrix4().multiply(proj).multiply(viewI).multiply(world);
  44991. frustum.setFromProjectionMatrix(fm);
  44992. frustums.push(frustum);
  44993. // camera position in object space
  44994. let view = camera.matrixWorld;
  44995. let worldI = world.clone().invert();
  44996. let camMatrixObject = new Matrix4().multiply(worldI).multiply(view);
  44997. let camObjPos = new Vector3().setFromMatrixPosition(camMatrixObject);
  44998. camObjPositions.push(camObjPos);
  44999. // 因漫游模式而隐藏的话 依旧需要加入visibleNodes,因为pick需要
  45000. /* viewer.getObjVisiByReason(pointcloud, 'datasetSelection') */
  45001. if (pointcloud.visible || pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode' && pointcloud.root !== null) {//改 visible ->
  45002. priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE});
  45003. }
  45004. // hide all previously visible nodes
  45005. // if(pointcloud.root instanceof PointCloudOctreeNode){
  45006. // pointcloud.hideDescendants(pointcloud.root.sceneNode);
  45007. // }
  45008. if (pointcloud.root.isTreeNode()) {
  45009. pointcloud.hideDescendants(pointcloud.root.sceneNode);
  45010. }
  45011. for (let j = 0; j < pointcloud.boundingBoxNodes.length; j++) {
  45012. pointcloud.boundingBoxNodes[j].visible = false;
  45013. }
  45014. }
  45015. return {
  45016. 'frustums': frustums,
  45017. 'camObjPositions': camObjPositions,
  45018. 'priorityQueue': priorityQueue
  45019. };
  45020. };
  45021. function updateVisibility(pointclouds, camera, areaSize){
  45022. let numVisibleNodes = 0;
  45023. let numVisiblePoints = 0;
  45024. let numVisiblePointsInPointclouds = new Map(pointclouds.map(pc => [pc, 0]));
  45025. let visibleNodes = [];
  45026. let visibleGeometry = [];
  45027. let unloadedGeometry = [];
  45028. let lowestSpacing = Infinity;
  45029. // calculate object space frustum and cam pos and setup priority queue
  45030. let s = updateVisibilityStructures(pointclouds, camera, areaSize);//得到相机可见范围
  45031. let frustums = s.frustums;
  45032. let camObjPositions = s.camObjPositions;
  45033. let priorityQueue = s.priorityQueue;
  45034. let loadedToGPUThisFrame = 0;
  45035. let domWidth = areaSize.x; //renderer.domElement.clientWidth;
  45036. let domHeight = areaSize.y;//renderer.domElement.clientHeight;
  45037. // check if pointcloud has been transformed
  45038. // some code will only be executed if changes have been detected
  45039. if(!Potree._pointcloudTransformVersion){
  45040. Potree._pointcloudTransformVersion = new Map();
  45041. }
  45042. let pointcloudTransformVersion = Potree._pointcloudTransformVersion;
  45043. for(let pointcloud of pointclouds){
  45044. if(!viewer.getObjVisiByReason(pointcloud, 'datasetSelection')){//改 visible ->
  45045. continue;
  45046. }
  45047. pointcloud.updateMatrixWorld();
  45048. if(!pointcloudTransformVersion.has(pointcloud)){
  45049. pointcloudTransformVersion.set(pointcloud, {number: 0, transform: pointcloud.matrixWorld.clone()});
  45050. }else {
  45051. let version = pointcloudTransformVersion.get(pointcloud);
  45052. if(!version.transform.equals(pointcloud.matrixWorld)){
  45053. version.number++;
  45054. version.transform.copy(pointcloud.matrixWorld);
  45055. pointcloud.dispatchEvent({
  45056. type: "transformation_changed",
  45057. target: pointcloud
  45058. });
  45059. }
  45060. }
  45061. }
  45062. while (priorityQueue.size() > 0) {
  45063. let element = priorityQueue.pop();//其实是拿第一个, 再把最后一个放到前面
  45064. let node = element.node;
  45065. let parent = element.parent;
  45066. let pointcloud = pointclouds[element.pointcloud];
  45067. // { // restrict to certain nodes for debugging
  45068. // let allowedNodes = ["r", "r0", "r4"];
  45069. // if(!allowedNodes.includes(node.name)){
  45070. // continue;
  45071. // }
  45072. // }
  45073. let box = node.getBoundingBox();
  45074. let frustum = frustums[element.pointcloud];
  45075. let camObjPos = camObjPositions[element.pointcloud];
  45076. let insideFrustum = frustum.intersectsBox(box);
  45077. let maxLevel = pointcloud.maxLevel == void 0 ? Infinity : pointcloud.maxLevel;
  45078. let level = node.getLevel();
  45079. let visible = insideFrustum;
  45080. visible = visible && !(numVisiblePoints + node.getNumPoints() > Potree.pointBudget);
  45081. visible = visible && !(numVisiblePointsInPointclouds.get(pointcloud) + node.getNumPoints() > pointcloud.pointBudget);
  45082. visible = visible && level <= maxLevel; //< 改为 <=
  45083. //visible = visible || node.getLevel() <= 2;
  45084. let clipBoxes = pointcloud.material.clipBoxes;
  45085. if(true && clipBoxes.length > 0){
  45086. //node.debug = false;
  45087. let numIntersecting = 0;
  45088. let numIntersectionVolumes = 0;
  45089. //if(node.name === "r60"){
  45090. // var a = 10;
  45091. //}
  45092. for(let clipBox of clipBoxes){
  45093. let pcWorldInverse = pointcloud.matrixWorld.clone().invert();
  45094. let toPCObject = pcWorldInverse.multiply(clipBox.box.matrixWorld);
  45095. let px = new Vector3(+0.5, 0, 0).applyMatrix4(pcWorldInverse);
  45096. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(pcWorldInverse);
  45097. let py = new Vector3(0, +0.5, 0).applyMatrix4(pcWorldInverse);
  45098. let ny = new Vector3(0, -0.5, 0).applyMatrix4(pcWorldInverse);
  45099. let pz = new Vector3(0, 0, +0.5).applyMatrix4(pcWorldInverse);
  45100. let nz = new Vector3(0, 0, -0.5).applyMatrix4(pcWorldInverse);
  45101. let pxN = new Vector3().subVectors(nx, px).normalize();
  45102. let nxN = pxN.clone().multiplyScalar(-1);
  45103. let pyN = new Vector3().subVectors(ny, py).normalize();
  45104. let nyN = pyN.clone().multiplyScalar(-1);
  45105. let pzN = new Vector3().subVectors(nz, pz).normalize();
  45106. let nzN = pzN.clone().multiplyScalar(-1);
  45107. let pxPlane = new Plane().setFromNormalAndCoplanarPoint(pxN, px);
  45108. let nxPlane = new Plane().setFromNormalAndCoplanarPoint(nxN, nx);
  45109. let pyPlane = new Plane().setFromNormalAndCoplanarPoint(pyN, py);
  45110. let nyPlane = new Plane().setFromNormalAndCoplanarPoint(nyN, ny);
  45111. let pzPlane = new Plane().setFromNormalAndCoplanarPoint(pzN, pz);
  45112. let nzPlane = new Plane().setFromNormalAndCoplanarPoint(nzN, nz);
  45113. //if(window.debugdraw !== undefined && window.debugdraw === true && node.name === "r60"){
  45114. // Potree.utils.debugPlane(viewer.scene.scene, pxPlane, 1, 0xFF0000);
  45115. // Potree.utils.debugPlane(viewer.scene.scene, nxPlane, 1, 0x990000);
  45116. // Potree.utils.debugPlane(viewer.scene.scene, pyPlane, 1, 0x00FF00);
  45117. // Potree.utils.debugPlane(viewer.scene.scene, nyPlane, 1, 0x009900);
  45118. // Potree.utils.debugPlane(viewer.scene.scene, pzPlane, 1, 0x0000FF);
  45119. // Potree.utils.debugPlane(viewer.scene.scene, nzPlane, 1, 0x000099);
  45120. // Potree.utils.debugBox(viewer.scene.scene, box, new THREE.Matrix4(), 0x00FF00);
  45121. // Potree.utils.debugBox(viewer.scene.scene, box, pointcloud.matrixWorld, 0xFF0000);
  45122. // Potree.utils.debugBox(viewer.scene.scene, clipBox.box.boundingBox, clipBox.box.matrixWorld, 0xFF0000);
  45123. // window.debugdraw = false;
  45124. //}
  45125. let frustum = new Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane);
  45126. let intersects = frustum.intersectsBox(box);
  45127. if(intersects){
  45128. numIntersecting++;
  45129. }
  45130. numIntersectionVolumes++;
  45131. }
  45132. let insideAny = numIntersecting > 0;
  45133. let insideAll = numIntersecting === numIntersectionVolumes;
  45134. if(pointcloud.material.clipTask === ClipTask.SHOW_INSIDE){
  45135. if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ANY && insideAny){
  45136. //node.debug = true
  45137. }else if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ALL && insideAll){
  45138. //node.debug = true;
  45139. }else {
  45140. visible = false;
  45141. }
  45142. } else if(pointcloud.material.clipTask === ClipTask.SHOW_OUTSIDE){
  45143. //if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ANY && !insideAny){
  45144. // //visible = true;
  45145. // let a = 10;
  45146. //}else if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ALL && !insideAll){
  45147. // //visible = true;
  45148. // let a = 20;
  45149. //}else{
  45150. // visible = false;
  45151. //}
  45152. }
  45153. }
  45154. // visible = ["r", "r0", "r06", "r060"].includes(node.name);
  45155. // visible = ["r"].includes(node.name);
  45156. if (node.spacing) {
  45157. lowestSpacing = Math.min(lowestSpacing, node.spacing);
  45158. } else if (node.geometryNode && node.geometryNode.spacing) {
  45159. lowestSpacing = Math.min(lowestSpacing, node.geometryNode.spacing);
  45160. }
  45161. if (numVisiblePoints + node.getNumPoints() > Potree.pointBudget) {
  45162. break;
  45163. }
  45164. if (!visible) {
  45165. continue;
  45166. }
  45167. // TODO: not used, same as the declaration?
  45168. // numVisibleNodes++;
  45169. numVisiblePoints += node.getNumPoints();
  45170. let numVisiblePointsInPointcloud = numVisiblePointsInPointclouds.get(pointcloud);
  45171. numVisiblePointsInPointclouds.set(pointcloud, numVisiblePointsInPointcloud + node.getNumPoints());
  45172. pointcloud.numVisibleNodes++;
  45173. pointcloud.numVisiblePoints += node.getNumPoints();
  45174. if (node.isGeometryNode() && (!parent || parent.isTreeNode())) {
  45175. if (node.isLoaded() && loadedToGPUThisFrame < 2) {
  45176. node = pointcloud.toTreeNode(node, parent);
  45177. loadedToGPUThisFrame++;
  45178. } else {
  45179. unloadedGeometry.push({pointcloud,node});
  45180. visibleGeometry.push(node);
  45181. }
  45182. }
  45183. if (node.isTreeNode()) {
  45184. exports.lru.touch(node.geometryNode);
  45185. node.sceneNode.visible = true;
  45186. node.sceneNode.material = pointcloud.material;
  45187. visibleNodes.push(node);
  45188. pointcloud.visibleNodes.push(node);
  45189. if(node._transformVersion === undefined){
  45190. node._transformVersion = -1;
  45191. }
  45192. let transformVersion = pointcloudTransformVersion.get(pointcloud);
  45193. if(node._transformVersion !== transformVersion.number){
  45194. node.sceneNode.updateMatrix();
  45195. //node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  45196. node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  45197. node._transformVersion = transformVersion.number;
  45198. }
  45199. if (pointcloud.showBoundingBox && !node.boundingBoxNode && node.getBoundingBox) {
  45200. let boxHelper = new Box3Helper$1(node.getBoundingBox());
  45201. boxHelper.matrixAutoUpdate = false;
  45202. pointcloud.boundingBoxNodes.push(boxHelper);
  45203. node.boundingBoxNode = boxHelper;
  45204. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  45205. } else if (pointcloud.showBoundingBox) {
  45206. node.boundingBoxNode.visible = true;
  45207. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  45208. } else if (!pointcloud.showBoundingBox && node.boundingBoxNode) {
  45209. node.boundingBoxNode.visible = false;
  45210. }
  45211. // if(node.boundingBoxNode !== undefined && exports.debug.allowedNodes !== undefined){
  45212. // if(!exports.debug.allowedNodes.includes(node.name)){
  45213. // node.boundingBoxNode.visible = false;
  45214. // }
  45215. // }
  45216. }
  45217. // add child nodes to priorityQueue
  45218. let children = node.getChildren();
  45219. for (let i = 0; i < children.length; i++) {
  45220. let child = children[i];
  45221. let weight = 0;
  45222. if(camera.isPerspectiveCamera){
  45223. let sphere = child.getBoundingSphere();
  45224. let center = sphere.center;
  45225. //let distance = sphere.center.distanceTo(camObjPos);
  45226. let dx = camObjPos.x - center.x;
  45227. let dy = camObjPos.y - center.y;
  45228. let dz = camObjPos.z - center.z;
  45229. let dd = dx * dx + dy * dy + dz * dz;
  45230. let distance = Math.sqrt(dd);
  45231. let radius = sphere.radius;
  45232. let fov = (camera.fov * Math.PI) / 180;
  45233. let slope = Math.tan(fov / 2);
  45234. let projFactor = (0.5 * domHeight) / (slope * distance);
  45235. let screenPixelRadius = radius * projFactor;
  45236. if(screenPixelRadius < pointcloud.minimumNodePixelSize){
  45237. continue;
  45238. }
  45239. weight = screenPixelRadius;
  45240. if(distance - radius < 0){
  45241. weight = Number.MAX_VALUE;
  45242. }
  45243. } else {
  45244. // TODO ortho visibility
  45245. let bb = child.getBoundingBox();
  45246. let distance = child.getBoundingSphere().center.distanceTo(camObjPos);
  45247. let diagonal = bb.max.clone().sub(bb.min).length();
  45248. //weight = diagonal / distance;
  45249. weight = diagonal;
  45250. }
  45251. priorityQueue.push({pointcloud: element.pointcloud, node: child, parent: node, weight: weight});
  45252. }
  45253. }// end priority queue loop
  45254. { // update DEM 这是什么
  45255. let maxDEMLevel = 4;
  45256. let candidates = pointclouds.filter(p => (p.generateDEM && p.dem instanceof Potree.DEM));
  45257. for (let pointcloud of candidates) {
  45258. let updatingNodes = pointcloud.visibleNodes.filter(n => n.getLevel() <= maxDEMLevel);
  45259. pointcloud.dem.update(updatingNodes);
  45260. }
  45261. }
  45262. //加载点云
  45263. for (let i = 0; i < Math.min(Potree.maxNodesLoading, unloadedGeometry.length); i++) {
  45264. unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry);
  45265. }
  45266. return {
  45267. visibleNodes: visibleNodes,
  45268. numVisiblePoints: numVisiblePoints,
  45269. lowestSpacing: lowestSpacing
  45270. };
  45271. };
  45272. //console
  45273. //viewer.scene.pointclouds[0].visibleNodes.map(e=> e && e.name )
  45274. //viewer.scene.pointclouds[0].visibleNodes.map(e=>e.children.map(e=>e && e.name))
  45275. class PointCloudArena4DNode extends PointCloudTreeNode {
  45276. constructor () {
  45277. super();
  45278. this.left = null;
  45279. this.right = null;
  45280. this.sceneNode = null;
  45281. this.kdtree = null;
  45282. }
  45283. getNumPoints () {
  45284. return this.geometryNode.numPoints;
  45285. }
  45286. isLoaded () {
  45287. return true;
  45288. }
  45289. isTreeNode () {
  45290. return true;
  45291. }
  45292. isGeometryNode () {
  45293. return false;
  45294. }
  45295. getLevel () {
  45296. return this.geometryNode.level;
  45297. }
  45298. getBoundingSphere () {
  45299. return this.geometryNode.boundingSphere;
  45300. }
  45301. getBoundingBox () {
  45302. return this.geometryNode.boundingBox;
  45303. }
  45304. toTreeNode (child) {
  45305. let geometryNode = null;
  45306. if (this.left === child) {
  45307. geometryNode = this.left;
  45308. } else if (this.right === child) {
  45309. geometryNode = this.right;
  45310. }
  45311. if (!geometryNode.loaded) {
  45312. return;
  45313. }
  45314. let node = new PointCloudArena4DNode();
  45315. let sceneNode = PointCloud(geometryNode.geometry, this.kdtree.material);
  45316. sceneNode.visible = false;
  45317. node.kdtree = this.kdtree;
  45318. node.geometryNode = geometryNode;
  45319. node.sceneNode = sceneNode;
  45320. node.parent = this;
  45321. node.left = this.geometryNode.left;
  45322. node.right = this.geometryNode.right;
  45323. }
  45324. getChildren () {
  45325. let children = [];
  45326. if (this.left) {
  45327. children.push(this.left);
  45328. }
  45329. if (this.right) {
  45330. children.push(this.right);
  45331. }
  45332. return children;
  45333. }
  45334. };
  45335. class PointCloudArena4D$1 extends PointCloudTree{
  45336. constructor (geometry) {
  45337. super();
  45338. this.root = null;
  45339. if (geometry.root) {
  45340. this.root = geometry.root;
  45341. } else {
  45342. geometry.addEventListener('hierarchy_loaded', () => {
  45343. this.root = geometry.root;
  45344. });
  45345. }
  45346. this.visiblePointsTarget = 2 * 1000 * 1000;
  45347. this.minimumNodePixelSize = 150;
  45348. this.position.sub(geometry.offset);
  45349. this.updateMatrix();
  45350. this.numVisibleNodes = 0;
  45351. this.numVisiblePoints = 0;
  45352. this.boundingBoxNodes = [];
  45353. this.loadQueue = [];
  45354. this.visibleNodes = [];
  45355. this.pcoGeometry = geometry;
  45356. this.boundingBox = this.pcoGeometry.boundingBox;
  45357. this.boundingSphere = this.pcoGeometry.boundingSphere;
  45358. this.material = new PointCloudMaterial$1({vertexColors: VertexColors, size: 0.05, treeType: TreeType.KDTREE});
  45359. this.material.sizeType = PointSizeType.ATTENUATED;
  45360. this.material.size = 0.05;
  45361. this.profileRequests = [];
  45362. this.name = '';
  45363. }
  45364. getBoundingBoxWorld () {
  45365. this.updateMatrixWorld(true);
  45366. let box = this.boundingBox;
  45367. let transform = this.matrixWorld;
  45368. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  45369. return tBox;
  45370. };
  45371. setName (name) {
  45372. if (this.name !== name) {
  45373. this.name = name;
  45374. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  45375. }
  45376. }
  45377. getName () {
  45378. return this.name;
  45379. }
  45380. getLevel () {
  45381. return this.level;
  45382. }
  45383. toTreeNode (geometryNode, parent) {
  45384. let node = new PointCloudArena4DNode();
  45385. let sceneNode = new Points(geometryNode.geometry, this.material);
  45386. sceneNode.frustumCulled = false;
  45387. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  45388. if (material.program) {
  45389. _this.getContext().useProgram(material.program.program);
  45390. if (material.program.getUniforms().map.level) {
  45391. let level = geometryNode.getLevel();
  45392. material.uniforms.level.value = level;
  45393. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  45394. }
  45395. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  45396. let vnStart = this.visibleNodeTextureOffsets.get(node);
  45397. material.uniforms.vnStart.value = vnStart;
  45398. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  45399. }
  45400. if (material.program.getUniforms().map.pcIndex) {
  45401. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  45402. material.uniforms.pcIndex.value = i;
  45403. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  45404. }
  45405. }
  45406. };
  45407. node.geometryNode = geometryNode;
  45408. node.sceneNode = sceneNode;
  45409. node.pointcloud = this;
  45410. node.left = geometryNode.left;
  45411. node.right = geometryNode.right;
  45412. if (!parent) {
  45413. this.root = node;
  45414. this.add(sceneNode);
  45415. } else {
  45416. parent.sceneNode.add(sceneNode);
  45417. if (parent.left === geometryNode) {
  45418. parent.left = node;
  45419. } else if (parent.right === geometryNode) {
  45420. parent.right = node;
  45421. }
  45422. }
  45423. let disposeListener = function () {
  45424. parent.sceneNode.remove(node.sceneNode);
  45425. if (parent.left === node) {
  45426. parent.left = geometryNode;
  45427. } else if (parent.right === node) {
  45428. parent.right = geometryNode;
  45429. }
  45430. };
  45431. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  45432. return node;
  45433. }
  45434. updateMaterial (material, visibleNodes, camera, renderer) {
  45435. material.fov = camera.fov * (Math.PI / 180);
  45436. material.screenWidth = renderer.domElement.clientWidth;
  45437. material.screenHeight = renderer.domElement.clientHeight;
  45438. material.spacing = this.pcoGeometry.spacing;
  45439. material.near = camera.near;
  45440. material.far = camera.far;
  45441. // reduce shader source updates by setting maxLevel slightly higher than actually necessary
  45442. if (this.maxLevel > material.levels) {
  45443. material.levels = this.maxLevel + 2;
  45444. }
  45445. // material.uniforms.octreeSize.value = this.boundingBox.size().x;
  45446. let bbSize = this.boundingBox.getSize(new Vector3());
  45447. material.bbSize = [bbSize.x, bbSize.y, bbSize.z];
  45448. }
  45449. updateVisibleBounds () {
  45450. }
  45451. hideDescendants (object) {
  45452. let stack = [];
  45453. for (let i = 0; i < object.children.length; i++) {
  45454. let child = object.children[i];
  45455. if (child.visible) {
  45456. stack.push(child);
  45457. }
  45458. }
  45459. while (stack.length > 0) {
  45460. let child = stack.shift();
  45461. child.visible = false;
  45462. if (child.boundingBoxNode) {
  45463. child.boundingBoxNode.visible = false;
  45464. }
  45465. for (let i = 0; i < child.children.length; i++) {
  45466. let childOfChild = child.children[i];
  45467. if (childOfChild.visible) {
  45468. stack.push(childOfChild);
  45469. }
  45470. }
  45471. }
  45472. }
  45473. updateMatrixWorld (force) {
  45474. // node.matrixWorld.multiplyMatrices( node.parent.matrixWorld, node.matrix );
  45475. if (this.matrixAutoUpdate === true) this.updateMatrix();
  45476. if (this.matrixWorldNeedsUpdate === true || force === true) {
  45477. if (this.parent === undefined) {
  45478. this.matrixWorld.copy(this.matrix);
  45479. } else {
  45480. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  45481. }
  45482. this.matrixWorldNeedsUpdate = false;
  45483. force = true;
  45484. }
  45485. }
  45486. nodesOnRay (nodes, ray) {
  45487. let nodesOnRay = [];
  45488. let _ray = ray.clone();
  45489. for (let i = 0; i < nodes.length; i++) {
  45490. let node = nodes[i];
  45491. let sphere = node.getBoundingSphere().clone().applyMatrix4(node.sceneNode.matrixWorld);
  45492. // TODO Unused: let box = node.getBoundingBox().clone().applyMatrix4(node.sceneNode.matrixWorld);
  45493. if (_ray.intersectsSphere(sphere)) {
  45494. nodesOnRay.push(node);
  45495. }
  45496. // if(_ray.isIntersectionBox(box)){
  45497. // nodesOnRay.push(node);
  45498. // }
  45499. }
  45500. return nodesOnRay;
  45501. }
  45502. pick(viewer, camera, ray, params = {}){
  45503. let renderer = viewer.renderer;
  45504. let pRenderer = viewer.pRenderer;
  45505. performance.mark("pick-start");
  45506. let getVal = (a, b) => a !== undefined ? a : b;
  45507. let pickWindowSize = getVal(params.pickWindowSize, 17);
  45508. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  45509. let size = renderer.getSize(new Vector2$1());
  45510. let width = Math.ceil(getVal(params.width, size.width));
  45511. let height = Math.ceil(getVal(params.height, size.height));
  45512. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  45513. let pointSize = getVal(params.pointSize, this.material.size);
  45514. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  45515. if (nodes.length === 0) {
  45516. return null;
  45517. }
  45518. if (!this.pickState) {
  45519. let scene = new Scene();
  45520. let material = new PointCloudMaterial$1();
  45521. material.activeAttributeName = "indices";
  45522. let renderTarget = new WebGLRenderTarget(
  45523. 1, 1,
  45524. { minFilter: LinearFilter,
  45525. magFilter: NearestFilter,
  45526. format: RGBAFormat }
  45527. );
  45528. this.pickState = {
  45529. renderTarget: renderTarget,
  45530. material: material,
  45531. scene: scene
  45532. };
  45533. };
  45534. let pickState = this.pickState;
  45535. let pickMaterial = pickState.material;
  45536. { // update pick material
  45537. pickMaterial.pointSizeType = pointSizeType;
  45538. pickMaterial.shape = this.material.shape;
  45539. pickMaterial.size = pointSize;
  45540. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  45541. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  45542. pickMaterial.classification = this.material.classification;
  45543. if(params.pickClipped){
  45544. pickMaterial.clipBoxes = this.material.clipBoxes;
  45545. if(this.material.clipTask === ClipTask.HIGHLIGHT){
  45546. pickMaterial.clipTask = ClipTask.NONE;
  45547. }else {
  45548. pickMaterial.clipTask = this.material.clipTask;
  45549. }
  45550. }else {
  45551. pickMaterial.clipBoxes = [];
  45552. }
  45553. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  45554. }
  45555. pickState.renderTarget.setSize(width, height);
  45556. let pixelPos = new Vector2$1(params.x, params.y);
  45557. let gl = renderer.getContext();
  45558. gl.enable(gl.SCISSOR_TEST);
  45559. gl.scissor(
  45560. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  45561. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  45562. parseInt(pickWindowSize), parseInt(pickWindowSize));
  45563. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  45564. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  45565. renderer.state.setBlending(NoBlending);
  45566. renderer.clearTarget(pickState.renderTarget, true, true, true);
  45567. { // RENDER
  45568. renderer.setRenderTarget(pickState.renderTarget);
  45569. gl.clearColor(0, 0, 0, 0);
  45570. renderer.clearTarget( pickState.renderTarget, true, true, true );
  45571. let tmp = this.material;
  45572. this.material = pickMaterial;
  45573. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  45574. this.material = tmp;
  45575. }
  45576. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  45577. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  45578. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  45579. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  45580. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  45581. let pixelCount = w * h;
  45582. let buffer = new Uint8Array(4 * pixelCount);
  45583. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  45584. renderer.setRenderTarget(null);
  45585. renderer.state.reset();
  45586. renderer.setScissorTest(false);
  45587. gl.disable(gl.SCISSOR_TEST);
  45588. let pixels = buffer;
  45589. let ibuffer = new Uint32Array(buffer.buffer);
  45590. // find closest hit inside pixelWindow boundaries
  45591. let min = Number.MAX_VALUE;
  45592. let hits = [];
  45593. for (let u = 0; u < pickWindowSize; u++) {
  45594. for (let v = 0; v < pickWindowSize; v++) {
  45595. let offset = (u + v * pickWindowSize);
  45596. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  45597. let pcIndex = pixels[4 * offset + 3];
  45598. pixels[4 * offset + 3] = 0;
  45599. let pIndex = ibuffer[offset];
  45600. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  45601. let hit = {
  45602. pIndex: pIndex,
  45603. pcIndex: pcIndex,
  45604. distanceToCenter: distance
  45605. };
  45606. if(params.all){
  45607. hits.push(hit);
  45608. }else {
  45609. if(hits.length > 0){
  45610. if(distance < hits[0].distanceToCenter){
  45611. hits[0] = hit;
  45612. }
  45613. }else {
  45614. hits.push(hit);
  45615. }
  45616. }
  45617. }
  45618. }
  45619. }
  45620. for(let hit of hits){
  45621. let point = {};
  45622. if (!nodes[hit.pcIndex]) {
  45623. return null;
  45624. }
  45625. let node = nodes[hit.pcIndex];
  45626. let pc = node.sceneNode;
  45627. let geometry = node.geometryNode.geometry;
  45628. for(let attributeName in geometry.attributes){
  45629. let attribute = geometry.attributes[attributeName];
  45630. if (attributeName === 'position') {
  45631. let x = attribute.array[3 * hit.pIndex + 0];
  45632. let y = attribute.array[3 * hit.pIndex + 1];
  45633. let z = attribute.array[3 * hit.pIndex + 2];
  45634. let position = new Vector3(x, y, z);
  45635. position.applyMatrix4(pc.matrixWorld);
  45636. point[attributeName] = position;
  45637. } else if (attributeName === 'indices') {
  45638. } else {
  45639. //if (values.itemSize === 1) {
  45640. // point[attribute.name] = values.array[hit.pIndex];
  45641. //} else {
  45642. // let value = [];
  45643. // for (let j = 0; j < values.itemSize; j++) {
  45644. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  45645. // }
  45646. // point[attribute.name] = value;
  45647. //}
  45648. }
  45649. }
  45650. hit.point = point;
  45651. }
  45652. performance.mark("pick-end");
  45653. performance.measure("pick", "pick-start", "pick-end");
  45654. if(params.all){
  45655. return hits.map(hit => hit.point);
  45656. }else {
  45657. if(hits.length === 0){
  45658. return null;
  45659. }else {
  45660. return hits[0].point;
  45661. }
  45662. }
  45663. }
  45664. computeVisibilityTextureData(nodes){
  45665. if(exports.measureTimings) performance.mark("computeVisibilityTextureData-start");
  45666. let data = new Uint8Array(nodes.length * 3);
  45667. let visibleNodeTextureOffsets = new Map();
  45668. // copy array
  45669. nodes = nodes.slice();
  45670. // sort by level and number
  45671. let sort = function (a, b) {
  45672. let la = a.geometryNode.level;
  45673. let lb = b.geometryNode.level;
  45674. let na = a.geometryNode.number;
  45675. let nb = b.geometryNode.number;
  45676. if (la !== lb) return la - lb;
  45677. if (na < nb) return -1;
  45678. if (na > nb) return 1;
  45679. return 0;
  45680. };
  45681. nodes.sort(sort);
  45682. let visibleNodeNames = [];
  45683. for (let i = 0; i < nodes.length; i++) {
  45684. visibleNodeNames.push(nodes[i].geometryNode.number);
  45685. }
  45686. for (let i = 0; i < nodes.length; i++) {
  45687. let node = nodes[i];
  45688. visibleNodeTextureOffsets.set(node, i);
  45689. let b1 = 0; // children
  45690. let b2 = 0; // offset to first child
  45691. let b3 = 0; // split
  45692. if (node.geometryNode.left && visibleNodeNames.indexOf(node.geometryNode.left.number) > 0) {
  45693. b1 += 1;
  45694. b2 = visibleNodeNames.indexOf(node.geometryNode.left.number) - i;
  45695. }
  45696. if (node.geometryNode.right && visibleNodeNames.indexOf(node.geometryNode.right.number) > 0) {
  45697. b1 += 2;
  45698. b2 = (b2 === 0) ? visibleNodeNames.indexOf(node.geometryNode.right.number) - i : b2;
  45699. }
  45700. if (node.geometryNode.split === 'X') {
  45701. b3 = 1;
  45702. } else if (node.geometryNode.split === 'Y') {
  45703. b3 = 2;
  45704. } else if (node.geometryNode.split === 'Z') {
  45705. b3 = 4;
  45706. }
  45707. data[i * 3 + 0] = b1;
  45708. data[i * 3 + 1] = b2;
  45709. data[i * 3 + 2] = b3;
  45710. }
  45711. if(exports.measureTimings){
  45712. performance.mark("computeVisibilityTextureData-end");
  45713. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  45714. }
  45715. return {
  45716. data: data,
  45717. offsets: visibleNodeTextureOffsets
  45718. };
  45719. }
  45720. get progress () {
  45721. if (this.pcoGeometry.root) {
  45722. return exports.numNodesLoading > 0 ? 0 : 1;
  45723. } else {
  45724. return 0;
  45725. }
  45726. }
  45727. };
  45728. // Copied from three.js: WebGLRenderer.js
  45729. function paramThreeToGL(_gl, p) {
  45730. let extension;
  45731. if (p === RepeatWrapping) return _gl.REPEAT;
  45732. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  45733. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  45734. if (p === NearestFilter) return _gl.NEAREST;
  45735. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  45736. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  45737. if (p === LinearFilter) return _gl.LINEAR;
  45738. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  45739. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  45740. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  45741. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  45742. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  45743. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  45744. if (p === ByteType) return _gl.BYTE;
  45745. if (p === ShortType) return _gl.SHORT;
  45746. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  45747. if (p === IntType) return _gl.INT;
  45748. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  45749. if (p === FloatType) return _gl.FLOAT;
  45750. if (p === HalfFloatType) {
  45751. extension = extensions.get('OES_texture_half_float');
  45752. if (extension !== null) return extension.HALF_FLOAT_OES;
  45753. }
  45754. if (p === AlphaFormat) return _gl.ALPHA;
  45755. if (p === RGBFormat) return _gl.RGB;
  45756. if (p === RGBAFormat) return _gl.RGBA;
  45757. if (p === LuminanceFormat) return _gl.LUMINANCE;
  45758. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  45759. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  45760. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  45761. if (p === AddEquation) return _gl.FUNC_ADD;
  45762. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  45763. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  45764. if (p === ZeroFactor) return _gl.ZERO;
  45765. if (p === OneFactor) return _gl.ONE;
  45766. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  45767. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  45768. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  45769. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  45770. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  45771. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  45772. if (p === DstColorFactor) return _gl.DST_COLOR;
  45773. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  45774. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  45775. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  45776. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  45777. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  45778. if (extension !== null) {
  45779. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45780. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45781. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45782. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45783. }
  45784. }
  45785. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  45786. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  45787. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  45788. if (extension !== null) {
  45789. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45790. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45791. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45792. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45793. }
  45794. }
  45795. if (p === RGB_ETC1_Format) {
  45796. extension = extensions.get('WEBGL_compressed_texture_etc1');
  45797. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  45798. }
  45799. if (p === MinEquation || p === MaxEquation) {
  45800. extension = extensions.get('EXT_blend_minmax');
  45801. if (extension !== null) {
  45802. if (p === MinEquation) return extension.MIN_EXT;
  45803. if (p === MaxEquation) return extension.MAX_EXT;
  45804. }
  45805. }
  45806. if (p === UnsignedInt248Type) {
  45807. extension = extensions.get('WEBGL_depth_texture');
  45808. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  45809. }
  45810. return 0;
  45811. };
  45812. let attributeLocations = {
  45813. "position": {name: "position", location: 0},
  45814. "color": {name: "color", location: 1},
  45815. "rgba": {name: "color", location: 1},
  45816. "intensity": {name: "intensity", location: 2},
  45817. "classification": {name: "classification", location: 3},
  45818. "returnNumber": {name: "returnNumber", location: 4},
  45819. "return number": {name: "returnNumber", location: 4},
  45820. "returns": {name: "returnNumber", location: 4},
  45821. "numberOfReturns": {name: "numberOfReturns", location: 5},
  45822. "number of returns": {name: "numberOfReturns", location: 5},
  45823. "pointSourceID": {name: "pointSourceID", location: 6},
  45824. "source id": {name: "pointSourceID", location: 6},
  45825. "point source id": {name: "pointSourceID", location: 6},
  45826. "indices": {name: "indices", location: 7},
  45827. "normal": {name: "normal", location: 8},
  45828. "spacing": {name: "spacing", location: 9},
  45829. "gps-time": {name: "gpsTime", location: 10},
  45830. "aExtra": {name: "aExtra", location: 11},
  45831. };
  45832. class Shader {
  45833. constructor(gl, name, vsSource, fsSource) {
  45834. this.gl = gl;
  45835. this.name = name;
  45836. this.vsSource = vsSource;
  45837. this.fsSource = fsSource;
  45838. this.cache = new Map();
  45839. this.vs = null;
  45840. this.fs = null;
  45841. this.program = null;
  45842. this.uniformLocations = {};
  45843. this.attributeLocations = {};
  45844. this.uniformBlockIndices = {};
  45845. this.uniformBlocks = {};
  45846. this.uniforms = {};
  45847. this.update(vsSource, fsSource);
  45848. }
  45849. update(vsSource, fsSource) {
  45850. this.vsSource = vsSource;
  45851. this.fsSource = fsSource;
  45852. this.linkProgram();
  45853. }
  45854. compileShader(shader, source){
  45855. let gl = this.gl;
  45856. gl.shaderSource(shader, source);
  45857. gl.compileShader(shader);
  45858. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  45859. if (!success) {
  45860. let info = gl.getShaderInfoLog(shader);
  45861. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  45862. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  45863. }
  45864. }
  45865. linkProgram() {
  45866. const tStart = performance.now();
  45867. let gl = this.gl;
  45868. this.uniformLocations = {};
  45869. this.attributeLocations = {};
  45870. this.uniforms = {};
  45871. gl.useProgram(null);
  45872. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  45873. if (cached) {
  45874. this.program = cached.program;
  45875. this.vs = cached.vs;
  45876. this.fs = cached.fs;
  45877. this.attributeLocations = cached.attributeLocations;
  45878. this.uniformLocations = cached.uniformLocations;
  45879. this.uniformBlocks = cached.uniformBlocks;
  45880. this.uniforms = cached.uniforms;
  45881. return;
  45882. } else {
  45883. this.vs = gl.createShader(gl.VERTEX_SHADER);
  45884. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  45885. this.program = gl.createProgram();
  45886. if( !gl.isProgram(this.program )){//创建失败 开启多个页面可能会,原因是webglcontextlost
  45887. //console.error('创建program失败');
  45888. viewer.dispatchEvent('webglError', {msg: 'potreeRenderer创建program失败'});
  45889. console.log(this.vs);
  45890. console.log(this.fs);
  45891. return;
  45892. }
  45893. for(let name of Object.keys(attributeLocations)){
  45894. let location = attributeLocations[name].location;
  45895. let glslName = attributeLocations[name].name;
  45896. gl.bindAttribLocation(this.program, location, glslName);
  45897. }
  45898. this.compileShader(this.vs, this.vsSource);
  45899. this.compileShader(this.fs, this.fsSource);
  45900. let program = this.program;
  45901. gl.attachShader(program, this.vs);
  45902. gl.attachShader(program, this.fs);
  45903. gl.linkProgram(program);
  45904. gl.detachShader(program, this.vs);
  45905. gl.detachShader(program, this.fs);
  45906. // 检测当前程序链接状态
  45907. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  45908. if (!success) {
  45909. let info = gl.getProgramInfoLog(program);
  45910. throw `could not link program ${this.name}: ${info}`;
  45911. }
  45912. { // attribute locations
  45913. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  45914. for (let i = 0; i < numAttributes; i++) {
  45915. let attribute = gl.getActiveAttrib(program, i);
  45916. let location = gl.getAttribLocation(program, attribute.name);
  45917. this.attributeLocations[attribute.name] = location;
  45918. }
  45919. }
  45920. { // uniform locations
  45921. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  45922. for (let i = 0; i < numUniforms; i++) {
  45923. let uniform = gl.getActiveUniform(program, i);
  45924. let location = gl.getUniformLocation(program, uniform.name);
  45925. this.uniformLocations[uniform.name] = location;
  45926. this.uniforms[uniform.name] = {
  45927. location: location,
  45928. value: null,
  45929. };
  45930. }
  45931. }
  45932. // uniform blocks
  45933. if( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext){ //WebGL2RenderingContext在mac的safari14以下是没有定义的
  45934. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  45935. for (let i = 0; i < numBlocks; i++) {
  45936. let blockName = gl.getActiveUniformBlockName(program, i);
  45937. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  45938. this.uniformBlockIndices[blockName] = blockIndex;
  45939. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  45940. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  45941. let uBuffer = gl.createBuffer();
  45942. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  45943. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  45944. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  45945. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  45946. this.uniformBlocks[blockName] = {
  45947. name: blockName,
  45948. index: blockIndex,
  45949. dataSize: dataSize,
  45950. buffer: uBuffer
  45951. };
  45952. }
  45953. }
  45954. let cached = {
  45955. program: this.program,
  45956. vs: this.vs,
  45957. fs: this.fs,
  45958. attributeLocations: this.attributeLocations,
  45959. uniformLocations: this.uniformLocations,
  45960. uniforms: this.uniforms,
  45961. uniformBlocks: this.uniformBlocks,
  45962. };
  45963. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  45964. }
  45965. const tEnd = performance.now();
  45966. const duration = tEnd - tStart;
  45967. //console.log(`shader compile duration: ${duration.toFixed(3)}`);
  45968. }
  45969. setUniformMatrix4(name, value) {
  45970. const gl = this.gl;
  45971. const location = this.uniformLocations[name];
  45972. if (location == null) {
  45973. return;
  45974. }
  45975. let tmp = new Float32Array(value.elements);
  45976. gl.uniformMatrix4fv(location, false, tmp);
  45977. }
  45978. setUniform1f(name, value) {
  45979. const gl = this.gl;
  45980. const uniform = this.uniforms[name];
  45981. if (uniform === undefined) {
  45982. return;
  45983. }
  45984. if(uniform.value === value){
  45985. return;
  45986. }
  45987. uniform.value = value;
  45988. gl.uniform1f(uniform.location, value);
  45989. }
  45990. setUniformBoolean(name, value) {
  45991. const gl = this.gl;
  45992. const uniform = this.uniforms[name];
  45993. if (uniform === undefined) {
  45994. return;
  45995. }
  45996. if(uniform.value === value){
  45997. return;
  45998. }
  45999. uniform.value = value;
  46000. gl.uniform1i(uniform.location, value);
  46001. }
  46002. setUniformTexture(name, value) {
  46003. const gl = this.gl;
  46004. const location = this.uniformLocations[name];
  46005. if (location == null) {
  46006. return;
  46007. }
  46008. gl.uniform1i(location, value);
  46009. }
  46010. setUniform2f(name, value) {
  46011. const gl = this.gl;
  46012. const location = this.uniformLocations[name];
  46013. if (location == null) {
  46014. return;
  46015. }
  46016. gl.uniform2f(location, value[0], value[1]);
  46017. }
  46018. setUniform3f(name, value) {
  46019. const gl = this.gl;
  46020. const location = this.uniformLocations[name];
  46021. if (location == null) {
  46022. return;
  46023. }
  46024. gl.uniform3f(location, value[0], value[1], value[2]);
  46025. }
  46026. setUniform(name, value) {
  46027. if (value.constructor === Matrix4) {
  46028. this.setUniformMatrix4(name, value);
  46029. } else if (typeof value === "number") {
  46030. this.setUniform1f(name, value);
  46031. } else if (typeof value === "boolean") {
  46032. this.setUniformBoolean(name, value);
  46033. } else if (value instanceof WebGLTexture) {
  46034. this.setUniformTexture(name, value);
  46035. } else if (value instanceof Array) {
  46036. if (value.length === 2) {
  46037. this.setUniform2f(name, value);
  46038. } else if (value.length === 3) {
  46039. this.setUniform3f(name, value);
  46040. }
  46041. } else {
  46042. console.error("unhandled uniform type: ", name, value);
  46043. }
  46044. }
  46045. setUniform1i(name, value) {
  46046. let gl = this.gl;
  46047. let location = this.uniformLocations[name];
  46048. if (location == null) {
  46049. return;
  46050. }
  46051. gl.uniform1i(location, value);
  46052. }
  46053. };
  46054. class WebGLTexture {
  46055. constructor(gl, texture) {
  46056. this.gl = gl;
  46057. this.texture = texture;
  46058. this.id = gl.createTexture();
  46059. this.target = gl.TEXTURE_2D;
  46060. this.version = -1;
  46061. this.update(texture);
  46062. }
  46063. update() {
  46064. if (!this.texture.image) {
  46065. this.version = this.texture.version;
  46066. return;
  46067. }
  46068. let gl = this.gl;
  46069. let texture = this.texture;
  46070. if (this.version === texture.version) {
  46071. return;
  46072. }
  46073. this.target = gl.TEXTURE_2D;
  46074. gl.bindTexture(this.target, this.id);
  46075. let level = 0;
  46076. let internalFormat = paramThreeToGL(gl, texture.format);
  46077. let width = texture.image.width;
  46078. let height = texture.image.height;
  46079. let border = 0;
  46080. let srcFormat = internalFormat;
  46081. let srcType = paramThreeToGL(gl, texture.type);
  46082. let data;
  46083. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  46084. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  46085. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  46086. if (texture instanceof DataTexture) {
  46087. data = texture.image.data;
  46088. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  46089. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46090. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  46091. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  46092. gl.texImage2D(this.target, level, internalFormat,
  46093. width, height, border, srcFormat, srcType,
  46094. data);
  46095. }/* else if(texture instanceof THREE.CubeTexture){//add
  46096. } */else if ((texture instanceof CanvasTexture) || (texture instanceof Texture)) {
  46097. data = texture.image;
  46098. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  46099. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  46100. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  46101. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  46102. gl.texImage2D(this.target, level, internalFormat,
  46103. internalFormat, srcType, data);
  46104. if (texture instanceof Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  46105. }
  46106. gl.bindTexture(this.target, null);
  46107. this.version = texture.version;
  46108. }
  46109. };
  46110. class WebGLBuffer {
  46111. constructor() {
  46112. this.numElements = 0;
  46113. this.vao = null;
  46114. this.vbos = new Map();
  46115. }
  46116. };
  46117. class Renderer {
  46118. constructor(threeRenderer) {
  46119. this.threeRenderer = threeRenderer;
  46120. this.gl = this.threeRenderer.getContext();
  46121. this.buffers = new Map();
  46122. this.shaders = new Map();
  46123. this.textures = new Map();
  46124. this.glTypeMapping = new Map();
  46125. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  46126. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  46127. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  46128. this.toggle = 0;
  46129. }
  46130. deleteBuffer(geometry) {
  46131. let gl = this.gl;
  46132. let webglBuffer = this.buffers.get(geometry);
  46133. if (webglBuffer != null) {
  46134. for (let attributeName in geometry.attributes) {
  46135. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  46136. }
  46137. this.buffers.delete(geometry);
  46138. }
  46139. }
  46140. createBuffer(geometry){
  46141. let gl = this.gl;
  46142. let webglBuffer = new WebGLBuffer();
  46143. webglBuffer.vao = gl.createVertexArray();
  46144. webglBuffer.numElements = geometry.attributes.position.count;
  46145. gl.bindVertexArray(webglBuffer.vao);
  46146. for(let attributeName in geometry.attributes){
  46147. let bufferAttribute = geometry.attributes[attributeName];
  46148. let vbo = gl.createBuffer();
  46149. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  46150. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  46151. let normalized = bufferAttribute.normalized;
  46152. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46153. if(attributeLocations[attributeName] === undefined){
  46154. //attributeLocation = attributeLocations["aExtra"];
  46155. }else {
  46156. let attributeLocation = attributeLocations[attributeName].location;
  46157. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46158. gl.enableVertexAttribArray(attributeLocation);
  46159. }
  46160. webglBuffer.vbos.set(attributeName, {
  46161. handle: vbo,
  46162. name: attributeName,
  46163. count: bufferAttribute.count,
  46164. itemSize: bufferAttribute.itemSize,
  46165. type: geometry.attributes.position.array.constructor,
  46166. version: 0
  46167. });
  46168. }
  46169. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46170. gl.bindVertexArray(null);
  46171. let disposeHandler = (event) => {
  46172. this.deleteBuffer(geometry);
  46173. geometry.removeEventListener("dispose", disposeHandler);
  46174. };
  46175. geometry.addEventListener("dispose", disposeHandler);
  46176. return webglBuffer;
  46177. }
  46178. updateBuffer(geometry){
  46179. let gl = this.gl;
  46180. let webglBuffer = this.buffers.get(geometry);
  46181. gl.bindVertexArray(webglBuffer.vao);
  46182. for(let attributeName in geometry.attributes){
  46183. let bufferAttribute = geometry.attributes[attributeName];
  46184. let normalized = bufferAttribute.normalized;
  46185. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46186. let vbo = null;
  46187. if(!webglBuffer.vbos.has(attributeName)){
  46188. vbo = gl.createBuffer();
  46189. webglBuffer.vbos.set(attributeName, {
  46190. handle: vbo,
  46191. name: attributeName,
  46192. count: bufferAttribute.count,
  46193. itemSize: bufferAttribute.itemSize,
  46194. type: geometry.attributes.position.array.constructor,
  46195. version: bufferAttribute.version
  46196. });
  46197. }else {
  46198. vbo = webglBuffer.vbos.get(attributeName).handle;
  46199. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  46200. }
  46201. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  46202. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  46203. if(attributeLocations[attributeName] === undefined){
  46204. //attributeLocation = attributeLocations["aExtra"];
  46205. }else {
  46206. let attributeLocation = attributeLocations[attributeName].location;
  46207. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46208. gl.enableVertexAttribArray(attributeLocation);
  46209. }
  46210. }
  46211. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46212. gl.bindVertexArray(null);
  46213. }
  46214. traverse(scene) {
  46215. let octrees = [];
  46216. let stack = [scene];
  46217. while (stack.length > 0) {
  46218. let node = stack.pop();
  46219. if (node instanceof PointCloudTree) {
  46220. octrees.push(node);
  46221. continue;
  46222. }
  46223. let visibleChildren = node.children.filter(c => c.visible);
  46224. stack.push(...visibleChildren);
  46225. }
  46226. let result = {
  46227. octrees: octrees
  46228. };
  46229. return result;
  46230. }
  46231. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  46232. if (exports.measureTimings) performance.mark("renderNodes-start");
  46233. let gl = this.gl;
  46234. let material = params.material ? params.material : octree.material;
  46235. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  46236. let view = camera.matrixWorldInverse;
  46237. if(params.viewOverride){
  46238. view = params.viewOverride;
  46239. }
  46240. let worldView = new Matrix4();
  46241. let mat4holder = new Float32Array(16);
  46242. let i = 0;
  46243. for (let node of nodes) {
  46244. if(exports.debug.allowedNodes !== undefined){
  46245. if(!exports.debug.allowedNodes.includes(node.name)){
  46246. continue;
  46247. }
  46248. }
  46249. let world = node.sceneNode.matrixWorld;
  46250. worldView.multiplyMatrices(view, world);
  46251. if (visibilityTextureData) {
  46252. let vnStart = visibilityTextureData.offsets.get(node);
  46253. shader.setUniform1f("uVNStart", vnStart);
  46254. }
  46255. let level = node.getLevel();
  46256. if(node.debug){
  46257. shader.setUniform("uDebug", true);
  46258. }else {
  46259. shader.setUniform("uDebug", false);
  46260. }
  46261. // let isLeaf = false;
  46262. // if(node instanceof PointCloudOctreeNode){
  46263. // isLeaf = Object.keys(node.children).length === 0;
  46264. // }else if(node instanceof PointCloudArena4DNode){
  46265. // isLeaf = node.geometryNode.isLeaf;
  46266. // }
  46267. // shader.setUniform("uIsLeafNode", isLeaf);
  46268. // let isLeaf = node.children.filter(n => n != null).length === 0;
  46269. // if(!isLeaf){
  46270. // continue;
  46271. // }
  46272. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  46273. const lModel = shader.uniformLocations["modelMatrix"];
  46274. if (lModel) {
  46275. mat4holder.set(world.elements);
  46276. gl.uniformMatrix4fv(lModel, false, mat4holder);
  46277. }
  46278. const lModelView = shader.uniformLocations["modelViewMatrix"];
  46279. //mat4holder.set(worldView.elements);
  46280. // faster then set in chrome 63
  46281. for(let j = 0; j < 16; j++){
  46282. mat4holder[j] = worldView.elements[j];
  46283. }
  46284. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  46285. { // Clip Polygons
  46286. if(material.clipPolygons && material.clipPolygons.length > 0){
  46287. let clipPolygonVCount = [];
  46288. let worldViewProjMatrices = [];
  46289. for(let clipPolygon of material.clipPolygons){
  46290. let view = clipPolygon.viewMatrix;
  46291. let proj = clipPolygon.projMatrix;
  46292. let worldViewProj = proj.clone().multiply(view).multiply(world);
  46293. clipPolygonVCount.push(clipPolygon.markers.length);
  46294. worldViewProjMatrices.push(worldViewProj);
  46295. }
  46296. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  46297. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  46298. for(let i = 0; i < material.clipPolygons.length; i++){
  46299. let clipPolygon = material.clipPolygons[i];
  46300. for(let j = 0; j < clipPolygon.markers.length; j++){
  46301. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  46302. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  46303. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  46304. }
  46305. }
  46306. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  46307. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  46308. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  46309. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  46310. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  46311. gl.uniform3fv(lClipPolygons, flattenedVertices);
  46312. }
  46313. }
  46314. //shader.setUniformMatrix4("modelMatrix", world);
  46315. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  46316. shader.setUniform1f("uLevel", level);
  46317. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  46318. shader.setUniform1f("uPCIndex", i);
  46319. // uBBSize
  46320. if (shadowMaps.length > 0) {
  46321. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  46322. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  46323. let bindingStart = 5;
  46324. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  46325. gl.uniform1iv(lShadowMap, bindingPoints);
  46326. for (let i = 0; i < shadowMaps.length; i++) {
  46327. let shadowMap = shadowMaps[i];
  46328. let bindingPoint = bindingPoints[i];
  46329. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  46330. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  46331. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  46332. }
  46333. {
  46334. let worldViewMatrices = shadowMaps
  46335. .map(sm => sm.camera.matrixWorldInverse)
  46336. .map(view => new Matrix4().multiplyMatrices(view, world));
  46337. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  46338. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  46339. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  46340. }
  46341. {
  46342. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  46343. const lProj = shader.uniformLocations["uShadowProj[0]"];
  46344. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  46345. }
  46346. }
  46347. const geometry = node.geometryNode.geometry;
  46348. if(geometry.attributes["gps-time"]){
  46349. const bufferAttribute = geometry.attributes["gps-time"];
  46350. const attGPS = octree.getAttribute("gps-time");
  46351. let initialRange = attGPS.initialRange;
  46352. let initialRangeSize = initialRange[1] - initialRange[0];
  46353. let globalRange = attGPS.range;
  46354. let globalRangeSize = globalRange[1] - globalRange[0];
  46355. let scale = initialRangeSize / globalRangeSize;
  46356. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  46357. scale = Number.isNaN(scale) ? 1 : scale;
  46358. offset = Number.isNaN(offset) ? 0 : offset;
  46359. shader.setUniform1f("uGpsScale", scale);
  46360. shader.setUniform1f("uGpsOffset", offset);
  46361. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  46362. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  46363. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  46364. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  46365. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  46366. let normalizedClipRange = [
  46367. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  46368. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  46369. ];
  46370. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  46371. // // ranges in full gps coordinate system
  46372. // const globalRange = attGPS.range;
  46373. // const bufferRange = bufferAttribute.potree.range;
  46374. // // ranges in [0, 1]
  46375. // // normalizedGlobalRange = [0, 1]
  46376. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  46377. // const globalWidth = globalRange[1] - globalRange[0];
  46378. // const normalizedBufferRange = [
  46379. // (bufferRange[0] - globalRange[0]) / globalWidth,
  46380. // (bufferRange[1] - globalRange[0]) / globalWidth,
  46381. // ];
  46382. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  46383. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  46384. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  46385. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  46386. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  46387. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  46388. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  46389. }
  46390. {
  46391. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  46392. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  46393. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  46394. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  46395. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  46396. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  46397. }
  46398. let webglBuffer = null;
  46399. if(!this.buffers.has(geometry)){
  46400. webglBuffer = this.createBuffer(geometry);
  46401. this.buffers.set(geometry, webglBuffer);
  46402. }else {
  46403. webglBuffer = this.buffers.get(geometry);
  46404. for(let attributeName in geometry.attributes){
  46405. let attribute = geometry.attributes[attributeName];
  46406. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  46407. this.updateBuffer(geometry);
  46408. }
  46409. }
  46410. }
  46411. gl.bindVertexArray(webglBuffer.vao);
  46412. let isExtraAttribute =
  46413. attributeLocations[material.activeAttributeName] === undefined
  46414. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  46415. if(isExtraAttribute){
  46416. const attributeLocation = attributeLocations["aExtra"].location;
  46417. for(const attributeName in geometry.attributes){
  46418. const bufferAttribute = geometry.attributes[attributeName];
  46419. const vbo = webglBuffer.vbos.get(attributeName);
  46420. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46421. gl.disableVertexAttribArray(attributeLocation);
  46422. }
  46423. const attName = material.activeAttributeName;
  46424. const bufferAttribute = geometry.attributes[attName];
  46425. const vbo = webglBuffer.vbos.get(attName);
  46426. if(bufferAttribute !== undefined && vbo !== undefined){
  46427. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46428. let normalized = bufferAttribute.normalized;
  46429. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46430. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46431. gl.enableVertexAttribArray(attributeLocation);
  46432. }
  46433. {
  46434. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  46435. .find(a => a.name === attName);
  46436. let range = material.getRange(attName);
  46437. if(!range){
  46438. range = attExtra.range;
  46439. }
  46440. if(!range){
  46441. range = [0, 1];
  46442. }
  46443. let initialRange = attExtra.initialRange;
  46444. let initialRangeSize = initialRange[1] - initialRange[0];
  46445. let globalRange = range;
  46446. let globalRangeSize = globalRange[1] - globalRange[0];
  46447. let scale = initialRangeSize / globalRangeSize;
  46448. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  46449. scale = Number.isNaN(scale) ? 1 : scale;
  46450. offset = Number.isNaN(offset) ? 0 : offset;
  46451. shader.setUniform1f("uExtraScale", scale);
  46452. shader.setUniform1f("uExtraOffset", offset);
  46453. }
  46454. }else {
  46455. for(const attributeName in geometry.attributes){
  46456. const bufferAttribute = geometry.attributes[attributeName];
  46457. const vbo = webglBuffer.vbos.get(attributeName);
  46458. if(attributeLocations[attributeName] !== undefined){
  46459. const attributeLocation = attributeLocations[attributeName].location;
  46460. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46461. let normalized = bufferAttribute.normalized;
  46462. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46463. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46464. gl.enableVertexAttribArray(attributeLocation);
  46465. }
  46466. }
  46467. }
  46468. let numPoints = webglBuffer.numElements;
  46469. gl.drawArrays(gl.POINTS, 0, numPoints);
  46470. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  46471. i++;
  46472. }
  46473. gl.bindVertexArray(null);
  46474. if (exports.measureTimings) {
  46475. performance.mark("renderNodes-end");
  46476. performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end");
  46477. }
  46478. }
  46479. renderOctree(octree, nodes, camera, target, params = {}){
  46480. let gl = this.gl;
  46481. let material = params.material ? params.material : octree.material;
  46482. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  46483. let view = camera.matrixWorldInverse;
  46484. let viewInv = camera.matrixWorld;
  46485. if(params.viewOverride){
  46486. view = params.viewOverride;
  46487. viewInv = view.clone().invert();
  46488. }
  46489. let proj = camera.projectionMatrix;
  46490. let projInv = proj.clone().invert();
  46491. //let worldView = new THREE.Matrix4();
  46492. let shader = null;
  46493. let visibilityTextureData = null;
  46494. let currentTextureBindingPoint = 0;
  46495. if (material.pointSizeType >= 0) {
  46496. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  46497. material.activeAttributeName === "level of detail") {
  46498. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  46499. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  46500. const vnt = material.visibleNodesTexture;
  46501. const data = vnt.image.data;
  46502. data.set(visibilityTextureData.data);
  46503. vnt.needsUpdate = true;
  46504. }
  46505. }
  46506. { // UPDATE SHADER AND TEXTURES
  46507. if (!this.shaders.has(material)) {
  46508. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  46509. let shader = new Shader(gl, "pointcloud", vs, fs);
  46510. this.shaders.set(material, shader);
  46511. }
  46512. shader = this.shaders.get(material);
  46513. //if(material.needsUpdate){
  46514. {
  46515. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  46516. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  46517. let numClipBoxes = (material.clipBoxes && material.clipBoxes.length) ? material.clipBoxes.length : 0;
  46518. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  46519. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  46520. let defines = [
  46521. `#define num_shadowmaps ${shadowMaps.length}`,
  46522. `#define num_snapshots ${numSnapshots}`,
  46523. `#define num_clipboxes ${numClipBoxes}`,
  46524. `#define num_clipspheres ${numClipSpheres}`,
  46525. `#define num_clippolygons ${numClipPolygons}`,
  46526. ];
  46527. //add:-----------
  46528. if(material.usePanoMap){
  46529. defines.push("#define usePanoMap");
  46530. }
  46531. if(material.useFilterByNormal){
  46532. defines.push("#define use_filter_by_normal");
  46533. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  46534. }
  46535. //---------------
  46536. if(octree.pcoGeometry.root.isLoaded()){
  46537. let attributes = octree.pcoGeometry.root.geometry.attributes;
  46538. if(attributes["gps-time"]){
  46539. defines.push("#define clip_gps_enabled");
  46540. }
  46541. if(attributes["return number"]){
  46542. defines.push("#define clip_return_number_enabled");
  46543. }
  46544. if(attributes["number of returns"]){
  46545. defines.push("#define clip_number_of_returns_enabled");
  46546. }
  46547. if(attributes["source id"] || attributes["point source id"]){
  46548. defines.push("#define clip_point_source_id_enabled");
  46549. }
  46550. }
  46551. let definesString = defines.join("\n");
  46552. let vsVersionIndex = vs.indexOf("#version ");
  46553. let fsVersionIndex = fs.indexOf("#version ");
  46554. if(vsVersionIndex >= 0){
  46555. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  46556. }else {
  46557. vs = `${definesString}\n${vs}`;
  46558. }
  46559. if(fsVersionIndex >= 0){
  46560. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  46561. }else {
  46562. fs = `${definesString}\n${fs}`;
  46563. }
  46564. shader.update(vs, fs);
  46565. material.needsUpdate = false;
  46566. }
  46567. for (let uniformName of Object.keys(material.uniforms)) {
  46568. let uniform = material.uniforms[uniformName];
  46569. if (uniform.type == "t") {
  46570. let texture = uniform.value;
  46571. if (!texture) {
  46572. continue;
  46573. }
  46574. //add
  46575. if(uniformName == 'pano0Map' || uniformName == 'pano1Map' ){ //属于cubeTex,另外设置
  46576. continue
  46577. }
  46578. if (!this.textures.has(texture)) {
  46579. let webglTexture = new WebGLTexture(gl, texture);
  46580. this.textures.set(texture, webglTexture);
  46581. }
  46582. let webGLTexture = this.textures.get(texture);
  46583. webGLTexture.update();
  46584. }
  46585. }
  46586. }
  46587. gl.useProgram(shader.program);
  46588. let transparent = false;
  46589. if(params.transparent !== undefined){
  46590. transparent = params.transparent && material.opacity < 1;
  46591. }else {
  46592. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  46593. }
  46594. if (transparent){
  46595. gl.enable(gl.BLEND);
  46596. if(params.notAdditiveBlending){
  46597. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  46598. gl.enable(gl.DEPTH_TEST);
  46599. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  46600. }else {
  46601. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  46602. gl.disable(gl.DEPTH_TEST);
  46603. gl.depthMask(false);
  46604. }
  46605. } else {
  46606. gl.disable(gl.BLEND);
  46607. gl.depthMask(true);
  46608. gl.enable(gl.DEPTH_TEST);
  46609. }
  46610. if(params.blendFunc !== undefined){
  46611. gl.enable(gl.BLEND);
  46612. gl.blendFunc(...params.blendFunc);
  46613. }
  46614. if(params.depthTest !== undefined){
  46615. if(params.depthTest === true){
  46616. gl.enable(gl.DEPTH_TEST);
  46617. }else {
  46618. gl.disable(gl.DEPTH_TEST);
  46619. }
  46620. }
  46621. if(params.depthWrite !== undefined){
  46622. if(params.depthWrite === true){
  46623. gl.depthMask(true);
  46624. }else {
  46625. gl.depthMask(false);
  46626. }
  46627. }
  46628. { // UPDATE UNIFORMS
  46629. shader.setUniformMatrix4("projectionMatrix", proj);
  46630. shader.setUniformMatrix4("viewMatrix", view);
  46631. shader.setUniformMatrix4("uViewInv", viewInv);
  46632. shader.setUniformMatrix4("uProjInv", projInv);
  46633. /* let screenWidth = target ? target.width : material.screenWidth;
  46634. let screenHeight = target ? target.height : material.screenHeight;
  46635. shader.setUniform1f("uScreenWidth", screenWidth);
  46636. shader.setUniform1f("uScreenHeight", screenHeight); */
  46637. shader.setUniform2f('resolution', material.resolution.toArray());
  46638. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  46639. shader.setUniform1f("near", camera.near);
  46640. shader.setUniform1f("far", camera.far);
  46641. if(camera instanceof OrthographicCamera){
  46642. shader.setUniform("uUseOrthographicCamera", true);
  46643. shader.setUniform("uOrthoWidth", camera.right - camera.left);
  46644. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  46645. }else {
  46646. shader.setUniform("uUseOrthographicCamera", false);
  46647. }
  46648. if(material.clipBoxes.length + material.clipPolygons.length === 0){
  46649. shader.setUniform1i("clipTask", ClipTask.NONE);
  46650. }else {
  46651. shader.setUniform1i("clipTask", material.clipTask);
  46652. }
  46653. shader.setUniform1i("clipMethod", material.clipMethod);
  46654. if (material.clipBoxes && material.clipBoxes.length > 0) {
  46655. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  46656. //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  46657. //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices);
  46658. const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  46659. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value);
  46660. }
  46661. // TODO CLIPSPHERES
  46662. if(params.clipSpheres && params.clipSpheres.length > 0){
  46663. let clipSpheres = params.clipSpheres;
  46664. let matrices = [];
  46665. for(let clipSphere of clipSpheres){
  46666. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  46667. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  46668. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  46669. let clipToWorld = clipSphere.matrixWorld;
  46670. let viewToWorld = camera.matrixWorld;
  46671. let worldToClip = clipToWorld.clone().invert();
  46672. let viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  46673. matrices.push(viewToClip);
  46674. }
  46675. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  46676. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  46677. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  46678. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  46679. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  46680. }
  46681. shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio,2) : material.size);//usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点
  46682. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  46683. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  46684. // uniform float uPCIndex
  46685. shader.setUniform1f("uOctreeSpacing", material.spacing);
  46686. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  46687. //uniform vec3 uColor;
  46688. shader.setUniform3f("uColor", material.color.toArray());
  46689. //uniform float opacity;
  46690. shader.setUniform1f("uOpacity", material.usePanoMap ? 1: material.opacity);
  46691. shader.setUniform2f("elevationRange", material.elevationRange);
  46692. shader.setUniform2f("intensityRange", material.intensityRange);
  46693. shader.setUniform3f("uIntensity_gbc", [
  46694. material.intensityGamma,
  46695. material.intensityBrightness,
  46696. material.intensityContrast
  46697. ]);
  46698. shader.setUniform3f("uRGB_gbc", [
  46699. material.rgbGamma,
  46700. material.rgbBrightness,
  46701. material.rgbContrast
  46702. ]);
  46703. shader.setUniform1f("uTransition", material.transition);
  46704. shader.setUniform1f("wRGB", material.weightRGB);
  46705. shader.setUniform1f("wIntensity", material.weightIntensity);
  46706. shader.setUniform1f("wElevation", material.weightElevation);
  46707. shader.setUniform1f("wClassification", material.weightClassification);
  46708. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  46709. shader.setUniform1f("wSourceID", material.weightSourceID);
  46710. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  46711. //==========================
  46712. //gl.TEXTURE_CUBE_MAP: 34067
  46713. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  46714. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);
  46715. if(vnWebGLTexture){
  46716. shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint);
  46717. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46718. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  46719. currentTextureBindingPoint++;
  46720. }
  46721. let gradientTexture = this.textures.get(material.gradientTexture);
  46722. shader.setUniform1i("gradient", currentTextureBindingPoint);
  46723. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46724. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  46725. const repeat = material.elevationGradientRepeat;
  46726. if(repeat === ElevationGradientRepeat.REPEAT){
  46727. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  46728. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  46729. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  46730. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  46731. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  46732. }else {
  46733. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  46734. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46735. }
  46736. currentTextureBindingPoint++;
  46737. let classificationTexture = this.textures.get(material.classificationTexture);
  46738. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  46739. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46740. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  46741. currentTextureBindingPoint++;
  46742. let matcapTexture = this.textures.get(material.matcapTexture);
  46743. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  46744. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46745. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  46746. currentTextureBindingPoint++;
  46747. if (material.snapEnabled === true) {
  46748. {
  46749. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  46750. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  46751. let bindingStart = currentTextureBindingPoint;
  46752. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  46753. let lSnapshotDepthBindingPoints = new Array(5)
  46754. .fill(1 + Math.max(...lSnapshotBindingPoints))
  46755. .map((a, i) => (a + i));
  46756. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  46757. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  46758. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  46759. for (let i = 0; i < 5; i++) {
  46760. let texture = material.uniforms[`uSnapshot`].value[i];
  46761. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  46762. if (!texture) {
  46763. break;
  46764. }
  46765. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  46766. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  46767. let bindingPoint = lSnapshotBindingPoints[i];
  46768. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  46769. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  46770. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  46771. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  46772. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  46773. }
  46774. }
  46775. {
  46776. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  46777. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  46778. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  46779. }
  46780. {
  46781. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  46782. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  46783. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  46784. }
  46785. {
  46786. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  46787. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  46788. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  46789. }
  46790. {
  46791. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  46792. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  46793. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  46794. }
  46795. }
  46796. //=============add===========
  46797. if(material.usePanoMap){//为什么pointsize失效
  46798. shader.setUniform1f("progress", material.uniforms.progress.value);
  46799. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  46800. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  46801. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  46802. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  46803. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  46804. let pano0Map = material.uniforms.pano0Map.value;
  46805. if(pano0Map){
  46806. this.threeRenderer._textures.safeSetTextureCube( pano0Map, ++currentTextureBindingPoint );
  46807. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  46808. }
  46809. let pano1Map = material.uniforms.pano1Map.value;
  46810. if(pano1Map){
  46811. this.threeRenderer._textures.safeSetTextureCube( pano1Map, ++currentTextureBindingPoint );
  46812. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  46813. }
  46814. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  46815. }
  46816. }
  46817. this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params);
  46818. gl.activeTexture(gl.TEXTURE2);
  46819. gl.bindTexture(gl.TEXTURE_2D, null);
  46820. gl.activeTexture(gl.TEXTURE0);
  46821. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  46822. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  46823. gl.disable(gl.BLEND);
  46824. gl.depthMask(true);
  46825. gl.enable(gl.DEPTH_TEST);
  46826. //DEPTH_TEST等需要恢复吗
  46827. }
  46828. render(scene, camera, target = null, params = {}) {
  46829. const gl = this.gl;
  46830. // PREPARE
  46831. if (target != null) {
  46832. this.threeRenderer.setRenderTarget(target);
  46833. }
  46834. //camera.updateProjectionMatrix();
  46835. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  46836. const traversalResult = this.traverse(scene);
  46837. //排序
  46838. if(Potree.settings.notAdditiveBlending){//add
  46839. traversalResult.octrees.forEach(tree=>{
  46840. if(tree.material.opacity==1){
  46841. tree._z = Infinity; //不透明的先渲染
  46842. }else {
  46843. let center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld);
  46844. center.project(camera);
  46845. tree._z = center.z;
  46846. }
  46847. });
  46848. traversalResult.octrees.sort((tree1,tree2)=>{
  46849. return tree2._z - tree1._z //降序 (-1 朝外)。 离屏幕近的后渲染
  46850. });
  46851. }
  46852. // RENDER
  46853. for (const octree of traversalResult.octrees) {
  46854. let nodes = octree.visibleNodes;
  46855. /* nodes.sort((node1,node2)=>{//姑且
  46856. let center = node.getBoundingSphere().center.clone().applyMatrix4(octree.matrixWorld)
  46857. return
  46858. }) */
  46859. this.renderOctree(octree, nodes, camera, target, params);
  46860. }
  46861. // CLEANUP
  46862. gl.activeTexture(gl.TEXTURE1);
  46863. gl.bindTexture(gl.TEXTURE_2D, null);
  46864. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46865. gl.bindVertexArray(null);
  46866. this.threeRenderer.resetState();
  46867. }
  46868. };
  46869. /*
  46870. 中东的链接http://indoor.popsmart.cn:8094/zdoblh-yz/?vlon=5.14&vlat=-0.13&fov=100.0&pc=true&lon=121.61136592&lat=29.87855579&z=16.577
  46871. geometry: 有的attributes: 属性是:
  46872. classification:
  46873. color:
  46874. indices:
  46875. normal:
  46876. position:
  46877. 最好有个spacing
  46878. */
  46879. class ProfileData {
  46880. constructor (profile) {
  46881. this.profile = profile;
  46882. this.segments = [];
  46883. this.boundingBox = new Box3();
  46884. for (let i = 0; i < profile.points.length - 1; i++) {
  46885. let start = profile.points[i];
  46886. let end = profile.points[i + 1];
  46887. let startGround = new Vector3(start.x, start.y, 0);
  46888. let endGround = new Vector3(end.x, end.y, 0);
  46889. let center = new Vector3().addVectors(endGround, startGround).multiplyScalar(0.5);
  46890. let length = startGround.distanceTo(endGround);
  46891. let side = new Vector3().subVectors(endGround, startGround).normalize();
  46892. let up = new Vector3(0, 0, 1);
  46893. let forward = new Vector3().crossVectors(side, up).normalize();
  46894. let N = forward;
  46895. let cutPlane = new Plane().setFromNormalAndCoplanarPoint(N, startGround);
  46896. let halfPlane = new Plane().setFromNormalAndCoplanarPoint(side, center);
  46897. let segment = {
  46898. start: start,
  46899. end: end,
  46900. cutPlane: cutPlane,
  46901. halfPlane: halfPlane,
  46902. length: length,
  46903. points: new Points$1()
  46904. };
  46905. this.segments.push(segment);
  46906. }
  46907. }
  46908. size () {
  46909. let size = 0;
  46910. for (let segment of this.segments) {
  46911. size += segment.points.numPoints;
  46912. }
  46913. return size;
  46914. }
  46915. };
  46916. class ProfileRequest {
  46917. constructor (pointcloud, profile, maxDepth, callback) {
  46918. this.pointcloud = pointcloud;
  46919. this.profile = profile;
  46920. this.maxDepth = maxDepth || Number.MAX_VALUE;
  46921. this.callback = callback;
  46922. this.temporaryResult = new ProfileData(this.profile);
  46923. this.pointsServed = 0;
  46924. this.highestLevelServed = 0;
  46925. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  46926. this.initialize();
  46927. }
  46928. initialize () {
  46929. this.priorityQueue.push({node: this.pointcloud.pcoGeometry.root, weight: Infinity});
  46930. };
  46931. // traverse the node and add intersecting descendants to queue
  46932. traverse (node) {
  46933. let stack = [];
  46934. for (let i = 0; i < 8; i++) {
  46935. let child = node.children[i];
  46936. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  46937. stack.push(child);
  46938. }
  46939. }
  46940. while (stack.length > 0) {
  46941. let node = stack.pop();
  46942. let weight = node.boundingSphere.radius;
  46943. this.priorityQueue.push({node: node, weight: weight});
  46944. // add children that intersect the cutting plane
  46945. if (node.level < this.maxDepth) {
  46946. for (let i = 0; i < 8; i++) {
  46947. let child = node.children[i];
  46948. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  46949. stack.push(child);
  46950. }
  46951. }
  46952. }
  46953. }
  46954. }
  46955. update(){
  46956. if(!this.updateGeneratorInstance){
  46957. this.updateGeneratorInstance = this.updateGenerator();
  46958. }
  46959. let result = this.updateGeneratorInstance.next();
  46960. if(result.done){
  46961. this.updateGeneratorInstance = null;
  46962. }
  46963. }
  46964. * updateGenerator(){
  46965. // load nodes in queue
  46966. // if hierarchy expands, also load nodes from expanded hierarchy
  46967. // once loaded, add data to this.points and remove node from queue
  46968. // only evaluate 1-50 nodes per frame to maintain responsiveness
  46969. let start = performance.now();
  46970. let maxNodesPerUpdate = 1;
  46971. let intersectedNodes = [];
  46972. for (let i = 0; i < Math.min(maxNodesPerUpdate, this.priorityQueue.size()); i++) {
  46973. let element = this.priorityQueue.pop();
  46974. let node = element.node;
  46975. if(node.level > this.maxDepth){
  46976. continue;
  46977. }
  46978. if (node.loaded) {
  46979. // add points to result
  46980. intersectedNodes.push(node);
  46981. exports.lru.touch(node);
  46982. this.highestLevelServed = Math.max(node.getLevel(), this.highestLevelServed);
  46983. var geom = node.pcoGeometry;
  46984. var hierarchyStepSize = geom ? geom.hierarchyStepSize : 1;
  46985. var doTraverse = node.getLevel() === 0 ||
  46986. (node.level % hierarchyStepSize === 0 && node.hasChildren);
  46987. if (doTraverse) {
  46988. this.traverse(node);
  46989. }
  46990. } else {
  46991. node.load();
  46992. this.priorityQueue.push(element);
  46993. }
  46994. }
  46995. if (intersectedNodes.length > 0) {
  46996. for(let done of this.getPointsInsideProfile(intersectedNodes, this.temporaryResult)){
  46997. if(!done){
  46998. //console.log("updateGenerator yields");
  46999. yield false;
  47000. }
  47001. }
  47002. if (this.temporaryResult.size() > 100) {
  47003. this.pointsServed += this.temporaryResult.size();
  47004. this.callback.onProgress({request: this, points: this.temporaryResult});
  47005. this.temporaryResult = new ProfileData(this.profile);
  47006. }
  47007. }
  47008. if (this.priorityQueue.size() === 0) {
  47009. // we're done! inform callback and remove from pending requests
  47010. if (this.temporaryResult.size() > 0) {
  47011. this.pointsServed += this.temporaryResult.size();
  47012. this.callback.onProgress({request: this, points: this.temporaryResult});
  47013. this.temporaryResult = new ProfileData(this.profile);
  47014. }
  47015. this.callback.onFinish({request: this});
  47016. let index = this.pointcloud.profileRequests.indexOf(this);
  47017. if (index >= 0) {
  47018. this.pointcloud.profileRequests.splice(index, 1);
  47019. }
  47020. }
  47021. yield true;
  47022. };
  47023. * getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage){
  47024. let checkpoint = performance.now();
  47025. let accepted = new Uint32Array(numPoints);
  47026. let mileage = new Float64Array(numPoints);
  47027. let acceptedPositions = new Float32Array(numPoints * 3);
  47028. let numAccepted = 0;
  47029. let pos = new Vector3();
  47030. let svp = new Vector3();
  47031. let view = new Float32Array(node.geometry.attributes.position.array);
  47032. for (let i = 0; i < numPoints; i++) {
  47033. pos.set(
  47034. view[i * 3 + 0],
  47035. view[i * 3 + 1],
  47036. view[i * 3 + 2]);
  47037. pos.applyMatrix4(matrix);
  47038. let distance = Math.abs(segment.cutPlane.distanceToPoint(pos));
  47039. let centerDistance = Math.abs(segment.halfPlane.distanceToPoint(pos));
  47040. if (distance < this.profile.width / 2 && centerDistance < segment.length / 2) {
  47041. svp.subVectors(pos, segment.start);
  47042. let localMileage = segmentDir.dot(svp);
  47043. accepted[numAccepted] = i;
  47044. mileage[numAccepted] = localMileage + totalMileage;
  47045. points.boundingBox.expandByPoint(pos);
  47046. pos.sub(this.pointcloud.position);
  47047. acceptedPositions[3 * numAccepted + 0] = pos.x;
  47048. acceptedPositions[3 * numAccepted + 1] = pos.y;
  47049. acceptedPositions[3 * numAccepted + 2] = pos.z;
  47050. numAccepted++;
  47051. }
  47052. if((i % 1000) === 0){
  47053. let duration = performance.now() - checkpoint;
  47054. if(duration > 4){
  47055. //console.log(`getAccepted yield after ${duration}ms`);
  47056. yield false;
  47057. checkpoint = performance.now();
  47058. }
  47059. }
  47060. }
  47061. accepted = accepted.subarray(0, numAccepted);
  47062. mileage = mileage.subarray(0, numAccepted);
  47063. acceptedPositions = acceptedPositions.subarray(0, numAccepted * 3);
  47064. //let end = performance.now();
  47065. //let duration = end - start;
  47066. //console.log("accepted duration ", duration)
  47067. //console.log(`getAccepted finished`);
  47068. yield [accepted, mileage, acceptedPositions];
  47069. }
  47070. * getPointsInsideProfile(nodes, target){
  47071. let checkpoint = performance.now();
  47072. let totalMileage = 0;
  47073. let pointsProcessed = 0;
  47074. for (let segment of target.segments) {
  47075. for (let node of nodes) {
  47076. let numPoints = node.numPoints;
  47077. let geometry = node.geometry;
  47078. if(!numPoints){
  47079. continue;
  47080. }
  47081. { // skip if current node doesn't intersect current segment
  47082. let bbWorld = node.boundingBox.clone().applyMatrix4(this.pointcloud.matrixWorld);
  47083. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  47084. let start = new Vector3(segment.start.x, segment.start.y, bsWorld.center.z);
  47085. let end = new Vector3(segment.end.x, segment.end.y, bsWorld.center.z);
  47086. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  47087. let distance = closest.distanceTo(bsWorld.center);
  47088. let intersects = (distance < (bsWorld.radius + target.profile.width));
  47089. if(!intersects){
  47090. continue;
  47091. }
  47092. }
  47093. //{// DEBUG
  47094. // console.log(node.name);
  47095. // let boxHelper = new Potree.Box3Helper(node.getBoundingBox());
  47096. // boxHelper.matrixAutoUpdate = false;
  47097. // boxHelper.matrix.copy(viewer.scene.pointclouds[0].matrixWorld);
  47098. // viewer.scene.scene.add(boxHelper);
  47099. //}
  47100. let sv = new Vector3().subVectors(segment.end, segment.start).setZ(0);
  47101. let segmentDir = sv.clone().normalize();
  47102. let points = new Points$1();
  47103. let nodeMatrix = new Matrix4().makeTranslation(...node.boundingBox.min.toArray());
  47104. let matrix = new Matrix4().multiplyMatrices(
  47105. this.pointcloud.matrixWorld, nodeMatrix);
  47106. pointsProcessed = pointsProcessed + numPoints;
  47107. let accepted = null;
  47108. let mileage = null;
  47109. let acceptedPositions = null;
  47110. for(let result of this.getAccepted(numPoints, node, matrix, segment, segmentDir, points,totalMileage)){
  47111. if(!result){
  47112. let duration = performance.now() - checkpoint;
  47113. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  47114. yield false;
  47115. checkpoint = performance.now();
  47116. }else {
  47117. [accepted, mileage, acceptedPositions] = result;
  47118. }
  47119. }
  47120. let duration = performance.now() - checkpoint;
  47121. if(duration > 4){
  47122. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  47123. yield false;
  47124. checkpoint = performance.now();
  47125. }
  47126. points.data.position = acceptedPositions;
  47127. let relevantAttributes = Object.keys(geometry.attributes).filter(a => !["position", "indices"].includes(a));
  47128. for(let attributeName of relevantAttributes){
  47129. let attribute = geometry.attributes[attributeName];
  47130. let numElements = attribute.array.length / numPoints;
  47131. if(numElements !== parseInt(numElements)){
  47132. debugger;
  47133. }
  47134. let Type = attribute.array.constructor;
  47135. let filteredBuffer = new Type(numElements * accepted.length);
  47136. let source = attribute.array;
  47137. let target = filteredBuffer;
  47138. for(let i = 0; i < accepted.length; i++){
  47139. let index = accepted[i];
  47140. let start = index * numElements;
  47141. let end = start + numElements;
  47142. let sub = source.subarray(start, end);
  47143. target.set(sub, i * numElements);
  47144. }
  47145. points.data[attributeName] = filteredBuffer;
  47146. }
  47147. points.data['mileage'] = mileage;
  47148. points.numPoints = accepted.length;
  47149. segment.points.add(points);
  47150. }
  47151. totalMileage += segment.length;
  47152. }
  47153. for (let segment of target.segments) {
  47154. target.boundingBox.union(segment.points.boundingBox);
  47155. }
  47156. //console.log(`getPointsInsideProfile finished`);
  47157. yield true;
  47158. };
  47159. finishLevelThenCancel () {
  47160. if (this.cancelRequested) {
  47161. return;
  47162. }
  47163. this.maxDepth = this.highestLevelServed;
  47164. this.cancelRequested = true;
  47165. //console.log(`maxDepth: ${this.maxDepth}`);
  47166. };
  47167. cancel () {
  47168. this.callback.onCancel();
  47169. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  47170. let index = this.pointcloud.profileRequests.indexOf(this);
  47171. if (index >= 0) {
  47172. this.pointcloud.profileRequests.splice(index, 1);
  47173. }
  47174. };
  47175. }
  47176. class Version{
  47177. constructor(version){
  47178. this.version = version;
  47179. let vmLength = (version.indexOf('.') === -1) ? version.length : version.indexOf('.');
  47180. this.versionMajor = parseInt(version.substr(0, vmLength));
  47181. this.versionMinor = parseInt(version.substr(vmLength + 1));
  47182. if (this.versionMinor.length === 0) {
  47183. this.versionMinor = 0;
  47184. }
  47185. }
  47186. newerThan(version){
  47187. let v = new Version(version);
  47188. if (this.versionMajor > v.versionMajor) {
  47189. return true;
  47190. } else if (this.versionMajor === v.versionMajor && this.versionMinor > v.versionMinor) {
  47191. return true;
  47192. } else {
  47193. return false;
  47194. }
  47195. }
  47196. equalOrHigher(version){
  47197. let v = new Version(version);
  47198. if (this.versionMajor > v.versionMajor) {
  47199. return true;
  47200. } else if (this.versionMajor === v.versionMajor && this.versionMinor >= v.versionMinor) {
  47201. return true;
  47202. } else {
  47203. return false;
  47204. }
  47205. }
  47206. upTo(version){
  47207. return !this.newerThan(version);
  47208. }
  47209. }
  47210. class WorkerPool{
  47211. constructor(){
  47212. this.workers = {};
  47213. }
  47214. getWorker(url){
  47215. if (!this.workers[url]){
  47216. this.workers[url] = [];
  47217. }
  47218. if (this.workers[url].length === 0){
  47219. let worker = new Worker(url);
  47220. this.workers[url].push(worker);
  47221. }
  47222. let worker = this.workers[url].pop();
  47223. return worker;
  47224. }
  47225. returnWorker(url, worker){
  47226. this.workers[url].push(worker);
  47227. }
  47228. };
  47229. //Potree.workerPool = new Potree.WorkerPool();
  47230. function createPointcloudData(pointcloud) {
  47231. let material = pointcloud.material;
  47232. let ranges = [];
  47233. for(let [name, value] of material.ranges){
  47234. ranges.push({
  47235. name: name,
  47236. value: value,
  47237. });
  47238. }
  47239. if(typeof material.elevationRange[0] === "number"){
  47240. ranges.push({
  47241. name: "elevationRange",
  47242. value: material.elevationRange,
  47243. });
  47244. }
  47245. if(typeof material.intensityRange[0] === "number"){
  47246. ranges.push({
  47247. name: "intensityRange",
  47248. value: material.intensityRange,
  47249. });
  47250. }
  47251. let pointSizeTypeName = Object.entries(Potree.PointSizeType).find(e => e[1] === material.pointSizeType)[0];
  47252. let jsonMaterial = {
  47253. activeAttributeName: material.activeAttributeName,
  47254. ranges: ranges,
  47255. size: material.size,
  47256. minSize: material.minSize,
  47257. pointSizeType: pointSizeTypeName,
  47258. matcap: material.matcap,
  47259. };
  47260. const pcdata = {
  47261. name: pointcloud.name,
  47262. url: pointcloud.pcoGeometry.url,
  47263. position: pointcloud.position.toArray(),
  47264. rotation: pointcloud.rotation.toArray(),
  47265. scale: pointcloud.scale.toArray(),
  47266. material: jsonMaterial,
  47267. };
  47268. return pcdata;
  47269. }
  47270. function createProfileData(profile){
  47271. const data = {
  47272. uuid: profile.uuid,
  47273. name: profile.name,
  47274. points: profile.points.map(p => p.toArray()),
  47275. height: profile.height,
  47276. width: profile.width,
  47277. };
  47278. return data;
  47279. }
  47280. function createVolumeData(volume){
  47281. const data = {
  47282. uuid: volume.uuid,
  47283. type: volume.constructor.name,
  47284. name: volume.name,
  47285. position: volume.position.toArray(),
  47286. rotation: volume.rotation.toArray(),
  47287. scale: volume.scale.toArray(),
  47288. visible: volume.visible,
  47289. clip: volume.clip,
  47290. };
  47291. return data;
  47292. }
  47293. function createCameraAnimationData(animation){
  47294. const controlPoints = animation.controlPoints.map( cp => {
  47295. const cpdata = {
  47296. position: cp.position.toArray(),
  47297. target: cp.target.toArray(),
  47298. };
  47299. return cpdata;
  47300. });
  47301. const data = {
  47302. uuid: animation.uuid,
  47303. name: animation.name,
  47304. duration: animation.duration,
  47305. t: animation.t,
  47306. curveType: animation.curveType,
  47307. visible: animation.visible,
  47308. controlPoints: controlPoints,
  47309. };
  47310. return data;
  47311. }
  47312. function createMeasurementData(measurement){
  47313. /* const data = {
  47314. uuid: measurement.uuid,
  47315. name: measurement.name,
  47316. measureType:measurement.measureType, //add
  47317. direction:measurement.direction,//add
  47318. minMarkers:measurement.minMarkers,//add
  47319. maxMarkers: measurement.maxMarkers,//add
  47320. isRect: measurement.isRect,//add
  47321. faceDirection: measurement.faceDirection,//add
  47322. points: measurement.points.map(p => p.position.toArray()),
  47323. showDistances: measurement.showDistances,
  47324. showCoordinates: measurement.showCoordinates,
  47325. showArea: measurement.showArea,
  47326. closed: measurement.closed,
  47327. showAngles: measurement.showAngles,
  47328. showHeight: measurement.showHeight,
  47329. showCircle: measurement.showCircle,
  47330. showAzimuth: measurement.showAzimuth,
  47331. showEdges: measurement.showEdges,
  47332. color: measurement.color.toArray(),
  47333. }; */
  47334. const data = {
  47335. uuid: measurement.uuid,
  47336. name: measurement.name,
  47337. measureType:measurement.measureType, //add
  47338. points: measurement.points.map(p => p.toArray()),
  47339. };
  47340. return data;
  47341. }
  47342. function createOrientedImagesData(images){
  47343. const data = {
  47344. cameraParamsPath: images.cameraParamsPath,
  47345. imageParamsPath: images.imageParamsPath,
  47346. };
  47347. return data;
  47348. }
  47349. function createGeopackageData(geopackage){
  47350. const data = {
  47351. path: geopackage.path,
  47352. };
  47353. return data;
  47354. }
  47355. function createAnnotationData(annotation){
  47356. const data = {
  47357. uuid: annotation.uuid,
  47358. title: annotation.title.toString(),
  47359. description: annotation.description,
  47360. position: annotation.position.toArray(),
  47361. offset: annotation.offset.toArray(),
  47362. children: [],
  47363. };
  47364. if(annotation.cameraPosition){
  47365. data.cameraPosition = annotation.cameraPosition.toArray();
  47366. }
  47367. if(annotation.cameraTarget){
  47368. data.cameraTarget = annotation.cameraTarget.toArray();
  47369. }
  47370. if(typeof annotation.radius !== "undefined"){
  47371. data.radius = annotation.radius;
  47372. }
  47373. return data;
  47374. }
  47375. function createAnnotationsData(viewer){
  47376. const map = new Map();
  47377. viewer.scene.annotations.traverseDescendants(a => {
  47378. const aData = createAnnotationData(a);
  47379. map.set(a, aData);
  47380. });
  47381. for(const [annotation, data] of map){
  47382. for(const child of annotation.children){
  47383. const childData = map.get(child);
  47384. data.children.push(childData);
  47385. }
  47386. }
  47387. const annotations = viewer.scene.annotations.children.map(a => map.get(a));
  47388. return annotations;
  47389. }
  47390. function createSettingsData(viewer){
  47391. return {
  47392. pointBudget: viewer.getPointBudget(),
  47393. fov: viewer.getFOV(),
  47394. edlEnabled: viewer.getEDLEnabled(),
  47395. edlRadius: viewer.getEDLRadius(),
  47396. edlStrength: viewer.getEDLStrength(),
  47397. background: viewer.getBackground(),
  47398. minNodeSize: viewer.getMinNodeSize(),
  47399. showBoundingBoxes: viewer.getShowBoundingBox(),
  47400. };
  47401. }
  47402. function createSceneContentData(viewer){
  47403. const data = [];
  47404. const potreeObjects = [];
  47405. viewer.scene.scene.traverse(node => {
  47406. if(node.potree){
  47407. potreeObjects.push(node);
  47408. }
  47409. });
  47410. for(const object of potreeObjects){
  47411. if(object.potree.file){
  47412. const saveObject = {
  47413. file: object.potree.file,
  47414. };
  47415. data.push(saveObject);
  47416. }
  47417. }
  47418. return data;
  47419. }
  47420. function createViewData(viewer){
  47421. const view = viewer.scene.view;
  47422. const data = {
  47423. position: view.position.toArray(),
  47424. target: view.getPivot().toArray(),
  47425. };
  47426. return data;
  47427. }
  47428. function createClassificationData(viewer){
  47429. const classifications = viewer.classifications;
  47430. const data = classifications;
  47431. return data;
  47432. }
  47433. function saveProject(viewer) {
  47434. const scene = viewer.scene;
  47435. const data = {
  47436. type: "Potree",
  47437. version: 1.7,
  47438. settings: createSettingsData(viewer),
  47439. view: createViewData(viewer),
  47440. classification: createClassificationData(viewer),
  47441. pointclouds: scene.pointclouds.map(createPointcloudData),
  47442. measurements: scene.measurements.map(createMeasurementData),
  47443. volumes: scene.volumes.map(createVolumeData),
  47444. cameraAnimations: scene.cameraAnimations.map(createCameraAnimationData),
  47445. profiles: scene.profiles.map(createProfileData),
  47446. annotations: createAnnotationsData(viewer),
  47447. orientedImages: scene.orientedImages.map(createOrientedImagesData),
  47448. geopackages: scene.geopackages.map(createGeopackageData),
  47449. // objects: createSceneContentData(viewer),
  47450. };
  47451. return data;
  47452. }
  47453. class HandleSvg extends EventDispatcher{
  47454. constructor(position, color){
  47455. super();
  47456. this.position = position;
  47457. this.color = '#'+new Color(color).getHexString();
  47458. this.svg = this.create();
  47459. this.visible_ = true;
  47460. let update = ()=>{
  47461. this.update();
  47462. };
  47463. viewer.addEventListener("camera_changed", update);
  47464. this.addEventListener('dispose', ()=>{
  47465. viewer.removeEventListener("camera_changed", update);
  47466. });
  47467. }
  47468. create(){
  47469. const svgns = "http://www.w3.org/2000/svg";
  47470. const svg = document.createElementNS(svgns, "svg");
  47471. svg.setAttribute("width", "2em");
  47472. svg.setAttribute("height", "2em");
  47473. svg.setAttribute("position", "absolute");
  47474. svg.style.left = "50px";
  47475. svg.style.top = "50px";
  47476. svg.style.position = "absolute";
  47477. svg.style.zIndex = "10000";
  47478. svg.style.cursor = 'grab';
  47479. svg.style.transform = 'translate(-50%,-50%)';
  47480. const circle = document.createElementNS(svgns, 'circle');
  47481. circle.setAttributeNS(null, 'cx', "1em");
  47482. circle.setAttributeNS(null, 'cy', "1em");
  47483. circle.setAttributeNS(null, 'r', "0.5em");
  47484. circle.setAttributeNS(null, 'style', 'fill: '+this.color+'; stroke: black; stroke-width: 0.2em;' );
  47485. svg.appendChild(circle);
  47486. const element = viewer.renderer.domElement.parentElement;
  47487. element.appendChild(svg);
  47488. const startDrag = (evt) => {
  47489. /* if(evt.button === THREE.MOUSE.RIGHT){
  47490. return
  47491. } */
  47492. this.selectedElement = svg;
  47493. document.addEventListener("mousemove", drag);
  47494. };
  47495. const endDrag = (evt) => {
  47496. this.selectedElement = null;
  47497. document.removeEventListener("mousemove", drag);
  47498. };
  47499. const drag = (evt) => {
  47500. if (this.selectedElement) {
  47501. evt.preventDefault();
  47502. const rect = viewer.renderer.domElement.getBoundingClientRect();
  47503. const x = evt.clientX - rect.x;
  47504. const y = evt.clientY - rect.y;
  47505. const {width, height} = viewer.renderer.getSize(new Vector2$1());
  47506. const camera = viewer.scene.getActiveCamera();
  47507. const projected = this.position.clone().project(camera);
  47508. projected.x = ((x / width) - 0.5) / 0.5;
  47509. projected.y = (-(y - height) / height - 0.5) / 0.5;
  47510. const unprojected = projected.clone().unproject(camera);
  47511. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  47512. this.update();
  47513. this.dispatchEvent({type:'dragged', position: this.position});
  47514. }
  47515. };
  47516. svg.addEventListener('mousedown', startDrag);
  47517. svg.addEventListener('mouseup', endDrag);
  47518. svg.style.display = this.visible ? "" : "none";
  47519. this.addEventListener('dispose',()=>{
  47520. svg.removeEventListener('mousedown', startDrag);
  47521. svg.removeEventListener('mouseup', endDrag);
  47522. });
  47523. return svg
  47524. }
  47525. set visible(v){
  47526. this.visible_ = v;
  47527. if(v){
  47528. this.update();
  47529. }else {
  47530. this.svg.style.display = "none";
  47531. }
  47532. }
  47533. get visible(){
  47534. return this.visible_
  47535. }
  47536. update(){
  47537. if(!this.visible)return
  47538. let camera = viewer.scene.getActiveCamera();
  47539. var p = Potree.Utils.getPos2d( this.position, camera , viewer.renderArea, viewer.mainViewport);
  47540. if(!p.trueSide){
  47541. return this.svg.style.display = 'none';
  47542. }
  47543. this.svg.style.left = p.posInViewport.x;
  47544. this.svg.style.top = p.posInViewport.y;
  47545. this.svg.style.display = '';
  47546. }
  47547. dispose(){
  47548. this.svg.remove();
  47549. this.dispatchEvent('dispose');
  47550. }
  47551. }
  47552. /*
  47553. 两种拖拽方式:
  47554. 1 只依附在点云上
  47555. 2 平行于镜头view移动 */
  47556. const geo$1 = new PlaneBufferGeometry(1,1);
  47557. class HandleSprite extends Sprite$1{
  47558. constructor(position,options={}){
  47559. options.sizeInfo = {width2d:60};
  47560. super(options);
  47561. this.position.copy(position);
  47562. this.dragStyle = options.dragStyle || 'default'; //'default'||'onPointCloud'
  47563. this.bindEvent();
  47564. }
  47565. bindEvent(){
  47566. let projectedStart, pointerStart;
  47567. const drag = (e)=>{
  47568. /* if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  47569. viewer.dispatchEvent({
  47570. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  47571. })
  47572. return
  47573. } */
  47574. const camera = viewer.scene.getActiveCamera();
  47575. if(projectedStart){
  47576. let move2d = new Vector2$1().subVectors(e.pointer, pointerStart);
  47577. let projectNow = projectedStart.clone();
  47578. projectNow.x += move2d.x;
  47579. projectNow.y += move2d.y;
  47580. let unprojected = projectNow.clone().unproject(camera);
  47581. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  47582. }else {
  47583. projectedStart = this.position.clone().project(camera);
  47584. pointerStart = e.pointer.clone();
  47585. }
  47586. this.update();
  47587. this.dispatchEvent({type:'dragged', position: this.position });
  47588. };
  47589. const drop = (e)=>{
  47590. projectedStart = null, pointerStart = null;
  47591. };
  47592. const mouseover = (e) => {
  47593. viewer.dispatchEvent({
  47594. type : "CursorChange", action : "add", name:"markerMove"
  47595. });
  47596. };
  47597. const mouseleave = (e) => {
  47598. viewer.dispatchEvent({
  47599. type : "CursorChange", action : "remove", name:"markerMove"
  47600. });
  47601. };
  47602. this.addEventListener('drag', drag);
  47603. this.addEventListener('drop', drop);
  47604. this.addEventListener('mouseover', mouseover);
  47605. this.addEventListener('mouseleave', mouseleave);
  47606. }
  47607. }
  47608. const sphere = new Mesh(new SphereBufferGeometry(0.08,0.08,3,2), new MeshBasicMaterial({color:'#f88'}));
  47609. class CurveCtrl extends Object3D {
  47610. constructor(points, lineMat, color, name, options={}){
  47611. super();
  47612. this.curve = new CatmullRomCurve3(points, false, "centripetal" /* , tension */);
  47613. this.name = name || 'curveNode';
  47614. this.handleMat = options.handleMat;
  47615. this.lineMat = lineMat;
  47616. this.createPath();
  47617. this.color = color;
  47618. this.handles = [];
  47619. this.wholeLength = 0;
  47620. this.viewports = options.viewports || [viewer.mainViewport]; //for HandleSprite
  47621. for(let i=0,j=this.points.length; i<j;i++){
  47622. this.handles.push(this.createHandle(this.points[i]));
  47623. }
  47624. this.visible_ = true;
  47625. if(Potree.settings.isTest){
  47626. this.spheres = new Object3D;
  47627. /* let i = Count+1;
  47628. while(i>0){
  47629. this.spheres.add(sphere.clone());
  47630. i--;
  47631. } */
  47632. this.add(this.spheres);
  47633. }
  47634. this.updatePath();
  47635. }
  47636. addPoint(position, index, ifUpdate){
  47637. let length = this.points.length;
  47638. if(index == void 0 ){
  47639. index = length;
  47640. }
  47641. let handle = this.createHandle(position);
  47642. this.handles = [...this.handles.slice(0,index), handle, ...this.handles.slice(index,length)];
  47643. this.points = [...this.points.slice(0,index), position, ...this.points.slice(index,length)];
  47644. ifUpdate && (this.updatePath(), this.updateHandle(index));
  47645. }
  47646. removePoint(index){
  47647. let handle = this.handles[index];
  47648. handle.dispose();
  47649. this.handles.splice(index,1);
  47650. this.points.splice(index,1);
  47651. this.updatePath();
  47652. }
  47653. createPath(){
  47654. const line = LineDraw.createFatLine( [ ],this.lineMat);
  47655. this.line = line;
  47656. this.add(line);
  47657. }
  47658. updatePath(){
  47659. this.curve.needsUpdate = true; //如果不更新,得到的点不均匀,开头点少。
  47660. let points, length = this.points.length;
  47661. this.wholeLength = this.points.reduce((total, currentValue, currentIndex, arr)=>{ //所有端点的距离总和
  47662. if(currentIndex == 0)return 0
  47663. return total + currentValue.distanceTo(arr[currentIndex-1]);
  47664. },0);
  47665. if(length > 1){
  47666. const count = MathUtils.clamp(Math.ceil(this.wholeLength * 5), 30, 500);
  47667. points = this.curve.getSpacedPoints( count );
  47668. if(this.needsPercent){ //获取每个节点在整条中的百分比,便于定位(但不精确)
  47669. this.pointsPercent = [0];
  47670. let sums = [0];
  47671. let sum = 0, last = points[0];
  47672. for(let i=1;i<length;i++){
  47673. let point = this.points[i];
  47674. sum += point.distanceTo(last); //参考getLengths函数,根据长度得到百分比
  47675. last = point;
  47676. sums.push(sum);
  47677. }
  47678. for(let i=1;i<length;i++){
  47679. this.pointsPercent.push(sum == 0 ? i/length : sums[i] / sum);
  47680. }
  47681. }
  47682. if(Potree.settings.isTest){
  47683. this.spheres.children.forEach(e=>e.visible = false);
  47684. points.forEach((e,i)=>{
  47685. let sphere1 = this.spheres.children[i];
  47686. if(!sphere1){
  47687. sphere1 = sphere.clone();
  47688. this.spheres.add(sphere1);
  47689. }
  47690. sphere1.position.copy(e);
  47691. sphere1.visible = true;
  47692. });
  47693. }
  47694. }else {
  47695. points = [];
  47696. }
  47697. LineDraw.updateLine(this.line, points);
  47698. this.dispatchEvent('updatePath');
  47699. }
  47700. createHandle(position){
  47701. if(this.handleMat){
  47702. var handle = new HandleSprite(position, {mat:this.handleMat, viewports:this.viewports});
  47703. this.add(handle);
  47704. }else {
  47705. var handle = new HandleSvg(position, this.color);
  47706. }
  47707. handle.visible = this.visible;
  47708. handle.addEventListener('dragged',(e)=>{
  47709. let index = this.handles.indexOf(handle);
  47710. this.points[index].copy(e.position);
  47711. this.updatePath();
  47712. this.dispatchEvent({type:'dragCurvePoint', index});
  47713. });
  47714. return handle
  47715. }
  47716. updateHandle(index){
  47717. if(!this.visible)return
  47718. this.handles[index].update();
  47719. }
  47720. updateHandles(){
  47721. this.handles.forEach((handle,index)=>{
  47722. this.updateHandle(index);
  47723. });
  47724. }
  47725. update(){
  47726. this.updateHandles();
  47727. this.updatePath();
  47728. }
  47729. set visible(v){
  47730. if(v != this.visible_ ){
  47731. this.visible_ = v;
  47732. this.visible = v;
  47733. if(this.handles){
  47734. this.handles.forEach(e=>e.visible = v );
  47735. if(v) this.updateHandles(); //因为不可见时没更新位置
  47736. }
  47737. }
  47738. }
  47739. get visible(){
  47740. return this.visible_
  47741. }
  47742. /* set visible(v){
  47743. this.handles.forEach(e=>e.svg.style.display = v ? "" : "none" )
  47744. if(v) this.updateHandles() //因为不可见时没更新位置
  47745. } */
  47746. get points(){
  47747. return this.curve.points;
  47748. }
  47749. set points(points){
  47750. this.curve.points = points;
  47751. }
  47752. getPointAt(t){
  47753. return this.curve.getPointAt(t)
  47754. }
  47755. getSpacedPoints(t){
  47756. return this.curve.getSpacedPoints(t)
  47757. }
  47758. dispose(){
  47759. this.parent && this.parent.remove(this);
  47760. this.handles.forEach(e=>e.dispose() );
  47761. this.line.geometry && this.line.geometry.dispose();
  47762. }
  47763. }
  47764. var easing = {};
  47765. //渐变曲线函数,反应加速度的变化
  47766. //currentTime:x轴当前时间(从0-到duration), startY:起始点, duration:总时长, wholeY:路程 (即endY-startY)
  47767. //参数基本是 x, 0, 1, 1
  47768. /*
  47769. easeOut 基本是y= m * (x-dur)^k + n, 若k为偶数,m<0, 若k为奇数,m>0; (因为偶数的话必须开口向下才能获得斜率递减的递增的那段,而奇数是对称的,单调递增. )
  47770. 根据x=0时y=0, x=dur时y=S , 得 n = S,m = -S/(-dur)^k
  47771. */
  47772. easing.getEaseOut = function(k){// k 是>=2的整数. 越大变化率越大, 相同初始速度所需要时间越久
  47773. let easeFun;
  47774. k = Math.round(k);
  47775. if(k<2){
  47776. k = Math.PI / 2;
  47777. easeFun = easing.easeOutSine;
  47778. }else {
  47779. easeFun = function(currentTime, startY, wholeY, duration) {
  47780. if(k>2){
  47781. console.log(k);
  47782. }
  47783. return -wholeY/Math.pow(-duration, k) * Math.pow(currentTime-duration, k) + wholeY
  47784. };
  47785. }
  47786. return {
  47787. k,
  47788. easeFun
  47789. }
  47790. };
  47791. easing.linearTween = function(currentTime, startY, wholeY, duration) {
  47792. return wholeY * currentTime / duration + startY
  47793. }
  47794. ,
  47795. easing.easeInQuad = function(currentTime, startY, wholeY, duration) {
  47796. return currentTime /= duration,
  47797. wholeY * currentTime * currentTime + startY
  47798. }
  47799. ,
  47800. easing.easeOutQuad = function(currentTime, startY, wholeY, duration) { // 如套上实际的距离S和时长dur, y = - S / dur *(x^2-2x) 当s为1,dur为1时,是 y = -(x-1)^2 + 1 , 在0-1中是斜率递减的递增函数. 导数- S / dur *(2x-2 ) 可求出实时速度 故在0这一时刻,速度为 2S/dur
  47801. return currentTime /= duration,
  47802. -wholeY * currentTime * (currentTime - 2) + startY
  47803. }
  47804. ,
  47805. easing.easeInOutQuad = function(currentTime, startY, wholeY, duration) {
  47806. return currentTime /= duration / 2,
  47807. currentTime < 1 ? wholeY / 2 * currentTime * currentTime + startY : (currentTime--,
  47808. -wholeY / 2 * (currentTime * (currentTime - 2) - 1) + startY)
  47809. }
  47810. ,
  47811. easing.easeInCubic = function(currentTime, startY, wholeY, duration) {
  47812. return currentTime /= duration,
  47813. wholeY * currentTime * currentTime * currentTime + startY
  47814. }
  47815. ,
  47816. easing.easeOutCubic = function(currentTime, startY, wholeY, duration) {// y = S / dur^3 *(x-dur)^3 + S,对称中心是(dur,S),从0-dur是 斜率递减的递增函数,导数为3S/dur^3 * (x-dur)^2, 0时速度为3S/dur
  47817. return currentTime /= duration,
  47818. currentTime--,
  47819. wholeY * (currentTime * currentTime * currentTime + 1) + startY
  47820. }
  47821. ,
  47822. easing.easeInOutCubic = function(currentTime, startY, wholeY, duration) {
  47823. return currentTime /= duration / 2,
  47824. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47825. wholeY / 2 * (currentTime * currentTime * currentTime + 2) + startY)
  47826. }
  47827. ,
  47828. easing.easeInQuart = function(currentTime, startY, wholeY, duration) {
  47829. return currentTime /= duration,
  47830. wholeY * currentTime * currentTime * currentTime * currentTime + startY
  47831. }
  47832. ,
  47833. easing.easeOutQuart = function(currentTime, startY, wholeY, duration) {//根据上面的计算,估计0时速度应该是4S/dur吧……
  47834. return currentTime /= duration,
  47835. currentTime--,
  47836. -wholeY * (currentTime * currentTime * currentTime * currentTime - 1) + startY
  47837. }
  47838. ,
  47839. easing.easeInOutQuart = function(currentTime, startY, wholeY, duration) {
  47840. return currentTime /= duration / 2,
  47841. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47842. -wholeY / 2 * (currentTime * currentTime * currentTime * currentTime - 2) + startY)
  47843. }
  47844. ,
  47845. easing.easeInQuint = function(currentTime, startY, wholeY, duration) {
  47846. return currentTime /= duration,
  47847. wholeY * currentTime * currentTime * currentTime * currentTime * currentTime + startY
  47848. }
  47849. ,
  47850. easing.easeOutQuint = function(currentTime, startY, wholeY, duration) {
  47851. return currentTime /= duration,
  47852. currentTime--,
  47853. wholeY * (currentTime * currentTime * currentTime * currentTime * currentTime + 1) + startY
  47854. }
  47855. ,
  47856. easing.easeInOutQuint = function(currentTime, startY, wholeY, duration) {
  47857. return currentTime /= duration / 2,
  47858. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47859. wholeY / 2 * (currentTime * currentTime * currentTime * currentTime * currentTime + 2) + startY)
  47860. }
  47861. ,
  47862. easing.easeInSine = function(currentTime, startY, wholeY, duration) {
  47863. return -wholeY * Math.cos(currentTime / duration * (Math.PI / 2)) + wholeY + startY
  47864. }
  47865. ,
  47866. easing.easeOutSine = function(currentTime, startY, wholeY, duration) {// y' = S * PI / 2 / dur * cos(PI/2/dur * x)
  47867. console.log('easeOutSine');
  47868. return wholeY * Math.sin(currentTime / duration * (Math.PI / 2)) + startY
  47869. }
  47870. ,
  47871. easing.easeInOutSine = function(currentTime, startY, wholeY, duration) {
  47872. return -wholeY / 2 * (Math.cos(Math.PI * currentTime / duration) - 1) + startY
  47873. }
  47874. ,
  47875. easing.easeInExpo = function(currentTime, startY, wholeY, duration) {
  47876. return wholeY * Math.pow(2, 10 * (currentTime / duration - 1)) + startY
  47877. }
  47878. ,
  47879. easing.easeOutExpo = function(currentTime, startY, wholeY, duration) {
  47880. return wholeY * (-Math.pow(2, -10 * currentTime / duration) + 1) + startY
  47881. }
  47882. ,
  47883. easing.easeInOutExpo = function(currentTime, startY, wholeY, duration) {
  47884. return currentTime /= duration / 2,
  47885. currentTime < 1 ? wholeY / 2 * Math.pow(2, 10 * (currentTime - 1)) + startY : (currentTime--,
  47886. wholeY / 2 * (-Math.pow(2, -10 * currentTime) + 2) + startY)
  47887. }
  47888. ,
  47889. easing.easeInCirc = function(currentTime, startY, wholeY, duration) {
  47890. return currentTime /= duration,
  47891. -wholeY * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY
  47892. }
  47893. ,
  47894. easing.easeOutCirc = function(currentTime, startY, wholeY, duration) {
  47895. return currentTime /= duration,
  47896. currentTime--,
  47897. wholeY * Math.sqrt(1 - currentTime * currentTime) + startY
  47898. }
  47899. ,
  47900. easing.easeInOutCirc = function(currentTime, startY, wholeY, duration) {
  47901. return currentTime /= duration / 2,
  47902. currentTime < 1 ? -wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY : (currentTime -= 2,
  47903. wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) + 1) + startY)
  47904. }
  47905. ,
  47906. easing.easeInElastic = function(currentTime, startY, wholeY, duration) {
  47907. var r = 1.70158
  47908. , o = 0
  47909. , a = wholeY;
  47910. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  47911. a < Math.abs(wholeY) ? (a = wholeY,
  47912. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47913. -(a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY)
  47914. }
  47915. ,
  47916. easing.easeOutElastic = function(currentTime, startY, wholeY, duration) {
  47917. var r = 1.70158
  47918. , o = 0
  47919. , a = wholeY;
  47920. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  47921. a < Math.abs(wholeY) ? (a = wholeY,
  47922. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47923. a * Math.pow(2, -10 * currentTime) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) + wholeY + startY)
  47924. }
  47925. ,
  47926. easing.easeInOutElastic = function(currentTime, startY, wholeY, duration) {
  47927. var r = 1.70158
  47928. , o = 0
  47929. , a = wholeY;
  47930. return 0 === currentTime ? startY : 2 === (currentTime /= duration / 2) ? startY + wholeY : (o || (o = duration * (.3 * 1.5)),
  47931. a < Math.abs(wholeY) ? (a = wholeY,
  47932. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47933. currentTime < 1 ? -.5 * (a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY : a * Math.pow(2, -10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) * .5 + wholeY + startY)
  47934. }
  47935. ,
  47936. easing.easeInBack = function(currentTime, startY, wholeY, duration, r) {
  47937. return void 0 === r && (r = 1.70158),
  47938. wholeY * (currentTime /= duration) * currentTime * ((r + 1) * currentTime - r) + startY
  47939. }
  47940. ,
  47941. easing.easeOutBack = function(currentTime, startY, wholeY, duration, r) {
  47942. return void 0 === r && (r = 1.70158),
  47943. wholeY * ((currentTime = currentTime / duration - 1) * currentTime * ((r + 1) * currentTime + r) + 1) + startY
  47944. }
  47945. ,
  47946. easing.easeInOutBack = function(currentTime, startY, wholeY, duration, r) {
  47947. return void 0 === r && (r = 1.70158),
  47948. (currentTime /= duration / 2) < 1 ? wholeY / 2 * (currentTime * currentTime * (((r *= 1.525) + 1) * currentTime - r)) + startY : wholeY / 2 * ((currentTime -= 2) * currentTime * (((r *= 1.525) + 1) * currentTime + r) + 2) + startY
  47949. }
  47950. ,
  47951. easing.easeOutBounce = function(currentTime, startY, wholeY, duration) {
  47952. return (currentTime /= duration) < 1 / 2.75 ? wholeY * (7.5625 * currentTime * currentTime) + startY : currentTime < 2 / 2.75 ? wholeY * (7.5625 * (currentTime -= 1.5 / 2.75) * currentTime + .75) + startY : currentTime < 2.5 / 2.75 ? wholeY * (7.5625 * (currentTime -= 2.25 / 2.75) * currentTime + .9375) + startY : wholeY * (7.5625 * (currentTime -= 2.625 / 2.75) * currentTime + .984375) + startY
  47953. }
  47954. ,
  47955. easing.easeInBounce = function(currentTime, startY, wholeY, r) {
  47956. return wholeY - easing.easeOutBounce(r - currentTime, 0, wholeY, r) + startY
  47957. }
  47958. ,
  47959. easing.easeInOutBounce = function(currentTime, startY, wholeY, r) {
  47960. return currentTime < r / 2 ? .5 * easing.easeInBounce(2 * currentTime, 0, wholeY, r) + startY : .5 * easing.easeOutBounce(x, 2 * currentTime - r, 0, wholeY, r) + .5 * wholeY + startY
  47961. };
  47962. var lerp = {
  47963. /* vector: function(currentTime, startY, f) {//xzw change, add f
  47964. var wholeY = currentTime.clone();
  47965. return startY = startY.clone(),
  47966. function(duration) {
  47967. currentTime.set(wholeY.x * (1 - duration) + startY.x * duration, wholeY.y * (1 - duration) + startY.y * duration, wholeY.z * (1 - duration) + startY.z * duration)
  47968. f && f(currentTime,duration);
  47969. }
  47970. },
  47971. quaternion: function(currentTime, startY, f) {//xzw change, add f
  47972. var wholeY = currentTime.clone();
  47973. return function(duration) {
  47974. currentTime.copy(wholeY).slerp(startY, duration);
  47975. f && f(currentTime,duration);
  47976. }
  47977. },
  47978. property: function(currentTime, startY, wholeY, duration) {
  47979. var r = currentTime[startY];
  47980. return function(o) {
  47981. currentTime[startY] = r * (1 - o) + wholeY * o,
  47982. duration && duration(currentTime[startY])
  47983. }
  47984. },
  47985. uniform: function(currentTime, startY, wholeY) {
  47986. var duration = currentTime.material.uniforms[startY].value;
  47987. return function(r) {
  47988. try{
  47989. currentTime.material.uniforms[startY] && (currentTime.material.uniforms[startY].value = duration * (1 - r) + wholeY * r)
  47990. }catch(currentTime){
  47991. console.log(1)
  47992. }
  47993. }
  47994. },
  47995. matrix4: function(currentTime, startY) {
  47996. var wholeY = currentTime.clone();
  47997. return function(duration) {
  47998. for (var r = currentTime.elements, o = wholeY.elements, a = startY.elements, s = 0; s < 16; s++)
  47999. r[s] = o[s] * (1 - duration) + a[s] * duration
  48000. }
  48001. },
  48002. allUniforms: function(currentTime, startY, wholeY) {
  48003. var duration = currentTime.map(function(currentTime) {
  48004. return this.uniform(currentTime, startY, wholeY)
  48005. }
  48006. .bind(this));
  48007. return function(currentTime) {
  48008. duration.forEach(function(startY) {
  48009. startY(currentTime)
  48010. })
  48011. }
  48012. } */
  48013. vector: function(t, i, f) {//xzw change, add f
  48014. var n = t.clone();
  48015. return i = i.clone(),
  48016. function(e) {
  48017. t.set(n.x * (1 - e) + i.x * e, n.y * (1 - e) + i.y * e, n.z * (1 - e) + i.z * e);
  48018. f && f(t,e);
  48019. }
  48020. },
  48021. quaternion: function(t, i, f) {//xzw change, add f
  48022. var n = t.clone();
  48023. return function(e) {
  48024. t.copy(n).slerp(i, e);
  48025. f && f(t,e);
  48026. }
  48027. },
  48028. property: function(t, i, n, r) {
  48029. var o = t[i];
  48030. return function(e) {
  48031. t[i] = o * (1 - e) + n * e,
  48032. r && r(t[i]);
  48033. }
  48034. },
  48035. uniform: function(t, i, n) {
  48036. var r = t.material.uniforms[i].value;
  48037. return function(e) {
  48038. t.material.uniforms[i] && (t.material.uniforms[i].value = r * (1 - e) + n * e);
  48039. }
  48040. },
  48041. matrix4: function(o, a) {
  48042. var s = o.clone();
  48043. return function(e) {
  48044. for (var t = o.elements, i = s.elements, n = a.elements, r = 0; r < 16; r++)
  48045. t[r] = i[r] * (1 - e) + n[r] * e;
  48046. }
  48047. },
  48048. allUniforms: function(e, t, i) {
  48049. var n = e.map(function(e) {
  48050. return this.uniform(e, t, i)
  48051. }
  48052. .bind(this));
  48053. return function(t) {
  48054. n.forEach(function(e) {
  48055. e(t);
  48056. });
  48057. }
  48058. }
  48059. };
  48060. /*
  48061. 渐变
  48062. */
  48063. var transitions = {
  48064. globalDone: null,
  48065. funcs: [],
  48066. counter: 0,
  48067. uniqueID: 0,
  48068. start: function(func, duration, done, delay, ease, name, id, cancelFun) {
  48069. return delay = delay || 0,
  48070. this.funcs.push({
  48071. func: func,
  48072. current: -delay * Math.abs(duration), //当前时间
  48073. duration: (1 - Math.max(delay, 0)) * Math.abs(duration), //总时长
  48074. done: done,
  48075. easing: ease || easing.linearTween, //渐变曲线
  48076. cycling: duration < 0,
  48077. running: !0,
  48078. debug: delay < 0,
  48079. name: name || "T" + this.counter,
  48080. id: void 0 === id ? this.counter : id,
  48081. paused: !1,
  48082. cancelFun : cancelFun, //取消时执行的函数
  48083. }),
  48084. func(0, 16),
  48085. this.counter += 1,
  48086. func
  48087. },
  48088. trigger: function(e) {
  48089. var t = void 0 === e.delayRatio ? 0 : e.delayRatio
  48090. , u = e.func || function() {}
  48091. , r = void 0 === e.duration ? 0 : e.duration;
  48092. void 0 !== e.cycling && e.cycling && (r = -Math.abs(r));
  48093. var o = e.done || null
  48094. , a = e.easing || easing.linearTween
  48095. , s = e.name || "R" + this.counter
  48096. , l = void 0 === e.id ? this.counter : e.id;
  48097. return this.start(u, r, o, t, a, s, l)
  48098. },
  48099. setTimeout: function(e, t, u) {
  48100. var duration = void 0 === u ? this.counter : u;
  48101. return this.trigger({
  48102. done: e,
  48103. duration: void 0 === t ? 0 : t,
  48104. name: "O" + this.counter,
  48105. id: duration
  48106. })
  48107. },
  48108. pause: function() {
  48109. this.paused = !0;
  48110. },
  48111. resume: function() {
  48112. this.paused = !1;
  48113. },
  48114. update: function(e) {
  48115. this.funcs.forEach(function(t) {
  48116. if (!(t.paused || (t.current += 1e3 * e,
  48117. t.current < 0)))
  48118. if (t.current >= t.duration && !t.cycling) {
  48119. var u = t.easing(1, 0, 1, 1);
  48120. t.func(u, 1e3 * e),
  48121. t.done && t.done(),
  48122. t.running = !1;
  48123. } else {
  48124. var duration = t.easing(t.current % t.duration / t.duration, 0, 1, 1)
  48125. , r = t.func(duration, 1e3 * e) || !1;
  48126. r && (t.done && t.done(),
  48127. t.running = !1);
  48128. }
  48129. });
  48130. var t = this.funcs.length;
  48131. this.funcs = this.funcs.filter(function(e) {
  48132. return e.running
  48133. });
  48134. var u = this.funcs.length;
  48135. if (t > 0 && 0 === u && this.globalDone) {
  48136. var duration = this.globalDone;
  48137. this.globalDone = null,
  48138. duration();
  48139. }
  48140. },
  48141. adjustSpeed: function(e, t) {
  48142. for (var u = this.getById(e), duration = 0; duration < u.length; duration++) {
  48143. var r = u[duration];
  48144. r.duration /= t,
  48145. r.current /= t;
  48146. }
  48147. },
  48148. getById: function(e) {
  48149. return this.funcs.filter(function(t) {
  48150. return e === t.id
  48151. })
  48152. },
  48153. get: function(e) {
  48154. for (var t = 0; t < this.funcs.length; t += 1)
  48155. if (this.funcs[t].func === e)
  48156. return this.funcs[t];
  48157. return null
  48158. },
  48159. isRunning: function(e) {
  48160. var t = this.get(e);
  48161. return null !== t && t.running
  48162. },
  48163. countActive: function() {
  48164. for (var e = 0, t = 0; t < this.funcs.length; t += 1)
  48165. e += this.funcs[t].running;
  48166. return e
  48167. },
  48168. listActive: function() {
  48169. for (var e = [], t = 0; t < this.funcs.length; t += 1)
  48170. this.funcs[t].running && e.push(this.funcs[t].name);
  48171. return e
  48172. },
  48173. done: function(e) {
  48174. this.globalDone = e;
  48175. },
  48176. cancelById: function(e, dealCancelFun) { //xzw add dealDone
  48177. var t = void 0 === e ? 0 : e;
  48178. let cancels = [];
  48179. this.funcs = this.funcs.filter(function(e) {
  48180. var is = e.id == t;
  48181. if(is && dealCancelFun){
  48182. e.cancelFun && cancels.push(e.cancelFun);
  48183. //e.cancelFun && e.cancelFun()
  48184. }
  48185. return !is
  48186. });
  48187. cancels.forEach(e=>{e();}); //先从funcs中去除后再执行
  48188. },
  48189. cancel: function(e) {
  48190. this.funcs = this.funcs.filter(function(t) {
  48191. return t.func !== e
  48192. });
  48193. },
  48194. getUniqueId: function() {
  48195. return this.uniqueID -= 1,
  48196. this.uniqueID
  48197. }
  48198. };
  48199. const colors = {
  48200. position: 'red',
  48201. target : 'blue'
  48202. };
  48203. let lineMats$1;
  48204. const getLineMat = function(name){
  48205. if(!lineMats$1){
  48206. lineMats$1 = {
  48207. position: LineDraw.createFatLineMat({
  48208. color: colors.position,
  48209. lineWidth: 3
  48210. }),
  48211. target : LineDraw.createFatLineMat({
  48212. color: colors.target,
  48213. lineWidth: 3
  48214. }),
  48215. frustum: LineDraw.createFatLineMat({
  48216. color: colors.position,
  48217. lineWidth: 2
  48218. }),
  48219. aimAtTarget: new LineBasicMaterial({color:colors.target})
  48220. };
  48221. }
  48222. return lineMats$1[name]
  48223. };
  48224. class CameraAnimation extends EventDispatcher{
  48225. constructor(viewer){
  48226. super();
  48227. this.viewer = viewer;
  48228. this.selectedElement = null;
  48229. //this.controlPoints = [];
  48230. this.uuid = MathUtils.generateUUID();
  48231. this.node = new Object3D();
  48232. this.node.name = "camera animation";
  48233. this.viewer.scene.scene.add(this.node);
  48234. this.frustum = this.createFrustum();
  48235. this.node.add(this.frustum);
  48236. this.name = "Camera Animation";
  48237. // "centripetal", "chordal", "catmullrom"
  48238. this.curveType = "centripetal";
  48239. this.visible = true;
  48240. this.targets = [];
  48241. this.createPath();
  48242. this.duration = 5;
  48243. this.percent = 0;
  48244. this.currentIndex = 0;
  48245. this.durations = [];
  48246. this.quaternions = [];
  48247. if(!Potree.settings.isTest){
  48248. this.setVisible(false);
  48249. }
  48250. this.addEventListener('dispose', ()=>{
  48251. this.dispose();
  48252. });
  48253. this.targetLines = new Object3D;
  48254. this.node.add(this.targetLines);
  48255. }
  48256. static defaultFromView(viewer){
  48257. const animation = new CameraAnimation(viewer);
  48258. const camera = viewer.scene.getActiveCamera();
  48259. const target = viewer.scene.view.getPivot();
  48260. const cpCenter = new Vector3(
  48261. 0.3 * camera.position.x + 0.7 * target.x,
  48262. 0.3 * camera.position.y + 0.7 * target.y,
  48263. 0.3 * camera.position.z + 0.7 * target.z,
  48264. );
  48265. const targetCenter = new Vector3(
  48266. 0.05 * camera.position.x + 0.95 * target.x,
  48267. 0.05 * camera.position.y + 0.95 * target.y,
  48268. 0.05 * camera.position.z + 0.95 * target.z,
  48269. );
  48270. const r = 2;//camera.position.distanceTo(target) * 0.3;
  48271. //const dir = target.clone().sub(camera.position).normalize();
  48272. const angle = Utils.computeAzimuth(camera.position, target);
  48273. const n = 5;
  48274. for(let i = 0; i < n; i++){
  48275. let u = 1.5 * Math.PI * (i / n) + angle;
  48276. const dx = r * Math.cos(u);
  48277. const dy = r * Math.sin(u);
  48278. const cpPos = new Vector3(
  48279. cpCenter.x + dx,
  48280. cpCenter.y + dy,
  48281. cpCenter.z,
  48282. );
  48283. const targetPos = new Vector3(
  48284. targetCenter.x + dx * 0.1,
  48285. targetCenter.y + dy * 0.1,
  48286. targetCenter.z,
  48287. );
  48288. animation.createControlPoint(null,{position:cpPos, target:targetPos});
  48289. }
  48290. animation.changeCallback();
  48291. return animation;
  48292. }
  48293. createControlPoint(index, posInfo ){
  48294. const length = this.posCurve.points.length;
  48295. const position = new Vector3;
  48296. const target = new Vector3;
  48297. if(index == void 0 ){
  48298. index = length;
  48299. }
  48300. if(!posInfo){
  48301. if(length >= 2 && index === 0){
  48302. const dir = new Vector3().subVectors(this.posCurve.points[0], this.posCurve.points[1] );
  48303. position.copy(this.posCurve.points[0]).add(dir);
  48304. const tDir = new Vector3().subVectors(this.targets[0].position, this.targets[1].position );
  48305. target.copy(this.targets[0].position).add(dir);
  48306. }else if(length >= 2 && index === length){
  48307. const dir = new Vector3().subVectors(this.posCurve.points[length-1], this.posCurve.points[length-2] );
  48308. position.copy(this.posCurve.points[length-2]).add(dir);
  48309. const tDir = new Vector3().subVectors(this.targets[length-1].position, this.targets[length-2].position );
  48310. target.copy(this.targets[length-2].position).add(dir);
  48311. }else if(length >= 2){
  48312. position.copy(this.posCurve.points[index-1].clone().add(this.posCurve.points[index]).multiplyScalar(0.5));
  48313. target.copy(this.targets[length-1].position.clone().add(this.targets[length]).multiplyScalar(0.5));
  48314. }
  48315. }else {
  48316. position.copy(posInfo.position);
  48317. target.copy(posInfo.target);
  48318. }
  48319. this.posCurve.addPoint(position, index/* , true */);
  48320. //this.targetCurve.addPoint(target, index/* , true */)
  48321. let targetSvg = new HandleSvg(target, colors.target);
  48322. targetSvg.visible = this.visible;
  48323. this.targets = [...this.targets.slice(0,index), targetSvg, ...this.targets.slice(index,length)];
  48324. if(this.useDurSlice){//不使用全局的duration,而是分段的
  48325. this.durations = [...this.durations.slice(0,index), posInfo.duration, ...this.durations.slice(index,length)];
  48326. }
  48327. this.dispatchEvent({
  48328. type: "controlpoint_added",
  48329. index
  48330. });
  48331. {
  48332. let targetLine = LineDraw.createLine([position,target] ,{mat: getLineMat('aimAtTarget')});
  48333. this.targetLines.children = [...this.targetLines.children.slice(0,index), targetLine, ...this.targetLines.children.slice(index,length)];
  48334. this.targets[index].addEventListener('dragged', (e)=>{
  48335. this.updatePathCallback();
  48336. this.dragPointCallback(e);
  48337. });
  48338. }
  48339. }
  48340. dragPointCallback(e){
  48341. let index = e.index;
  48342. if(e.index == void 0){
  48343. index = this.targets.indexOf(e.target);
  48344. }
  48345. LineDraw.moveLine(this.targetLines.children[index], [this.posCurve.points[index], this.targets[index].position] );
  48346. this.updateFrustum();
  48347. }
  48348. updatePathCallback(){
  48349. {
  48350. this.quaternions = [];
  48351. let length = this.posCurve.points.length;
  48352. for(let i=0; i<length; i++){
  48353. let quaternion = math.getQuaFromPosAim(this.posCurve.points[i], this.targets[i].position);
  48354. this.quaternions.push( quaternion);
  48355. }
  48356. }
  48357. this.reMapCurvePercent();
  48358. }
  48359. removeControlPoint(index){
  48360. this.posCurve.removePoint(index);
  48361. //this.targetCurve.removePoint(index)
  48362. this.targets[index].dispose();
  48363. this.targets.splice(index, 1);
  48364. this.dispatchEvent({
  48365. type: "controlpoint_removed",
  48366. index
  48367. });
  48368. this.targetLines.remove(this.targetLines.children[index]);
  48369. if(this.useDurSlice){
  48370. this.durations.splice(index, 1);
  48371. }
  48372. }
  48373. createPath(){
  48374. this.posCurve = new CurveCtrl([],getLineMat('position'), colors.position, 'posCurve');
  48375. //this.targetCurve = new CurveCtrl([], getLineMat('target'), colors.target, 'targetCurve', {noLine:true});
  48376. this.posCurve.needsPercent = true;
  48377. this.node.add(this.posCurve);
  48378. //this.node.add(this.targetCurve)
  48379. this.posCurve.addEventListener('dragCurvePoint', this.dragPointCallback.bind(this));
  48380. this.posCurve.addEventListener('updatePath', this.updatePathCallback.bind(this));
  48381. }
  48382. createFrustum(){
  48383. const f = 0.3;
  48384. const positions = [
  48385. new Vector3( 0, 0, 0),
  48386. new Vector3(-f, -f, +1),
  48387. new Vector3( 0, 0, 0),
  48388. new Vector3( f, -f, +1),
  48389. new Vector3( 0, 0, 0),
  48390. new Vector3( f, f, +1),
  48391. new Vector3( 0, 0, 0),
  48392. new Vector3(-f, f, +1),
  48393. new Vector3(-f, -f, +1),
  48394. new Vector3( f, -f, +1),
  48395. new Vector3( f, -f, +1),
  48396. new Vector3( f, f, +1),
  48397. new Vector3( f, f, +1),
  48398. new Vector3(-f, f, +1),
  48399. new Vector3(-f, f, +1),
  48400. new Vector3(-f, -f, +1),
  48401. ];
  48402. positions.forEach(e=>e.z *= -1); //因为得到的rotation是camera的,作用在物体上要反向,所以这里反向一下
  48403. //geometry.computeBoundingSphere();//?
  48404. const line = LineDraw.createFatLine( positions, {material:getLineMat('frustum')});
  48405. //line.scale.set(20, 20, 20);
  48406. line.visible = false;
  48407. return line;
  48408. }
  48409. reMapCurvePercent(){ //因在不同点在相同位置旋转,由于间隔仅和位置距离相关,导致时间间隔为0,采取重新调整间隔的策略。
  48410. var length = this.posCurve.points.length;
  48411. if(length<2){
  48412. return this.newPointsPercents = []
  48413. }
  48414. var newPercents = [0];
  48415. if(this.useDurSlice){ //已经设定好了每一段的duration的话
  48416. let sums = [0];
  48417. let sum = 0, last;
  48418. for(let i=0;i<length-1;i++){ //去掉最后一个duration,因为已到终点
  48419. let duration = this.durations[i];
  48420. sum += duration;
  48421. last = duration;
  48422. sums.push(sum);
  48423. }
  48424. for(let i=1;i<length;i++){
  48425. newPercents.push(sum == 0 ? i/length : sums[i] / sum);
  48426. }
  48427. }else {
  48428. const maxSpaceDur = this.duration / length; //每两点之间修改间隔时间后,最大时间
  48429. const durPerRad = 0.8; //每弧度应该占用的时间
  48430. const minSpaceDur = Math.min(0.8, maxSpaceDur);//每两点之间修改间隔时间后,最小时间
  48431. const maxAngleSpaceDur = MathUtils.clamp(durPerRad * Math.PI, minSpaceDur, maxSpaceDur );// 最大可能差距是180度
  48432. var percents = this.posCurve.pointsPercent;
  48433. for(let i=1;i<length;i++){
  48434. let diff = (percents[i] - percents[i-1]) * this.duration; //间隔时间
  48435. let percent;
  48436. let curMin = minSpaceDur;
  48437. if(diff < maxAngleSpaceDur){ //若小于最大旋转时间
  48438. let rad = this.quaternions[i].angleTo(this.quaternions[i-1]);
  48439. curMin = MathUtils.clamp(rad * durPerRad, minSpaceDur, maxSpaceDur);
  48440. }
  48441. diff = Math.max(diff, curMin);
  48442. percent = newPercents[i-1] + (diff / this.duration); //得到新的percent
  48443. newPercents.push(percent);
  48444. }
  48445. let maxPercent = newPercents[length-1]; //最后一个,若扩充过时间,就会>1
  48446. if( !math.closeTo(maxPercent, 1)){
  48447. let scale = 1 / maxPercent; //需要压缩的比例 <1 这一步会让实际得到的间隔更小
  48448. newPercents = newPercents.map(e=> e*=scale );
  48449. }
  48450. }
  48451. this.newPointsPercents = newPercents;
  48452. //console.log(newPercents)
  48453. }
  48454. at(originPercent, delta, transitionRatio){
  48455. originPercent = MathUtils.clamp(originPercent, 0, 1);
  48456. //修改第一层:起始时间
  48457. let percent = originPercent;
  48458. /* const easePercent = 0.3; //缓动占比 //如果能在所有从静止到运动的中间加缓动就好了呀:lastPos * 0.9 + currentPos * 0.1 ?
  48459. if(originPercent < easePercent){
  48460. console.log('easeIn')
  48461. percent = easing.easeInSine(originPercent, 0, easePercent, easePercent) //currentTime, startY, wholeY, duration 选了一个衔接时接近斜率1的缓动函数
  48462. }else if(originPercent > 1-easePercent){
  48463. console.log('easeOut')
  48464. percent = easing.easeOutSine(originPercent-(1-easePercent), 1-easePercent, easePercent, easePercent)
  48465. } */
  48466. let quaternion;
  48467. if(percent < 1){
  48468. //修改第二层:使用每个点的重定位的 newPointsPercents
  48469. this.currentIndex = this.newPointsPercents.findIndex(e=> e>percent ) - 1;
  48470. //假设每个节点的百分比是精确的,那么:
  48471. let curIndexPercent = this.newPointsPercents[this.currentIndex];
  48472. let nextIndexPercent = this.newPointsPercents[this.currentIndex+1];
  48473. let progress = (percent - curIndexPercent) / (nextIndexPercent - curIndexPercent);//在这两个节点间的百分比
  48474. //投影到原本的 posCurve.pointsPercent上:
  48475. let curIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex];
  48476. let nextIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex+1];
  48477. percent = curIndexOriPercent + (nextIndexOriPercent - curIndexOriPercent) * progress;
  48478. let endQuaternion = this.quaternions[this.currentIndex+1];
  48479. let startQuaternion = this.quaternions[this.currentIndex];
  48480. quaternion = (new Quaternion()).copy(startQuaternion);
  48481. lerp.quaternion(quaternion, endQuaternion)(progress);
  48482. }else {
  48483. this.currentIndex = this.posCurve.points.length - 1;
  48484. quaternion = math.getQuaFromPosAim(this.posCurve.points[this.currentIndex], this.targets[this.currentIndex].position);
  48485. }
  48486. const position = this.posCurve.getPointAt(percent); // 需要this.posCurve.points.length>1 否则报错
  48487. //console.log(this.currentIndex, originPercent)
  48488. //缓动:
  48489. var aimQua, aimPos;
  48490. if(delta != void 0 ){
  48491. if(Potree.settings.tourTestCameraMove){
  48492. aimQua = this.frustum.quaternion.clone();
  48493. aimPos = this.frustum.position.clone();
  48494. }else {
  48495. var camera = viewer.scene.getActiveCamera();
  48496. aimQua = camera.quaternion.clone();
  48497. aimPos = camera.position.clone();
  48498. }
  48499. transitionRatio = transitionRatio || 1 / Potree.settings.cameraAniSmoothRatio;//渐变系数,越小缓动程度越高,越平滑
  48500. transitionRatio *= delta * 60; //假设标准帧率为60fps,当帧率低时(delta大时)要降低缓动
  48501. //console.log(transitionRatio, delta) //画面ui变化会使delta变大
  48502. transitionRatio = MathUtils.clamp(transitionRatio, 0, 1);
  48503. lerp.quaternion(aimQua, quaternion)(transitionRatio); //每次只改变一点点
  48504. lerp.vector(aimPos, position)(transitionRatio);
  48505. }else {
  48506. aimQua = quaternion; aimPos = position;
  48507. }
  48508. let rotation = new Euler().setFromQuaternion(aimQua );
  48509. const frame = {
  48510. position: aimPos,
  48511. rotation
  48512. };
  48513. return frame;
  48514. }
  48515. set(percent){
  48516. this.percent = percent;
  48517. }
  48518. setVisible(visible){
  48519. this.node.visible = visible;
  48520. this.posCurve.visible = visible;
  48521. this.targets.forEach(e=>e.visible = visible );
  48522. this.visible = visible;
  48523. }
  48524. setDuration(duration){
  48525. if(duration != this.duration){
  48526. this.duration = duration;
  48527. if(this.quaternions.length == this.posCurve.points.length)this.reMapCurvePercent();
  48528. }
  48529. }
  48530. getDuration(duration){
  48531. return this.duration;
  48532. }
  48533. play(startOptions={}){
  48534. if(this.onUpdate){
  48535. return console.error('已经开始播放')
  48536. }
  48537. let startPercent = 0, currentIndex = 0;
  48538. if(startOptions.percent != void 0 ){
  48539. startPercent = startOptions.percent;
  48540. }else if(startOptions.index){
  48541. currentIndex = index;
  48542. //startPercent = index/(this.posCurve.points.length-1)
  48543. startPercent = this.posCurve.pointsPercent[index];
  48544. }
  48545. //const tStart = performance.now();
  48546. const duration = this.duration;
  48547. this.originalyVisible = this.visible;
  48548. Potree.settings.tourTestCameraMove || this.setVisible(false);
  48549. let tStart, startTransitionRatio = 0.2;
  48550. let startDelay = 1/startTransitionRatio / 20 ;//因为缓动所以延迟开始,前面前都是at(0),使过渡到开始点位(但是依旧不能准确停在起始点,因为缓动是乘百分比有残留。所以直接平滑衔接到开始后的位置)
  48551. let hasPlayedTime = 0;
  48552. let finishDelay = Potree.settings.cameraAniSmoothRatio / 60 * 3;//结束后还需要多久时间才能大致达到缓动的最终目标
  48553. let hasStoppedTime = 0;
  48554. this.onUpdate = (e) => {
  48555. if(this.posCurve.points.length<2){
  48556. if(this.posCurve.points.length == 1){
  48557. viewer.scene.view.position.copy(this.posCurve.points[0]);
  48558. viewer.scene.view.rotation = new Euler().setFromQuaternion(this.quaternions[0]);
  48559. }
  48560. this.pause();
  48561. return
  48562. }
  48563. let percent, transitionRatio;
  48564. if(tStart){
  48565. let tNow = performance.now();
  48566. let elapsed = (tNow - tStart) / 1000;
  48567. percent = elapsed / duration + startPercent;
  48568. }else {//从当前位置过渡到开始位置
  48569. percent = 0;
  48570. hasPlayedTime += e.delta;
  48571. transitionRatio = startTransitionRatio;
  48572. console.log('延迟开始');
  48573. if(hasPlayedTime > startDelay){
  48574. tStart = performance.now();
  48575. }
  48576. }
  48577. this.set(percent);
  48578. const frame = this.at(percent, e.delta, transitionRatio);
  48579. if(currentIndex != this.currentIndex){
  48580. currentIndex = this.currentIndex;
  48581. console.log('updateCurrentIndex', currentIndex);
  48582. this.dispatchEvent({type:'updateCurrentIndex', currentIndex });
  48583. }
  48584. if(!Potree.settings.tourTestCameraMove){
  48585. viewer.scene.view.position.copy(frame.position);
  48586. //viewer.scene.view.lookAt(frame.target);
  48587. viewer.scene.view.rotation = frame.rotation;
  48588. }
  48589. this.updateFrustum(frame);
  48590. if(percent >= 1){
  48591. if(hasStoppedTime > finishDelay){
  48592. this.pause();
  48593. }else {
  48594. hasStoppedTime += e.delta;
  48595. console.log('延迟结束');
  48596. }
  48597. }
  48598. };
  48599. this.viewer.addEventListener("update", this.onUpdate);
  48600. }
  48601. pause(){
  48602. this.setVisible(this.originalyVisible);
  48603. this.viewer.removeEventListener("update", this.onUpdate);
  48604. this.dispatchEvent('playDone');
  48605. this.onUpdate = null;
  48606. }
  48607. updateFrustum(frame){
  48608. const frustum = this.frustum;
  48609. if(this.posCurve.points.length>1){
  48610. frustum.visible = true;
  48611. }else {
  48612. frustum.visible = false;
  48613. return
  48614. }
  48615. frame = frame || this.at(this.percent);
  48616. frustum.position.copy(frame.position);
  48617. //frustum.lookAt(...frame.target.toArray());
  48618. frustum.rotation.copy(frame.rotation);
  48619. }
  48620. changeCallback(){
  48621. this.posCurve.update();
  48622. //this.targetCurve.update()
  48623. this.targets.forEach(e=>e.update());
  48624. this.updateFrustum();
  48625. }
  48626. dispose(){//add
  48627. this.posCurve.dispose();
  48628. //this.targetCurve.dispatchEvent({type:'dispose'})
  48629. this.targets.forEach(e=>e.dispose());
  48630. this.durations = [];
  48631. this.node.parent.remove(this.node);
  48632. }
  48633. }
  48634. //scene.removeCameraAnimation
  48635. //修改:不使用targetCurve作为target曲线,因为播放时posCuve的节点和targetCurve并没有对应,且使用target的曲线会使角度变化大的情况过渡生硬。
  48636. // 改完旋转了。但是位置也有问题。速度完全和路程相关,当在同一位置设置多点时,这段的总时长为0. (是否要设置最小时长?不过也做不到 - -)
  48637. function loadPointCloud(viewer, data){
  48638. let loadMaterial = (target) => {
  48639. if(data.material){
  48640. if(data.material.activeAttributeName != null){
  48641. target.activeAttributeName = data.material.activeAttributeName;
  48642. }
  48643. if(data.material.ranges != null){
  48644. for(let range of data.material.ranges){
  48645. if(range.name === "elevationRange"){
  48646. target.elevationRange = range.value;
  48647. }else if(range.name === "intensityRange"){
  48648. target.intensityRange = range.value;
  48649. }else {
  48650. target.setRange(range.name, range.value);
  48651. }
  48652. }
  48653. }
  48654. if(data.material.size != null){
  48655. target.size = data.material.size;
  48656. }
  48657. if(data.material.minSize != null){
  48658. target.minSize = data.material.minSize;
  48659. }
  48660. if(data.material.pointSizeType != null){
  48661. target.pointSizeType = PointSizeType[data.material.pointSizeType];
  48662. }
  48663. if(data.material.matcap != null){
  48664. target.matcap = data.material.matcap;
  48665. }
  48666. }else if(data.activeAttributeName != null){
  48667. target.activeAttributeName = data.activeAttributeName;
  48668. }else {
  48669. // no material data
  48670. }
  48671. };
  48672. const promise = new Promise((resolve) => {
  48673. const names = viewer.scene.pointclouds.map(p => p.name);
  48674. const alreadyExists = names.includes(data.name);
  48675. if(alreadyExists){
  48676. resolve();
  48677. return;
  48678. }
  48679. Potree.loadPointCloud(data.url, data.name, (e) => {
  48680. const {pointcloud} = e;
  48681. pointcloud.position.set(...data.position);
  48682. pointcloud.rotation.set(...data.rotation);
  48683. pointcloud.scale.set(...data.scale);
  48684. loadMaterial(pointcloud.material);
  48685. viewer.scene.addPointCloud(pointcloud);
  48686. resolve(pointcloud);
  48687. });
  48688. });
  48689. return promise;
  48690. }
  48691. function loadMeasurement(viewer, data){
  48692. const duplicate = viewer.scene.measurements.find(measure => measure.uuid === data.uuid);
  48693. if(duplicate){
  48694. return;
  48695. }
  48696. data.points = data.points.map(point=>new Vector3(...point));
  48697. const measure = viewer.measuringTool.createMeasureFromData(data);
  48698. }
  48699. function loadVolume(viewer, data){
  48700. const duplicate = viewer.scene.volumes.find(volume => volume.uuid === data.uuid);
  48701. if(duplicate){
  48702. return;
  48703. }
  48704. let volume = new Potree[data.type];
  48705. volume.uuid = data.uuid;
  48706. volume.name = data.name;
  48707. volume.position.set(...data.position);
  48708. volume.rotation.set(...data.rotation);
  48709. volume.scale.set(...data.scale);
  48710. volume.visible = data.visible;
  48711. volume.clip = data.clip;
  48712. viewer.scene.addVolume(volume);
  48713. }
  48714. function loadCameraAnimation(viewer, data){
  48715. const duplicate = viewer.scene.cameraAnimations.find(a => a.uuid === data.uuid);
  48716. if(duplicate){
  48717. return;
  48718. }
  48719. const animation = new CameraAnimation(viewer);
  48720. animation.uuid = data.uuid;
  48721. animation.name = data.name;
  48722. animation.duration = data.duration;
  48723. animation.t = data.t;
  48724. animation.curveType = data.curveType;
  48725. animation.visible = data.visible;
  48726. animation.controlPoints = [];
  48727. for(const cpdata of data.controlPoints){
  48728. const cp = animation.createControlPoint();
  48729. cp.position.set(...cpdata.position);
  48730. cp.target.set(...cpdata.target);
  48731. }
  48732. viewer.scene.addCameraAnimation(animation);
  48733. }
  48734. function loadOrientedImages(viewer, images){
  48735. const {cameraParamsPath, imageParamsPath} = images;
  48736. const duplicate = viewer.scene.orientedImages.find(i => i.imageParamsPath === imageParamsPath);
  48737. if(duplicate){
  48738. return;
  48739. }
  48740. Potree.OrientedImageLoader.load(cameraParamsPath, imageParamsPath, viewer).then( images => {
  48741. viewer.scene.addOrientedImages(images);
  48742. });
  48743. }
  48744. function loadGeopackage(viewer, geopackage){
  48745. const path = geopackage.path;
  48746. const duplicate = viewer.scene.geopackages.find(i => i.path === path);
  48747. if(duplicate){
  48748. return;
  48749. }
  48750. const projection = viewer.getProjection();
  48751. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  48752. proj4.defs("pointcloud", projection);
  48753. const transform = proj4("WGS84", "pointcloud");
  48754. const params = {
  48755. transform: transform,
  48756. };
  48757. Potree.GeoPackageLoader.loadUrl(path, params).then(data => {
  48758. viewer.scene.addGeopackage(data);
  48759. });
  48760. }
  48761. function loadSettings(viewer, data){
  48762. if(!data){
  48763. return;
  48764. }
  48765. viewer.setPointBudget(data.pointBudget);
  48766. viewer.setFOV(data.fov);
  48767. viewer.setEDLEnabled(data.edlEnabled);
  48768. viewer.setEDLRadius(data.edlRadius);
  48769. viewer.setEDLStrength(data.edlStrength);
  48770. viewer.setBackground(data.background);
  48771. viewer.setMinNodeSize(data.minNodeSize);
  48772. viewer.setShowBoundingBox(data.showBoundingBoxes);
  48773. }
  48774. function loadView(viewer, view){
  48775. viewer.scene.view.position.set(...view.position);
  48776. viewer.scene.view.lookAt(...view.target);
  48777. }
  48778. function loadAnnotationItem(item){
  48779. const annotation = new Annotation({
  48780. position: item.position,
  48781. title: item.title,
  48782. cameraPosition: item.cameraPosition,
  48783. cameraTarget: item.cameraTarget,
  48784. });
  48785. annotation.description = item.description;
  48786. annotation.uuid = item.uuid;
  48787. if(item.offset){
  48788. annotation.offset.set(...item.offset);
  48789. }
  48790. return annotation;
  48791. }
  48792. function loadAnnotations(viewer, data){
  48793. if(!data){
  48794. return;
  48795. }
  48796. const findDuplicate = (item) => {
  48797. let duplicate = null;
  48798. viewer.scene.annotations.traverse( a => {
  48799. if(a.uuid === item.uuid){
  48800. duplicate = a;
  48801. }
  48802. });
  48803. return duplicate;
  48804. };
  48805. const traverse = (item, parent) => {
  48806. const duplicate = findDuplicate(item);
  48807. if(duplicate){
  48808. return;
  48809. }
  48810. const annotation = loadAnnotationItem(item);
  48811. for(const childItem of item.children){
  48812. traverse(childItem, annotation);
  48813. }
  48814. parent.add(annotation);
  48815. };
  48816. for(const item of data){
  48817. traverse(item, viewer.scene.annotations);
  48818. }
  48819. }
  48820. function loadProfile(viewer, data){
  48821. const {name, points} = data;
  48822. const duplicate = viewer.scene.profiles.find(profile => profile.uuid === data.uuid);
  48823. if(duplicate){
  48824. return;
  48825. }
  48826. let profile = new Potree.Profile();
  48827. profile.name = name;
  48828. profile.uuid = data.uuid;
  48829. profile.setWidth(data.width);
  48830. for(const point of points){
  48831. profile.addMarker(new Vector3(...point));
  48832. }
  48833. viewer.scene.addProfile(profile);
  48834. }
  48835. function loadClassification(viewer, data){
  48836. if(!data){
  48837. return;
  48838. }
  48839. const classifications = data;
  48840. viewer.setClassifications(classifications);
  48841. }
  48842. async function loadProject(viewer, data, done){
  48843. if(data.type !== "Potree"){
  48844. console.error("not a valid Potree project");
  48845. return;
  48846. }
  48847. loadSettings(viewer, data.settings);
  48848. loadView(viewer, data.view);
  48849. /* const pointcloudPromises = [];
  48850. for(const pointcloud of data.pointclouds){
  48851. const promise = loadPointCloud(viewer, pointcloud);
  48852. pointcloudPromises.push(promise);
  48853. } */
  48854. for(const measure of data.measurements){
  48855. loadMeasurement(viewer, measure);
  48856. }
  48857. for(const volume of data.volumes){
  48858. loadVolume(viewer, volume);
  48859. }
  48860. for(const animation of data.cameraAnimations){
  48861. loadCameraAnimation(viewer, animation);
  48862. }
  48863. for(const profile of data.profiles){
  48864. loadProfile(viewer, profile);
  48865. }
  48866. if(data.orientedImages){
  48867. for(const images of data.orientedImages){
  48868. loadOrientedImages(viewer, images);
  48869. }
  48870. }
  48871. loadAnnotations(viewer, data.annotations);
  48872. loadClassification(viewer, data.classification);
  48873. done && done();
  48874. // need to load at least one point cloud that defines the scene projection,
  48875. // before we can load stuff in other projections such as geopackages
  48876. //await Promise.any(pointcloudPromises); // (not yet supported)
  48877. /* Utils.waitAny(pointcloudPromises).then( () => {
  48878. if(data.geopackages){
  48879. for(const geopackage of data.geopackages){
  48880. loadGeopackage(viewer, geopackage);
  48881. }
  48882. }
  48883. });
  48884. await Promise.all(pointcloudPromises); */
  48885. }
  48886. //
  48887. // Algorithm by Christian Boucheny
  48888. // shader code taken and adapted from CloudCompare
  48889. //
  48890. // see
  48891. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  48892. // http://www.kitware.com/source/home/post/9
  48893. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  48894. class EyeDomeLightingMaterial extends RawShaderMaterial{
  48895. constructor(parameters = {}){
  48896. super();
  48897. let uniforms = {
  48898. /* screenWidth: { type: 'f', value: 0 },
  48899. screenHeight: { type: 'f', value: 0 }, */
  48900. resolution: { type: 'v2', value: new Vector2$1() },
  48901. edlStrength: { type: 'f', value: 1.0 },
  48902. uNear: { type: 'f', value: 1.0 },
  48903. uFar: { type: 'f', value: 1.0 },
  48904. radius: { type: 'f', value: 1.0 },
  48905. neighbours: { type: '2fv', value: [] },
  48906. depthMap: { type: 't', value: null },
  48907. uEDLColor: { type: 't', value: null },
  48908. uEDLDepth: { type: 't', value: null },
  48909. opacity: { type: 'f', value: 1.0 },
  48910. uProj: { type: "Matrix4fv", value: [] },
  48911. useEDL: { type: 'i', value: 1 }//add
  48912. };
  48913. this.setValues({
  48914. uniforms: uniforms,
  48915. vertexShader: this.getDefines() + Shaders['edl.vs'],
  48916. fragmentShader: this.getDefines() + Shaders['edl.fs'],
  48917. lights: false
  48918. });
  48919. this.neighbourCount = 8;
  48920. }
  48921. getDefines() {
  48922. let defines = '';
  48923. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  48924. return defines;
  48925. }
  48926. updateShaderSource() {
  48927. let vs = this.getDefines() + Shaders['edl.vs'];
  48928. let fs = this.getDefines() + Shaders['edl.fs'];
  48929. this.setValues({
  48930. vertexShader: vs,
  48931. fragmentShader: fs
  48932. });
  48933. this.uniforms.neighbours.value = this.neighbours;
  48934. this.needsUpdate = true;
  48935. }
  48936. get neighbourCount(){
  48937. return this._neighbourCount;
  48938. }
  48939. set neighbourCount(value){
  48940. if (this._neighbourCount !== value) { //周围八个格子
  48941. this._neighbourCount = value;
  48942. this.neighbours = new Float32Array(this._neighbourCount * 2);
  48943. for (let c = 0; c < this._neighbourCount; c++) {
  48944. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  48945. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  48946. }
  48947. this.updateShaderSource();
  48948. }
  48949. }
  48950. }
  48951. class NormalizationEDLMaterial extends RawShaderMaterial{
  48952. constructor(parameters = {}){
  48953. super();
  48954. let uniforms = {
  48955. screenWidth: { type: 'f', value: 0 },
  48956. screenHeight: { type: 'f', value: 0 },
  48957. edlStrength: { type: 'f', value: 1.0 },
  48958. radius: { type: 'f', value: 1.0 },
  48959. neighbours: { type: '2fv', value: [] },
  48960. uEDLMap: { type: 't', value: null },
  48961. uDepthMap: { type: 't', value: null },
  48962. uWeightMap: { type: 't', value: null },
  48963. };
  48964. this.setValues({
  48965. uniforms: uniforms,
  48966. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  48967. fragmentShader: this.getDefines() + Shaders['normalize_and_edl.fs'],
  48968. });
  48969. this.neighbourCount = 8;
  48970. }
  48971. getDefines() {
  48972. let defines = '';
  48973. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  48974. return defines;
  48975. }
  48976. updateShaderSource() {
  48977. let vs = this.getDefines() + Shaders['normalize.vs'];
  48978. let fs = this.getDefines() + Shaders['normalize_and_edl.fs'];
  48979. this.setValues({
  48980. vertexShader: vs,
  48981. fragmentShader: fs
  48982. });
  48983. this.uniforms.neighbours.value = this.neighbours;
  48984. this.needsUpdate = true;
  48985. }
  48986. get neighbourCount(){
  48987. return this._neighbourCount;
  48988. }
  48989. set neighbourCount(value){
  48990. if (this._neighbourCount !== value) {
  48991. this._neighbourCount = value;
  48992. this.neighbours = new Float32Array(this._neighbourCount * 2);
  48993. for (let c = 0; c < this._neighbourCount; c++) {
  48994. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  48995. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  48996. }
  48997. this.updateShaderSource();
  48998. }
  48999. }
  49000. }
  49001. class NormalizationMaterial extends RawShaderMaterial{
  49002. constructor(parameters = {}){
  49003. super();
  49004. let uniforms = {
  49005. uDepthMap: { type: 't', value: null },
  49006. uWeightMap: { type: 't', value: null },
  49007. };
  49008. this.setValues({
  49009. uniforms: uniforms,
  49010. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  49011. fragmentShader: this.getDefines() + Shaders['normalize.fs'],
  49012. });
  49013. }
  49014. getDefines() {
  49015. let defines = '';
  49016. return defines;
  49017. }
  49018. updateShaderSource() {
  49019. let vs = this.getDefines() + Shaders['normalize.vs'];
  49020. let fs = this.getDefines() + Shaders['normalize.fs'];
  49021. this.setValues({
  49022. vertexShader: vs,
  49023. fragmentShader: fs
  49024. });
  49025. this.needsUpdate = true;
  49026. }
  49027. }
  49028. /**
  49029. * laslaz code taken and adapted from plas.io js-laslaz
  49030. * http://plas.io/
  49031. * https://github.com/verma/plasio
  49032. *
  49033. * Thanks to Uday Verma and Howard Butler
  49034. *
  49035. */
  49036. class LasLazLoader {
  49037. constructor (version, extension) {
  49038. if (typeof (version) === 'string') {
  49039. this.version = new Version(version);
  49040. } else {
  49041. this.version = version;
  49042. }
  49043. this.extension = extension;
  49044. }
  49045. static progressCB () {
  49046. }
  49047. load (node) {
  49048. if (node.loaded) {
  49049. return;
  49050. }
  49051. let url = node.getURL();
  49052. if (this.version.equalOrHigher('1.4')) {
  49053. url += `.${this.extension}`;
  49054. }
  49055. let xhr = XHRFactory.createXMLHttpRequest();
  49056. xhr.open('GET', url, true);
  49057. xhr.responseType = 'arraybuffer';
  49058. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49059. xhr.onreadystatechange = () => {
  49060. if (xhr.readyState === 4) {
  49061. if (xhr.status === 200 || xhr.status === 0) {
  49062. let buffer = xhr.response;
  49063. this.parse(node, buffer);
  49064. } else {
  49065. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url);
  49066. }
  49067. }
  49068. };
  49069. xhr.send(null);
  49070. }
  49071. async parse(node, buffer){
  49072. let lf = new LASFile(buffer);
  49073. let handler = new LasLazBatcher(node);
  49074. try{
  49075. await lf.open();
  49076. lf.isOpen = true;
  49077. }catch(e){
  49078. console.log("failed to open file. :(");
  49079. return;
  49080. }
  49081. let header = await lf.getHeader();
  49082. let skip = 1;
  49083. let totalRead = 0;
  49084. let totalToRead = (skip <= 1 ? header.pointsCount : header.pointsCount / skip);
  49085. let hasMoreData = true;
  49086. while(hasMoreData){
  49087. let data = await lf.readData(1000 * 1000, 0, skip);
  49088. handler.push(new LASDecoder(data.buffer,
  49089. header.pointsFormatId,
  49090. header.pointsStructSize,
  49091. data.count,
  49092. header.scale,
  49093. header.offset,
  49094. header.mins, header.maxs));
  49095. totalRead += data.count;
  49096. LasLazLoader.progressCB(totalRead / totalToRead);
  49097. hasMoreData = data.hasMoreData;
  49098. }
  49099. header.totalRead = totalRead;
  49100. header.versionAsString = lf.versionAsString;
  49101. header.isCompressed = lf.isCompressed;
  49102. LasLazLoader.progressCB(1);
  49103. try{
  49104. await lf.close();
  49105. lf.isOpen = false;
  49106. }catch(e){
  49107. console.error("failed to close las/laz file!!!");
  49108. throw e;
  49109. }
  49110. }
  49111. handle (node, url) {
  49112. }
  49113. };
  49114. class LasLazBatcher{
  49115. constructor (node) {
  49116. this.node = node;
  49117. }
  49118. push (lasBuffer) {
  49119. const workerPath = Potree.scriptPath + '/workers/LASDecoderWorker.js';
  49120. const worker = Potree.workerPool.getWorker(workerPath);
  49121. const node = this.node;
  49122. const pointAttributes = node.pcoGeometry.pointAttributes;
  49123. worker.onmessage = (e) => {
  49124. let geometry = new BufferGeometry();
  49125. let numPoints = lasBuffer.pointsCount;
  49126. let positions = new Float32Array(e.data.position);
  49127. let colors = new Uint8Array(e.data.color);
  49128. let intensities = new Float32Array(e.data.intensity);
  49129. let classifications = new Uint8Array(e.data.classification);
  49130. let returnNumbers = new Uint8Array(e.data.returnNumber);
  49131. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49132. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  49133. let indices = new Uint8Array(e.data.indices);
  49134. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  49135. geometry.setAttribute('color', new BufferAttribute(colors, 4, true));
  49136. geometry.setAttribute('intensity', new BufferAttribute(intensities, 1));
  49137. geometry.setAttribute('classification', new BufferAttribute(classifications, 1));
  49138. geometry.setAttribute('return number', new BufferAttribute(returnNumbers, 1));
  49139. geometry.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  49140. geometry.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1));
  49141. geometry.setAttribute('indices', new BufferAttribute(indices, 4));
  49142. geometry.attributes.indices.normalized = true;
  49143. for(const key in e.data.ranges){
  49144. const range = e.data.ranges[key];
  49145. const attribute = pointAttributes.attributes.find(a => a.name === key);
  49146. attribute.range[0] = Math.min(attribute.range[0], range[0]);
  49147. attribute.range[1] = Math.max(attribute.range[1], range[1]);
  49148. }
  49149. let tightBoundingBox = new Box3(
  49150. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49151. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49152. );
  49153. geometry.boundingBox = this.node.boundingBox;
  49154. this.node.tightBoundingBox = tightBoundingBox;
  49155. this.node.geometry = geometry;
  49156. this.node.numPoints = numPoints;
  49157. this.node.loaded = true;
  49158. this.node.loading = false;
  49159. Potree.numNodesLoading--;
  49160. this.node.mean = new Vector3(...e.data.mean);
  49161. Potree.workerPool.returnWorker(workerPath, worker);
  49162. };
  49163. let message = {
  49164. buffer: lasBuffer.arrayb,
  49165. numPoints: lasBuffer.pointsCount,
  49166. pointSize: lasBuffer.pointSize,
  49167. pointFormatID: 2,
  49168. scale: lasBuffer.scale,
  49169. offset: lasBuffer.offset,
  49170. mins: lasBuffer.mins,
  49171. maxs: lasBuffer.maxs
  49172. };
  49173. worker.postMessage(message, [message.buffer]);
  49174. };
  49175. }
  49176. //加载 解析点云
  49177. class BinaryLoader{
  49178. constructor(version, boundingBox, scale){
  49179. if (typeof (version) === 'string') {
  49180. this.version = new Version(version);
  49181. } else {
  49182. this.version = version;
  49183. }
  49184. this.boundingBox = boundingBox;
  49185. this.scale = scale;
  49186. }
  49187. load(node){
  49188. if (node.loaded) {
  49189. return;
  49190. }
  49191. let url = node.getURL();
  49192. if (this.version.equalOrHigher('1.4')) {
  49193. url += '.bin';
  49194. }
  49195. url += '?m='+node.pcoGeometry.timeStamp; //add
  49196. let xhr = XHRFactory.createXMLHttpRequest();
  49197. xhr.open('GET', url, true);
  49198. xhr.responseType = 'arraybuffer';
  49199. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49200. xhr.onreadystatechange = () => {
  49201. if (xhr.readyState === 4) {
  49202. if((xhr.status === 200 || xhr.status === 0) && xhr.response !== null){
  49203. let buffer = xhr.response;
  49204. this.parse(node, buffer);
  49205. } else {
  49206. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  49207. throw new Error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  49208. }
  49209. }
  49210. };
  49211. try {
  49212. xhr.send(null);
  49213. } catch (e) {
  49214. console.log('fehler beim laden der punktwolke: ' + e);
  49215. }
  49216. };
  49217. parse(node, buffer){ //解析点云
  49218. let pointAttributes = node.pcoGeometry.pointAttributes;
  49219. let numPoints = buffer.byteLength / node.pcoGeometry.pointAttributes.byteSize;
  49220. if (this.version.upTo('1.5')) {
  49221. node.numPoints = numPoints;
  49222. }
  49223. let workerPath = Potree.scriptPath + '/workers/BinaryDecoderWorker.js';
  49224. let worker = Potree.workerPool.getWorker(workerPath);
  49225. worker.onmessage = function (e) {
  49226. let data = e.data;
  49227. let buffers = data.attributeBuffers;
  49228. let tightBoundingBox = new Box3(
  49229. new Vector3().fromArray(data.tightBoundingBox.min),
  49230. new Vector3().fromArray(data.tightBoundingBox.max)
  49231. );
  49232. Potree.workerPool.returnWorker(workerPath, worker);
  49233. let geometry = new BufferGeometry();
  49234. for(let property in buffers){
  49235. let buffer = buffers[property].buffer;
  49236. let batchAttribute = buffers[property].attribute;
  49237. if (property === "POSITION_CARTESIAN") {
  49238. geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3));
  49239. } else if (property === "rgba") {
  49240. geometry.setAttribute("rgba", new BufferAttribute(new Uint8Array(buffer), 4, true));
  49241. } else if (property === "NORMAL_SPHEREMAPPED") {
  49242. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49243. } else if (property === "NORMAL_OCT16") {
  49244. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49245. } else if (property === "NORMAL") {
  49246. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49247. } else if (property === "INDICES") {
  49248. let bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4);
  49249. bufferAttribute.normalized = true;
  49250. geometry.setAttribute('indices', bufferAttribute);
  49251. } else if (property === "SPACING") {
  49252. let bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  49253. geometry.setAttribute('spacing', bufferAttribute);
  49254. } else {
  49255. const bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  49256. bufferAttribute.potree = {
  49257. offset: buffers[property].offset,
  49258. scale: buffers[property].scale,
  49259. preciseBuffer: buffers[property].preciseBuffer,
  49260. range: batchAttribute.range,
  49261. };
  49262. geometry.setAttribute(property, bufferAttribute);
  49263. const attribute = pointAttributes.attributes.find(a => a.name === batchAttribute.name);
  49264. attribute.range[0] = Math.min(attribute.range[0], batchAttribute.range[0]);
  49265. attribute.range[1] = Math.max(attribute.range[1], batchAttribute.range[1]);
  49266. if(node.getLevel() === 0){
  49267. attribute.initialRange = batchAttribute.range;
  49268. }
  49269. }
  49270. }
  49271. tightBoundingBox.max.sub(tightBoundingBox.min);
  49272. tightBoundingBox.min.set(0, 0, 0);
  49273. let numPoints = e.data.buffer.byteLength / pointAttributes.byteSize;
  49274. node.numPoints = numPoints;
  49275. node.geometry = geometry;
  49276. node.mean = new Vector3(...data.mean);
  49277. node.tightBoundingBox = tightBoundingBox;
  49278. node.loaded = true;
  49279. node.loading = false;
  49280. node.estimatedSpacing = data.estimatedSpacing;
  49281. Potree.numNodesLoading--;
  49282. };
  49283. let message = {
  49284. buffer: buffer,
  49285. pointAttributes: pointAttributes,
  49286. version: this.version.version,
  49287. min: [ node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z ],
  49288. offset: [node.pcoGeometry.offset.x, node.pcoGeometry.offset.y, node.pcoGeometry.offset.z],
  49289. scale: this.scale,
  49290. spacing: node.spacing,
  49291. hasChildren: node.hasChildren,
  49292. name: node.name
  49293. };
  49294. worker.postMessage(message, [message.buffer]);
  49295. };
  49296. }
  49297. var transformFrom4dkk = function(name){
  49298. var jsAttribute = PointAttribute[name];
  49299. return jsAttribute
  49300. /* if(name == "POSITION_CARTESIAN"){
  49301. jsAttribute = {
  49302. description: "",
  49303. elementSize: 4,
  49304. elements: 3,
  49305. name: "POSITION_CARTESIAN",
  49306. size: 12,
  49307. type: "int32",
  49308. }
  49309. }else if(name == "COLOR_PACKED"){
  49310. jsAttribute = {
  49311. description: "" ,
  49312. elementSize: 1,
  49313. elements: 4,
  49314. name: "RGBA",
  49315. size: 4,
  49316. type: 'int8',
  49317. }
  49318. }else if(name == "NORMAL_OCT16"){
  49319. jsAttribute = {
  49320. description: "" ,
  49321. elementSize: 4,
  49322. elements: 2,
  49323. name: "NORMAL_OCT16",
  49324. size: 12,
  49325. type: "uint8",
  49326. }
  49327. } */
  49328. /* var Q = q(L.COLOR_PACKED, K.DATA_TYPE_INT8, 4)
  49329. POSITION_CARTESIAN: q(L.POSITION_CARTESIAN, K.DATA_TYPE_FLOAT, 3),
  49330. RGBA_PACKED: Q,
  49331. COLOR_PACKED: Q,
  49332. RGB_PACKED: q(L.COLOR_PACKED, K.DATA_TYPE_INT8, 3),
  49333. NORMAL_FLOATS: q(L.NORMAL_FLOATS, K.DATA_TYPE_FLOAT, 3),
  49334. FILLER_1B: q(L.FILLER, K.DATA_TYPE_UINT8, 1),
  49335. INTENSITY: q(L.INTENSITY, K.DATA_TYPE_UINT16, 1),
  49336. CLASSIFICATION: q(L.CLASSIFICATION, K.DATA_TYPE_UINT8, 1),
  49337. NORMAL_SPHEREMAPPED: q(L.NORMAL_SPHEREMAPPED, K.DATA_TYPE_UINT8, 2),
  49338. NORMAL_OCT16: q(L.NORMAL_OCT16, K.DATA_TYPE_UINT8, 2),
  49339. NORMAL: q(L.NORMAL, K.DATA_TYPE_FLOAT, 3) */
  49340. };
  49341. function parseAttributes(cloudjs){
  49342. let version = new Version(cloudjs.version);
  49343. const replacements = {
  49344. "COLOR_PACKED": "rgba",
  49345. "RGBA": "rgba",
  49346. "INTENSITY": "intensity",
  49347. "CLASSIFICATION": "classification",
  49348. "GPS_TIME": "gps-time",
  49349. };
  49350. const replaceOldNames = (old) => {
  49351. if(replacements[old]){
  49352. return replacements[old];
  49353. }else {
  49354. return old;
  49355. }
  49356. };
  49357. const pointAttributes = [];
  49358. if(version.upTo('1.7')){
  49359. for(let attributeName of cloudjs.pointAttributes){
  49360. const oldAttribute = PointAttribute[attributeName];
  49361. const attribute = {
  49362. name: oldAttribute.name,
  49363. size: oldAttribute.byteSize,
  49364. elements: oldAttribute.numElements,
  49365. elementSize: oldAttribute.byteSize / oldAttribute.numElements,
  49366. type: oldAttribute.type.name,
  49367. description: "",
  49368. };
  49369. pointAttributes.push(attribute);
  49370. }
  49371. }else {
  49372. pointAttributes.push(...cloudjs.pointAttributes);
  49373. }
  49374. {
  49375. const attributes = new PointAttributes();
  49376. const typeConversion = {
  49377. int8: PointAttributeTypes.DATA_TYPE_INT8,
  49378. int16: PointAttributeTypes.DATA_TYPE_INT16,
  49379. int32: PointAttributeTypes.DATA_TYPE_INT32,
  49380. int64: PointAttributeTypes.DATA_TYPE_INT64,
  49381. uint8: PointAttributeTypes.DATA_TYPE_UINT8,
  49382. uint16: PointAttributeTypes.DATA_TYPE_UINT16,
  49383. uint32: PointAttributeTypes.DATA_TYPE_UINT32,
  49384. uint64: PointAttributeTypes.DATA_TYPE_UINT64,
  49385. double: PointAttributeTypes.DATA_TYPE_DOUBLE,
  49386. float: PointAttributeTypes.DATA_TYPE_FLOAT,
  49387. };
  49388. for(let jsAttribute of pointAttributes){
  49389. if(jsAttribute.name == void 0){//是来自四维看看的数据
  49390. //attribute = transformFrom4dkk(jsAttribute)
  49391. var attribute_ = PointAttribute[jsAttribute];
  49392. attributes.add(attribute_);
  49393. continue;
  49394. }
  49395. const name = replaceOldNames(jsAttribute.name);
  49396. const type = typeConversion[jsAttribute.type];
  49397. const numElements = jsAttribute.elements;
  49398. const description = jsAttribute.description;
  49399. const attribute = new PointAttribute(name, type, numElements);
  49400. attributes.add(attribute);
  49401. }
  49402. {
  49403. // check if it has normals
  49404. let hasNormals =
  49405. pointAttributes.find(a => a.name === "NormalX") !== undefined &&
  49406. pointAttributes.find(a => a.name === "NormalY") !== undefined &&
  49407. pointAttributes.find(a => a.name === "NormalZ") !== undefined;
  49408. if(hasNormals){
  49409. let vector = {
  49410. name: "NORMAL",
  49411. attributes: ["NormalX", "NormalY", "NormalZ"],
  49412. };
  49413. attributes.addVector(vector);
  49414. }
  49415. }
  49416. return attributes;
  49417. }
  49418. }
  49419. function lasLazAttributes(fMno){
  49420. const attributes = new PointAttributes();
  49421. attributes.add(PointAttribute.POSITION_CARTESIAN);
  49422. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  49423. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  49424. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49425. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  49426. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49427. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49428. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  49429. //attributes.add(new PointAttribute("pointSourceID", PointAttributeTypes.DATA_TYPE_INT8, 4));
  49430. return attributes;
  49431. }
  49432. class POCLoader {
  49433. static load(url, timeStamp, callback){ //add timeStamp
  49434. try {
  49435. let pco = new PointCloudOctreeGeometry();
  49436. pco.timeStamp = timeStamp;
  49437. pco.url = url;
  49438. let xhr = XHRFactory.createXMLHttpRequest();
  49439. xhr.open('GET', url+'?m='+timeStamp, true);
  49440. xhr.onreadystatechange = function () {
  49441. if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
  49442. let fMno = JSON.parse(xhr.responseText);
  49443. let version = new Version(fMno.version);
  49444. // assume octreeDir is absolute if it starts with http
  49445. if (fMno.octreeDir.indexOf('http') === 0) {
  49446. pco.octreeDir = fMno.octreeDir;
  49447. } else {
  49448. pco.octreeDir = url + '/../' + fMno.octreeDir;
  49449. }
  49450. pco.spacing = fMno.spacing;
  49451. pco.hierarchyStepSize = fMno.hierarchyStepSize;
  49452. pco.pointAttributes = fMno.pointAttributes;
  49453. let min = new Vector3(fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz);
  49454. let max = new Vector3(fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz);
  49455. let boundingBox = new Box3(min, max);
  49456. let tightBoundingBox = boundingBox.clone();
  49457. if (fMno.tightBoundingBox) {//这个才是真实的bounding,前面那个bounding的size是个正方体,似乎取了最长边作为边长
  49458. tightBoundingBox.min.copy(new Vector3(fMno.tightBoundingBox.lx, fMno.tightBoundingBox.ly, fMno.tightBoundingBox.lz));
  49459. tightBoundingBox.max.copy(new Vector3(fMno.tightBoundingBox.ux, fMno.tightBoundingBox.uy, fMno.tightBoundingBox.uz));
  49460. }
  49461. let offset = min.clone(); //将成为点云的position,被我用作旋转中心(但在点云中不那么居中,navvis也是这样, 这样可能是为了让模型在这数据的bounding上)
  49462. boundingBox.min.sub(offset); //点云的真实坐标的min都是0,0,0吗(我看案例是,因绕角落旋转,也就是原点)
  49463. boundingBox.max.sub(offset);
  49464. tightBoundingBox.min.sub(offset);
  49465. tightBoundingBox.max.sub(offset);
  49466. //改
  49467. //pco.projection = fMno.projection || "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs ",
  49468. //"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" //给地图
  49469. pco.boundingBox = boundingBox;
  49470. pco.tightBoundingBox = tightBoundingBox;
  49471. pco.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  49472. pco.tightBoundingSphere = tightBoundingBox.getBoundingSphere(new Sphere());
  49473. pco.offset = offset;
  49474. if (fMno.pointAttributes === 'LAS') {
  49475. pco.loader = new LasLazLoader(fMno.version, "las");
  49476. pco.pointAttributes = lasLazAttributes(fMno);
  49477. } else if (fMno.pointAttributes === 'LAZ') {
  49478. pco.loader = new LasLazLoader(fMno.version, "laz");
  49479. pco.pointAttributes = lasLazAttributes(fMno);
  49480. } else {
  49481. pco.loader = new BinaryLoader(fMno.version, boundingBox, fMno.scale);
  49482. pco.pointAttributes = parseAttributes(fMno);
  49483. }
  49484. let nodes = {};
  49485. { // load root
  49486. let name = 'r';
  49487. let root = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  49488. root.level = 0;
  49489. root.hasChildren = true;
  49490. root.spacing = pco.spacing;
  49491. if (version.upTo('1.5')) {
  49492. root.numPoints = fMno.hierarchy[0][1];
  49493. } else {
  49494. root.numPoints = 0;
  49495. }
  49496. pco.root = root;
  49497. pco.root.load();
  49498. nodes[name] = root;
  49499. }
  49500. // load remaining hierarchy
  49501. if (version.upTo('1.4')) {
  49502. for (let i = 1; i < fMno.hierarchy.length; i++) {
  49503. let name = fMno.hierarchy[i][0];
  49504. let numPoints = fMno.hierarchy[i][1];
  49505. let index = parseInt(name.charAt(name.length - 1));
  49506. let parentName = name.substring(0, name.length - 1);
  49507. let parentNode = nodes[parentName];
  49508. let level = name.length - 1;
  49509. //let boundingBox = POCLoader.createChildAABB(parentNode.boundingBox, index);
  49510. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  49511. let node = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  49512. node.level = level;
  49513. node.numPoints = numPoints;
  49514. node.spacing = pco.spacing / Math.pow(2, level);
  49515. parentNode.addChild(node);
  49516. nodes[name] = node;
  49517. }
  49518. }
  49519. pco.nodes = nodes;
  49520. callback(pco);
  49521. }
  49522. };
  49523. xhr.send(null);
  49524. } catch (e) {
  49525. console.log("loading failed: '" + url + "'");
  49526. console.log(e);
  49527. callback();
  49528. }
  49529. }
  49530. loadPointAttributes(mno){
  49531. let fpa = mno.pointAttributes;
  49532. let pa = new PointAttributes();
  49533. for (let i = 0; i < fpa.length; i++) {
  49534. let pointAttribute = PointAttribute[fpa[i]];
  49535. pa.add(pointAttribute);
  49536. }
  49537. return pa;
  49538. }
  49539. createChildAABB(aabb, index){
  49540. let min = aabb.min.clone();
  49541. let max = aabb.max.clone();
  49542. let size = new Vector3().subVectors(max, min);
  49543. if ((index & 0b0001) > 0) {
  49544. min.z += size.z / 2;
  49545. } else {
  49546. max.z -= size.z / 2;
  49547. }
  49548. if ((index & 0b0010) > 0) {
  49549. min.y += size.y / 2;
  49550. } else {
  49551. max.y -= size.y / 2;
  49552. }
  49553. if ((index & 0b0100) > 0) {
  49554. min.x += size.x / 2;
  49555. } else {
  49556. max.x -= size.x / 2;
  49557. }
  49558. return new Box3(min, max);
  49559. }
  49560. }
  49561. /**
  49562. * @author Connor Manning
  49563. */
  49564. class EptLoader {
  49565. static async load(file, callback) {
  49566. let response = await fetch(file);
  49567. let json = await response.json();
  49568. let url = file.substr(0, file.lastIndexOf('ept.json'));
  49569. let geometry = new Potree.PointCloudEptGeometry(url, json);
  49570. let root = new Potree.PointCloudEptGeometryNode(geometry);
  49571. geometry.root = root;
  49572. geometry.root.load();
  49573. callback(geometry);
  49574. }
  49575. };
  49576. class EptBinaryLoader {
  49577. extension() {
  49578. return '.bin';
  49579. }
  49580. workerPath() {
  49581. return Potree.scriptPath + '/workers/EptBinaryDecoderWorker.js';
  49582. }
  49583. load(node) {
  49584. if (node.loaded) return;
  49585. let url = node.url() + this.extension();
  49586. let xhr = XHRFactory.createXMLHttpRequest();
  49587. xhr.open('GET', url, true);
  49588. xhr.responseType = 'arraybuffer';
  49589. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49590. xhr.onreadystatechange = () => {
  49591. if (xhr.readyState === 4) {
  49592. if (xhr.status === 200) {
  49593. let buffer = xhr.response;
  49594. this.parse(node, buffer);
  49595. } else {
  49596. console.log('Failed ' + url + ': ' + xhr.status);
  49597. }
  49598. }
  49599. };
  49600. try {
  49601. xhr.send(null);
  49602. }
  49603. catch (e) {
  49604. console.log('Failed request: ' + e);
  49605. }
  49606. }
  49607. parse(node, buffer) {
  49608. let workerPath = this.workerPath();
  49609. let worker = Potree.workerPool.getWorker(workerPath);
  49610. worker.onmessage = function(e) {
  49611. let g = new BufferGeometry();
  49612. let numPoints = e.data.numPoints;
  49613. let position = new Float32Array(e.data.position);
  49614. g.setAttribute('position', new BufferAttribute(position, 3));
  49615. let indices = new Uint8Array(e.data.indices);
  49616. g.setAttribute('indices', new BufferAttribute(indices, 4));
  49617. if (e.data.color) {
  49618. let color = new Uint8Array(e.data.color);
  49619. g.setAttribute('color', new BufferAttribute(color, 4, true));
  49620. }
  49621. if (e.data.intensity) {
  49622. let intensity = new Float32Array(e.data.intensity);
  49623. g.setAttribute('intensity',
  49624. new BufferAttribute(intensity, 1));
  49625. }
  49626. if (e.data.classification) {
  49627. let classification = new Uint8Array(e.data.classification);
  49628. g.setAttribute('classification',
  49629. new BufferAttribute(classification, 1));
  49630. }
  49631. if (e.data.returnNumber) {
  49632. let returnNumber = new Uint8Array(e.data.returnNumber);
  49633. g.setAttribute('return number',
  49634. new BufferAttribute(returnNumber, 1));
  49635. }
  49636. if (e.data.numberOfReturns) {
  49637. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49638. g.setAttribute('number of returns',
  49639. new BufferAttribute(numberOfReturns, 1));
  49640. }
  49641. if (e.data.pointSourceId) {
  49642. let pointSourceId = new Uint16Array(e.data.pointSourceId);
  49643. g.setAttribute('source id',
  49644. new BufferAttribute(pointSourceId, 1));
  49645. }
  49646. g.attributes.indices.normalized = true;
  49647. let tightBoundingBox = new Box3(
  49648. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49649. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49650. );
  49651. node.doneLoading(
  49652. g,
  49653. tightBoundingBox,
  49654. numPoints,
  49655. new Vector3(...e.data.mean));
  49656. Potree.workerPool.returnWorker(workerPath, worker);
  49657. };
  49658. let toArray = (v) => [v.x, v.y, v.z];
  49659. let message = {
  49660. buffer: buffer,
  49661. schema: node.ept.schema,
  49662. scale: node.ept.eptScale,
  49663. offset: node.ept.eptOffset,
  49664. mins: toArray(node.key.b.min)
  49665. };
  49666. worker.postMessage(message, [message.buffer]);
  49667. }
  49668. };
  49669. /**
  49670. * laslaz code taken and adapted from plas.io js-laslaz
  49671. * http://plas.io/
  49672. * https://github.com/verma/plasio
  49673. *
  49674. * Thanks to Uday Verma and Howard Butler
  49675. *
  49676. */
  49677. class EptLaszipLoader {
  49678. load(node) {
  49679. if (node.loaded) return;
  49680. let url = node.url() + '.laz';
  49681. let xhr = XHRFactory.createXMLHttpRequest();
  49682. xhr.open('GET', url, true);
  49683. xhr.responseType = 'arraybuffer';
  49684. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49685. xhr.onreadystatechange = () => {
  49686. if (xhr.readyState === 4) {
  49687. if (xhr.status === 200) {
  49688. let buffer = xhr.response;
  49689. this.parse(node, buffer);
  49690. } else {
  49691. console.log('Failed ' + url + ': ' + xhr.status);
  49692. }
  49693. }
  49694. };
  49695. xhr.send(null);
  49696. }
  49697. async parse(node, buffer){
  49698. let lf = new LASFile(buffer);
  49699. let handler = new EptLazBatcher(node);
  49700. try{
  49701. await lf.open();
  49702. lf.isOpen = true;
  49703. const header = await lf.getHeader();
  49704. {
  49705. let i = 0;
  49706. let toArray = (v) => [v.x, v.y, v.z];
  49707. let mins = toArray(node.key.b.min);
  49708. let maxs = toArray(node.key.b.max);
  49709. let hasMoreData = true;
  49710. while(hasMoreData){
  49711. const data = await lf.readData(1000000, 0, 1);
  49712. let d = new LASDecoder(
  49713. data.buffer,
  49714. header.pointsFormatId,
  49715. header.pointsStructSize,
  49716. data.count,
  49717. header.scale,
  49718. header.offset,
  49719. mins,
  49720. maxs);
  49721. d.extraBytes = header.extraBytes;
  49722. d.pointsFormatId = header.pointsFormatId;
  49723. handler.push(d);
  49724. i += data.count;
  49725. hasMoreData = data.hasMoreData;
  49726. }
  49727. header.totalRead = i;
  49728. header.versionAsString = lf.versionAsString;
  49729. header.isCompressed = lf.isCompressed;
  49730. await lf.close();
  49731. lf.isOpen = false;
  49732. }
  49733. }catch(err){
  49734. console.error('Error reading LAZ:', err);
  49735. if (lf.isOpen) {
  49736. await lf.close();
  49737. lf.isOpen = false;
  49738. }
  49739. throw err;
  49740. }
  49741. }
  49742. };
  49743. class EptLazBatcher {
  49744. constructor(node) { this.node = node; }
  49745. push(las) {
  49746. let workerPath = Potree.scriptPath +
  49747. '/workers/EptLaszipDecoderWorker.js';
  49748. let worker = Potree.workerPool.getWorker(workerPath);
  49749. worker.onmessage = (e) => {
  49750. let g = new BufferGeometry();
  49751. let numPoints = las.pointsCount;
  49752. let positions = new Float32Array(e.data.position);
  49753. let colors = new Uint8Array(e.data.color);
  49754. let intensities = new Float32Array(e.data.intensity);
  49755. let classifications = new Uint8Array(e.data.classification);
  49756. let returnNumbers = new Uint8Array(e.data.returnNumber);
  49757. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49758. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  49759. let indices = new Uint8Array(e.data.indices);
  49760. let gpsTime = new Float32Array(e.data.gpsTime);
  49761. g.setAttribute('position',
  49762. new BufferAttribute(positions, 3));
  49763. g.setAttribute('rgba',
  49764. new BufferAttribute(colors, 4, true));
  49765. g.setAttribute('intensity',
  49766. new BufferAttribute(intensities, 1));
  49767. g.setAttribute('classification',
  49768. new BufferAttribute(classifications, 1));
  49769. g.setAttribute('return number',
  49770. new BufferAttribute(returnNumbers, 1));
  49771. g.setAttribute('number of returns',
  49772. new BufferAttribute(numberOfReturns, 1));
  49773. g.setAttribute('source id',
  49774. new BufferAttribute(pointSourceIDs, 1));
  49775. g.setAttribute('indices',
  49776. new BufferAttribute(indices, 4));
  49777. g.setAttribute('gpsTime',
  49778. new BufferAttribute(gpsTime, 1));
  49779. this.node.gpsTime = e.data.gpsMeta;
  49780. g.attributes.indices.normalized = true;
  49781. let tightBoundingBox = new Box3(
  49782. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49783. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49784. );
  49785. this.node.doneLoading(
  49786. g,
  49787. tightBoundingBox,
  49788. numPoints,
  49789. new Vector3(...e.data.mean));
  49790. Potree.workerPool.returnWorker(workerPath, worker);
  49791. };
  49792. let message = {
  49793. buffer: las.arrayb,
  49794. numPoints: las.pointsCount,
  49795. pointSize: las.pointSize,
  49796. pointFormatID: las.pointsFormatId,
  49797. scale: las.scale,
  49798. offset: las.offset,
  49799. mins: las.mins,
  49800. maxs: las.maxs
  49801. };
  49802. worker.postMessage(message, [message.buffer]);
  49803. };
  49804. };
  49805. class EptZstandardLoader extends EptBinaryLoader {
  49806. extension() {
  49807. return '.zst';
  49808. }
  49809. workerPath() {
  49810. return Potree.scriptPath + '/workers/EptZstandardDecoderWorker.js';
  49811. }
  49812. };
  49813. class ShapefileLoader{
  49814. constructor(){
  49815. this.transform = null;
  49816. }
  49817. async load(path){
  49818. const matLine = new LineMaterial( {
  49819. color: 0xff0000,
  49820. lineWidth: 3, // in pixels
  49821. resolution: new Vector2$1(1000, 1000),
  49822. dashed: false
  49823. } );
  49824. const features = await this.loadShapefileFeatures(path);
  49825. const node = new Object3D();
  49826. for(const feature of features){
  49827. const fnode = this.featureToSceneNode(feature, matLine);
  49828. node.add(fnode);
  49829. }
  49830. let setResolution = (x, y) => {
  49831. matLine.resolution.set(x, y);
  49832. };
  49833. const result = {
  49834. features: features,
  49835. node: node,
  49836. setResolution: setResolution,
  49837. };
  49838. return result;
  49839. }
  49840. featureToSceneNode(feature, matLine){
  49841. let geometry = feature.geometry;
  49842. let color = new Color(1, 1, 1);
  49843. let transform = this.transform;
  49844. if(transform === null){
  49845. transform = {forward: (v) => v};
  49846. }
  49847. if(feature.geometry.type === "Point"){
  49848. let sg = new SphereGeometry(1, 18, 18);
  49849. let sm = new MeshNormalMaterial();
  49850. let s = new Mesh(sg, sm);
  49851. let [long, lat] = geometry.coordinates;
  49852. let pos = transform.forward([long, lat]);
  49853. s.position.set(...pos, 20);
  49854. s.scale.set(10, 10, 10);
  49855. return s;
  49856. }else if(geometry.type === "LineString"){
  49857. let coordinates = [];
  49858. let min = new Vector3(Infinity, Infinity, Infinity);
  49859. for(let i = 0; i < geometry.coordinates.length; i++){
  49860. let [long, lat] = geometry.coordinates[i];
  49861. let pos = transform.forward([long, lat]);
  49862. min.x = Math.min(min.x, pos[0]);
  49863. min.y = Math.min(min.y, pos[1]);
  49864. min.z = Math.min(min.z, 20);
  49865. coordinates.push(...pos, 20);
  49866. if(i > 0 && i < geometry.coordinates.length - 1){
  49867. coordinates.push(...pos, 20);
  49868. }
  49869. }
  49870. for(let i = 0; i < coordinates.length; i += 3){
  49871. coordinates[i+0] -= min.x;
  49872. coordinates[i+1] -= min.y;
  49873. coordinates[i+2] -= min.z;
  49874. }
  49875. const lineGeometry = new LineGeometry();
  49876. lineGeometry.setPositions( coordinates );
  49877. const line = new Line2( lineGeometry, matLine );
  49878. line.computeLineDistances();
  49879. line.scale.set( 1, 1, 1 );
  49880. line.position.copy(min);
  49881. return line;
  49882. }else if(geometry.type === "Polygon"){
  49883. for(let pc of geometry.coordinates){
  49884. let coordinates = [];
  49885. let min = new Vector3(Infinity, Infinity, Infinity);
  49886. for(let i = 0; i < pc.length; i++){
  49887. let [long, lat] = pc[i];
  49888. let pos = transform.forward([long, lat]);
  49889. min.x = Math.min(min.x, pos[0]);
  49890. min.y = Math.min(min.y, pos[1]);
  49891. min.z = Math.min(min.z, 20);
  49892. coordinates.push(...pos, 20);
  49893. if(i > 0 && i < pc.length - 1){
  49894. coordinates.push(...pos, 20);
  49895. }
  49896. }
  49897. for(let i = 0; i < coordinates.length; i += 3){
  49898. coordinates[i+0] -= min.x;
  49899. coordinates[i+1] -= min.y;
  49900. coordinates[i+2] -= min.z;
  49901. }
  49902. const lineGeometry = new LineGeometry();
  49903. lineGeometry.setPositions( coordinates );
  49904. const line = new Line2( lineGeometry, matLine );
  49905. line.computeLineDistances();
  49906. line.scale.set( 1, 1, 1 );
  49907. line.position.copy(min);
  49908. return line;
  49909. }
  49910. }else {
  49911. console.log("unhandled feature: ", feature);
  49912. }
  49913. }
  49914. async loadShapefileFeatures(file){
  49915. let features = [];
  49916. let source = await shapefile.open(file);
  49917. while(true){
  49918. let result = await source.read();
  49919. if (result.done) {
  49920. break;
  49921. }
  49922. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  49923. features.push(result.value);
  49924. }
  49925. }
  49926. return features;
  49927. }
  49928. };
  49929. const defaultColors = {
  49930. "landuse": [0.5, 0.5, 0.5],
  49931. "natural": [0.0, 1.0, 0.0],
  49932. "places": [1.0, 0.0, 1.0],
  49933. "points": [0.0, 1.0, 1.0],
  49934. "roads": [1.0, 1.0, 0.0],
  49935. "waterways": [0.0, 0.0, 1.0],
  49936. "default": [0.9, 0.6, 0.1],
  49937. };
  49938. function getColor(feature){
  49939. let color = defaultColors[feature];
  49940. if(!color){
  49941. color = defaultColors["default"];
  49942. }
  49943. return color;
  49944. }
  49945. class Geopackage$1{
  49946. constructor(){
  49947. this.path = null;
  49948. this.node = null;
  49949. }
  49950. };
  49951. class GeoPackageLoader{
  49952. constructor(){
  49953. }
  49954. static async loadUrl(url, params){
  49955. await Promise.all([
  49956. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  49957. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  49958. ]);
  49959. const result = await fetch(url);
  49960. const buffer = await result.arrayBuffer();
  49961. params = params || {};
  49962. params.source = url;
  49963. return GeoPackageLoader.loadBuffer(buffer, params);
  49964. }
  49965. static async loadBuffer(buffer, params){
  49966. await Promise.all([
  49967. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  49968. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  49969. ]);
  49970. params = params || {};
  49971. const resolver = async (resolve) => {
  49972. let transform = params.transform;
  49973. if(!transform){
  49974. transform = {forward: (arg) => arg};
  49975. }
  49976. const wasmPath = `${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.wasm`;
  49977. const SQL = await initSqlJs({ locateFile: filename => wasmPath});
  49978. const u8 = new Uint8Array(buffer);
  49979. const data = await geopackage.open(u8);
  49980. window.data = data;
  49981. const geopackageNode = new Object3D();
  49982. geopackageNode.name = params.source;
  49983. geopackageNode.potree = {
  49984. source: params.source,
  49985. };
  49986. const geo = new Geopackage$1();
  49987. geo.path = params.source;
  49988. geo.node = geopackageNode;
  49989. const tables = data.getTables();
  49990. for(const table of tables.features){
  49991. const dao = data.getFeatureDao(table);
  49992. let boundingBox = dao.getBoundingBox();
  49993. boundingBox = boundingBox.projectBoundingBox(dao.projection, 'EPSG:4326');
  49994. const geoJson = data.queryForGeoJSONFeaturesInTable(table, boundingBox);
  49995. const matLine = new LineMaterial( {
  49996. color: new Color().setRGB(...getColor(table)),
  49997. lineWidth: 2,
  49998. resolution: new Vector2$1(1000, 1000),
  49999. dashed: false
  50000. } );
  50001. const node = new Object3D();
  50002. node.name = table;
  50003. geo.node.add(node);
  50004. for(const [index, feature] of Object.entries(geoJson)){
  50005. //const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, transform);
  50006. const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, dao.projection, transform);
  50007. node.add(featureNode);
  50008. }
  50009. }
  50010. resolve(geo);
  50011. };
  50012. return new Promise(resolver);
  50013. }
  50014. static featureToSceneNode(feature, matLine, geopackageProjection, transform){
  50015. let geometry = feature.geometry;
  50016. let color = new Color(1, 1, 1);
  50017. if(feature.geometry.type === "Point"){
  50018. let sg = new SphereGeometry(1, 18, 18);
  50019. let sm = new MeshNormalMaterial();
  50020. let s = new Mesh(sg, sm);
  50021. let [long, lat] = geometry.coordinates;
  50022. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50023. s.position.set(...pos, 20);
  50024. s.scale.set(10, 10, 10);
  50025. return s;
  50026. }else if(geometry.type === "LineString"){
  50027. let coordinates = [];
  50028. let min = new Vector3(Infinity, Infinity, Infinity);
  50029. for(let i = 0; i < geometry.coordinates.length; i++){
  50030. let [long, lat] = geometry.coordinates[i];
  50031. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50032. min.x = Math.min(min.x, pos[0]);
  50033. min.y = Math.min(min.y, pos[1]);
  50034. min.z = Math.min(min.z, 20);
  50035. coordinates.push(...pos, 20);
  50036. if(i > 0 && i < geometry.coordinates.length - 1){
  50037. coordinates.push(...pos, 20);
  50038. }
  50039. }
  50040. for(let i = 0; i < coordinates.length; i += 3){
  50041. coordinates[i+0] -= min.x;
  50042. coordinates[i+1] -= min.y;
  50043. coordinates[i+2] -= min.z;
  50044. }
  50045. const lineGeometry = new LineGeometry();
  50046. lineGeometry.setPositions( coordinates );
  50047. const line = new Line2( lineGeometry, matLine );
  50048. line.computeLineDistances();
  50049. line.scale.set( 1, 1, 1 );
  50050. line.position.copy(min);
  50051. return line;
  50052. }else if(geometry.type === "Polygon"){
  50053. for(let pc of geometry.coordinates){
  50054. let coordinates = [];
  50055. let min = new Vector3(Infinity, Infinity, Infinity);
  50056. for(let i = 0; i < pc.length; i++){
  50057. let [long, lat] = pc[i];
  50058. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50059. min.x = Math.min(min.x, pos[0]);
  50060. min.y = Math.min(min.y, pos[1]);
  50061. min.z = Math.min(min.z, 20);
  50062. coordinates.push(...pos, 20);
  50063. if(i > 0 && i < pc.length - 1){
  50064. coordinates.push(...pos, 20);
  50065. }
  50066. }
  50067. for(let i = 0; i < coordinates.length; i += 3){
  50068. coordinates[i+0] -= min.x;
  50069. coordinates[i+1] -= min.y;
  50070. coordinates[i+2] -= min.z;
  50071. }
  50072. const lineGeometry = new LineGeometry();
  50073. lineGeometry.setPositions( coordinates );
  50074. const line = new Line2( lineGeometry, matLine );
  50075. line.computeLineDistances();
  50076. line.scale.set( 1, 1, 1 );
  50077. line.position.copy(min);
  50078. return line;
  50079. }
  50080. }else {
  50081. console.log("unhandled feature: ", feature);
  50082. }
  50083. }
  50084. };
  50085. class ClipVolume extends Object3D{
  50086. constructor(args={}){
  50087. super();
  50088. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  50089. this.name = "clip_volume_" + this.constructor.counter;
  50090. let alpha = args.alpha || 0;
  50091. let beta = args.beta || 0;
  50092. let gamma = args.gamma || 0;
  50093. this.rotation.x = alpha;
  50094. this.rotation.y = beta;
  50095. this.rotation.z = gamma;
  50096. this.clipOffset = 0.001;
  50097. this.clipRotOffset = 1;
  50098. let boxGeometry = new BoxGeometry(1, 1, 1);
  50099. boxGeometry.computeBoundingBox();
  50100. let boxFrameGeometry = new Geometry();
  50101. {
  50102. // bottom
  50103. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50104. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50105. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50106. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50107. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50108. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50109. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50110. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50111. // top
  50112. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50113. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50114. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50115. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50116. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50117. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50118. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50119. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50120. // sides
  50121. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50122. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50123. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50124. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50125. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50126. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50127. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50128. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50129. boxFrameGeometry.colors.push(new Vector3(1, 1, 1));
  50130. }
  50131. let planeFrameGeometry = new Geometry();
  50132. {
  50133. // middle line
  50134. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  50135. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  50136. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  50137. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  50138. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  50139. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  50140. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  50141. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  50142. }
  50143. this.dimension = new Vector3(1, 1, 1);
  50144. this.material = new MeshBasicMaterial( {
  50145. color: 0x00ff00,
  50146. transparent: true,
  50147. opacity: 0.3,
  50148. depthTest: true,
  50149. depthWrite: false} );
  50150. this.box = new Mesh(boxGeometry, this.material);
  50151. this.box.geometry.computeBoundingBox();
  50152. this.boundingBox = this.box.geometry.boundingBox;
  50153. this.add(this.box);
  50154. this.frame = new LineSegments( boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  50155. this.add(this.frame);
  50156. this.planeFrame = new LineSegments( planeFrameGeometry, new LineBasicMaterial({color: 0xff0000}));
  50157. this.add(this.planeFrame);
  50158. // set default thickness
  50159. this.setScaleZ(0.1);
  50160. // create local coordinate system
  50161. let createArrow = (name, direction, color) => {
  50162. let material = new MeshBasicMaterial({
  50163. color: color,
  50164. depthTest: false,
  50165. depthWrite: false});
  50166. let shaftGeometry = new Geometry();
  50167. shaftGeometry.vertices.push(new Vector3(0, 0, 0));
  50168. shaftGeometry.vertices.push(new Vector3(0, 1, 0));
  50169. let shaftMaterial = new LineBasicMaterial({
  50170. color: color,
  50171. depthTest: false,
  50172. depthWrite: false,
  50173. transparent: true
  50174. });
  50175. let shaft = new Line(shaftGeometry, shaftMaterial);
  50176. shaft.name = name + "_shaft";
  50177. let headGeometry = new CylinderGeometry(0, 0.04, 0.1, 10, 1, false);
  50178. let headMaterial = material;
  50179. let head = new Mesh(headGeometry, headMaterial);
  50180. head.name = name + "_head";
  50181. head.position.y = 1;
  50182. let arrow = new Object3D();
  50183. arrow.name = name;
  50184. arrow.add(shaft);
  50185. arrow.add(head);
  50186. return arrow;
  50187. };
  50188. this.arrowX = createArrow("arrow_x", new Vector3(1, 0, 0), 0xFF0000);
  50189. this.arrowY = createArrow("arrow_y", new Vector3(0, 1, 0), 0x00FF00);
  50190. this.arrowZ = createArrow("arrow_z", new Vector3(0, 0, 1), 0x0000FF);
  50191. this.arrowX.rotation.z = -Math.PI / 2;
  50192. this.arrowZ.rotation.x = Math.PI / 2;
  50193. this.arrowX.visible = false;
  50194. this.arrowY.visible = false;
  50195. this.arrowZ.visible = false;
  50196. this.add(this.arrowX);
  50197. this.add(this.arrowY);
  50198. this.add(this.arrowZ);
  50199. { // event listeners
  50200. this.addEventListener("ui_select", e => {
  50201. this.arrowX.visible = true;
  50202. this.arrowY.visible = true;
  50203. this.arrowZ.visible = true;
  50204. });
  50205. this.addEventListener("ui_deselect", e => {
  50206. this.arrowX.visible = false;
  50207. this.arrowY.visible = false;
  50208. this.arrowZ.visible = false;
  50209. });
  50210. this.addEventListener("select", e => {
  50211. let scene_header = $("#" + this.name + " .scene_header");
  50212. if(!scene_header.next().is(":visible")) {
  50213. scene_header.click();
  50214. }
  50215. });
  50216. this.addEventListener("deselect", e => {
  50217. let scene_header = $("#" + this.name + " .scene_header");
  50218. if(scene_header.next().is(":visible")) {
  50219. scene_header.click();
  50220. }
  50221. });
  50222. }
  50223. this.update();
  50224. };
  50225. setClipOffset(offset) {
  50226. this.clipOffset = offset;
  50227. }
  50228. setClipRotOffset(offset) {
  50229. this.clipRotOffset = offset;
  50230. }
  50231. setScaleX(x) {
  50232. this.box.scale.x = x;
  50233. this.frame.scale.x = x;
  50234. this.planeFrame.scale.x = x;
  50235. }
  50236. setScaleY(y) {
  50237. this.box.scale.y = y;
  50238. this.frame.scale.y = y;
  50239. this.planeFrame.scale.y = y;
  50240. }
  50241. setScaleZ(z) {
  50242. this.box.scale.z = z;
  50243. this.frame.scale.z = z;
  50244. this.planeFrame.scale.z = z;
  50245. }
  50246. offset(args) {
  50247. let cs = args.cs || null;
  50248. let axis = args.axis || null;
  50249. let dir = args.dir || null;
  50250. if(!cs || !axis || !dir) return;
  50251. if(axis === "x") {
  50252. if(cs === "local") {
  50253. this.position.add(this.localX.clone().multiplyScalar(dir * this.clipOffset));
  50254. } else if(cs === "global") {
  50255. this.position.x = this.position.x + dir * this.clipOffset;
  50256. }
  50257. }else if(axis === "y") {
  50258. if(cs === "local") {
  50259. this.position.add(this.localY.clone().multiplyScalar(dir * this.clipOffset));
  50260. } else if(cs === "global") {
  50261. this.position.y = this.position.y + dir * this.clipOffset;
  50262. }
  50263. }else if(axis === "z") {
  50264. if(cs === "local") {
  50265. this.position.add(this.localZ.clone().multiplyScalar(dir * this.clipOffset));
  50266. } else if(cs === "global") {
  50267. this.position.z = this.position.z + dir * this.clipOffset;
  50268. }
  50269. }
  50270. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  50271. }
  50272. rotate(args) {
  50273. let cs = args.cs || null;
  50274. let axis = args.axis || null;
  50275. let dir = args.dir || null;
  50276. if(!cs || !axis || !dir) return;
  50277. if(cs === "local") {
  50278. if(axis === "x") {
  50279. this.rotateOnAxis(new Vector3(1, 0, 0), dir * this.clipRotOffset * Math.PI / 180);
  50280. } else if(axis === "y") {
  50281. this.rotateOnAxis(new Vector3(0, 1, 0), dir * this.clipRotOffset * Math.PI / 180);
  50282. } else if(axis === "z") {
  50283. this.rotateOnAxis(new Vector3(0, 0, 1), dir * this.clipRotOffset * Math.PI / 180);
  50284. }
  50285. } else if(cs === "global") {
  50286. let rotaxis = new Vector4(1, 0, 0, 0);
  50287. if(axis === "y") {
  50288. rotaxis = new Vector4(0, 1, 0, 0);
  50289. } else if(axis === "z") {
  50290. rotaxis = new Vector4(0, 0, 1, 0);
  50291. }
  50292. this.updateMatrixWorld();
  50293. let invM = newthis.matrixWorld.clone().invert();
  50294. rotaxis = rotaxis.applyMatrix4(invM).normalize();
  50295. rotaxis = new Vector3(rotaxis.x, rotaxis.y, rotaxis.z);
  50296. this.rotateOnAxis(rotaxis, dir * this.clipRotOffset * Math.PI / 180);
  50297. }
  50298. this.updateLocalSystem();
  50299. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  50300. }
  50301. update(){
  50302. this.boundingBox = this.box.geometry.boundingBox;
  50303. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  50304. this.box.visible = false;
  50305. this.updateLocalSystem();
  50306. };
  50307. updateLocalSystem() {
  50308. // extract local coordinate axes
  50309. let rotQuat = this.getWorldQuaternion();
  50310. this.localX = new Vector3(1, 0, 0).applyQuaternion(rotQuat).normalize();
  50311. this.localY = new Vector3(0, 1, 0).applyQuaternion(rotQuat).normalize();
  50312. this.localZ = new Vector3(0, 0, 1).applyQuaternion(rotQuat).normalize();
  50313. }
  50314. raycast(raycaster, intersects){
  50315. let is = [];
  50316. this.box.raycast(raycaster, is);
  50317. if(is.length > 0){
  50318. let I = is[0];
  50319. intersects.push({
  50320. distance: I.distance,
  50321. object: this,
  50322. point: I.point.clone()
  50323. });
  50324. }
  50325. };
  50326. };
  50327. class ClippingTool extends EventDispatcher{
  50328. constructor(viewer){
  50329. super();
  50330. this.viewer = viewer;
  50331. this.maxPolygonVertices = 8;
  50332. this.addEventListener("start_inserting_clipping_volume", e => {
  50333. this.viewer.dispatchEvent({
  50334. type: "cancel_insertions"
  50335. });
  50336. });
  50337. this.sceneMarker = new Scene();
  50338. this.sceneVolume = new Scene();
  50339. this.sceneVolume.name = "scene_clip_volume";
  50340. this.viewer.inputHandler.registerInteractiveScene(this.sceneVolume);
  50341. this.onRemove = e => {
  50342. this.sceneVolume.remove(e.volume);
  50343. };
  50344. this.onAdd = e => {
  50345. this.sceneVolume.add(e.volume);
  50346. };
  50347. this.viewer.inputHandler.addEventListener("delete", e => {
  50348. let volumes = e.selection.filter(e => (e instanceof ClipVolume));
  50349. volumes.forEach(e => this.viewer.scene.removeClipVolume(e));
  50350. let polyVolumes = e.selection.filter(e => (e instanceof PolygonClipVolume));
  50351. polyVolumes.forEach(e => this.viewer.scene.removePolygonClipVolume(e));
  50352. });
  50353. //----
  50354. /* var a = new ClipVolume()
  50355. viewer.scene.addVolume(a);
  50356. viewer.setObjectLayers(a, 'volume' ) */
  50357. }
  50358. setScene(scene){
  50359. if(this.scene === scene){
  50360. return;
  50361. }
  50362. if(this.scene){
  50363. this.scene.removeEventListeners("clip_volume_added", this.onAdd);
  50364. this.scene.removeEventListeners("clip_volume_removed", this.onRemove);
  50365. this.scene.removeEventListeners("polygon_clip_volume_added", this.onAdd);
  50366. this.scene.removeEventListeners("polygon_clip_volume_removed", this.onRemove);
  50367. }
  50368. this.scene = scene;
  50369. this.scene.addEventListener("clip_volume_added", this.onAdd);
  50370. this.scene.addEventListener("clip_volume_removed", this.onRemove);
  50371. this.scene.addEventListener("polygon_clip_volume_added", this.onAdd);
  50372. this.scene.addEventListener("polygon_clip_volume_removed", this.onRemove);
  50373. }
  50374. startInsertion(args = {}) {
  50375. let type = args.type || null;
  50376. if(!type) return null;
  50377. let domElement = this.viewer.renderer.domElement;
  50378. let canvasSize = this.viewer.renderer.getSize(new Vector2$1());
  50379. let svg = $(`
  50380. <svg height="${canvasSize.height}" width="${canvasSize.width}" style="position:absolute; pointer-events: none">
  50381. <defs>
  50382. <marker id="diamond" markerWidth="24" markerHeight="24" refX="12" refY="12"
  50383. markerUnits="userSpaceOnUse">
  50384. <circle cx="12" cy="12" r="6" fill="white" stroke="black" stroke-width="3"/>
  50385. </marker>
  50386. </defs>
  50387. <polyline fill="none" stroke="black"
  50388. style="stroke:rgb(0, 0, 0);
  50389. stroke-width:6;"
  50390. stroke-dasharray="9, 6"
  50391. stroke-dashoffset="2"
  50392. />
  50393. <polyline fill="none" stroke="black"
  50394. style="stroke:rgb(255, 255, 255);
  50395. stroke-width:2;"
  50396. stroke-dasharray="5, 10"
  50397. marker-start="url(#diamond)"
  50398. marker-mid="url(#diamond)"
  50399. marker-end="url(#diamond)"
  50400. />
  50401. </svg>`);
  50402. $(domElement.parentElement).append(svg);
  50403. let polyClipVol = new PolygonClipVolume(this.viewer.scene.getActiveCamera().clone());
  50404. this.dispatchEvent({"type": "start_inserting_clipping_volume"});
  50405. this.viewer.scene.addPolygonClipVolume(polyClipVol);
  50406. this.sceneMarker.add(polyClipVol);
  50407. let cancel = {
  50408. callback: null
  50409. };
  50410. let insertionCallback = (e) => {
  50411. if(e.button === MOUSE.LEFT){
  50412. polyClipVol.addMarker();
  50413. // SVC Screen Line
  50414. svg.find("polyline").each((index, target) => {
  50415. let newPoint = svg[0].createSVGPoint();
  50416. newPoint.x = e.offsetX;
  50417. newPoint.y = e.offsetY;
  50418. let polyline = target.points.appendItem(newPoint);
  50419. });
  50420. if(polyClipVol.markers.length > this.maxPolygonVertices){
  50421. cancel.callback();
  50422. }
  50423. this.viewer.inputHandler.startDragging(
  50424. polyClipVol.markers[polyClipVol.markers.length - 1]);
  50425. }else if(e.button === MOUSE.RIGHT){
  50426. cancel.callback(e);
  50427. }
  50428. };
  50429. cancel.callback = e => {
  50430. //let first = svg.find("polyline")[0].points[0];
  50431. //svg.find("polyline").each((index, target) => {
  50432. // let newPoint = svg[0].createSVGPoint();
  50433. // newPoint.x = first.x;
  50434. // newPoint.y = first.y;
  50435. // let polyline = target.points.appendItem(newPoint);
  50436. //});
  50437. svg.remove();
  50438. if(polyClipVol.markers.length > 3) {
  50439. polyClipVol.removeLastMarker();
  50440. polyClipVol.initialized = true;
  50441. } else {
  50442. this.viewer.scene.removePolygonClipVolume(polyClipVol);
  50443. }
  50444. this.viewer.renderer.domElement.removeEventListener("mouseup", insertionCallback, true);
  50445. this.viewer.removeEventListener("cancel_insertions", cancel.callback);
  50446. this.viewer.inputHandler.enabled = true;
  50447. };
  50448. this.viewer.addEventListener("cancel_insertions", cancel.callback);
  50449. this.viewer.renderer.domElement.addEventListener("mouseup", insertionCallback , true);
  50450. this.viewer.inputHandler.enabled = false;
  50451. polyClipVol.addMarker();
  50452. this.viewer.inputHandler.startDragging(
  50453. polyClipVol.markers[polyClipVol.markers.length - 1]);
  50454. return polyClipVol;
  50455. }
  50456. update() {
  50457. }
  50458. };
  50459. var GeoTIFF = (function (exports) {
  50460. 'use strict';
  50461. const Endianness = new Enum({
  50462. LITTLE: "II",
  50463. BIG: "MM",
  50464. });
  50465. const Type = new Enum({
  50466. BYTE: {value: 1, bytes: 1},
  50467. ASCII: {value: 2, bytes: 1},
  50468. SHORT: {value: 3, bytes: 2},
  50469. LONG: {value: 4, bytes: 4},
  50470. RATIONAL: {value: 5, bytes: 8},
  50471. SBYTE: {value: 6, bytes: 1},
  50472. UNDEFINED: {value: 7, bytes: 1},
  50473. SSHORT: {value: 8, bytes: 2},
  50474. SLONG: {value: 9, bytes: 4},
  50475. SRATIONAL: {value: 10, bytes: 8},
  50476. FLOAT: {value: 11, bytes: 4},
  50477. DOUBLE: {value: 12, bytes: 8},
  50478. });
  50479. const Tag = new Enum({
  50480. IMAGE_WIDTH: 256,
  50481. IMAGE_HEIGHT: 257,
  50482. BITS_PER_SAMPLE: 258,
  50483. COMPRESSION: 259,
  50484. PHOTOMETRIC_INTERPRETATION: 262,
  50485. STRIP_OFFSETS: 273,
  50486. ORIENTATION: 274,
  50487. SAMPLES_PER_PIXEL: 277,
  50488. ROWS_PER_STRIP: 278,
  50489. STRIP_BYTE_COUNTS: 279,
  50490. X_RESOLUTION: 282,
  50491. Y_RESOLUTION: 283,
  50492. PLANAR_CONFIGURATION: 284,
  50493. RESOLUTION_UNIT: 296,
  50494. SOFTWARE: 305,
  50495. COLOR_MAP: 320,
  50496. SAMPLE_FORMAT: 339,
  50497. MODEL_PIXEL_SCALE: 33550, // [GeoTIFF] TYPE: double N: 3
  50498. MODEL_TIEPOINT: 33922, // [GeoTIFF] TYPE: double N: 6 * NUM_TIEPOINTS
  50499. GEO_KEY_DIRECTORY: 34735, // [GeoTIFF] TYPE: short N: >= 4
  50500. GEO_DOUBLE_PARAMS: 34736, // [GeoTIFF] TYPE: short N: variable
  50501. GEO_ASCII_PARAMS: 34737, // [GeoTIFF] TYPE: ascii N: variable
  50502. });
  50503. const typeMapping = new Map([
  50504. [Type.BYTE, Uint8Array],
  50505. [Type.ASCII, Uint8Array],
  50506. [Type.SHORT, Uint16Array],
  50507. [Type.LONG, Uint32Array],
  50508. [Type.RATIONAL, Uint32Array],
  50509. [Type.SBYTE, Int8Array],
  50510. [Type.UNDEFINED, Uint8Array],
  50511. [Type.SSHORT, Int16Array],
  50512. [Type.SLONG, Int32Array],
  50513. [Type.SRATIONAL, Int32Array],
  50514. [Type.FLOAT, Float32Array],
  50515. [Type.DOUBLE, Float64Array],
  50516. ]);
  50517. class IFDEntry{
  50518. constructor(tag, type, count, offset, value){
  50519. this.tag = tag;
  50520. this.type = type;
  50521. this.count = count;
  50522. this.offset = offset;
  50523. this.value = value;
  50524. }
  50525. }
  50526. class Image{
  50527. constructor(){
  50528. this.width = 0;
  50529. this.height = 0;
  50530. this.buffer = null;
  50531. this.metadata = [];
  50532. }
  50533. }
  50534. class Reader{
  50535. constructor(){
  50536. }
  50537. static read(data){
  50538. let endiannessTag = String.fromCharCode(...Array.from(data.slice(0, 2)));
  50539. let endianness = Endianness.fromValue(endiannessTag);
  50540. let tiffCheckTag = data.readUInt8(2);
  50541. if(tiffCheckTag !== 42){
  50542. throw new Error("not a valid tiff file");
  50543. }
  50544. let offsetToFirstIFD = data.readUInt32LE(4);
  50545. console.log("offsetToFirstIFD", offsetToFirstIFD);
  50546. let ifds = [];
  50547. let IFDsRead = false;
  50548. let currentIFDOffset = offsetToFirstIFD;
  50549. let i = 0;
  50550. while(IFDsRead || i < 100){
  50551. console.log("currentIFDOffset", currentIFDOffset);
  50552. let numEntries = data.readUInt16LE(currentIFDOffset);
  50553. let nextIFDOffset = data.readUInt32LE(currentIFDOffset + 2 + numEntries * 12);
  50554. console.log("next offset: ", currentIFDOffset + 2 + numEntries * 12);
  50555. let entryBuffer = data.slice(currentIFDOffset + 2, currentIFDOffset + 2 + 12 * numEntries);
  50556. for(let i = 0; i < numEntries; i++){
  50557. let tag = Tag.fromValue(entryBuffer.readUInt16LE(i * 12));
  50558. let type = Type.fromValue(entryBuffer.readUInt16LE(i * 12 + 2));
  50559. let count = entryBuffer.readUInt32LE(i * 12 + 4);
  50560. let offsetOrValue = entryBuffer.readUInt32LE(i * 12 + 8);
  50561. let valueBytes = type.bytes * count;
  50562. let value;
  50563. if(valueBytes <= 4){
  50564. value = offsetOrValue;
  50565. }else {
  50566. let valueBuffer = new Uint8Array(valueBytes);
  50567. valueBuffer.set(data.slice(offsetOrValue, offsetOrValue + valueBytes));
  50568. let ArrayType = typeMapping.get(type);
  50569. value = new ArrayType(valueBuffer.buffer);
  50570. if(type === Type.ASCII){
  50571. value = String.fromCharCode(...value);
  50572. }
  50573. }
  50574. let ifd = new IFDEntry(tag, type, count, offsetOrValue, value);
  50575. ifds.push(ifd);
  50576. }
  50577. console.log("nextIFDOffset", nextIFDOffset);
  50578. if(nextIFDOffset === 0){
  50579. break;
  50580. }
  50581. currentIFDOffset = nextIFDOffset;
  50582. i++;
  50583. }
  50584. let ifdForTag = (tag) => {
  50585. for(let entry of ifds){
  50586. if(entry.tag === tag){
  50587. return entry;
  50588. }
  50589. }
  50590. return null;
  50591. };
  50592. let width = ifdForTag(Tag.IMAGE_WIDTH, ifds).value;
  50593. let height = ifdForTag(Tag.IMAGE_HEIGHT, ifds).value;
  50594. let compression = ifdForTag(Tag.COMPRESSION, ifds).value;
  50595. let rowsPerStrip = ifdForTag(Tag.ROWS_PER_STRIP, ifds).value;
  50596. let ifdStripOffsets = ifdForTag(Tag.STRIP_OFFSETS, ifds);
  50597. let ifdStripByteCounts = ifdForTag(Tag.STRIP_BYTE_COUNTS, ifds);
  50598. let numStrips = Math.ceil(height / rowsPerStrip);
  50599. let stripByteCounts = [];
  50600. for(let i = 0; i < ifdStripByteCounts.count; i++){
  50601. let type = ifdStripByteCounts.type;
  50602. let offset = ifdStripByteCounts.offset + i * type.bytes;
  50603. let value;
  50604. if(type === Type.SHORT){
  50605. value = data.readUInt16LE(offset);
  50606. }else if(type === Type.LONG){
  50607. value = data.readUInt32LE(offset);
  50608. }
  50609. stripByteCounts.push(value);
  50610. }
  50611. let stripOffsets = [];
  50612. for(let i = 0; i < ifdStripOffsets.count; i++){
  50613. let type = ifdStripOffsets.type;
  50614. let offset = ifdStripOffsets.offset + i * type.bytes;
  50615. let value;
  50616. if(type === Type.SHORT){
  50617. value = data.readUInt16LE(offset);
  50618. }else if(type === Type.LONG){
  50619. value = data.readUInt32LE(offset);
  50620. }
  50621. stripOffsets.push(value);
  50622. }
  50623. let imageBuffer = new Uint8Array(width * height * 3);
  50624. let linesProcessed = 0;
  50625. for(let i = 0; i < numStrips; i++){
  50626. let stripOffset = stripOffsets[i];
  50627. let stripBytes = stripByteCounts[i];
  50628. let stripData = data.slice(stripOffset, stripOffset + stripBytes);
  50629. let lineBytes = width * 3;
  50630. for(let y = 0; y < rowsPerStrip; y++){
  50631. let line = stripData.slice(y * lineBytes, y * lineBytes + lineBytes);
  50632. imageBuffer.set(line, linesProcessed * lineBytes);
  50633. if(line.length === lineBytes){
  50634. linesProcessed++;
  50635. }else {
  50636. break;
  50637. }
  50638. }
  50639. }
  50640. console.log(`width: ${width}`);
  50641. console.log(`height: ${height}`);
  50642. console.log(`numStrips: ${numStrips}`);
  50643. console.log("stripByteCounts", stripByteCounts.join(", "));
  50644. console.log("stripOffsets", stripOffsets.join(", "));
  50645. let image = new Image();
  50646. image.width = width;
  50647. image.height = height;
  50648. image.buffer = imageBuffer;
  50649. image.metadata = ifds;
  50650. return image;
  50651. }
  50652. }
  50653. class Exporter{
  50654. constructor(){
  50655. }
  50656. static toTiffBuffer(image, params = {}){
  50657. let offsetToFirstIFD = 8;
  50658. let headerBuffer = new Uint8Array([0x49, 0x49, 42, 0, offsetToFirstIFD, 0, 0, 0]);
  50659. let [width, height] = [image.width, image.height];
  50660. let ifds = [
  50661. new IFDEntry(Tag.IMAGE_WIDTH, Type.SHORT, 1, null, width),
  50662. new IFDEntry(Tag.IMAGE_HEIGHT, Type.SHORT, 1, null, height),
  50663. new IFDEntry(Tag.BITS_PER_SAMPLE, Type.SHORT, 4, null, new Uint16Array([8, 8, 8, 8])),
  50664. new IFDEntry(Tag.COMPRESSION, Type.SHORT, 1, null, 1),
  50665. new IFDEntry(Tag.PHOTOMETRIC_INTERPRETATION, Type.SHORT, 1, null, 2),
  50666. new IFDEntry(Tag.ORIENTATION, Type.SHORT, 1, null, 1),
  50667. new IFDEntry(Tag.SAMPLES_PER_PIXEL, Type.SHORT, 1, null, 4),
  50668. new IFDEntry(Tag.ROWS_PER_STRIP, Type.LONG, 1, null, height),
  50669. new IFDEntry(Tag.STRIP_BYTE_COUNTS, Type.LONG, 1, null, width * height * 3),
  50670. new IFDEntry(Tag.PLANAR_CONFIGURATION, Type.SHORT, 1, null, 1),
  50671. new IFDEntry(Tag.RESOLUTION_UNIT, Type.SHORT, 1, null, 1),
  50672. new IFDEntry(Tag.SOFTWARE, Type.ASCII, 6, null, "......"),
  50673. new IFDEntry(Tag.STRIP_OFFSETS, Type.LONG, 1, null, null),
  50674. new IFDEntry(Tag.X_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  50675. new IFDEntry(Tag.Y_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  50676. ];
  50677. if(params.ifdEntries){
  50678. ifds.push(...params.ifdEntries);
  50679. }
  50680. let valueOffset = offsetToFirstIFD + 2 + ifds.length * 12 + 4;
  50681. // create 12 byte buffer for each ifd and variable length buffers for ifd values
  50682. let ifdEntryBuffers = new Map();
  50683. let ifdValueBuffers = new Map();
  50684. for(let ifd of ifds){
  50685. let entryBuffer = new ArrayBuffer(12);
  50686. let entryView = new DataView(entryBuffer);
  50687. let valueBytes = ifd.type.bytes * ifd.count;
  50688. entryView.setUint16(0, ifd.tag.value, true);
  50689. entryView.setUint16(2, ifd.type.value, true);
  50690. entryView.setUint32(4, ifd.count, true);
  50691. if(ifd.count === 1 && ifd.type.bytes <= 4){
  50692. entryView.setUint32(8, ifd.value, true);
  50693. }else {
  50694. entryView.setUint32(8, valueOffset, true);
  50695. let valueBuffer = new Uint8Array(ifd.count * ifd.type.bytes);
  50696. if(ifd.type === Type.ASCII){
  50697. valueBuffer.set(new Uint8Array(ifd.value.split("").map(c => c.charCodeAt(0))));
  50698. }else {
  50699. valueBuffer.set(new Uint8Array(ifd.value.buffer));
  50700. }
  50701. ifdValueBuffers.set(ifd.tag, valueBuffer);
  50702. valueOffset = valueOffset + valueBuffer.byteLength;
  50703. }
  50704. ifdEntryBuffers.set(ifd.tag, entryBuffer);
  50705. }
  50706. let imageBufferOffset = valueOffset;
  50707. new DataView(ifdEntryBuffers.get(Tag.STRIP_OFFSETS)).setUint32(8, imageBufferOffset, true);
  50708. let concatBuffers = (buffers) => {
  50709. let totalLength = buffers.reduce( (sum, buffer) => (sum + buffer.byteLength), 0);
  50710. let merged = new Uint8Array(totalLength);
  50711. let offset = 0;
  50712. for(let buffer of buffers){
  50713. merged.set(new Uint8Array(buffer), offset);
  50714. offset += buffer.byteLength;
  50715. }
  50716. return merged;
  50717. };
  50718. let ifdBuffer = concatBuffers([
  50719. new Uint16Array([ifds.length]),
  50720. ...ifdEntryBuffers.values(),
  50721. new Uint32Array([0])]);
  50722. let ifdValueBuffer = concatBuffers([...ifdValueBuffers.values()]);
  50723. let tiffBuffer = concatBuffers([
  50724. headerBuffer,
  50725. ifdBuffer,
  50726. ifdValueBuffer,
  50727. image.buffer
  50728. ]);
  50729. return {width: width, height: height, buffer: tiffBuffer};
  50730. }
  50731. }
  50732. exports.Tag = Tag;
  50733. exports.Type = Type;
  50734. exports.IFDEntry = IFDEntry;
  50735. exports.Image = Image;
  50736. exports.Reader = Reader;
  50737. exports.Exporter = Exporter;
  50738. return exports;
  50739. }({}));
  50740. function updateAzimuth(viewer, measure){
  50741. if(!measure.showAzimuth)return
  50742. const azimuth = measure.azimuth;
  50743. const isOkay = measure.points.length === 2;
  50744. azimuth.node.visible = isOkay;
  50745. if(!azimuth.node.visible){
  50746. return;
  50747. }
  50748. const camera = viewer.scene.getActiveCamera();
  50749. const renderAreaSize = viewer.renderer.getSize(new Vector2$1());
  50750. const width = renderAreaSize.width;
  50751. const height = renderAreaSize.height;
  50752. const [p0, p1] = measure.points;
  50753. const r = p0.position.distanceTo(p1.position);
  50754. const northVec = Utils.getNorthVec(p0.position, r, viewer.getProjection());
  50755. const northPos = p0.position.clone().add(northVec);
  50756. azimuth.center.position.copy(p0.position);
  50757. azimuth.center.scale.set(2, 2, 2);
  50758. azimuth.center.visible = false;
  50759. // azimuth.target.visible = false;
  50760. { // north
  50761. azimuth.north.position.copy(northPos);
  50762. azimuth.north.scale.set(2, 2, 2);
  50763. let distance = azimuth.north.position.distanceTo(camera.position);
  50764. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50765. let scale = (5 / pr);
  50766. azimuth.north.scale.set(scale, scale, scale);
  50767. }
  50768. { // target
  50769. azimuth.target.position.copy(p1.position);
  50770. azimuth.target.position.z = azimuth.north.position.z;
  50771. let distance = azimuth.target.position.distanceTo(camera.position);
  50772. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50773. let scale = (5 / pr);
  50774. azimuth.target.scale.set(scale, scale, scale);
  50775. }
  50776. azimuth.circle.position.copy(p0.position);
  50777. azimuth.circle.scale.set(r, r, r);
  50778. azimuth.circle.material.resolution.set(width, height);
  50779. // to target
  50780. azimuth.centerToTarget.geometry.setPositions([
  50781. 0, 0, 0,
  50782. ...p1.position.clone().sub(p0.position).toArray(),
  50783. ]);
  50784. azimuth.centerToTarget.position.copy(p0.position);
  50785. azimuth.centerToTarget.geometry.verticesNeedUpdate = true;
  50786. azimuth.centerToTarget.geometry.computeBoundingSphere();
  50787. azimuth.centerToTarget.computeLineDistances();
  50788. azimuth.centerToTarget.material.resolution.set(width, height);
  50789. // to target ground
  50790. azimuth.centerToTargetground.geometry.setPositions([
  50791. 0, 0, 0,
  50792. p1.position.x - p0.position.x,
  50793. p1.position.y - p0.position.y,
  50794. 0,
  50795. ]);
  50796. azimuth.centerToTargetground.position.copy(p0.position);
  50797. azimuth.centerToTargetground.geometry.verticesNeedUpdate = true;
  50798. azimuth.centerToTargetground.geometry.computeBoundingSphere();
  50799. azimuth.centerToTargetground.computeLineDistances();
  50800. azimuth.centerToTargetground.material.resolution.set(width, height);
  50801. // to north
  50802. azimuth.centerToNorth.geometry.setPositions([
  50803. 0, 0, 0,
  50804. northPos.x - p0.position.x,
  50805. northPos.y - p0.position.y,
  50806. 0,
  50807. ]);
  50808. azimuth.centerToNorth.position.copy(p0.position);
  50809. azimuth.centerToNorth.geometry.verticesNeedUpdate = true;
  50810. azimuth.centerToNorth.geometry.computeBoundingSphere();
  50811. azimuth.centerToNorth.computeLineDistances();
  50812. azimuth.centerToNorth.material.resolution.set(width, height);
  50813. // label
  50814. const radians = Utils.computeAzimuth(p0.position, p1.position, viewer.getProjection());
  50815. let degrees = MathUtils.radToDeg(radians);
  50816. if(degrees < 0){
  50817. degrees = 360 + degrees;
  50818. }
  50819. const txtDegrees = `${degrees.toFixed(2)}°`;
  50820. const labelDir = northPos.clone().add(p1.position).multiplyScalar(0.5).sub(p0.position);
  50821. if(labelDir.length() > 0){
  50822. labelDir.z = 0;
  50823. labelDir.normalize();
  50824. const labelVec = labelDir.clone().multiplyScalar(r);
  50825. const labelPos = p0.position.clone().add(labelVec);
  50826. azimuth.label.position.copy(labelPos);
  50827. }
  50828. azimuth.label.setText(txtDegrees);
  50829. let distance = azimuth.label.position.distanceTo(camera.position);
  50830. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50831. let scale = (70 / pr);
  50832. azimuth.label.scale.set(scale, scale, scale);
  50833. }
  50834. class MeasuringTool extends EventDispatcher{
  50835. constructor (viewer) {
  50836. super();
  50837. this.viewer = viewer;
  50838. this.renderer = viewer.renderer;
  50839. this.viewer.addEventListener('start_inserting_measurement', e => {
  50840. this.viewer.dispatchEvent({
  50841. type: 'cancel_insertions'
  50842. });
  50843. });
  50844. this.showLabels = true;
  50845. this.scene = new Scene();
  50846. this.scene.name = 'scene_measurement';
  50847. //this.light = new THREE.PointLight(0xffffff, 1.0);
  50848. //this.scene.add(this.light);
  50849. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  50850. //this.scene = viewer.overlay//
  50851. this.onRemove = (e) => { e.measurement.dispose();/* this.scene.remove(e.measurement); */};
  50852. this.onAdd = e => {this.scene.add(e.measurement);};
  50853. for(let measurement of viewer.scene.measurements){
  50854. this.onAdd({measurement: measurement});
  50855. }
  50856. viewer.addEventListener('camera_changed',(e)=>{
  50857. if(e.viewport == viewer.mainViewport ) this.update();
  50858. });
  50859. //viewer.addEventListener("update", this.update.bind(this));
  50860. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  50861. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  50862. viewer.scene.addEventListener('measurement_added', this.onAdd);
  50863. viewer.scene.addEventListener('measurement_removed', this.onRemove);
  50864. viewer.addEventListener('resize',this.setSize.bind(this));
  50865. }
  50866. onSceneChange(e){
  50867. if(e.oldScene){
  50868. e.oldScene.removeEventListener('measurement_added', this.onAdd);
  50869. e.oldScene.removeEventListener('measurement_removed', this.onRemove);
  50870. }
  50871. e.scene.addEventListener('measurement_added', this.onAdd);
  50872. e.scene.addEventListener('measurement_removed', this.onRemove);
  50873. }
  50874. createMeasureFromData(data){//add
  50875. const measure = new Measure(data);
  50876. if(measure.failBuilded){
  50877. return
  50878. }
  50879. viewer.scene.addMeasurement(measure);
  50880. if(measure.guideLine)measure.guideLine.visible = false;
  50881. return measure
  50882. }
  50883. update(){
  50884. return;
  50885. let camera = this.viewer.scene.getActiveCamera();
  50886. let domElement = this.renderer.domElement;
  50887. let measurements = this.viewer.scene.measurements;
  50888. // make size independant of distance
  50889. let mainLabels = [], subLabels = [];
  50890. for (let measure of measurements) {
  50891. measure.lengthUnit = this.viewer.lengthUnit;
  50892. measure.lengthUnitDisplay = this.viewer.lengthUnitDisplay;
  50893. //measure.update();
  50894. updateAzimuth(this.viewer, measure);
  50895. /* [...measure.markers, ...measure.edgeLabels, measure.areaLabel].forEach(e=>{
  50896. e && e.update()
  50897. }); */
  50898. // labels
  50899. /* let labels = measure.edgeLabels.concat(measure.angleLabels);
  50900. for(let label of labels){
  50901. label.update()
  50902. if(label.elem.hasClass('sub')){
  50903. subLabels.push(label)
  50904. }else{
  50905. mainLabels.push(label)
  50906. }
  50907. }
  50908. // coordinate labels
  50909. for (let j = 0; j < measure.coordinateLabels.length; j++) {
  50910. let label = measure.coordinateLabels[j];
  50911. label.update()
  50912. mainLabels.push(label)
  50913. }
  50914. if(measure.showArea){ // area label
  50915. let label = measure.areaLabel;
  50916. label.update()
  50917. mainLabels.push(label)
  50918. } */
  50919. /* if(measure.showCircle){ // radius label
  50920. let label = measure.circleRadiusLabel;
  50921. let distance = label.position.distanceTo(camera.position);
  50922. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  50923. let scale = (70 / pr);
  50924. label.scale.set(scale, scale, scale);
  50925. } */
  50926. if(!this.showLabels){
  50927. const labels = [
  50928. ...measure.sphereLabels,
  50929. ...measure.angleLabels,
  50930. measure.circleRadiusLabel,
  50931. ];
  50932. for(const label of labels){
  50933. label.visible = false;
  50934. }
  50935. }
  50936. }
  50937. //this.updateLabelZIndex([{labels:subLabels},{labels:mainLabels}])
  50938. }
  50939. setSize(e){ //e.resolution
  50940. /* if(Measure.lineMats){
  50941. for(var m in Measure.lineMats){
  50942. Measure.lineMats[m].resolution.set(e.canvasWidth, e.canvasHeight);
  50943. }
  50944. }
  50945. if(Measure.sphereMats){
  50946. for(var s in Measure.sphereMats){
  50947. Measure.sphereMats[s].uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  50948. }
  50949. }
  50950. for (let measure of this.viewer.scene.measurements) {
  50951. measure.edgeLabels.concat(measure.areaLabel).forEach(label=>{
  50952. label.sprite.material.uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  50953. })
  50954. } */
  50955. }
  50956. updateLabelZIndex(group){//[{labels:[]},{}] 顺序按照z-index低到高
  50957. group.forEach((e,i)=>{
  50958. e.base = group[i-1] ? group[i-1].base + group[i-1].labels.length : 0;
  50959. var labels = e.labels.sort((a,b)=>{
  50960. return b.pos2d.z - a.pos2d.z
  50961. });
  50962. labels.forEach((label,index)=>{
  50963. $(label.elem).css('z-index', e.base+index);
  50964. });
  50965. });
  50966. }
  50967. editStateChange(e){
  50968. //console.log("editStateChange" , e.state)
  50969. let state = e.state;
  50970. if(!state){
  50971. state = viewer.scene.measurements.some(e=>e.isEditing);
  50972. }
  50973. if(state){
  50974. viewer.dispatchEvent({type:"measureMovePoint"});
  50975. }else {
  50976. viewer.dispatchEvent({type:"endMeasureMove"});
  50977. }
  50978. //this.editing =
  50979. }
  50980. startInsertion (args = {}, callback, cancelFun) {
  50981. let domElement = this.viewer.renderer.domElement;
  50982. const pick = (defaul, alternative) => {
  50983. if(defaul != null){
  50984. return defaul;
  50985. }else {
  50986. return alternative;
  50987. }
  50988. };
  50989. args.showDistances = (args.showDistances === null) ? true : args.showDistances;
  50990. args.showArea = pick(args.showArea, false);
  50991. args.showAngles = pick(args.showAngles, false);
  50992. args.showCoordinates = pick(args.showCoordinates, false);
  50993. args.showHeight = pick(args.showHeight, false);
  50994. args.showCircle = pick(args.showCircle, false);
  50995. args.showAzimuth = pick(args.showAzimuth, false);
  50996. args.showEdges = pick(args.showEdges, true);
  50997. args.closed = pick(args.closed, false);
  50998. args.maxMarkers = pick(args.maxMarkers, Infinity);
  50999. args.direction = args.direction;//add
  51000. args.type = args.type; /* || 'Measurement'; */
  51001. args.showGuideLine = pick(args.showGuideLine, false);
  51002. args.isRect = pick(args.isRect, false);
  51003. let measure = new Measure(args);
  51004. this.scene.add(measure);
  51005. measure.isNew = true;
  51006. this.viewer.dispatchEvent({
  51007. type: 'start_inserting_measurement',
  51008. measure: measure
  51009. });
  51010. measure.addEventListener('editStateChange', this.editStateChange.bind(this));
  51011. measure.editStateChange(true);
  51012. let timer;
  51013. let endDragFun = (e) => {
  51014. let length = measure.points.length;
  51015. if (e.button == MOUSE.LEFT || e.isTouch) {
  51016. if (length >= measure.maxMarkers) {
  51017. end({finish:true});
  51018. }else {
  51019. var marker = measure.addMarker({point:measure.points[length - 1].clone()});
  51020. if(args.isRect && measure.markers.length == 3){//marker全可见
  51021. measure.addMarker({point:measure.points[0].clone()});
  51022. }else {
  51023. measure.markers[length].visible = false;
  51024. measure.edges[length].visible = false;
  51025. }
  51026. measure.edges[length-1].visible = true;
  51027. measure.markers[length-1].visible = true;
  51028. measure.editStateChange(true); //重新激活reticule状态
  51029. marker.isDragging = true;
  51030. measure.continueDrag(marker, e);
  51031. }
  51032. } else if (e.button === MOUSE.RIGHT ) { //触屏怎么取消?
  51033. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  51034. else measure.continueDrag(null, e);
  51035. }
  51036. };
  51037. let end = (e={}) => {//确定、结束
  51038. if(!measure.isNew)return
  51039. if(args.minMarkers != void 0){
  51040. if(!e.finish && measure.markers.length<=args.minMarkers){//右键 当个数不够时取消
  51041. //this.viewer.scene.removeMeasurement(measure)
  51042. //cancelFun && cancelFun()
  51043. //重新开始画
  51044. measure.markers[0].removeEventListener('mousedown',end);
  51045. measure.reDraw();
  51046. this.viewer.addEventListener('global_click', click, 10);
  51047. measure.editStateChange(true);
  51048. return
  51049. /* if(!Potree.settings.isOfficial) this.viewer.scene.removeMeasurement(measure)
  51050. else if(e.drag){ //正式版本不允许右键退出, 继续
  51051. continueDrag(e.drag.object)
  51052. measure.editStateChange(true)
  51053. return
  51054. } */
  51055. }
  51056. }
  51057. if (/* !e.finish && */measure.markers.length > 3) {
  51058. measure.removeMarker(measure.points.length - 1);
  51059. measure.markers[0].removeEventListener('mouseover', mouseover);
  51060. measure.markers[0].removeEventListener('mouseleave', mouseleave);
  51061. measure.markers[0].removeEventListener('click'/* 'mousedown' */,Exit);
  51062. if(e.byClickMarker && measure.markers.length > 3){//通过点击第一个marker而结束的话,会多一个marker
  51063. measure.removeMarker(measure.points.length - 1);
  51064. }
  51065. }
  51066. measure.isNew = false;
  51067. let length = measure.points.length;
  51068. if(length){
  51069. measure.markers[length-1].visible = true;
  51070. measure.edges[length-1].visible = true;
  51071. measure.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  51072. measure.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  51073. }
  51074. clearTimeout(timer);
  51075. this.viewer.removeEventListener('cancel_insertions', Exit);
  51076. //pressExit && this.viewer.inputHandler.removeEventListener('keydown', pressExit);
  51077. this.viewer.removeEventListener('global_click', click);
  51078. this.viewer.removeEventListener('global_mousemove', ifAtWrongPlace);
  51079. viewer.dispatchEvent({
  51080. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  51081. });
  51082. viewer.inputHandler.dispatchEvent({type:'isMeasuring', v:false, cause:'stopInsertion'} );
  51083. e.remove || callback && callback();
  51084. /* this.viewer.dispatchEvent({
  51085. type: 'finish_inserting_measurement',
  51086. measure: measure
  51087. }); */
  51088. };
  51089. let Exit = (e)=>{//强制退出
  51090. if(e.measure && e.measure != measure){
  51091. return;//若指定了退出的measure但和该measure不一致,就返回
  51092. }
  51093. console.log('Exit: ' + measure.id);
  51094. if(e.remove){
  51095. viewer.scene.removeMeasurement(measure);
  51096. }
  51097. measure.editStateChange(false);
  51098. measure.cannotConfirmNormal = false; //一些dropMarker中的句子
  51099. measure.guideLine &&(measure.guideLine.visible = false);
  51100. /*
  51101. if(this.viewer.inputHandler.drag && !e.remove ){//还未触发drop的话
  51102. this.viewer.inputHandler.drag.object.dispatchEvent({ //这句会导致又增一个marker
  51103. type: 'drop',
  51104. drag: this.viewer.inputHandler.drag,
  51105. viewer: this.viewer,
  51106. pressDistance:0,
  51107. button : THREE.MOUSE.RIGHT
  51108. });
  51109. } else {*///未结束时添加新的measure时会触发
  51110. end({finish:true, remove:e.remove, byClickMarker: e.type == 'click'});
  51111. //}
  51112. this.viewer.inputHandler.drag && (this.viewer.inputHandler.drag.object = null);
  51113. };
  51114. this.viewer.addEventListener('cancel_insertions', Exit);
  51115. /*let pressExit
  51116. if(!Potree.settings.isOfficial){
  51117. pressExit = (e)=>{
  51118. if(e.keyCode == 27){//Esc
  51119. //Exit()
  51120. //怎么模拟右键???//现由前端发出
  51121. }
  51122. }
  51123. this.viewer.inputHandler.addEventListener('keydown', pressExit)
  51124. } */
  51125. let mouseover = (e) => {
  51126. measure.setMarkerSelected(e.object, 'hover', 'single');
  51127. };
  51128. let mouseleave = (e) => {
  51129. measure.setMarkerSelected(e.object, 'unhover', 'single');
  51130. };
  51131. let click = (e)=>{//一旦点击就立刻增加两marker
  51132. if(ifAtWrongPlace(e))return
  51133. if(e.clickElement)return //如点击label时focusOnObject
  51134. if(e.button === MOUSE.RIGHT)return
  51135. //console.log('measure clicked33', !!e.intersectPoint)
  51136. //var I = e.intersectPoint && (e.intersectPoint.orthoIntersect || e.intersectPoint.location)
  51137. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  51138. if(!I){
  51139. return measure.dispatchEvent('intersectNoPointcloud')
  51140. }
  51141. var atMap = e.drag.dragViewport.name == 'mapViewport';
  51142. //在地图上测量的首个点按楼层高度(暂时先只按mainViewport相机高度吧,但navvis是按楼层,画在楼层的地面上,可能因为平面图显示的是楼层近地面),
  51143. if(atMap){
  51144. I = I.clone().setZ(viewer.mainViewport.camera.position.z );
  51145. }
  51146. var marker = measure.addMarker({point:I});
  51147. marker.isDragging = true;
  51148. this.viewer.inputHandler.startDragging(marker , {endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽
  51149. e.drag = this.viewer.inputHandler.drag;
  51150. e.drag.endDragFun = endDragFun;
  51151. e.drag.notPressMouse = true;
  51152. //if(!measure.dragMarker(e) || !measure.dropMarker(e))return
  51153. measure.dragMarker(e);
  51154. measure.dropMarker(e);
  51155. if(measure.maxMarkers > 1 ){
  51156. measure.markers[1].visible = false;
  51157. measure.edges[1].visible = false;
  51158. }
  51159. if(measure.maxMarkers>2 && !measure.isRect){
  51160. measure.markers[0].addEventListener('mouseover', mouseover);
  51161. measure.markers[0].addEventListener('mouseleave', mouseleave);
  51162. measure.markers[0].addEventListener('click'/* 'mousedown' */,Exit); //点击到第一个marker就结束
  51163. }
  51164. this.viewer.removeEventListener('global_click', click);///* global_drop */
  51165. //console.log('measure clicked')
  51166. e.consume && e.consume();
  51167. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  51168. };
  51169. //点击第n下拥有n+1个marker, n>0
  51170. viewer.inputHandler.dispatchEvent({type: 'isMeasuring', v: true, cause:'startInsertion'});
  51171. this.viewer.addEventListener('global_click', click, 10);//add importance:10
  51172. let ifAtWrongPlace = (e)=>{
  51173. if(measure.unableDragAtMap && e.hoverViewport.name == 'mapViewport' ){
  51174. if(e.isTouch){
  51175. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  51176. }else {
  51177. viewer.dispatchEvent({
  51178. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  51179. });
  51180. }
  51181. return true
  51182. }else {
  51183. if(e.isTouch){
  51184. viewer.dispatchEvent({type:'reticule_forbit',v:false});
  51185. }else {
  51186. viewer.dispatchEvent({
  51187. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  51188. });
  51189. }
  51190. }
  51191. };
  51192. if(measure.unableDragAtMap){
  51193. this.viewer.addEventListener('global_mousemove', ifAtWrongPlace);
  51194. }
  51195. this.viewer.scene.addMeasurement(measure);
  51196. return measure;
  51197. }
  51198. render(o={}){
  51199. if(this.scene.children.length == 0)return
  51200. viewer.setCameraLayers(o.camera, ['measure']);
  51201. if(o.screenshot){ //抗锯齿
  51202. this.viewer.ssaaRenderPass.sampleLevel = 4;
  51203. this.viewer.composer.render(this.scene, o.camera );
  51204. /* viewer.scene.measurements.forEach(e=>{ //隐藏除了label以外的
  51205. e.children.forEach((c)=>{
  51206. if(!(c instanceof TextSprite)){
  51207. c.visible = false
  51208. }
  51209. })
  51210. }) */
  51211. }else {
  51212. this.viewer.renderer.render(this.scene, o.camera );
  51213. }
  51214. }
  51215. };
  51216. class Message{
  51217. constructor(content){
  51218. this.content = content;
  51219. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  51220. this.element = $(`
  51221. <div class="potree_message">
  51222. <span name="content_container" style="flex-grow: 1; padding: 5px"></span>
  51223. <img name="close" src="${closeIcon}" class="button-icon" style="width: 16px; height: 16px;">
  51224. </div>`);
  51225. this.elClose = this.element.find("img[name=close]");
  51226. this.elContainer = this.element.find("span[name=content_container]");
  51227. if(typeof content === "string"){
  51228. this.elContainer.append($(`<span>${content}</span>`));
  51229. }else {
  51230. this.elContainer.append(content);
  51231. }
  51232. }
  51233. setMessage(content){
  51234. this.elContainer.empty();
  51235. if(typeof content === "string"){
  51236. this.elContainer.append($(`<span>${content}</span>`));
  51237. }else {
  51238. this.elContainer.append(content);
  51239. }
  51240. }
  51241. }
  51242. class PointCloudSM{//shadow material ?
  51243. constructor(potreeRenderer){
  51244. this.potreeRenderer = potreeRenderer;
  51245. this.threeRenderer = this.potreeRenderer.threeRenderer;
  51246. this.target = new WebGLRenderTarget(2 * 1024, 2 * 1024, {
  51247. minFilter: LinearFilter,
  51248. magFilter: LinearFilter,
  51249. format: RGBAFormat,
  51250. type: FloatType,
  51251. });
  51252. this.target.depthTexture = new DepthTexture();
  51253. this.target.depthTexture.type = UnsignedIntType;
  51254. //this.threeRenderer.setClearColor(0x000000, 1);
  51255. this.threeRenderer.setClearColor(0xff0000, 1);
  51256. //HACK? removed while moving to three.js 109
  51257. //this.threeRenderer.clearTarget(this.target, true, true, true);
  51258. {
  51259. const oldTarget = this.threeRenderer.getRenderTarget();
  51260. this.threeRenderer.setRenderTarget(this.target);
  51261. //this.threeRenderer.clear(true, true, true); //救命,为什么iphoneX ios13.6执行这一句clear会崩溃?即使把target的大小改为1*1.
  51262. this.threeRenderer.setRenderTarget(oldTarget);
  51263. }
  51264. }
  51265. setLight(light){
  51266. this.light = light;
  51267. let fov = (180 * light.angle) / Math.PI;
  51268. let aspect = light.shadow.mapSize.width / light.shadow.mapSize.height;
  51269. let near = 0.1;
  51270. let far = light.distance === 0 ? 10000 : light.distance;
  51271. this.camera = new PerspectiveCamera(fov, aspect, near, far);
  51272. this.camera.up.set(0, 0, 1);
  51273. this.camera.position.copy(light.position);
  51274. let target = new Vector3().subVectors(light.position, light.getWorldDirection(new Vector3()));
  51275. this.camera.lookAt(target);
  51276. this.camera.updateProjectionMatrix();
  51277. this.camera.updateMatrix();
  51278. this.camera.updateMatrixWorld();
  51279. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  51280. }
  51281. setSize(width, height){
  51282. if(this.target.width !== width || this.target.height !== height){
  51283. this.target.dispose();
  51284. }
  51285. this.target.setSize(width, height);
  51286. }
  51287. render(scene, camera){
  51288. this.threeRenderer.setClearColor(0x000000, 1);
  51289. const oldTarget = this.threeRenderer.getRenderTarget();
  51290. this.threeRenderer.setRenderTarget(this.target);
  51291. this.threeRenderer.clear(true, true, true);
  51292. this.potreeRenderer.render(scene, this.camera, this.target, {});
  51293. this.threeRenderer.setRenderTarget(oldTarget);
  51294. }
  51295. }
  51296. class ProfileTool extends EventDispatcher {
  51297. constructor (viewer) {
  51298. super();
  51299. this.viewer = viewer;
  51300. this.renderer = viewer.renderer;
  51301. this.addEventListener('start_inserting_profile', e => {
  51302. this.viewer.dispatchEvent({
  51303. type: 'cancel_insertions'
  51304. });
  51305. });
  51306. this.scene = new Scene();
  51307. this.scene.name = 'scene_profile';
  51308. this.light = new PointLight(0xffffff, 1.0);
  51309. this.scene.add(this.light);
  51310. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  51311. this.onRemove = e => this.scene.remove(e.profile);
  51312. this.onAdd = e => this.scene.add(e.profile);
  51313. for(let profile of viewer.scene.profiles){
  51314. this.onAdd({profile: profile});
  51315. }
  51316. viewer.addEventListener("update", this.update.bind(this));
  51317. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  51318. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  51319. viewer.scene.addEventListener('profile_added', this.onAdd);
  51320. viewer.scene.addEventListener('profile_removed', this.onRemove);
  51321. }
  51322. onSceneChange(e){
  51323. if(e.oldScene){
  51324. e.oldScene.removeEventListeners('profile_added', this.onAdd);
  51325. e.oldScene.removeEventListeners('profile_removed', this.onRemove);
  51326. }
  51327. e.scene.addEventListener('profile_added', this.onAdd);
  51328. e.scene.addEventListener('profile_removed', this.onRemove);
  51329. }
  51330. startInsertion (args = {}) {
  51331. let domElement = this.viewer.renderer.domElement;
  51332. let profile = new Profile();
  51333. profile.name = args.name || 'Profile';
  51334. this.dispatchEvent({
  51335. type: 'start_inserting_profile',
  51336. profile: profile
  51337. });
  51338. this.scene.add(profile);
  51339. let cancel = {
  51340. callback: null
  51341. };
  51342. let insertionCallback = (e) => {
  51343. if(e.button === MOUSE.LEFT){
  51344. if(profile.points.length <= 1){
  51345. let camera = this.viewer.scene.getActiveCamera();
  51346. let distance = camera.position.distanceTo(profile.points[0]);
  51347. let clientSize = this.viewer.renderer.getSize(new Vector2$1());
  51348. let pr = Utils.projectedRadius(1, camera, distance, clientSize.width, clientSize.height);
  51349. let width = (10 / pr);
  51350. profile.setWidth(width);
  51351. }
  51352. profile.addMarker(profile.points[profile.points.length - 1].clone());
  51353. this.viewer.inputHandler.startDragging(
  51354. profile.spheres[profile.spheres.length - 1]);
  51355. } else if (e.button === MOUSE.RIGHT) {
  51356. cancel.callback();
  51357. }
  51358. };
  51359. cancel.callback = e => {
  51360. profile.removeMarker(profile.points.length - 1);
  51361. domElement.removeEventListener('mouseup', insertionCallback, false);
  51362. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  51363. };
  51364. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  51365. domElement.addEventListener('mouseup', insertionCallback, false);
  51366. profile.addMarker(new Vector3(0, 0, 0));
  51367. this.viewer.inputHandler.startDragging(
  51368. profile.spheres[profile.spheres.length - 1]);
  51369. this.viewer.scene.addProfile(profile);
  51370. return profile;
  51371. }
  51372. update(){
  51373. let camera = this.viewer.scene.getActiveCamera();
  51374. let profiles = this.viewer.scene.profiles;
  51375. let renderAreaSize = this.viewer.renderer.getSize(new Vector2$1());
  51376. let clientWidth = renderAreaSize.width;
  51377. let clientHeight = renderAreaSize.height;
  51378. this.light.position.copy(camera.position);
  51379. // make size independant of distance
  51380. for(let profile of profiles){
  51381. for(let sphere of profile.spheres){
  51382. let distance = camera.position.distanceTo(sphere.getWorldPosition(new Vector3()));
  51383. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  51384. let scale = (15 / pr);
  51385. sphere.scale.set(scale, scale, scale);
  51386. }
  51387. }
  51388. }
  51389. render(){
  51390. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  51391. }
  51392. }
  51393. class ScreenBoxSelectTool extends EventDispatcher{
  51394. constructor(viewer){
  51395. super();
  51396. this.viewer = viewer;
  51397. this.scene = new Scene();
  51398. viewer.addEventListener("update", this.update.bind(this));
  51399. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  51400. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  51401. }
  51402. onSceneChange(scene){
  51403. console.log("scene changed");
  51404. }
  51405. startInsertion(){
  51406. let domElement = this.viewer.renderer.domElement;
  51407. let volume = new BoxVolume();
  51408. volume.position.set(12345, 12345, 12345);
  51409. volume.showVolumeLabel = false;
  51410. volume.visible = false;
  51411. volume.update();
  51412. this.viewer.scene.addVolume(volume);
  51413. this.importance = 10;
  51414. let selectionBox = $(`<div style="position: absolute; border: 2px solid white; pointer-events: none; border-style:dashed"></div>`);
  51415. $(domElement.parentElement).append(selectionBox);
  51416. selectionBox.css("right", "10px");
  51417. selectionBox.css("bottom", "10px");
  51418. let drag = e =>{
  51419. volume.visible = true;
  51420. let mStart = e.drag.start;
  51421. let mEnd = e.drag.end;
  51422. let box2D = new Box2();
  51423. box2D.expandByPoint(mStart);
  51424. box2D.expandByPoint(mEnd);
  51425. selectionBox.css("left", `${box2D.min.x}px`);
  51426. selectionBox.css("top", `${box2D.min.y}px`);
  51427. selectionBox.css("width", `${box2D.max.x - box2D.min.x}px`);
  51428. selectionBox.css("height", `${box2D.max.y - box2D.min.y}px`);
  51429. let camera = e.viewer.scene.getActiveCamera();
  51430. let size = e.viewer.renderer.getSize(new Vector2$1());
  51431. let frustumSize = new Vector2$1(
  51432. camera.right - camera.left,
  51433. camera.top - camera.bottom);
  51434. let screenCentroid = new Vector2$1().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  51435. let pointer = new Vector3(0, 0, 0.5);
  51436. Utils.convertScreenPositionToNDC(pointer, screenCentroid, size.width, size.height);
  51437. pointer.unproject(camera);
  51438. //let ray = Utils.mouseToRay( pointer, camera, size.width, size.height);
  51439. let diff = new Vector2$1().subVectors(e.drag.end, e.drag.start);
  51440. diff.divide(size).multiply(frustumSize);
  51441. volume.position.copy(pointer);
  51442. //volume.position.copy(ray.origin); //orthographicCamera不能用这种方式 而且也该是用end
  51443. volume.up.copy(camera.up);
  51444. volume.rotation.copy(camera.rotation);
  51445. volume.scale.set(diff.x, diff.y, 1000 * 100);
  51446. e.consume();
  51447. };
  51448. let drop = e => {
  51449. this.importance = 0;
  51450. $(selectionBox).remove();
  51451. this.viewer.inputHandler.deselectAll();
  51452. this.viewer.inputHandler.toggleSelection(volume);
  51453. let camera = e.viewer.scene.getActiveCamera();
  51454. let size = e.viewer.renderer.getSize(new Vector2$1());
  51455. let screenCentroid = new Vector2$1().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  51456. let pointer = new Vector3(0, 0, 0.5);
  51457. Utils.convertScreenPositionToNDC(pointer, screenCentroid, size.width, size.height);
  51458. let ray = Utils.mouseToRay(pointer/* screenCentroid */, camera, size.width, size.height);
  51459. //let line = new THREE.Line3(ray.origin, new THREE.Vector3().addVectors(ray.origin, ray.direction));
  51460. this.removeEventListener("drag", drag);
  51461. this.removeEventListener("drop", drop);
  51462. let allPointsNear = [];
  51463. let allPointsFar = [];
  51464. // TODO support more than one point cloud
  51465. for(let pointcloud of this.viewer.scene.pointclouds){
  51466. if(!pointcloud.visible){
  51467. continue;
  51468. }
  51469. let volCam = camera.clone();
  51470. volCam.left = -volume.scale.x / 2;
  51471. volCam.right = +volume.scale.x / 2;
  51472. volCam.top = +volume.scale.y / 2;
  51473. volCam.bottom = -volume.scale.y / 2;
  51474. volCam.near = -volume.scale.z / 2;
  51475. volCam.far = +volume.scale.z / 2;
  51476. volCam.rotation.copy(volume.rotation);
  51477. volCam.position.copy(volume.position);
  51478. volCam.updateMatrix();
  51479. volCam.updateMatrixWorld();
  51480. volCam.updateProjectionMatrix();
  51481. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  51482. let ray = new Ray(volCam.getWorldPosition(new Vector3()), volCam.getWorldDirection(new Vector3()));
  51483. let rayInverse = new Ray(
  51484. ray.origin.clone().add(ray.direction.clone().multiplyScalar(volume.scale.z)),
  51485. ray.direction.clone().multiplyScalar(-1));
  51486. let diff = new Vector2$1().subVectors(e.drag.end, e.drag.start);
  51487. let pickerSettings = {
  51488. width: 16, //renderTarget大小,数值越大识别精度越高 原本的8太低了
  51489. height: 16,
  51490. pickWindowSize: 16, //??????
  51491. all: true,
  51492. pickClipped: true,
  51493. pointSizeType: PointSizeType.FIXED,
  51494. pointSize: 1
  51495. };
  51496. let pointsNear = pointcloud.pick(viewer, null, volCam, ray, pickerSettings);
  51497. volCam.rotateX(Math.PI);
  51498. volCam.updateMatrix();
  51499. volCam.updateMatrixWorld();
  51500. volCam.updateProjectionMatrix();
  51501. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  51502. let pointsFar = pointcloud.pick(viewer,null, volCam, rayInverse, pickerSettings);
  51503. pointsNear && allPointsNear.push(...pointsNear);
  51504. pointsFar && allPointsFar.push(...pointsFar);
  51505. }
  51506. /* if(allPointsNear.length > 0 && allPointsFar.length > 0){
  51507. let viewLine = new THREE.Line3(ray.origin, new THREE.Vector3().addVectors(ray.origin, ray.direction));
  51508. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new THREE.Vector3()));
  51509. let closest = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b))[0];
  51510. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new THREE.Vector3()));
  51511. let farthest = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a))[0];
  51512. let distance = closest.distanceTo(farthest);
  51513. let centroid = new THREE.Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  51514. volume.scale.z = distance * 1.1;
  51515. volume.position.copy(centroid);
  51516. } */
  51517. if(allPointsNear.length > 0 || allPointsFar.length > 0){
  51518. let viewLine = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  51519. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  51520. let closests = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b));//[0];
  51521. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  51522. let farthests = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a));//[0];
  51523. let closest, farthest;
  51524. if(closests.length == 0){
  51525. closest = farthests[farthests.length-1];
  51526. farthest = farthests[0];
  51527. }else if(farthests.length == 0){
  51528. closest = closests[closests.length-1];
  51529. farthest = closests[0];
  51530. }else {
  51531. closest = closests[0];
  51532. farthest = farthests[0];
  51533. }
  51534. let distance = closest.distanceTo(farthest);
  51535. let centroid = new Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  51536. volume.scale.z = distance * 1.1;
  51537. //volume.position.copy(centroid);
  51538. var pos2d = centroid.project(camera); //改变深度
  51539. pointer.setZ(pos2d.z);
  51540. pointer.unproject(camera);
  51541. volume.position.copy(pointer);
  51542. }
  51543. volume.clip = true;
  51544. };
  51545. this.addEventListener("drag", drag);
  51546. this.addEventListener("drop", drop);
  51547. viewer.inputHandler.addInputListener(this);
  51548. return volume;
  51549. }
  51550. update(e){
  51551. //console.log(e.delta)
  51552. }
  51553. render(){
  51554. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  51555. }
  51556. }
  51557. class SpotLightHelper$1 extends Object3D{
  51558. constructor(light, color){
  51559. super();
  51560. this.light = light;
  51561. this.color = color;
  51562. //this.up.set(0, 0, 1);
  51563. this.updateMatrix();
  51564. this.updateMatrixWorld();
  51565. { // SPHERE
  51566. let sg = new SphereGeometry(1, 32, 32);
  51567. let sm = new MeshNormalMaterial();
  51568. this.sphere = new Mesh(sg, sm);
  51569. this.sphere.scale.set(0.5, 0.5, 0.5);
  51570. this.add(this.sphere);
  51571. }
  51572. { // LINES
  51573. let positions = new Float32Array([
  51574. +0, +0, +0, +0, +0, -1,
  51575. +0, +0, +0, -1, -1, -1,
  51576. +0, +0, +0, +1, -1, -1,
  51577. +0, +0, +0, +1, +1, -1,
  51578. +0, +0, +0, -1, +1, -1,
  51579. -1, -1, -1, +1, -1, -1,
  51580. +1, -1, -1, +1, +1, -1,
  51581. +1, +1, -1, -1, +1, -1,
  51582. -1, +1, -1, -1, -1, -1,
  51583. ]);
  51584. let geometry = new BufferGeometry();
  51585. geometry.setAttribute("position", new BufferAttribute(positions, 3));
  51586. let material = new LineBasicMaterial();
  51587. this.frustum = new LineSegments(geometry, material);
  51588. this.add(this.frustum);
  51589. }
  51590. this.update();
  51591. }
  51592. update(){
  51593. this.light.updateMatrix();
  51594. this.light.updateMatrixWorld();
  51595. let position = this.light.position;
  51596. let target = new Vector3().addVectors(
  51597. this.light.position, this.light.getWorldDirection(new Vector3()).multiplyScalar(-1));
  51598. let quat = new Quaternion().setFromRotationMatrix(
  51599. new Matrix4().lookAt( position, target, new Vector3( 0, 0, 1 ) )
  51600. );
  51601. this.setRotationFromQuaternion(quat);
  51602. this.position.copy(position);
  51603. let coneLength = (this.light.distance > 0) ? this.light.distance : 1000;
  51604. let coneWidth = coneLength * Math.tan( this.light.angle * 0.5 );
  51605. this.frustum.scale.set(coneWidth, coneWidth, coneLength);
  51606. }
  51607. }
  51608. //add-------------------------------------
  51609. const OpaWhenNotSelect = 0.6;
  51610. const ScaleRatio = 8;
  51611. const OutlineColor = 0x666666;
  51612. //----------------------------------------
  51613. const hideFocusHandles = true;//add
  51614. class TransformationTool {
  51615. constructor(viewer) {
  51616. this.viewer = viewer;
  51617. this.scene = new Scene();
  51618. this.modesEnabled = {scale:true,translation:true,rotation:true};//add
  51619. this.selection = [];
  51620. this.pivot = new Vector3();
  51621. this.dragging = false;
  51622. this.showPickVolumes = false;
  51623. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  51624. this.viewer.inputHandler.addEventListener('selection_changed', (e) => {
  51625. for(let selected of this.selection){
  51626. this.viewer.inputHandler.blacklist.delete(selected);
  51627. }
  51628. this.selection = e.selection;
  51629. for(let selected of this.selection){
  51630. this.viewer.inputHandler.blacklist.add(selected);
  51631. }
  51632. });
  51633. this.viewer.addEventListener('global_touchstart',(e)=>{ //add
  51634. this.update();
  51635. });
  51636. let red = Potree.config.axis.x.color;
  51637. let green = Potree.config.axis.y.color;
  51638. let blue = Potree.config.axis.z.color;
  51639. this.activeHandle = null;
  51640. this.scaleHandles = {
  51641. "scale.x+": {name: "scale.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  51642. "scale.x-": {name: "scale.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  51643. "scale.y+": {name: "scale.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  51644. "scale.y-": {name: "scale.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  51645. "scale.z+": {name: "scale.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  51646. "scale.z-": {name: "scale.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  51647. };
  51648. this.focusHandles = {
  51649. "focus.x+": {name: "focus.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  51650. "focus.x-": {name: "focus.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  51651. "focus.y+": {name: "focus.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  51652. "focus.y-": {name: "focus.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  51653. "focus.z+": {name: "focus.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  51654. "focus.z-": {name: "focus.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  51655. };
  51656. this.translationHandles = {
  51657. "translation.x": {name: "translation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  51658. "translation.y": {name: "translation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  51659. "translation.z": {name: "translation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  51660. };
  51661. this.rotationHandles = {
  51662. "rotation.x": {name: "rotation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  51663. "rotation.y": {name: "rotation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  51664. "rotation.z": {name: "rotation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  51665. };
  51666. this.handles = Object.assign({}, this.scaleHandles, hideFocusHandles?{}:this.focusHandles, this.translationHandles, this.rotationHandles);
  51667. this.pickVolumes = [];
  51668. this.initializeScaleHandles();
  51669. this.initializeFocusHandles();
  51670. this.initializeTranslationHandles();
  51671. this.initializeRotationHandles();
  51672. let boxFrameGeometry = new Geometry();
  51673. {
  51674. // bottom
  51675. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51676. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51677. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51678. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51679. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51680. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51681. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51682. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51683. // top
  51684. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51685. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51686. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51687. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51688. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51689. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51690. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51691. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51692. // sides
  51693. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51694. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51695. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51696. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51697. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51698. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51699. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51700. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51701. }
  51702. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0xffff00}));
  51703. this.scene.add(this.frame);
  51704. viewer.setObjectLayers(this.scene, 'transformationTool' );
  51705. this.scene.traverse(e=>{
  51706. e.pickDontCheckDis = true; //pick时不需要识别是否在点云之上
  51707. });
  51708. }
  51709. setModeEnable(mode,enable){//xzw add
  51710. let handels = this[mode + 'Handles'];
  51711. if(!handels)return
  51712. for(let o in handels){
  51713. handels[o].node.visible = !!enable;
  51714. }
  51715. this.modesEnabled[mode] = !!enable;
  51716. }
  51717. initializeScaleHandles(){
  51718. let sgSphere = new SphereGeometry(1, 32, 32);
  51719. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  51720. for(let handleName of Object.keys(this.scaleHandles)){
  51721. let handle = this.scaleHandles[handleName];
  51722. let node = handle.node;
  51723. this.scene.add(node);
  51724. node.position.set(...handle.alignment).multiplyScalar(0.5);
  51725. let material = new MeshBasicMaterial({
  51726. color: handle.color,
  51727. opacity: OpaWhenNotSelect,
  51728. transparent: true
  51729. });
  51730. let outlineMaterial = new MeshBasicMaterial({
  51731. color: OutlineColor,
  51732. side: BackSide,
  51733. opacity: OpaWhenNotSelect,
  51734. transparent: true});
  51735. let pickMaterial = new MeshNormalMaterial({
  51736. opacity: 0.2,
  51737. transparent: true,
  51738. visible: this.showPickVolumes});
  51739. let sphere = new Mesh(sgSphere, material);
  51740. sphere.scale.set(2, 2, 2 );
  51741. sphere.name = `${handleName}.handle`;
  51742. node.add(sphere);
  51743. let outline = new Mesh(sgSphere, outlineMaterial);
  51744. outline.scale.set(1.1, 1.1, 1.1);
  51745. outline.name = `${handleName}.outline`;
  51746. sphere.add(outline);
  51747. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  51748. pickSphere.name = `${handleName}.pick_volume`;
  51749. pickSphere.scale.set(2, 2, 2);
  51750. sphere.add(pickSphere);
  51751. pickSphere.handle = handleName;
  51752. this.pickVolumes.push(pickSphere);
  51753. node.setOpacity = (target) => {
  51754. let opacity = {x: material.opacity};
  51755. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51756. t.onUpdate(() => {
  51757. sphere.visible = opacity.x > 0;
  51758. pickSphere.visible = opacity.x > 0;
  51759. material.opacity = opacity.x;
  51760. outlineMaterial.opacity = opacity.x;
  51761. pickSphere.material.opacity = opacity.x * 0.5;
  51762. });
  51763. t.start();
  51764. };
  51765. pickSphere.addEventListener("drag", (e) => this.dragScaleHandle(e));
  51766. pickSphere.addEventListener("drop", (e) => this.dropScaleHandle(e));
  51767. pickSphere.addEventListener("mouseover", e => {
  51768. //node.setOpacity(1);
  51769. });
  51770. pickSphere.addEventListener("click", e => {
  51771. //e.consume();
  51772. });
  51773. pickSphere.addEventListener("mouseleave", e => {
  51774. //node.setOpacity(OpaWhenNotSelect);
  51775. });
  51776. }
  51777. }
  51778. initializeFocusHandles(){
  51779. if(hideFocusHandles)return//add
  51780. //let sgBox = new THREE.BoxGeometry(1, 1, 1);
  51781. let sgPlane = new PlaneGeometry(4, 4, 1, 1);
  51782. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  51783. let texture = new TextureLoader().load(`${exports.resourcePath}/icons/eye_2.png`);
  51784. for(let handleName of Object.keys(this.focusHandles)){
  51785. let handle = this.focusHandles[handleName];
  51786. let node = handle.node;
  51787. this.scene.add(node);
  51788. let align = handle.alignment;
  51789. //node.lookAt(new THREE.Vector3().addVectors(node.position, new THREE.Vector3(...align)));
  51790. node.lookAt(new Vector3(...align));
  51791. let off = 0.8;
  51792. if(align[0] === 1){
  51793. node.position.set(1, off, -off).multiplyScalar(0.5);
  51794. node.rotation.z = Math.PI / 2;
  51795. }else if(align[0] === -1){
  51796. node.position.set(-1, -off, -off).multiplyScalar(0.5);
  51797. node.rotation.z = Math.PI / 2;
  51798. }else if(align[1] === 1){
  51799. node.position.set(-off, 1, -off).multiplyScalar(0.5);
  51800. node.rotation.set(Math.PI / 2, Math.PI, 0.0);
  51801. }else if(align[1] === -1){
  51802. node.position.set(off, -1, -off).multiplyScalar(0.5);
  51803. node.rotation.set(Math.PI / 2, 0.0, 0.0);
  51804. }else if(align[2] === 1){
  51805. node.position.set(off, off, 1).multiplyScalar(0.5);
  51806. }else if(align[2] === -1){
  51807. node.position.set(-off, off, -1).multiplyScalar(0.5);
  51808. }
  51809. let material = new MeshBasicMaterial({
  51810. color: handle.color,
  51811. opacity: 0,
  51812. transparent: true,
  51813. map: texture
  51814. });
  51815. //let outlineMaterial = new THREE.MeshBasicMaterial({
  51816. // color: 0x000000,
  51817. // side: THREE.BackSide,
  51818. // opacity: 0,
  51819. // transparent: true});
  51820. let pickMaterial = new MeshNormalMaterial({
  51821. //opacity: 0,
  51822. transparent: true,
  51823. visible: this.showPickVolumes});
  51824. let box = new Mesh(sgPlane, material);
  51825. box.name = `${handleName}.handle`;
  51826. box.scale.set(1.5, 1.5, 1.5);
  51827. box.position.set(0, 0, 0);
  51828. box.visible = false;
  51829. node.add(box);
  51830. //handle.focusNode = box;
  51831. //let outline = new THREE.Mesh(sgPlane, outlineMaterial);
  51832. //outline.scale.set(1.4, 1.4, 1.4);
  51833. //outline.name = `${handleName}.outline`;
  51834. //box.add(outline);
  51835. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  51836. pickSphere.name = `${handleName}.pick_volume`;
  51837. pickSphere.scale.set(2, 2, 2);
  51838. box.add(pickSphere);
  51839. pickSphere.handle = handleName;
  51840. this.pickVolumes.push(pickSphere);
  51841. node.setOpacity = (target) => {
  51842. let opacity = {x: material.opacity};
  51843. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51844. t.onUpdate(() => {
  51845. pickSphere.visible = opacity.x > 0;
  51846. box.visible = opacity.x > 0;
  51847. material.opacity = opacity.x;
  51848. //outlineMaterial.opacity = opacity.x;
  51849. pickSphere.material.opacity = opacity.x * 0.5;
  51850. });
  51851. t.start();
  51852. };
  51853. //pickSphere.addEventListener("drag", e => {});
  51854. pickSphere.addEventListener("mouseup", e => {
  51855. //e.consume();
  51856. });
  51857. pickSphere.addEventListener("mousedown", e => {
  51858. //e.consume();
  51859. });
  51860. pickSphere.addEventListener("click", e => {
  51861. //e.consume();
  51862. let selected = this.selection[0];
  51863. let maxScale = Math.max(...selected.scale.toArray());
  51864. let minScale = Math.min(...selected.scale.toArray());
  51865. let handleLength = Math.abs(selected.scale.dot(new Vector3(...handle.alignment)));
  51866. let alignment = new Vector3(...handle.alignment).multiplyScalar(2 * maxScale / handleLength);
  51867. alignment.applyMatrix4(selected.matrixWorld);
  51868. let newCamPos = alignment;
  51869. let newCamTarget = selected.getWorldPosition(new Vector3());
  51870. Utils.moveTo(this.viewer.scene, newCamPos, newCamTarget);
  51871. });
  51872. pickSphere.addEventListener("mouseover", e => {
  51873. //box.setOpacity(1);
  51874. });
  51875. pickSphere.addEventListener("mouseleave", e => {
  51876. //box.setOpacity(OpaWhenNotSelect);
  51877. });
  51878. }
  51879. }
  51880. initializeTranslationHandles(){
  51881. let boxGeometry = new BoxGeometry(1, 1, 1);
  51882. for(let handleName of Object.keys(this.translationHandles)){
  51883. let handle = this.handles[handleName];
  51884. let node = handle.node;
  51885. this.scene.add(node);
  51886. let material = new MeshBasicMaterial({
  51887. color: handle.color,
  51888. opacity: OpaWhenNotSelect,
  51889. transparent: true});
  51890. let outlineMaterial = new MeshBasicMaterial({
  51891. color: OutlineColor,
  51892. side: BackSide,
  51893. opacity: OpaWhenNotSelect,
  51894. transparent: true});
  51895. let pickMaterial = new MeshNormalMaterial({
  51896. opacity: 0.2,
  51897. transparent: true,
  51898. visible: this.showPickVolumes
  51899. });
  51900. let box = new Mesh(boxGeometry, material);
  51901. box.name = `${handleName}.handle`;
  51902. box.scale.set(1, 1, 72);
  51903. box.lookAt(new Vector3(...handle.alignment));
  51904. box.renderOrder = 10;
  51905. node.add(box);
  51906. handle.translateNode = box;
  51907. let outline = new Mesh(boxGeometry, outlineMaterial);
  51908. outline.name = `${handleName}.outline`;
  51909. outline.scale.set(1.3, 1.3, 1.01);
  51910. outline.renderOrder = 0;
  51911. box.add(outline);
  51912. let pickVolume = new Mesh(boxGeometry, pickMaterial);
  51913. pickVolume.name = `${handleName}.pick_volume`;
  51914. pickVolume.scale.set(4, 4, 1.1);
  51915. pickVolume.handle = handleName;
  51916. box.add(pickVolume);
  51917. this.pickVolumes.push(pickVolume);
  51918. node.setOpacity = (target) => {
  51919. let opacity = {x: material.opacity};
  51920. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51921. t.onUpdate(() => {
  51922. box.visible = opacity.x > 0;
  51923. pickVolume.visible = opacity.x > 0;
  51924. material.opacity = opacity.x;
  51925. outlineMaterial.opacity = opacity.x;
  51926. pickMaterial.opacity = opacity.x * 0.5;
  51927. });
  51928. t.start();
  51929. };
  51930. pickVolume.addEventListener("drag", (e) => {this.dragTranslationHandle(e);});
  51931. pickVolume.addEventListener("drop", (e) => {this.dropTranslationHandle(e);});
  51932. }
  51933. }
  51934. initializeRotationHandles(){
  51935. let adjust = 1.5;
  51936. let torusGeometry = new TorusGeometry(1, adjust * 0.015, 8, 64, Math.PI / 2);
  51937. let outlineGeometry = new TorusGeometry(1, adjust * 0.018, 8, 64, Math.PI / 2);
  51938. let pickGeometry = new TorusGeometry(1, adjust * 0.04, 6, 4, Math.PI / 2);
  51939. for(let handleName of Object.keys(this.rotationHandles)){
  51940. let handle = this.handles[handleName];
  51941. let node = handle.node;
  51942. this.scene.add(node);
  51943. let material = new MeshBasicMaterial({
  51944. color: handle.color,
  51945. opacity: OpaWhenNotSelect,
  51946. transparent: true
  51947. });
  51948. let outlineMaterial = new MeshBasicMaterial({
  51949. color: OutlineColor,
  51950. side: BackSide,
  51951. opacity: OpaWhenNotSelect,
  51952. transparent: true
  51953. });
  51954. let pickMaterial = new MeshNormalMaterial({
  51955. opacity: 0.2,
  51956. transparent: true,
  51957. visible: this.showPickVolumes
  51958. });
  51959. let box = new Mesh(torusGeometry, material);
  51960. box.name = `${handleName}.handle`;
  51961. box.scale.set(30, 30, 30);
  51962. box.lookAt(new Vector3(...handle.alignment));
  51963. node.add(box);
  51964. handle.translateNode = box;
  51965. let outline = new Mesh(outlineGeometry, outlineMaterial);
  51966. outline.name = `${handleName}.outline`;
  51967. outline.scale.set(1, 1, 1);
  51968. outline.renderOrder = 0;
  51969. box.add(outline);
  51970. let pickVolume = new Mesh(pickGeometry, pickMaterial);
  51971. pickVolume.name = `${handleName}.pick_volume`;
  51972. pickVolume.scale.set(1, 1, 1);
  51973. pickVolume.handle = handleName;
  51974. box.add(pickVolume);
  51975. this.pickVolumes.push(pickVolume);
  51976. node.setOpacity = (target) => {
  51977. let opacity = {x: material.opacity};
  51978. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51979. t.onUpdate(() => {
  51980. box.visible = opacity.x > 0;
  51981. pickVolume.visible = opacity.x > 0;
  51982. material.opacity = opacity.x;
  51983. outlineMaterial.opacity = opacity.x;
  51984. pickMaterial.opacity = opacity.x * 0.5;
  51985. });
  51986. t.start();
  51987. };
  51988. //pickVolume.addEventListener("mouseover", (e) => {
  51989. // //let a = this.viewer.scene.getActiveCamera().getWorldDirection(new THREE.Vector3()).dot(pickVolume.getWorldDirection(new THREE.Vector3()));
  51990. // console.log(pickVolume.getWorldDirection(new THREE.Vector3()));
  51991. //});
  51992. pickVolume.addEventListener("drag", (e) => {this.dragRotationHandle(e);});
  51993. pickVolume.addEventListener("drop", (e) => {this.dropRotationHandle(e);});
  51994. }
  51995. }
  51996. dragRotationHandle(e){
  51997. let drag = e.drag;
  51998. let handle = this.activeHandle;
  51999. let camera = this.viewer.scene.getActiveCamera();
  52000. if(!handle){
  52001. return
  52002. };
  52003. let localNormal = new Vector3(...handle.alignment);
  52004. let n = new Vector3();
  52005. n.copy(new Vector4(...localNormal.toArray(), 0).applyMatrix4(handle.node.matrixWorld));
  52006. n.normalize();
  52007. if (!drag.intersectionStart){
  52008. //this.viewer.scene.scene.remove(this.debug);
  52009. //this.debug = new THREE.Object3D();
  52010. //this.viewer.scene.scene.add(this.debug);
  52011. //Utils.debugSphere(this.debug, drag.location, 3, 0xaaaaaa);
  52012. //let debugEnd = drag.location.clone().add(n.clone().multiplyScalar(20));
  52013. //Utils.debugLine(this.debug, drag.location, debugEnd, 0xff0000);
  52014. drag.intersectionStart = drag.location;
  52015. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52016. drag.handle = handle;
  52017. let plane = new Plane().setFromNormalAndCoplanarPoint(n, drag.intersectionStart);
  52018. drag.dragPlane = plane;
  52019. drag.pivot = drag.intersectionStart;
  52020. }else {
  52021. handle = drag.handle;
  52022. }
  52023. this.dragging = true;
  52024. let pointer = this.viewer.inputHandler.pointer;
  52025. let domElement = this.viewer.renderer.domElement;
  52026. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52027. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52028. if (I) {
  52029. let center = this.scene.getWorldPosition(new Vector3());
  52030. let from = drag.pivot;
  52031. let to = I;
  52032. let v1 = from.clone().sub(center).normalize();
  52033. let v2 = to.clone().sub(center).normalize();
  52034. let angle = Math.acos(v1.dot(v2));
  52035. let sign = Math.sign(v1.cross(v2).dot(n));
  52036. angle = angle * sign;
  52037. if (Number.isNaN(angle)) {
  52038. return;
  52039. }
  52040. let normal = new Vector3(...handle.alignment);
  52041. for (let selection of this.selection) {
  52042. selection.rotateOnAxis(normal, angle);
  52043. selection.dispatchEvent({
  52044. type: "orientation_changed",
  52045. object: selection
  52046. });
  52047. }
  52048. drag.pivot = I;
  52049. }
  52050. }
  52051. dropRotationHandle(e){
  52052. this.dragging = false;
  52053. this.setActiveHandle(null);
  52054. }
  52055. dragTranslationHandle(e){
  52056. let drag = e.drag;
  52057. let handle = this.activeHandle;
  52058. let camera = this.viewer.scene.getActiveCamera();
  52059. if(!drag.intersectionStart && handle){
  52060. drag.intersectionStart = drag.location;
  52061. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52062. let start = drag.intersectionStart;
  52063. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  52064. let end = new Vector3().addVectors(start, dir);
  52065. let line = new Line3(start.clone(), end.clone());
  52066. drag.line = line;
  52067. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  52068. let normal = new Vector3().subVectors(camera.position, camOnLine);
  52069. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart);
  52070. drag.dragPlane = plane;
  52071. drag.pivot = drag.intersectionStart;
  52072. }else {
  52073. handle = drag.handle;
  52074. }
  52075. this.dragging = true;
  52076. {
  52077. let pointer = this.viewer.inputHandler.pointer;
  52078. let domElement = this.viewer.renderer.domElement;
  52079. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52080. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52081. if (I) {
  52082. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  52083. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  52084. for (let selection of this.selection) {
  52085. selection.position.add(diff);
  52086. selection.dispatchEvent({
  52087. type: "position_changed",
  52088. object: selection
  52089. });
  52090. }
  52091. drag.pivot = drag.pivot.add(diff);
  52092. }
  52093. }
  52094. }
  52095. dropTranslationHandle(e){
  52096. this.dragging = false;
  52097. this.setActiveHandle(null);
  52098. }
  52099. dropScaleHandle(e){
  52100. this.dragging = false;
  52101. this.setActiveHandle(null);
  52102. }
  52103. dragScaleHandle(e){
  52104. let drag = e.drag;
  52105. let handle = this.activeHandle;
  52106. let camera = this.viewer.scene.getActiveCamera();
  52107. if(!drag.intersectionStart){
  52108. drag.intersectionStart = drag.location;
  52109. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52110. drag.handle = handle;
  52111. let start = drag.intersectionStart;
  52112. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  52113. let end = new Vector3().addVectors(start, dir);
  52114. let line = new Line3(start.clone(), end.clone());
  52115. drag.line = line;
  52116. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  52117. let normal = new Vector3().subVectors(camera.position, camOnLine);
  52118. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart);
  52119. drag.dragPlane = plane;
  52120. drag.pivot = drag.intersectionStart;
  52121. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  52122. }else {
  52123. handle = drag.handle;
  52124. }
  52125. this.dragging = true;
  52126. {
  52127. let pointer = this.viewer.inputHandler.pointer;
  52128. let domElement = this.viewer.renderer.domElement;
  52129. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52130. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52131. if (I) {
  52132. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  52133. let direction = handle.alignment.reduce( (a, v) => a + v, 0);
  52134. let toObjectSpace = this.selection[0].matrixWorld.clone().invert();
  52135. let iOnLineOS = iOnLine.clone().applyMatrix4(toObjectSpace);
  52136. let pivotOS = drag.pivot.clone().applyMatrix4(toObjectSpace);
  52137. let diffOS = new Vector3().subVectors(iOnLineOS, pivotOS);
  52138. let dragDirectionOS = diffOS.clone().normalize();
  52139. if(iOnLine.distanceTo(drag.pivot) === 0){
  52140. dragDirectionOS.set(0, 0, 0);
  52141. }
  52142. let dragDirection = dragDirectionOS.dot(new Vector3(...handle.alignment));
  52143. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  52144. let diffScale = new Vector3(...handle.alignment).multiplyScalar(diff.length() * direction * dragDirection);
  52145. let diffPosition = diff.clone().multiplyScalar(0.5);
  52146. for (let selection of this.selection) {
  52147. //xzw 改:否则不跟手
  52148. let diffScale_ = diffScale.clone().divide(selection.boundingBox.getSize(new Vector3));
  52149. selection.scale.add(diffScale_);
  52150. //selection.scale.add(diffScale);
  52151. selection.scale.x = Math.max(0.1, selection.scale.x);
  52152. selection.scale.y = Math.max(0.1, selection.scale.y);
  52153. selection.scale.z = Math.max(0.1, selection.scale.z);
  52154. selection.position.add(diffPosition);
  52155. selection.dispatchEvent({
  52156. type: "position_changed",
  52157. object: selection
  52158. });
  52159. selection.dispatchEvent({
  52160. type: "scale_changed",
  52161. object: selection
  52162. });
  52163. }
  52164. drag.pivot.copy(iOnLine);
  52165. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  52166. }
  52167. }
  52168. }
  52169. setActiveHandle(handle){
  52170. if(this.dragging){
  52171. return;
  52172. }
  52173. if(this.activeHandle === handle){
  52174. return;
  52175. }
  52176. this.activeHandle = handle;
  52177. if(handle === null){
  52178. for(let handleName of Object.keys(this.handles)){
  52179. let handle = this.handles[handleName];
  52180. handle.node.setOpacity(0);
  52181. }
  52182. }
  52183. if(!hideFocusHandles){
  52184. for(let handleName of Object.keys(this.focusHandles)){
  52185. let handle = this.focusHandles[handleName];
  52186. if(this.activeHandle === handle){
  52187. handle.node.setOpacity(1.0);
  52188. }else {
  52189. handle.node.setOpacity(OpaWhenNotSelect);
  52190. }
  52191. }
  52192. }
  52193. for(let handleName of Object.keys(this.translationHandles)){
  52194. let handle = this.translationHandles[handleName];
  52195. if(this.activeHandle === handle){
  52196. handle.node.setOpacity(1.0);
  52197. }else {
  52198. handle.node.setOpacity(OpaWhenNotSelect);
  52199. }
  52200. }
  52201. for(let handleName of Object.keys(this.rotationHandles)){
  52202. let handle = this.rotationHandles[handleName];
  52203. //if(this.activeHandle === handle){
  52204. // handle.node.setOpacity(1.0);
  52205. //}else{
  52206. // handle.node.setOpacity(OpaWhenNotSelect)
  52207. //}
  52208. handle.node.setOpacity(OpaWhenNotSelect);
  52209. }
  52210. for(let handleName of Object.keys(this.scaleHandles)){
  52211. let handle = this.scaleHandles[handleName];
  52212. if(this.activeHandle === handle){
  52213. handle.node.setOpacity(1.0);
  52214. if(!hideFocusHandles){
  52215. let relatedFocusHandle = this.focusHandles[handle.name.replace("scale", "focus")];
  52216. let relatedFocusNode = relatedFocusHandle.node;
  52217. relatedFocusNode.setOpacity(OpaWhenNotSelect);
  52218. }
  52219. for(let translationHandleName of Object.keys(this.translationHandles)){
  52220. let translationHandle = this.translationHandles[translationHandleName];
  52221. translationHandle.node.setOpacity(OpaWhenNotSelect);
  52222. }
  52223. //let relatedTranslationHandle = this.translationHandles[
  52224. // handle.name.replace("scale", "translation").replace(/[+-]/g, "")];
  52225. //let relatedTranslationNode = relatedTranslationHandle.node;
  52226. //relatedTranslationNode.setOpacity(OpaWhenNotSelect);
  52227. }else {
  52228. handle.node.setOpacity(OpaWhenNotSelect);
  52229. }
  52230. }
  52231. if(handle){
  52232. handle.node.setOpacity(1.0);
  52233. }
  52234. }
  52235. update () {
  52236. if(this.selection.length === 1){
  52237. this.scene.visible = true;
  52238. this.scene.updateMatrix();
  52239. this.scene.updateMatrixWorld();
  52240. let selected = this.selection[0];
  52241. let world = selected.matrixWorld;
  52242. let camera = this.viewer.scene.getActiveCamera();
  52243. let domElement = this.viewer.renderer.domElement;
  52244. let pointer = this.viewer.inputHandler.pointer;
  52245. let center = selected.boundingBox.getCenter(new Vector3()).clone().applyMatrix4(selected.matrixWorld);
  52246. this.scene.scale.copy(selected.boundingBox.getSize(new Vector3()).multiply(selected.scale));
  52247. this.scene.position.copy(center);
  52248. this.scene.rotation.copy(selected.rotation);
  52249. this.scene.updateMatrixWorld();
  52250. {
  52251. // adjust rotation handles
  52252. if(!this.dragging){
  52253. let tWorld = this.scene.matrixWorld;
  52254. let tObject = tWorld.clone().invert();
  52255. let camObjectPos = camera.getWorldPosition(new Vector3()).applyMatrix4(tObject);
  52256. let x = this.rotationHandles["rotation.x"].node.rotation;
  52257. let y = this.rotationHandles["rotation.y"].node.rotation;
  52258. let z = this.rotationHandles["rotation.z"].node.rotation;
  52259. x.order = "ZYX";
  52260. y.order = "ZYX";
  52261. let above = camObjectPos.z > 0;
  52262. let below = !above;
  52263. let PI_HALF = Math.PI / 2;
  52264. if(above){
  52265. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  52266. x.x = 1 * PI_HALF;
  52267. y.y = 3 * PI_HALF;
  52268. z.z = 0 * PI_HALF;
  52269. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  52270. x.x = 1 * PI_HALF;
  52271. y.y = 2 * PI_HALF;
  52272. z.z = 1 * PI_HALF;
  52273. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  52274. x.x = 2 * PI_HALF;
  52275. y.y = 2 * PI_HALF;
  52276. z.z = 2 * PI_HALF;
  52277. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  52278. x.x = 2 * PI_HALF;
  52279. y.y = 3 * PI_HALF;
  52280. z.z = 3 * PI_HALF;
  52281. }
  52282. }else if(below){
  52283. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  52284. x.x = 0 * PI_HALF;
  52285. y.y = 0 * PI_HALF;
  52286. z.z = 0 * PI_HALF;
  52287. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  52288. x.x = 0 * PI_HALF;
  52289. y.y = 1 * PI_HALF;
  52290. z.z = 1 * PI_HALF;
  52291. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  52292. x.x = 3 * PI_HALF;
  52293. y.y = 1 * PI_HALF;
  52294. z.z = 2 * PI_HALF;
  52295. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  52296. x.x = 3 * PI_HALF;
  52297. y.y = 0 * PI_HALF;
  52298. z.z = 3 * PI_HALF;
  52299. }
  52300. }
  52301. }
  52302. // adjust scale of components
  52303. for(let handleName of Object.keys(this.handles)){
  52304. let handle = this.handles[handleName];
  52305. let node = handle.node;
  52306. let handlePos = node.getWorldPosition(new Vector3());
  52307. let distance = handlePos.distanceTo(camera.position);
  52308. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  52309. let ws = node.parent.getWorldScale(new Vector3());
  52310. let s = (ScaleRatio / pr);
  52311. let scale = new Vector3(s, s, s).divide(ws);
  52312. let rot = new Matrix4().makeRotationFromEuler(node.rotation); //需要使用到旋转,所以我把设置scale的移到旋转后了,否则在视图上下旋转的分界线处rotateHandel会被拉长从而闪烁。
  52313. let rotInv = rot.clone().invert();
  52314. scale.applyMatrix4(rotInv);
  52315. scale.x = Math.abs(scale.x);
  52316. scale.y = Math.abs(scale.y);
  52317. scale.z = Math.abs(scale.z);
  52318. node.scale.copy(scale);
  52319. }
  52320. {
  52321. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52322. let raycaster = new Raycaster(ray.origin, ray.direction);
  52323. raycaster.layers.enableAll();//add
  52324. let pickVolumes = this.pickVolumes.filter(v=>{
  52325. let mode = v.handle.split('.')[0];
  52326. return this.modesEnabled[mode]
  52327. });
  52328. let intersects = raycaster.intersectObjects(pickVolumes, true);
  52329. if(intersects.length > 0){
  52330. let I = intersects[0];
  52331. let handleName = I.object.handle;
  52332. console.log(handleName);
  52333. this.setActiveHandle(this.handles[handleName]);
  52334. }else {
  52335. this.setActiveHandle(null);
  52336. }
  52337. }
  52338. //
  52339. for(let handleName of Object.keys(this.scaleHandles)){
  52340. let handle = this.handles[handleName];
  52341. let node = handle.node;
  52342. let alignment = handle.alignment;
  52343. }
  52344. }
  52345. }else {
  52346. this.scene.visible = false;
  52347. }
  52348. }
  52349. };
  52350. /*
  52351. note:
  52352. transformationTool.scene会跟随选中物体,其scale就是boundingbox的大小。因此transformationTool.frame这个框也会跟着缩放
  52353. */
  52354. class VolumeTool extends EventDispatcher{
  52355. constructor (viewer) {
  52356. super();
  52357. this.viewer = viewer;
  52358. this.renderer = viewer.renderer;
  52359. this.addEventListener('start_inserting_volume', e => {
  52360. this.viewer.dispatchEvent({
  52361. type: 'cancel_insertions'
  52362. });
  52363. });
  52364. this.scene = new Scene();
  52365. this.scene.name = 'scene_volume';
  52366. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  52367. this.onRemove = e => {
  52368. this.scene.remove(e.volume);
  52369. };
  52370. this.onAdd = e => {
  52371. this.scene.add(e.volume);
  52372. };
  52373. for(let volume of viewer.scene.volumes){
  52374. this.onAdd({volume: volume});
  52375. }
  52376. this.viewer.inputHandler.addEventListener('delete', e => {
  52377. let volumes = e.selection.filter(e => (e instanceof Volume));
  52378. volumes.forEach(e => this.viewer.scene.removeVolume(e));
  52379. });
  52380. viewer.addEventListener("update", this.update.bind(this));
  52381. viewer.addEventListener("render.pass.scene", e => this.render(e));
  52382. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  52383. viewer.scene.addEventListener('volume_added', this.onAdd);
  52384. viewer.scene.addEventListener('volume_removed', this.onRemove);
  52385. }
  52386. onSceneChange(e){
  52387. if(e.oldScene){
  52388. e.oldScene.removeEventListeners('volume_added', this.onAdd);
  52389. e.oldScene.removeEventListeners('volume_removed', this.onRemove);
  52390. }
  52391. e.scene.addEventListener('volume_added', this.onAdd);
  52392. e.scene.addEventListener('volume_removed', this.onRemove);
  52393. }
  52394. startInsertion (args = {}) {
  52395. let volume;
  52396. if(args.type){
  52397. volume = new args.type();
  52398. }else {
  52399. volume = new BoxVolume();
  52400. }
  52401. volume.clip = args.clip || false;
  52402. volume.name = args.name || 'Volume';
  52403. this.dispatchEvent({
  52404. type: 'start_inserting_volume',
  52405. volume: volume
  52406. });
  52407. this.viewer.scene.addVolume(volume);
  52408. //this.scene.add(volume);
  52409. let cancel = {
  52410. callback: null
  52411. };
  52412. let drag = e => {
  52413. let camera = this.viewer.scene.getActiveCamera();
  52414. var I = e.intersect;
  52415. if (I) {
  52416. volume.position.copy(I.location);
  52417. let wp = volume.getWorldPosition(new Vector3()).applyMatrix4(camera.matrixWorldInverse);
  52418. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  52419. let w = Math.abs((wp.z / 5));
  52420. volume.scale.set(w, w, w);
  52421. }
  52422. };
  52423. let drop = e => {
  52424. volume.removeEventListener('drag', drag);
  52425. volume.removeEventListener('drop', drop);
  52426. cancel.callback();
  52427. };
  52428. cancel.callback = e => {
  52429. volume.removeEventListener('drag', drag);
  52430. volume.removeEventListener('drop', drop);
  52431. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  52432. };
  52433. volume.addEventListener('drag', drag);
  52434. volume.addEventListener('drop', drop);
  52435. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  52436. this.viewer.inputHandler.startDragging(volume);
  52437. return volume;
  52438. }
  52439. update(){
  52440. if (!this.viewer.scene) {
  52441. return;
  52442. }
  52443. let camera = this.viewer.scene.getActiveCamera();
  52444. let renderAreaSize = this.viewer.renderer.getSize(new Vector2$1());
  52445. let clientWidth = renderAreaSize.width;
  52446. let clientHeight = renderAreaSize.height;
  52447. let volumes = this.viewer.scene.volumes;
  52448. for (let volume of volumes) {
  52449. }
  52450. }
  52451. render(params){
  52452. const renderer = this.viewer.renderer;
  52453. const oldTarget = renderer.getRenderTarget();
  52454. if(params.renderTarget){
  52455. renderer.setRenderTarget(params.renderTarget);
  52456. }
  52457. renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  52458. renderer.setRenderTarget(oldTarget);
  52459. }
  52460. }
  52461. const initDir = new Vector3(0,1,0);//指南针模型的北方向 向屏幕里
  52462. class Compass extends EventDispatcher{
  52463. constructor(dom, viewport){
  52464. super();
  52465. this.angle = 0;
  52466. this.show = false;
  52467. if(dom){
  52468. this.dom = $(dom);
  52469. }
  52470. this.viewport = viewport;
  52471. this.init();
  52472. }
  52473. init(){
  52474. var width = 100, height = 100;
  52475. if(!this.dom){
  52476. this.dom = $('<div name="compass"></div>');
  52477. $(viewer.renderArea).append(this.dom);
  52478. }
  52479. this.dom.css({ display:"none", position:"absolute",right:"1%",top: "60px",width:width+"px",height:height+"px", "z-index":100,"pointer-events":"none" });
  52480. let child = $("<div class='dirText north'><span>"+/* (config.lang=='zh'? */'北'/* :'N') */+"</span></div><div class='center'></div>");
  52481. this.dom.append(child);
  52482. this.dom.find(".dirText").css({textAlign:"center","font-size":"10px","position":"absolute",
  52483. width: "100%",
  52484. height: "25px",
  52485. "line-height": "25px"});
  52486. this.dom.find(".north").css({"color":"#02a0e9","top":"0"});
  52487. this.dom.find(".south").css({"color":"#ff1414","bottom":"0"});
  52488. this.dom.find(".center").css({
  52489. //"background":`url(${config.getStaticResource('img')}/dire.png)`,
  52490. width: width/2+"px",
  52491. height: height/2+"px",
  52492. "background-size": "contain",
  52493. "background-position": "center",
  52494. left: "50%",
  52495. top: "50%",
  52496. transform: "translate(-50%,-50%)",
  52497. position: "absolute"
  52498. });
  52499. this.dom.find(".dirText").css({
  52500. "text-align": "center",
  52501. "font-size": "10px",
  52502. "color": "rgb(255, 255, 255)",
  52503. "position": "absolute",
  52504. "top": "50%",
  52505. "left": "50%",
  52506. "width": "45%",
  52507. "height": "0px",
  52508. "transform-origin": "left center",
  52509. });
  52510. this.dom.find(".dirText span").css({
  52511. display: "block",
  52512. position: "absolute",
  52513. right: "5px",
  52514. top: "0",
  52515. width: "20px",
  52516. height: "20px",
  52517. "line-height": "20px",
  52518. // "font-size": ".75rem ",
  52519. "margin-top": "-10px",
  52520. });
  52521. try {
  52522. this.renderer = new WebGLRenderer({ antialias: true, alpha:true });//许钟文 添加个抗锯齿,否则添加的线条锯齿严重,
  52523. this.renderer.autoClear = !0;
  52524. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
  52525. this.renderer.domElement.setAttribute('name','compass');
  52526. this.renderer.setClearAlpha(0.0);
  52527. this.renderer.setSize(width/2, height/2, false, window.devicePixelRatio ? window.devicePixelRatio : 1);
  52528. //this.emit(SceneRendererEvents.ContextCreated)
  52529. } catch (e) {
  52530. viewer.dispatchEvent('webglError', {msg:e});
  52531. }
  52532. this.dom.find(".center")[0].appendChild(this.renderer.domElement);
  52533. this.renderer.domElement.style.width = this.renderer.domElement.style.height = '100%';
  52534. this.camera = new PerspectiveCamera;
  52535. this.camera.fov = 50;
  52536. this.camera.updateProjectionMatrix();
  52537. this.scene = new Scene,
  52538. this.scene.add(this.camera);
  52539. this.createCompass();
  52540. viewer.addEventListener('camera_changed', e => {
  52541. if (e.viewport == this.viewport && (e.changeInfo.positionChanged || e.changeInfo.quaternionChanged)) {
  52542. this.update();
  52543. }
  52544. });
  52545. this.setDomPos();
  52546. if(this.viewport)this.setDisplay(true);
  52547. }
  52548. createCompass(){
  52549. //ConeBufferGeometry(radius : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)
  52550. const height = 2;
  52551. const geometry1 = new ConeBufferGeometry( 0.7, height, 4, true );
  52552. const geometry2 = new ConeBufferGeometry( 0.7, height, 4, true );
  52553. const material = new MeshBasicMaterial({
  52554. vertexColors :true
  52555. });
  52556. //指南针由两个四棱锥拼成,为了渐变颜色,采用指定vertexColor的方式。
  52557. var setColor = function(geometry, color1,color2){
  52558. const colors = [];
  52559. for ( let i = 0, n = geometry.attributes.position.count; i < n; ++ i ) {
  52560. colors.push( 1, 1, 1 );
  52561. }
  52562. var set = function(index, color){//设置第index个点的颜色
  52563. colors[index*3+0] = color[0];
  52564. colors[index*3+1] = color[1];
  52565. colors[index*3+2] = color[2];
  52566. };
  52567. var mid = [(color1[0]+color2[0])/2, (color1[1]+color2[1])/2, (color1[2]+color2[2])/2 ];
  52568. set(1,color1); set(5,color1);set(6,color1);
  52569. set(2,mid); set(3,mid);set(7,mid);
  52570. set(4,color2); set(8,color2);set(9,color2);
  52571. geometry.addAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
  52572. };
  52573. var blue1 = [1/255,238/255,245/255]; //逐渐变深
  52574. var blue2 = [20/255,146/255,170/255];
  52575. var blue3 = [40/255,60/255,103/255];
  52576. setColor(geometry1, blue1,blue2);
  52577. setColor(geometry2, blue2,blue3);
  52578. /* 朝箭头方向看点构成如下 虽然geometry.attributes.position.count = 19 只有1-9设置的颜色是有效的 另外为什么7决定了上下两边的颜色呢…… 5、9可将其分成上下两个颜色
  52579. 6
  52580. /|\
  52581. / | \
  52582. 7 /_2|1_\ 5
  52583. \ 3|4 / 9
  52584. \ | /
  52585. \|/
  52586. 8
  52587. */
  52588. const cone = new Mesh( geometry1, material );
  52589. cone.position.setY(height/2);
  52590. geometry1.computeVertexNormals();//computeFaceNormals
  52591. geometry2.computeVertexNormals();
  52592. const cones = new Object3D();
  52593. cones.add(cone);
  52594. let cone2 = new Mesh( geometry2, material );
  52595. cone2.rotation.x = Math.PI;
  52596. cone2.position.setY(-height/2);
  52597. cones.add(cone2);
  52598. //cones.rotation.x = Math.PI / 2;//转向initDir的方向
  52599. //cones.rotation.z = Math.PI / 2;
  52600. cones.rotation.z = Math.PI ;//转向initDir的方向
  52601. cones.scale.set(0.7,0.7,0.7);
  52602. this.scene.add(cones);
  52603. this.cones = cones;
  52604. }
  52605. setNorth(){ //设置北方向,这决定了指南针自身的朝向。
  52606. const floors = store.getters['scene/houstFloor'].floors;
  52607. if(!floors || !floors.length){
  52608. return
  52609. }
  52610. const floor = floors[0];
  52611. const metadata = app.store.getters['scene/metadata'] || {};
  52612. this.angle = (floor && floor.dire || 0) + MathUtils.radToDeg(parseFloat(metadata.floorPlanAngle || 0)); //基础朝向
  52613. this.cones.rotation.y = Math.PI / 2 - MathUtils.degToRad(this.angle);
  52614. //console.log("dir:"+floor.dire+", floorPlanAngle:"+metadata.floorPlanAngle)
  52615. this.update();
  52616. }
  52617. update(quaternion){
  52618. if(!this.show)return;
  52619. if(!quaternion) quaternion = this.viewport.camera.quaternion.clone();
  52620. this.updateCamera(quaternion);
  52621. this.updateLabel(quaternion);
  52622. this.render();
  52623. }
  52624. /*updateLabel(quaternion){//更新北标签
  52625. var dir = viewer.mainViewport.view.direction;
  52626. var oriDir = initDir.clone() //指南针最初始时的北方向
  52627. var extraQua
  52628. if(objects.player.mode == "transitioning"){//当transitioning时,相机的quaternion不是用control的lookAt算出来,而是直接由一个quaternion过渡到另一个,这样相机将会是歪的,投影面也就不会是原先的水平面。
  52629. var tempCamera = new THREE.Camera(); //借用camera的lookAt算出如果正视同样的target, quaternion会是什么值。 将它乘以当前相机quaternion,得到的就是相机歪的旋转值。
  52630. tempCamera.position.copy(this.camera.position);
  52631. tempCamera.lookAt(tempCamera.position.clone().add(dir))
  52632. var q = tempCamera.quaternion.inverse()
  52633. extraQua = q.premultiply(quaternion) //歪掉的额外旋转值
  52634. }
  52635. //北标签的方向为指南针轮盘方向,也就是要将camera的方向投影到水平面上。 但是如果相机歪了,看到的世界都会歪一定角度,投影面也要歪一定角度。
  52636. var up = new THREE.Vector3(0,0,1) //投影水平面的法线,也是相机的摆正的up方向
  52637. extraQua && up.applyQuaternion(extraQua)
  52638. dir.projectOnPlane(up) //将方向投影到水平面上; 如果相机不是正视(extraQua不为0001),就要将水平面也转动
  52639. oriDir.projectOnPlane(up)//为什么initDir投影了和没有投影angle结果一样
  52640. var angle = dir.angleTo(oriDir)
  52641. if(dir.cross(oriDir).y > 0)angle = -angle
  52642. var deg = this.angle - 90 + THREE.Math.radToDeg(angle) //因为css写的样式初始是指向右方,和initDir差了90°,所以减去。
  52643. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" )
  52644. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)")
  52645. } */
  52646. updateLabel(quaternion){//更新北标签
  52647. let deg = MathUtils.radToDeg(this.viewport.view.yaw) - 90;
  52648. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" );
  52649. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)");
  52650. }
  52651. updateCamera(quaternion){ //更新canvas中的指南针表现,也就是更新相机,和场景中的相机朝向一致。
  52652. const radius = 5; //相机距离
  52653. this.camera.quaternion.copy(quaternion);
  52654. var dir = this.viewport.view.direction; //相机朝向
  52655. this.camera.position.copy(dir.multiplyScalar(radius).negate()); //相机绕着指南针中心(000)转动
  52656. }
  52657. changeViewport(viewport){
  52658. this.viewport = viewport;
  52659. this.update(); //因相机更新了
  52660. }
  52661. render(){
  52662. this.renderer.render(this.scene, this.camera);
  52663. }
  52664. setDisplay(state){
  52665. this.show = !!state;
  52666. if(this.show){
  52667. this.update();
  52668. this.dom.fadeIn(100);
  52669. }else {
  52670. this.dom.fadeOut(100);
  52671. }
  52672. }
  52673. autoJudgeDisplay(){
  52674. }
  52675. setDomPos(){
  52676. if(!this.viewport)return
  52677. let right = this.viewport.left + this.viewport.width;
  52678. this.dom.css({'right':((1-right)*100 + 1) + '%'});
  52679. }
  52680. }
  52681. class PotreeRenderer {
  52682. constructor (viewer) {
  52683. this.viewer = viewer;
  52684. this.renderer = viewer.renderer;
  52685. {
  52686. let dummyScene = new Scene();
  52687. let geometry = new SphereGeometry(0.001, 2, 2);
  52688. let mesh = new Mesh(geometry, new MeshBasicMaterial());
  52689. mesh.position.set(36453, 35163, 764712);
  52690. dummyScene.add(mesh);
  52691. this.dummyMesh = mesh;
  52692. this.dummyScene = dummyScene;
  52693. }
  52694. }
  52695. clearTargets(params){//add
  52696. const viewer = this.viewer;
  52697. const {renderer} = viewer;
  52698. const oldTarget = renderer.getRenderTarget();
  52699. if(params.target){//add
  52700. renderer.setRenderTarget( params.target);
  52701. renderer.clear();
  52702. }
  52703. if(params.rtEDL){
  52704. renderer.setRenderTarget( params.rtEDL);
  52705. renderer.clear();
  52706. }else {
  52707. renderer.setRenderTarget( this.rtEDL );
  52708. renderer.clear( true, true, true );
  52709. }
  52710. /* renderer.setRenderTarget( this.rtRegular );
  52711. renderer.clear( true, true, false ); */
  52712. renderer.setRenderTarget(oldTarget);
  52713. }
  52714. clear(params={}){
  52715. let {viewer, renderer} = this;
  52716. // render skybox
  52717. if(viewer.background === "skybox"){
  52718. renderer.setClearColor(0xff0000, 1);
  52719. }else if(viewer.background === "gradient"){
  52720. renderer.setClearColor(0x00ff00, 1);
  52721. }else if(viewer.background === "black"){
  52722. renderer.setClearColor(0x000000, 1);
  52723. }else if(viewer.background === "white"){
  52724. renderer.setClearColor(0xFFFFFF, 1);
  52725. }else {
  52726. renderer.setClearColor(0x000000, 0);
  52727. }
  52728. params.target || renderer.clear();
  52729. renderer.clear();
  52730. this.clearTargets(params);
  52731. }
  52732. render(params={}){
  52733. let {viewer, renderer} = this;
  52734. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52735. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52736. const renderAreaSize = renderer.getSize(new Vector2$1());
  52737. const width = params.width ? params.width : params.viewport ? params.viewport[2] : renderAreaSize.x;
  52738. const height = params.height ? params.height : params.viewport ? params.viewport[3] : renderAreaSize.y;
  52739. // render skybox
  52740. if(viewer.background === "skybox"){
  52741. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  52742. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  52743. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  52744. viewer.skybox.parent.rotation.x = 0;
  52745. viewer.skybox.parent.updateMatrixWorld();
  52746. viewer.skybox.camera.updateProjectionMatrix();
  52747. renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  52748. }else if(viewer.background === "gradient"){
  52749. if(params.target){//add
  52750. renderer.setRenderTarget(params.target);
  52751. renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  52752. renderer.setRenderTarget(null);
  52753. }else {
  52754. renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  52755. }
  52756. }
  52757. for(let pointcloud of this.viewer.scene.pointclouds){
  52758. const {material} = pointcloud;
  52759. material.useEDL = false;
  52760. }
  52761. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.target || null, {
  52762. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof Potree.SphereVolume)),
  52763. });
  52764. // render scene
  52765. viewer.dispatchEvent({type: "render.pass.scene",viewer: viewer});
  52766. renderer.setRenderTarget(params.target ? params.target : null);//add
  52767. renderer.render(viewer.scene.scene, camera);
  52768. renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  52769. renderer.clearDepth();
  52770. viewer.transformationTool.update();
  52771. if(!params.target){
  52772. //测量线
  52773. viewer.dispatchEvent({type: "render.pass.perspective_overlay", viewer: viewer, camera});
  52774. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  52775. }
  52776. viewer.clippingTool.update();
  52777. renderer.render(viewer.clippingTool.sceneMarker, viewer.scene.cameraScreenSpace); //viewer.scene.cameraScreenSpace);
  52778. renderer.render(viewer.clippingTool.sceneVolume, camera);
  52779. renderer.render(viewer.controls.sceneControls, camera);
  52780. viewer.renderer.render(viewer.transformationTool.scene, camera);
  52781. //viewer.renderer.render(viewer.transformationTool.scene, camera);
  52782. // renderer.render(viewer.controls.sceneControls, camera);
  52783. // renderer.render(viewer.clippingTool.sceneVolume, camera);
  52784. // renderer.render(viewer.transformationTool.scene, camera);
  52785. // renderer.setViewport(width - viewer.navigationCube.width,
  52786. // height - viewer.navigationCube.width,
  52787. // viewer.navigationCube.width, viewer.navigationCube.width);
  52788. // renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  52789. // renderer.setViewport(0, 0, width, height);
  52790. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  52791. }
  52792. }
  52793. const copyShader = {
  52794. uniforms: {
  52795. tDiffuse: {
  52796. type: "t",
  52797. value: null
  52798. },
  52799. opacity: {
  52800. type: "f",
  52801. value: 1
  52802. }
  52803. },
  52804. vertexShader: `
  52805. varying vec2 vUv;
  52806. void main() {
  52807. vUv = uv;
  52808. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  52809. }
  52810. `,
  52811. fragmentShader: `
  52812. uniform float opacity;
  52813. uniform sampler2D tDiffuse;
  52814. varying vec2 vUv;
  52815. void main() {
  52816. vec4 texel = texture2D( tDiffuse, vUv );
  52817. gl_FragColor = opacity * texel;
  52818. }
  52819. `
  52820. };
  52821. class EDLRenderer{//Eye-Dome Lighting 眼罩照明
  52822. constructor(viewer){
  52823. this.viewer = viewer;
  52824. this.edlMaterial = null;
  52825. //this.rtRegular;
  52826. this.rtEDLs = new Map;
  52827. this.gl = viewer.renderer.getContext();
  52828. //反正也没用到,注释了:
  52829. //this.shadowMap = new PointCloudSM(this.viewer.pRenderer);
  52830. viewer.addEventListener('resize',this.resize.bind(this));
  52831. this.initEDL(viewer);
  52832. }
  52833. initEDL(viewer){
  52834. if (this.edlMaterial != null) {
  52835. return;
  52836. }
  52837. this.edlMaterial = new EyeDomeLightingMaterial();
  52838. this.edlMaterial.depthTest = true;
  52839. this.edlMaterial.depthWrite = true;
  52840. this.edlMaterial.transparent = true;
  52841. /* this.rtRegular = new THREE.WebGLRenderTarget(viewer.mainViewport.resolution2.x, viewer.mainViewport.resolution2.y, {
  52842. minFilter: THREE.NearestFilter,
  52843. magFilter: THREE.NearestFilter,
  52844. format: THREE.RGBAFormat,
  52845. depthTexture: new THREE.DepthTexture(undefined, undefined, THREE.UnsignedIntType)
  52846. });
  52847. */
  52848. /* let copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
  52849. this.copyMaterial = new THREE.ShaderMaterial( {
  52850. uniforms: copyUniforms,
  52851. vertexShader: copyShader.vertexShader,
  52852. fragmentShader: copyShader.fragmentShader,
  52853. //premultipliedAlpha: true,
  52854. transparent: true,
  52855. //blending: THREE.AdditiveBlending,
  52856. depthTest: false,
  52857. depthWrite: false
  52858. }); */
  52859. };
  52860. resize(e ){
  52861. if(Features.EXT_DEPTH.isSupported()){
  52862. let viewport = e.viewport;
  52863. this.getRtEDL(viewport).setSize(viewport.resolution2.x, viewport.resolution2.y);
  52864. }
  52865. }
  52866. clearTargets(params={}){
  52867. const viewer = this.viewer;
  52868. const {renderer} = viewer;
  52869. const oldTarget = renderer.getRenderTarget();
  52870. if(params.target){//add
  52871. renderer.setRenderTarget( params.target);
  52872. renderer.clear();
  52873. }
  52874. if(Features.EXT_DEPTH.isSupported()){
  52875. if(params.rtEDL){
  52876. renderer.setRenderTarget( params.rtEDL);
  52877. renderer.clear();
  52878. }else {
  52879. var rtEDL = this.getRtEDL(params.viewport);
  52880. if(rtEDL){
  52881. renderer.setRenderTarget( rtEDL );
  52882. renderer.clear( true, true, true );
  52883. }
  52884. }
  52885. }
  52886. //renderer.setRenderTarget( this.rtRegular );
  52887. //renderer.clear( true, true, false );
  52888. renderer.setRenderTarget(oldTarget);
  52889. }
  52890. getRtEDL(viewport){//根据不同viewport返回rtEDL的texture
  52891. if(!viewport){
  52892. console.warn('getRtEDL没传viewport!!!! !!!!!!!!!!');
  52893. viewport = viewer.mainViewport;
  52894. }
  52895. var rtEDL = this.rtEDLs.get(viewport);
  52896. if(!rtEDL){
  52897. if(Features.EXT_DEPTH.isSupported()){
  52898. rtEDL = new WebGLRenderTarget(viewport.resolution2.x, viewport.resolution2.y, {
  52899. minFilter: NearestFilter,
  52900. magFilter: NearestFilter,
  52901. format: RGBAFormat,
  52902. type: FloatType,
  52903. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  52904. });
  52905. //注: 部分手机在resize时会崩溃,经检验去掉rtEDL的resize可以解决,所以更应该注释掉这个
  52906. this.rtEDLs.set(viewport, rtEDL);
  52907. }
  52908. }
  52909. return rtEDL
  52910. }
  52911. renderShadowMap(visiblePointClouds, camera, lights){
  52912. const {viewer} = this;
  52913. const doShadows = lights.length > 0 && !(lights[0].disableShadowUpdates);
  52914. if(doShadows){
  52915. let light = lights[0];
  52916. this.shadowMap.setLight(light);
  52917. let originalAttributes = new Map();
  52918. for(let pointcloud of viewer.scene.pointclouds){
  52919. // TODO IMPORTANT !!! check
  52920. originalAttributes.set(pointcloud, pointcloud.material.activeAttributeName);
  52921. pointcloud.material.disableEvents();
  52922. pointcloud.material.activeAttributeName = "depth";
  52923. //pointcloud.material.pointColorType = PointColorType.DEPTH;
  52924. }
  52925. this.shadowMap.render(viewer.scene.scenePointCloud, camera);
  52926. for(let pointcloud of visiblePointClouds){
  52927. let originalAttribute = originalAttributes.get(pointcloud);
  52928. // TODO IMPORTANT !!! check
  52929. pointcloud.material.activeAttributeName = originalAttribute;
  52930. pointcloud.material.enableEvents();
  52931. }
  52932. viewer.shadowTestCam.updateMatrixWorld();
  52933. viewer.shadowTestCam.matrixWorldInverse.copy(viewer.shadowTestCam.matrixWorld).invert();
  52934. viewer.shadowTestCam.updateProjectionMatrix();
  52935. }
  52936. }
  52937. render(params={}){
  52938. /*
  52939. 渲染顺序:
  52940. 底层:背景 -> skybox(也可中间)
  52941. 中间层(含有深度信息):1 点云、marker等mesh,
  52942. 2 测量线(现在被做成借用depthTex
  52943. 顶层:maginifier
  52944. magnifier的贴图渲染不需要顶层、中间层只需要点云。
  52945. */
  52946. const viewer = this.viewer;
  52947. let camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52948. const resolution = params.viewport ? params.viewport.resolution2 : this.viewer.renderer.getSize(new Vector2$1());
  52949. //viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52950. let lights = [];
  52951. /* viewer.scene.scene.traverse(node => {
  52952. if(node.type === "SpotLight"){
  52953. lights.push(node);
  52954. }
  52955. }); */
  52956. viewer.renderer.setRenderTarget(params.target || null);
  52957. let background = params.background || viewer.background;
  52958. let backgroundOpacity = params.backgroundOpacity == void 0 ? viewer.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  52959. if(backgroundOpacity != 0){//绘制背景
  52960. if(background === "skybox"){
  52961. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  52962. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  52963. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  52964. viewer.skybox.parent.rotation.x = 0;
  52965. viewer.skybox.parent.updateMatrixWorld();
  52966. viewer.skybox.camera.updateProjectionMatrix();
  52967. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  52968. }else if(background === 'gradient'){
  52969. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  52970. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  52971. }else if(background === 'overlayColor'){//在不clear的前提下加一层背景色
  52972. viewer.scene.bg2.material.color.copy(params.backgroundColor);
  52973. viewer.scene.bg2.material.opacity = params.backgroundOpacity;
  52974. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg2);
  52975. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  52976. }
  52977. }
  52978. //skybox 全景图
  52979. if(!params.magnifier){
  52980. viewer.setCameraLayers(camera, ['skybox']);
  52981. let useDepthTex;
  52982. if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && Features.EXT_DEPTH.isSupported()){//渲染深度图
  52983. useDepthTex = true;
  52984. viewer.renderer.setRenderTarget(params.rtEDL || this.getRtEDL(params.viewport)); //将带有深度图的skybox画在rtEDL一下,这样就不需要绘制后边的点云了
  52985. viewer.renderer.render(viewer.scene.scene, camera);
  52986. viewer.renderer.setRenderTarget(params.target || null);
  52987. }
  52988. viewer.renderer.render(viewer.scene.scene, camera);
  52989. if(useDepthTex)return
  52990. }
  52991. const visiblePointClouds2 = viewer.scene.pointclouds.filter(pc => viewer.getObjVisiByReason(pc,'datasetSelection') ); //需要绘制到rtEDL的
  52992. const showPointClouds = params.magnifier ? visiblePointClouds2.length>0 : viewer.scene.pointclouds.some(e=>e.visible); //是否有需要绘制到屏幕的
  52993. visiblePointClouds2.forEach(e=>{//为了绘制到depthTexture,先显示(展示全景图时隐藏了点云,所以需要显示下。且放大镜需要绘制点云)
  52994. e.oldVisi = e.visible;
  52995. e.visible = true;
  52996. });
  52997. viewer.setCameraLayers(camera, ['pointcloud']);
  52998. camera.layers.set(Potree.config.renderLayers.pointcloud);
  52999. //TODO adapt to multiple lights
  53000. //this.renderShadowMap(visiblePointClouds2, camera, lights); //???????
  53001. {
  53002. for (let pointcloud of visiblePointClouds2) {
  53003. let material = pointcloud.material;
  53004. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  53005. material.fov = MathUtils.degToRad(camera.fov);
  53006. /* material.screenWidth = width;
  53007. material.screenHeight = height; */
  53008. material.resolution = resolution;
  53009. material.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  53010. material.near = camera.near;
  53011. material.far = camera.far;
  53012. material.uniforms.octreeSize.value = octreeSize;
  53013. if(viewer.useEDL && Potree.settings.displayMode != 'showPanos'){
  53014. /* material.weighted = false;
  53015. material.useLogarithmicDepthBuffer = false; */
  53016. material.useEDL = true;
  53017. //material.fakeEDL = false; //add
  53018. }else {
  53019. material.useEDL = false;
  53020. //material.fakeEDL = true; //add 使也输出深度
  53021. }
  53022. }
  53023. if(Features.EXT_DEPTH.isSupported() && !params.dontRenderRtEDL){
  53024. //借用rtEDL存储深度信息
  53025. viewer.renderer.setRenderTarget(params.rtEDL || this.getRtEDL(params.viewport)/* this.rtEDL */);
  53026. if(visiblePointClouds2.length>0){
  53027. //渲染scenePointCloud到rtEDL
  53028. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.rtEDL || this.getRtEDL(params.viewport), {
  53029. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  53030. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53031. transparent: false,
  53032. });
  53033. }
  53034. if(Potree.settings.intersectOnObjs){// model也要渲染到rtEDL
  53035. camera.layers.set(Potree.config.renderLayers.model);
  53036. viewer.objs.traverse(e=>{if(e.material)e._OlddepthWrite = e.material.depthWrite, e.material.depthWrite = true;}); //否则半透明的mesh无法遮住测量线
  53037. viewer.renderer.render(viewer.scene.scene, camera);
  53038. viewer.objs.traverse(e=>{if(e.material)e.material.depthWrite = e._OlddepthWrite;});
  53039. //缺点:半透明的model 就算完全透明, 也会遮住测量线
  53040. }
  53041. //test
  53042. /* {
  53043. viewer.objs.traverse((obj)=>{
  53044. if(obj.material){
  53045. obj.material = obj.depthMat
  53046. }
  53047. })
  53048. viewer.setCameraLayers(camera, ['sceneObjects'])
  53049. viewer.renderer.render(viewer.scene.scene, camera)
  53050. viewer.objs.traverse((obj)=>{
  53051. if(obj.material){
  53052. obj.material = obj.standardMat
  53053. }
  53054. })
  53055. } */
  53056. }
  53057. }
  53058. //渲染到rtEDL完毕
  53059. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer/* , renderTarget: this.rtRegular */});
  53060. viewer.renderer.setRenderTarget(params.target || null);
  53061. if(!params.magnifier)visiblePointClouds2.forEach(e=>{//放大镜显示点云
  53062. e.visible = e.oldVisi;
  53063. });
  53064. if(showPointClouds){ //绘制点云到画布
  53065. if(viewer.useEDL) { //设置edlMaterial
  53066. //Features.EXT_DEPTH不支持的话不会到这一块
  53067. const uniforms = this.edlMaterial.uniforms;
  53068. //if(viewer.useEDL){
  53069. /* uniforms.screenWidth.value = width;
  53070. uniforms.screenHeight.value = height; */
  53071. uniforms.resolution.value.copy(resolution);
  53072. uniforms.edlStrength.value = viewer.edlStrength;
  53073. uniforms.radius.value = viewer.edlRadius;
  53074. uniforms.useEDL.value = 1;//add
  53075. /* }else{
  53076. uniforms.useEDL.value = 0;//add
  53077. } */
  53078. let proj = camera.projectionMatrix;
  53079. let projArray = new Float32Array(16);
  53080. projArray.set(proj.elements);
  53081. uniforms.uProj.value = projArray;
  53082. uniforms.uEDLColor.value = (params.rtEDL || this.getRtEDL(params.viewport)).texture;
  53083. //uniforms.uEDLDepth.value = (params.rtEDL || this.getRtEDL(params.viewport)).depthTexture; //其实没用到
  53084. uniforms.opacity.value = viewer.edlOpacity; // HACK
  53085. Utils.screenPass.render(viewer.renderer, this.edlMaterial, params.target);
  53086. }else {
  53087. //渲染点云 (直接用rtEDL上的会失去抗锯齿)
  53088. let prop = {
  53089. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  53090. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)) ,
  53091. notAdditiveBlending: Potree.settings.notAdditiveBlending//add 否则透明的点云会挡住后面的模型。 加上这句后竟然透明不会叠加了!
  53092. };
  53093. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, null , prop);
  53094. }
  53095. }
  53096. //viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  53097. visiblePointClouds2.forEach(e=>{
  53098. e.visible = e.oldVisi;
  53099. });
  53100. }
  53101. }
  53102. class HQSplatRenderer{
  53103. //rtAttribute 估计需要给magnifer复制一份
  53104. constructor(viewer){
  53105. this.viewer = viewer;
  53106. this.depthMaterials = new Map();
  53107. this.attributeMaterials = new Map();
  53108. this.normalizationMaterial = null;
  53109. this.rtDepth = null;
  53110. this.rtAttribute = null;
  53111. this.gl = viewer.renderer.getContext();
  53112. this.initialized = false;
  53113. viewer.addEventListener('resize',this.resize.bind(this));
  53114. }
  53115. init(){
  53116. if (this.initialized) {
  53117. return;
  53118. }
  53119. this.normalizationMaterial = new NormalizationMaterial();
  53120. this.normalizationMaterial.depthTest = true;
  53121. this.normalizationMaterial.depthWrite = true;
  53122. this.normalizationMaterial.transparent = true;
  53123. this.normalizationEDLMaterial = new NormalizationEDLMaterial();
  53124. this.normalizationEDLMaterial.depthTest = true;
  53125. this.normalizationEDLMaterial.depthWrite = true;
  53126. this.normalizationEDLMaterial.transparent = true;
  53127. this.rtDepth = new WebGLRenderTarget(1024, 1024, {
  53128. minFilter: NearestFilter,
  53129. magFilter: NearestFilter,
  53130. format: RGBAFormat,
  53131. type: FloatType,
  53132. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  53133. });
  53134. this.rtAttribute = new WebGLRenderTarget(1024, 1024, {
  53135. minFilter: NearestFilter,
  53136. magFilter: NearestFilter,
  53137. format: RGBAFormat,
  53138. type: FloatType,
  53139. depthTexture: this.rtDepth.depthTexture,
  53140. });
  53141. this.initialized = true;
  53142. };
  53143. resize(e/* width, height */){
  53144. this.rtDepth.setSize(e.canvasWidth, e.canvasHeight);
  53145. this.rtAttribute.setSize(e.canvasWidth, e.canvasHeight);
  53146. }
  53147. clearTargets(params){
  53148. const viewer = this.viewer;
  53149. const {renderer} = viewer;
  53150. const oldTarget = renderer.getRenderTarget();
  53151. if(params.target){//add
  53152. renderer.setRenderTarget( params.target);
  53153. renderer.clear();
  53154. }
  53155. renderer.setClearColor(0x000000, 0);
  53156. renderer.setRenderTarget( this.rtDepth );
  53157. renderer.clear( true, true, true );
  53158. renderer.setRenderTarget( this.rtAttribute );
  53159. renderer.clear( true, true, true );
  53160. renderer.setRenderTarget(oldTarget);
  53161. }
  53162. clear(params={}){
  53163. this.init();
  53164. const {renderer, background} = this.viewer;
  53165. if(background === "skybox"){
  53166. renderer.setClearColor(0x000000, 0);
  53167. } else if (background === 'gradient') {
  53168. renderer.setClearColor(0x000000, 0);
  53169. } else if (background === 'black') {
  53170. renderer.setClearColor(0x000000, 1);
  53171. } else if (background === 'white') {
  53172. renderer.setClearColor(0xFFFFFF, 1);
  53173. } else {
  53174. renderer.setClearColor(0x000000, 0);
  53175. }
  53176. params.target || renderer.clear();
  53177. this.clearTargets(params);
  53178. }
  53179. render(params={}) {
  53180. this.init();
  53181. const viewer = this.viewer;
  53182. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  53183. const {width, height} = params.width ? params : this.viewer.renderer.getSize(new Vector2$1());
  53184. viewer.renderer.setRenderTarget(params.target||null);
  53185. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  53186. //params.target || this.resize(width, height);
  53187. const visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  53188. const originalMaterials = new Map();
  53189. for(let pointcloud of visiblePointClouds){
  53190. originalMaterials.set(pointcloud, pointcloud.material);
  53191. if(!this.attributeMaterials.has(pointcloud)){
  53192. let attributeMaterial = new PointCloudMaterial$1();
  53193. this.attributeMaterials.set(pointcloud, attributeMaterial);
  53194. }
  53195. if(!this.depthMaterials.has(pointcloud)){
  53196. let depthMaterial = new PointCloudMaterial$1();
  53197. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  53198. depthMaterial.setDefine("use_edl", "#define use_edl");
  53199. this.depthMaterials.set(pointcloud, depthMaterial);
  53200. }
  53201. }
  53202. { // DEPTH PASS
  53203. for (let pointcloud of visiblePointClouds) {
  53204. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  53205. let material = originalMaterials.get(pointcloud);
  53206. let depthMaterial = this.depthMaterials.get(pointcloud);
  53207. depthMaterial.size = material.size;
  53208. depthMaterial.minSize = material.minSize;
  53209. depthMaterial.maxSize = material.maxSize;
  53210. depthMaterial.pointSizeType = material.pointSizeType;
  53211. depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  53212. depthMaterial.weighted = false;
  53213. depthMaterial.screenWidth = width;
  53214. depthMaterial.shape = PointShape.CIRCLE;
  53215. depthMaterial.screenHeight = height;
  53216. depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  53217. depthMaterial.uniforms.octreeSize.value = octreeSize;
  53218. depthMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  53219. depthMaterial.classification = material.classification;
  53220. depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  53221. depthMaterial.classificationTexture.needsUpdate = true;
  53222. depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  53223. depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  53224. depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  53225. depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  53226. depthMaterial.clipTask = material.clipTask;
  53227. depthMaterial.clipMethod = material.clipMethod;
  53228. depthMaterial.setClipBoxes(material.clipBoxes);
  53229. depthMaterial.setClipPolygons(material.clipPolygons);
  53230. pointcloud.material = depthMaterial;
  53231. }
  53232. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, (params.rtEDL || this.rtDepth), {
  53233. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53234. });
  53235. }
  53236. { // ATTRIBUTE PASS
  53237. for (let pointcloud of visiblePointClouds) {
  53238. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  53239. let material = originalMaterials.get(pointcloud);
  53240. let attributeMaterial = this.attributeMaterials.get(pointcloud);
  53241. attributeMaterial.size = material.size;
  53242. attributeMaterial.minSize = material.minSize;
  53243. attributeMaterial.maxSize = material.maxSize;
  53244. attributeMaterial.pointSizeType = material.pointSizeType;
  53245. attributeMaterial.activeAttributeName = material.activeAttributeName;
  53246. attributeMaterial.visibleNodesTexture = material.visibleNodesTexture;
  53247. attributeMaterial.weighted = true;
  53248. attributeMaterial.screenWidth = width;
  53249. attributeMaterial.screenHeight = height;
  53250. attributeMaterial.shape = PointShape.CIRCLE;
  53251. attributeMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  53252. attributeMaterial.uniforms.octreeSize.value = octreeSize;
  53253. attributeMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  53254. attributeMaterial.classification = material.classification;
  53255. attributeMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  53256. attributeMaterial.classificationTexture.needsUpdate = true;
  53257. attributeMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  53258. attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  53259. attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  53260. attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  53261. attributeMaterial.elevationGradientRepeat = material.elevationGradientRepeat;
  53262. attributeMaterial.elevationRange = material.elevationRange;
  53263. attributeMaterial.gradient = material.gradient;
  53264. attributeMaterial.matcap = material.matcap;
  53265. attributeMaterial.intensityRange = material.intensityRange;
  53266. attributeMaterial.intensityGamma = material.intensityGamma;
  53267. attributeMaterial.intensityContrast = material.intensityContrast;
  53268. attributeMaterial.intensityBrightness = material.intensityBrightness;
  53269. attributeMaterial.rgbGamma = material.rgbGamma;
  53270. attributeMaterial.rgbContrast = material.rgbContrast;
  53271. attributeMaterial.rgbBrightness = material.rgbBrightness;
  53272. attributeMaterial.weightRGB = material.weightRGB;
  53273. attributeMaterial.weightIntensity = material.weightIntensity;
  53274. attributeMaterial.weightElevation = material.weightElevation;
  53275. attributeMaterial.weightRGB = material.weightRGB;
  53276. attributeMaterial.weightClassification = material.weightClassification;
  53277. attributeMaterial.weightReturnNumber = material.weightReturnNumber;
  53278. attributeMaterial.weightSourceID = material.weightSourceID;
  53279. attributeMaterial.color = material.color;
  53280. attributeMaterial.clipTask = material.clipTask;
  53281. attributeMaterial.clipMethod = material.clipMethod;
  53282. attributeMaterial.setClipBoxes(material.clipBoxes);
  53283. attributeMaterial.setClipPolygons(material.clipPolygons);
  53284. pointcloud.material = attributeMaterial;
  53285. }
  53286. let gl = this.gl;
  53287. //viewer.renderer.setRenderTarget(null);
  53288. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  53289. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53290. //material: this.attributeMaterial,
  53291. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  53292. //depthTest: false,
  53293. depthWrite: false
  53294. });
  53295. }
  53296. for(let [pointcloud, material] of originalMaterials){
  53297. pointcloud.material = material;
  53298. }
  53299. if(viewer.background === "skybox"){
  53300. viewer.renderer.setClearColor(0x000000, 0);
  53301. viewer.renderer.clear();
  53302. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  53303. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  53304. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  53305. viewer.skybox.parent.rotation.x = 0;
  53306. viewer.skybox.parent.updateMatrixWorld();
  53307. viewer.skybox.camera.updateProjectionMatrix();
  53308. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  53309. } else if (viewer.background === 'gradient') {
  53310. viewer.renderer.setClearColor(0x000000, 0);
  53311. viewer.renderer.clear();
  53312. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  53313. } else if (viewer.background === 'black') {
  53314. viewer.renderer.setClearColor(0x000000, 1);
  53315. viewer.renderer.clear();
  53316. } else if (viewer.background === 'white') {
  53317. viewer.renderer.setClearColor(0xFFFFFF, 1);
  53318. viewer.renderer.clear();
  53319. } else {
  53320. viewer.renderer.setClearColor(0x000000, 0);
  53321. viewer.renderer.clear();
  53322. }
  53323. { // NORMALIZATION PASS
  53324. let normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  53325. if(this.useEDL){
  53326. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  53327. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  53328. normalizationMaterial.uniforms.screenWidth.value = width;
  53329. normalizationMaterial.uniforms.screenHeight.value = height;
  53330. normalizationMaterial.uniforms.uEDLMap.value = (params.rtEDL || this.rtDepth).texture;
  53331. }
  53332. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  53333. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  53334. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  53335. }
  53336. viewer.renderer.render(viewer.scene.scene, camera);
  53337. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  53338. viewer.renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  53339. viewer.renderer.clearDepth();
  53340. viewer.transformationTool.update();
  53341. if(!params.target){
  53342. //测量线
  53343. viewer.dispatchEvent({type: "render.pass.perspective_overlay",viewer: viewer, camera});
  53344. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  53345. }
  53346. viewer.renderer.render(viewer.controls.sceneControls, camera);
  53347. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  53348. viewer.renderer.render(viewer.transformationTool.scene, camera);
  53349. viewer.renderer.setViewport(width - viewer.navigationCube.width,
  53350. height - viewer.navigationCube.width,
  53351. viewer.navigationCube.width, viewer.navigationCube.width);
  53352. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  53353. viewer.renderer.setViewport(0, 0, width, height);
  53354. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  53355. viewer.renderer.setRenderTarget(null);
  53356. }
  53357. }
  53358. let sid = 0;
  53359. class View extends EventDispatcher{
  53360. constructor () {
  53361. super();
  53362. this.position = new Vector3(0, 0, 0);
  53363. this.yaw = 0;//Math.PI / 4; // = 4dkk lon + 90
  53364. this._pitch = 0;//-Math.PI / 4; //上下旋转 = 4dkk lat
  53365. this.radius = 1;
  53366. this.maxPitch = Math.PI / 2;
  53367. this.minPitch = -Math.PI / 2;
  53368. this.sid = sid++;
  53369. this.LookTransition = 'LookTransition'+this.sid;
  53370. }
  53371. //add------
  53372. applyToCamera(camera){
  53373. camera.position.copy(this.position);
  53374. camera.rotation.copy(this.rotation);
  53375. camera.updateMatrix();
  53376. camera.updateMatrixWorld();
  53377. //camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  53378. }
  53379. get rotation(){
  53380. var rotation = new Euler;
  53381. rotation.order = "ZXY";
  53382. rotation.x = Math.PI / 2 + this.pitch;
  53383. rotation.z = this.yaw;
  53384. return rotation
  53385. }
  53386. set rotation(rotation){
  53387. //因为 rotation的y不一定是0 , 所以不能直接逆着写。
  53388. this.direction = new Vector3(0,0,-1).applyEuler(rotation);
  53389. }
  53390. copy(a){
  53391. Common.CopyClassObject(this, a);
  53392. }
  53393. clone () {
  53394. /* let c = new View();
  53395. c.yaw = this.yaw;
  53396. c._pitch = this.pitch;
  53397. c.radius = this.radius;
  53398. c.maxPitch = this.maxPitch;
  53399. c.minPitch = this.minPitch;
  53400. return c; */
  53401. return Common.CloneClassObject(this)
  53402. }
  53403. //----------
  53404. get pitch () {
  53405. return this._pitch;
  53406. }
  53407. set pitch (angle) {
  53408. this._pitch = Math.max(Math.min(angle, this.maxPitch), this.minPitch);
  53409. }
  53410. get direction () {
  53411. let dir = new Vector3(0, 1, 0);
  53412. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  53413. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  53414. return dir;
  53415. }
  53416. set direction (dir) {
  53417. //if(dir.x === dir.y){
  53418. if(dir.x === 0 && dir.y === 0){
  53419. this.pitch = Math.PI / 2 * Math.sign(dir.z);
  53420. }else {
  53421. let yaw = Math.atan2(dir.y, dir.x) - Math.PI / 2;
  53422. let pitch = Math.atan2(dir.z, Math.sqrt(dir.x * dir.x + dir.y * dir.y));
  53423. this.yaw = yaw;
  53424. this.pitch = pitch;
  53425. }
  53426. }
  53427. lookAt(t){//setPivot
  53428. let V;
  53429. if(arguments.length === 1){
  53430. V = new Vector3().subVectors(t, this.position);
  53431. }else if(arguments.length === 3){
  53432. V = new Vector3().subVectors(new Vector3(...arguments), this.position);
  53433. }
  53434. let radius = V.length();
  53435. let dir = V.normalize();
  53436. this.radius = radius;
  53437. this.direction = dir;
  53438. }
  53439. getPivot () {
  53440. return new Vector3().addVectors(this.position, this.direction.multiplyScalar(this.radius));
  53441. }
  53442. getSide () {
  53443. let side = new Vector3(1, 0, 0);
  53444. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  53445. return side;
  53446. }
  53447. /* pan (x, y) {
  53448. let dir = new THREE.Vector3(0, 1, 0);
  53449. dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), this.pitch);
  53450. dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  53451. // let side = new THREE.Vector3(1, 0, 0);
  53452. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  53453. let side = this.getSide();
  53454. let up = side.clone().cross(dir);
  53455. let pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  53456. this.position = this.position.add(pan);
  53457. // this.target = this.target.add(pan);
  53458. } */
  53459. pan (x, y) { //发现pan其实就是translate
  53460. this.translate(x, 0, y);
  53461. }
  53462. translate (x, y, z, forceHorizon ) {
  53463. //相机方向
  53464. let dir = new Vector3(0, 1, 0);
  53465. dir.applyAxisAngle(new Vector3(1, 0, 0), forceHorizon ? 0 : this.pitch); //上下角度
  53466. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);//水平角度
  53467. let side = new Vector3(1, 0, 0);
  53468. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //垂直于相机当前水平朝向的 左右方向
  53469. let up = side.clone().cross(dir); //垂直于相机当前水平朝向的 向上方向
  53470. let t = side.multiplyScalar(x) //x影响 左右分量
  53471. .add(dir.multiplyScalar(y)) //y影响 前后分量
  53472. .add(up.multiplyScalar(z)); //z影响 上下分量
  53473. this.position = this.position.add(t);
  53474. this.restrictPos();
  53475. }
  53476. translateWorld (x, y, z) {
  53477. this.position.x += x;
  53478. this.position.y += y;
  53479. this.position.z += z;
  53480. this.restrictPos();
  53481. }
  53482. restrictPos(){//add
  53483. if(this.limitBound){
  53484. this.position.clamp(this.limitBound.min, this.limitBound.max);
  53485. }
  53486. }
  53487. setCubeView(dir) {
  53488. switch(dir) {
  53489. case "front":
  53490. this.yaw = 0;
  53491. this.pitch = 0;
  53492. break;
  53493. case "back":
  53494. this.yaw = Math.PI;
  53495. this.pitch = 0;
  53496. break;
  53497. case "left":
  53498. this.yaw = -Math.PI / 2;
  53499. this.pitch = 0;
  53500. break;
  53501. case "right":
  53502. this.yaw = Math.PI / 2;
  53503. this.pitch = 0;
  53504. break;
  53505. case "top":
  53506. this.yaw = 0;
  53507. this.pitch = -Math.PI / 2;
  53508. break;
  53509. case "bottom":
  53510. this.yaw = -Math.PI;
  53511. this.pitch = Math.PI / 2;
  53512. break;
  53513. }
  53514. }
  53515. isFlying(){
  53516. return transitions.getById(this.LookTransition).length > 0
  53517. }
  53518. cancelFlying(){//外界只能通过这个来cancel
  53519. transitions.cancelById(this.LookTransition, true );
  53520. }
  53521. setView( info = {}){
  53522. // position, target, duration = 0, callback = null, onUpdate = null, Easing='', cancelFun
  53523. this.cancelFlying();
  53524. let done = ()=>{
  53525. if(endTarget){
  53526. this.lookAt(endTarget); //compute radius for orbitcontrol
  53527. }else if(endQuaternion){
  53528. this.rotation = new Euler().setFromQuaternion(endQuaternion);
  53529. }
  53530. let f = ()=>{
  53531. info.callback && info.callback();
  53532. this.dispatchEvent('flyingDone');
  53533. };
  53534. if(info.duration){
  53535. setTimeout(f,1);//延迟是为了使isFlying先为false
  53536. }else {
  53537. f(); //有的需要迅速执行回调
  53538. }
  53539. };
  53540. let endPosition = new Vector3().copy(info.position);
  53541. let startPosition = this.position.clone();
  53542. let startQuaternion, endQuaternion, endTarget = null ;
  53543. if(info.target ){
  53544. endTarget = new Vector3().copy(info.target);
  53545. endQuaternion = math.getQuaFromPosAim(endPosition,endTarget);
  53546. }else if(info.quaternion){
  53547. endQuaternion = info.quaternion.clone();
  53548. }
  53549. if(endQuaternion){
  53550. startQuaternion = new Quaternion().setFromEuler(this.rotation);
  53551. /* const startTarget = this.getPivot();
  53552. let startQuaternion = math.getQuaFromPosAim(startPosition,startTarget) */
  53553. }
  53554. if(!info.duration){
  53555. this.position.copy(endPosition);
  53556. this.restrictPos();
  53557. info.onUpdate && info.onUpdate(1);
  53558. done();
  53559. }else {
  53560. transitions.start(lerp.vector(this.position, endPosition, (pos, progress)=>{
  53561. let t = progress;
  53562. if(endQuaternion){
  53563. let quaternion = (new Quaternion()).copy(startQuaternion);
  53564. lerp.quaternion(quaternion, endQuaternion)(progress),
  53565. this.rotation = new Euler().setFromQuaternion(quaternion);
  53566. }
  53567. this.restrictPos();
  53568. info.onUpdate && info.onUpdate(t);//add
  53569. }), info.duration, done, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine /*easeInOutQuad */,null, this.LookTransition, info.cancelFun);
  53570. }
  53571. }
  53572. //平移Ortho相机
  53573. moveOrthoCamera(viewport, info, duration, easeName){//boundSize优先于endZoom。
  53574. let camera = viewport.camera;
  53575. let startZoom = camera.zoom;
  53576. let endPosition = info.endPosition;
  53577. let boundSize = info.boundSize;
  53578. let endZoom = info.endZoom;
  53579. let margin = info.margin || {x:0,y:0};/* 200 */ //像素
  53580. if(info.bound){//需要修改boundSize以适应相机的旋转,当相机不在xy水平面上朝向z时
  53581. endPosition = endPosition || info.bound.getCenter(new Vector3());
  53582. let matrixRot = new Matrix4().makeRotationFromEuler(this.rotation).invert();
  53583. let boundingBox = info.bound.clone().applyMatrix4(matrixRot);
  53584. boundSize = boundingBox.getSize(new Vector3());
  53585. }
  53586. if(boundSize && boundSize.x == 0 && boundSize.y == 0){
  53587. boundSize.set(1,1); //避免infinity
  53588. }
  53589. this.setView({ position:endPosition, duration,
  53590. callback:()=>{//done
  53591. },
  53592. onUpdate:(progress)=>{
  53593. if(boundSize || endZoom){
  53594. if(boundSize){
  53595. let aspect = boundSize.x / boundSize.y;
  53596. let w, h;
  53597. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  53598. h = boundSize.y;
  53599. endZoom = (viewport.resolution.y - margin.y) / h; //注意,要在resolution不为0时执行
  53600. }else {
  53601. w = boundSize.x;
  53602. endZoom = (viewport.resolution.x - margin.x) / w;
  53603. }
  53604. //onUpdate时更新endzoom是因为画布大小可能更改
  53605. }
  53606. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  53607. camera.updateProjectionMatrix();
  53608. }
  53609. },
  53610. Easing:easeName
  53611. });
  53612. }
  53613. zoomOrthoCamera(camera, endZoom, pointer, duration, onProgress){//定点缩放
  53614. let startZoom = camera.zoom;
  53615. let pointerPos = new Vector3(pointer.x, pointer.y,0.5);
  53616. transitions.start(( progress)=>{
  53617. let oldPos = pointerPos.clone().unproject(camera);
  53618. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  53619. camera.updateProjectionMatrix();
  53620. let newPos = pointerPos.clone().unproject(camera);
  53621. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  53622. let moveVec = new Vector3().subVectors(newPos, oldPos);
  53623. camera.position.sub(moveVec);
  53624. this.position.copy(camera.position);
  53625. onProgress && onProgress();
  53626. } , duration, null/* done */, 0, easing.easeInOutSine, null, "zoomInView"/* , info.cancelFun */);
  53627. }
  53628. };
  53629. /*
  53630. z
  53631. |
  53632. |
  53633. |
  53634. |
  53635. x <-------| 中心为点云position加boudingbox中心
  53636. /
  53637. /
  53638. y
  53639. */
  53640. var lineLen$1 = 2, stemLen = 4, arrowLen = 2, lineDisToStem = 5;
  53641. var opacity = 0.5;
  53642. class Axis extends Object3D {// 坐标轴
  53643. constructor (position) {
  53644. super();
  53645. this.getArrow();
  53646. this.createArrows();
  53647. //this.position.copy(position) 点云的中心点就是在(0,0,0)
  53648. //this.scale.set(2,2,2)
  53649. }
  53650. getArrow(){
  53651. var arrowGroup = new Object3D();
  53652. var line = LineDraw.createLine([new Vector3, new Vector3(0,0,lineLen$1)]);
  53653. var stem = new Mesh(new BoxGeometry(0.3, 0.3, stemLen));
  53654. stem.position.set(0,0,lineLen$1+lineDisToStem+stemLen/2);
  53655. var arrow = new Mesh(new CylinderBufferGeometry( 0, 0.6, arrowLen, 12, 1, false ));//radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2
  53656. arrow.position.set(0,0,lineLen$1+lineDisToStem+stemLen + arrowLen/2);
  53657. arrow.rotation.set(Math.PI/2,0,0);
  53658. arrowGroup.add(stem);
  53659. arrowGroup.add(line);
  53660. arrowGroup.add(arrow);
  53661. this.arrowGroup = arrowGroup;
  53662. }
  53663. createArrows(){
  53664. var material = new MeshBasicMaterial({color:"#00d7df",side:2,transparent:true,opacity:0.8, depthWrite:false});
  53665. let axis = Object.keys(Potree.config.axis);
  53666. axis.forEach((axisText)=>{
  53667. let color = Potree.config.axis[axisText].color;
  53668. var group = this.arrowGroup.clone();
  53669. group.children.forEach(e=>{
  53670. e.material = e.material.clone();
  53671. /* e.material.opacity = opacity
  53672. e.material.transparent = true */
  53673. e.material.color.set(color);
  53674. });
  53675. var label = this.createLabel(axisText, color);
  53676. label.position.set(0, 0, lineLen$1 + stemLen + arrowLen + lineDisToStem + 3);
  53677. group.add(label);
  53678. if(axisText == 'y'){
  53679. group.rotation.x = -Math.PI / 2;
  53680. }else if(axisText == 'x'){
  53681. group.rotation.y = Math.PI / 2;
  53682. }
  53683. this.add(group);
  53684. });
  53685. }
  53686. createLabel(text,color){
  53687. var canvas = document.createElement("canvas");
  53688. var context = canvas.getContext("2d");
  53689. canvas.width = 256,
  53690. canvas.height = 256;
  53691. var fontSize = 120;
  53692. context.fillStyle = color; //"#00ffee";
  53693. context.font = "normal " + fontSize + "px 微软雅黑";
  53694. var textWidth = context.measureText(text).width;
  53695. context.clearRect(0,0,canvas.width,canvas.height);
  53696. context.fillText(text, (canvas.width - textWidth) / 2 , (canvas.height + fontSize) / 2);
  53697. var tex = new Texture(canvas);
  53698. tex.needsUpdate = true;
  53699. tex.minFilter = NearestFilter;//防止边缘发黑
  53700. tex.magFilter = NearestFilter;//防止边缘发黑
  53701. var sprite = new Sprite(new SpriteMaterial({
  53702. map: tex , // depthWrite:false,
  53703. }));
  53704. sprite.renderOrder = 1;//防止在透明后还是出现白矩形挡住其他mesh
  53705. sprite.scale.set(3,3,3);
  53706. return sprite
  53707. }
  53708. }
  53709. class Scene$1 extends EventDispatcher{
  53710. constructor(){
  53711. super();
  53712. this.annotations = new Annotation();
  53713. this.scene = new Scene();
  53714. //this.sceneBG = new THREE.Scene(); //用来放skybox
  53715. //this.sceneOverlay = new THREE.Scene();
  53716. this.scenePointCloud = new Scene();
  53717. this.cameraP = new PerspectiveCamera(this.fov, 1, Potree.config.view.near, Potree.config.view.near);
  53718. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  53719. this.cameraP.limitFar = true;//add
  53720. this.cameraVR = new PerspectiveCamera();
  53721. this.cameraBG = new Camera();
  53722. this.cameraScreenSpace = new OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
  53723. this.cameraMode = CameraMode.PERSPECTIVE;
  53724. this.overrideCamera = null;
  53725. this.pointclouds = [];
  53726. this.measurements = [];
  53727. this.profiles = [];
  53728. this.volumes = [];
  53729. this.polygonClipVolumes = [];
  53730. this.cameraAnimations = [];
  53731. this.orientedImages = [];
  53732. this.images360 = [];
  53733. this.geopackages = [];
  53734. this.fpControls = null;
  53735. this.orbitControls = null;
  53736. this.earthControls = null;
  53737. this.geoControls = null;
  53738. this.deviceControls = null;
  53739. this.inputHandler = null;
  53740. this.view = new View();
  53741. this.directionalLight = null;
  53742. this.initialize();
  53743. //-------------
  53744. this.axisArrow = new Axis();
  53745. this.scene.add(this.axisArrow);
  53746. if(!Potree.settings.isDebug)this.axisArrow.visible = false;
  53747. viewer.setObjectLayers(this.axisArrow, 'bothMapAndScene' );
  53748. this.tags = new Object3D;
  53749. this.scene.add(this.tags);
  53750. }
  53751. estimateHeightAt (position) {
  53752. let height = null;
  53753. let fromSpacing = Infinity;
  53754. for (let pointcloud of this.pointclouds) {
  53755. if (pointcloud.root.geometryNode === undefined) {
  53756. continue;
  53757. }
  53758. let pHeight = null;
  53759. let pFromSpacing = Infinity;
  53760. let lpos = position.clone().sub(pointcloud.position);
  53761. lpos.z = 0;
  53762. let ray = new Ray(lpos, new Vector3(0, 0, 1));
  53763. let stack = [pointcloud.root];
  53764. while (stack.length > 0) {
  53765. let node = stack.pop();
  53766. let box = node.getBoundingBox();
  53767. let inside = ray.intersectBox(box);
  53768. if (!inside) {
  53769. continue;
  53770. }
  53771. let h = node.geometryNode.mean.z +
  53772. pointcloud.position.z +
  53773. node.geometryNode.boundingBox.min.z;
  53774. if (node.geometryNode.spacing <= pFromSpacing) {
  53775. pHeight = h;
  53776. pFromSpacing = node.geometryNode.spacing;
  53777. }
  53778. for (let index of Object.keys(node.children)) {
  53779. let child = node.children[index];
  53780. if (child.geometryNode) {
  53781. stack.push(node.children[index]);
  53782. }
  53783. }
  53784. }
  53785. if (height === null || pFromSpacing < fromSpacing) {
  53786. height = pHeight;
  53787. fromSpacing = pFromSpacing;
  53788. }
  53789. }
  53790. return height;
  53791. }
  53792. getBoundingBox(pointclouds = this.pointclouds){
  53793. let box = new Box3();
  53794. this.scenePointCloud.updateMatrixWorld(true);
  53795. this.referenceFrame.updateMatrixWorld(true);
  53796. for (let pointcloud of pointclouds) {
  53797. pointcloud.updateMatrixWorld(true);
  53798. let pointcloudBox = pointcloud.pcoGeometry.tightBoundingBox ? pointcloud.pcoGeometry.tightBoundingBox : pointcloud.boundingBox;
  53799. let boxWorld = Utils.computeTransformedBoundingBox(pointcloudBox, pointcloud.matrixWorld);
  53800. box.union(boxWorld);
  53801. }
  53802. return box;
  53803. }
  53804. addPointCloud (pointcloud) {
  53805. this.pointclouds.push(pointcloud);
  53806. this.scenePointCloud.add(pointcloud);
  53807. this.dispatchEvent({
  53808. type: 'pointcloud_added',
  53809. pointcloud: pointcloud
  53810. });
  53811. }
  53812. //add:
  53813. removePointCloud (pointcloud) {
  53814. let index = this.pointclouds.indexOf(pointcloud);
  53815. if(index == -1)return
  53816. this.pointclouds.splice(index, 1);
  53817. this.scenePointCloud.remove(pointcloud);
  53818. pointcloud.panos.forEach(pano=>{
  53819. pano.dispose();
  53820. });
  53821. }
  53822. addVolume (volume) {
  53823. this.volumes.push(volume);
  53824. this.dispatchEvent({
  53825. 'type': 'volume_added',
  53826. 'scene': this,
  53827. 'volume': volume
  53828. });
  53829. }
  53830. addOrientedImages(images){
  53831. this.orientedImages.push(images);
  53832. this.scene.add(images.node);
  53833. this.dispatchEvent({
  53834. 'type': 'oriented_images_added',
  53835. 'scene': this,
  53836. 'images': images
  53837. });
  53838. };
  53839. removeOrientedImages(images){
  53840. let index = this.orientedImages.indexOf(images);
  53841. if (index > -1) {
  53842. this.orientedImages.splice(index, 1);
  53843. this.dispatchEvent({
  53844. 'type': 'oriented_images_removed',
  53845. 'scene': this,
  53846. 'images': images
  53847. });
  53848. }
  53849. };
  53850. add360Images(images){
  53851. this.images360.push(images);
  53852. this.scene.add(images.node);
  53853. //this.sceneOverlay.add(images.node);//add
  53854. this.dispatchEvent({
  53855. 'type': '360_images_added',
  53856. 'scene': this,
  53857. 'images': images
  53858. });
  53859. }
  53860. remove360Images(images){
  53861. let index = this.images360.indexOf(images);
  53862. if (index > -1) {
  53863. this.images360.splice(index, 1);
  53864. this.dispatchEvent({
  53865. 'type': '360_images_removed',
  53866. 'scene': this,
  53867. 'images': images
  53868. });
  53869. }
  53870. }
  53871. addGeopackage(geopackage){
  53872. this.geopackages.push(geopackage);
  53873. this.scene.add(geopackage.node);
  53874. this.dispatchEvent({
  53875. 'type': 'geopackage_added',
  53876. 'scene': this,
  53877. 'geopackage': geopackage
  53878. });
  53879. };
  53880. removeGeopackage(geopackage){
  53881. let index = this.geopackages.indexOf(geopackage);
  53882. if (index > -1) {
  53883. this.geopackages.splice(index, 1);
  53884. this.dispatchEvent({
  53885. 'type': 'geopackage_removed',
  53886. 'scene': this,
  53887. 'geopackage': geopackage
  53888. });
  53889. }
  53890. };
  53891. removeVolume (volume) {
  53892. let index = this.volumes.indexOf(volume);
  53893. if (index > -1) {
  53894. this.volumes.splice(index, 1);
  53895. this.dispatchEvent({
  53896. 'type': 'volume_removed',
  53897. 'scene': this,
  53898. 'volume': volume
  53899. });
  53900. }
  53901. };
  53902. addCameraAnimation(animation) {
  53903. this.cameraAnimations.push(animation);
  53904. this.dispatchEvent({
  53905. 'type': 'camera_animation_added',
  53906. 'scene': this,
  53907. 'animation': animation
  53908. });
  53909. };
  53910. removeCameraAnimation(animation){
  53911. let index = this.cameraAnimations.indexOf(animation);
  53912. if (index > -1) {
  53913. this.cameraAnimations.splice(index, 1);
  53914. this.dispatchEvent({
  53915. 'type': 'camera_animation_removed',
  53916. 'scene': this,
  53917. 'animation': animation
  53918. });
  53919. }
  53920. };
  53921. addPolygonClipVolume(volume){
  53922. this.polygonClipVolumes.push(volume);
  53923. this.dispatchEvent({
  53924. "type": "polygon_clip_volume_added",
  53925. "scene": this,
  53926. "volume": volume
  53927. });
  53928. };
  53929. removePolygonClipVolume(volume){
  53930. let index = this.polygonClipVolumes.indexOf(volume);
  53931. if (index > -1) {
  53932. this.polygonClipVolumes.splice(index, 1);
  53933. this.dispatchEvent({
  53934. "type": "polygon_clip_volume_removed",
  53935. "scene": this,
  53936. "volume": volume
  53937. });
  53938. }
  53939. };
  53940. addMeasurement(measurement){
  53941. measurement.lengthUnit = this.lengthUnit;
  53942. measurement.lengthUnitDisplay = this.lengthUnitDisplay;
  53943. this.measurements.push(measurement);
  53944. this.dispatchEvent({
  53945. 'type': 'measurement_added',
  53946. 'scene': this,
  53947. 'measurement': measurement
  53948. });
  53949. };
  53950. removeMeasurement (measurement) {
  53951. let index = this.measurements.indexOf(measurement);
  53952. if (index > -1) {
  53953. this.measurements.splice(index, 1);
  53954. this.dispatchEvent({
  53955. 'type': 'measurement_removed',
  53956. 'scene': this,
  53957. 'measurement': measurement
  53958. });
  53959. }
  53960. }
  53961. addProfile (profile) {
  53962. this.profiles.push(profile);
  53963. this.dispatchEvent({
  53964. 'type': 'profile_added',
  53965. 'scene': this,
  53966. 'profile': profile
  53967. });
  53968. }
  53969. removeProfile (profile) {
  53970. let index = this.profiles.indexOf(profile);
  53971. if (index > -1) {
  53972. this.profiles.splice(index, 1);
  53973. this.dispatchEvent({
  53974. 'type': 'profile_removed',
  53975. 'scene': this,
  53976. 'profile': profile
  53977. });
  53978. }
  53979. }
  53980. removeAllMeasurements () {
  53981. while (this.measurements.length > 0) {
  53982. this.removeMeasurement(this.measurements[0]);
  53983. }
  53984. while (this.profiles.length > 0) {
  53985. this.removeProfile(this.profiles[0]);
  53986. }
  53987. while (this.volumes.length > 0) {
  53988. this.removeVolume(this.volumes[0]);
  53989. }
  53990. }
  53991. removeAllClipVolumes(){
  53992. let clipVolumes = this.volumes.filter(volume => volume.clip === true);
  53993. for(let clipVolume of clipVolumes){
  53994. this.removeVolume(clipVolume);
  53995. }
  53996. while(this.polygonClipVolumes.length > 0){
  53997. this.removePolygonClipVolume(this.polygonClipVolumes[0]);
  53998. }
  53999. }
  54000. getActiveCamera() {
  54001. return viewer.mainViewport.camera
  54002. if(this.overrideCamera){
  54003. return this.overrideCamera;
  54004. }
  54005. if(this.cameraMode === CameraMode.PERSPECTIVE){
  54006. return this.cameraP;
  54007. }else if(this.cameraMode === CameraMode.ORTHOGRAPHIC){
  54008. return this.cameraO;
  54009. }else if(this.cameraMode === CameraMode.VR){
  54010. return this.cameraVR;
  54011. }
  54012. return null;
  54013. }
  54014. initialize(){
  54015. this.referenceFrame = new Object3D();
  54016. this.referenceFrame.matrixAutoUpdate = false;
  54017. this.scenePointCloud.add(this.referenceFrame);
  54018. if(window.axisYup){
  54019. }else {
  54020. this.cameraP.up.set(0, 0, 1);
  54021. this.cameraO.up.set(0, 0, 1);
  54022. }
  54023. this.cameraP.position.set(1000, 1000, 1000);
  54024. this.cameraO.position.set(1000, 1000, 1000);
  54025. //this.camera.rotation.y = -Math.PI / 4;
  54026. //this.camera.rotation.x = -Math.PI / 6;
  54027. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  54028. this.directionalLight = new DirectionalLight( 0xffffff, 0.5 );
  54029. this.directionalLight.position.set( 10, 10, 10 );
  54030. this.directionalLight.lookAt( new Vector3(0, 0, 0));
  54031. this.scenePointCloud.add( this.directionalLight );
  54032. let light = new AmbientLight( 0x555555 ); // soft white light
  54033. this.scenePointCloud.add( light );
  54034. //add:------给空间模型的box 或其他obj------
  54035. let light2 = new AmbientLight( 16777215, 1 );
  54036. viewer.setObjectLayers(light2, 'bothMapAndScene');
  54037. this.scene.add(light2);
  54038. let light3 = new DirectionalLight( 16777215, 1);
  54039. light3.position.set( 10, 10, 10 );
  54040. light3.lookAt( new Vector3(0, 0, 0));
  54041. viewer.setObjectLayers(light3, 'bothMapAndScene');
  54042. this.scene.add(light3);
  54043. //--------------------------------------------
  54044. { // background
  54045. let texture = Utils.createBackgroundTexture(512, 512);
  54046. texture.minFilter = texture.magFilter = NearestFilter;
  54047. texture.minFilter = texture.magFilter = LinearFilter;
  54048. let bg = new Mesh(
  54049. new PlaneBufferGeometry(2, 2, 1),
  54050. new MeshBasicMaterial({
  54051. map: texture
  54052. })
  54053. );
  54054. bg.material.depthTest = false;
  54055. bg.material.depthWrite = false;
  54056. bg.name = 'bg';
  54057. //this.sceneBG.add(bg);
  54058. this.scene.add(bg);
  54059. bg.layers.set(Potree.config.renderLayers.bg);
  54060. }
  54061. { // background color
  54062. let bg2 = new Mesh(
  54063. new PlaneBufferGeometry(2, 2, 1),
  54064. new MeshBasicMaterial({
  54065. transparent : true
  54066. })
  54067. );
  54068. bg2.material.depthTest = false;
  54069. bg2.material.depthWrite = false;
  54070. bg2.name = 'bg2';
  54071. this.scene.add(bg2);
  54072. bg2.layers.set(Potree.config.renderLayers.bg2);
  54073. this.bg2 = bg2;
  54074. }
  54075. // { // lights
  54076. // {
  54077. // let light = new THREE.DirectionalLight(0xffffff);
  54078. // light.position.set(10, 10, 1);
  54079. // light.target.position.set(0, 0, 0);
  54080. // this.scene.add(light);
  54081. // }
  54082. // {
  54083. // let light = new THREE.DirectionalLight(0xffffff);
  54084. // light.position.set(-10, 10, 1);
  54085. // light.target.position.set(0, 0, 0);
  54086. // this.scene.add(light);
  54087. // }
  54088. // {
  54089. // let light = new THREE.DirectionalLight(0xffffff);
  54090. // light.position.set(0, -10, 20);
  54091. // light.target.position.set(0, 0, 0);
  54092. // this.scene.add(light);
  54093. // }
  54094. // }
  54095. }
  54096. /* switchBg(type){//add
  54097. let bg,;
  54098. if(type == 'gradient'){
  54099. bg
  54100. }else if(type == 'overlayColor'){
  54101. }
  54102. } */
  54103. addAnnotation(position, args = {}){
  54104. if(position instanceof Array){
  54105. args.position = new Vector3().fromArray(position);
  54106. } else if (position.x != null) {
  54107. args.position = position;
  54108. }
  54109. let annotation = new Annotation(args);
  54110. this.annotations.add(annotation);
  54111. return annotation;
  54112. }
  54113. getAnnotations () {
  54114. return this.annotations;
  54115. };
  54116. removeAnnotation(annotationToRemove) {
  54117. this.annotations.remove(annotationToRemove);
  54118. }
  54119. };
  54120. // http://epsg.io/
  54121. //see http://openlayers.org/
  54122. proj4.defs([
  54123. ['UTM10N', '+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'],
  54124. ['EPSG:6339', '+proj=utm +zone=10 +ellps=GRS80 +units=m +no_defs'],
  54125. ['EPSG:6340', '+proj=utm +zone=11 +ellps=GRS80 +units=m +no_defs'],
  54126. ['EPSG:6341', '+proj=utm +zone=12 +ellps=GRS80 +units=m +no_defs'],
  54127. ['EPSG:6342', '+proj=utm +zone=13 +ellps=GRS80 +units=m +no_defs'],
  54128. ['EPSG:6343', '+proj=utm +zone=14 +ellps=GRS80 +units=m +no_defs'],
  54129. ['EPSG:6344', '+proj=utm +zone=15 +ellps=GRS80 +units=m +no_defs'],
  54130. ['EPSG:6345', '+proj=utm +zone=16 +ellps=GRS80 +units=m +no_defs'],
  54131. ['EPSG:6346', '+proj=utm +zone=17 +ellps=GRS80 +units=m +no_defs'],
  54132. ['EPSG:6347', '+proj=utm +zone=18 +ellps=GRS80 +units=m +no_defs'],
  54133. ['EPSG:6348', '+proj=utm +zone=19 +ellps=GRS80 +units=m +no_defs'],
  54134. ['EPSG:26910', '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54135. ['EPSG:26911', '+proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54136. ['EPSG:26912', '+proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54137. ['EPSG:26913', '+proj=utm +zone=13 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54138. ['EPSG:26914', '+proj=utm +zone=14 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54139. ['EPSG:26915', '+proj=utm +zone=15 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54140. ['EPSG:26916', '+proj=utm +zone=16 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54141. ['EPSG:26917', '+proj=utm +zone=17 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54142. ['EPSG:26918', '+proj=utm +zone=18 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54143. ['EPSG:26919', '+proj=utm +zone=19 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54144. ]);
  54145. class MapView{
  54146. constructor (viewer) {
  54147. this.viewer = viewer;
  54148. this.webMapService = 'WMTS';
  54149. this.mapProjectionName = 'EPSG:3857'; //navvis也是这个
  54150. this.mapProjection = proj4.defs(this.mapProjectionName);
  54151. this.sceneProjection = null;
  54152. this.extentsLayer = null;
  54153. this.cameraLayer = null;
  54154. this.toolLayer = null;
  54155. this.sourcesLayer = null;
  54156. this.sourcesLabelLayer = null;
  54157. this.images360Layer = null;
  54158. this.enabled = false;
  54159. this.createAnnotationStyle = (text) => {
  54160. return [
  54161. new ol.style.Style({
  54162. image: new ol.style.Circle({
  54163. radius: 10,
  54164. stroke: new ol.style.Stroke({
  54165. color: [255, 255, 255, 0.5],
  54166. width: 2
  54167. }),
  54168. fill: new ol.style.Fill({
  54169. color: [0, 0, 0, 0.5]
  54170. })
  54171. })
  54172. })
  54173. ];
  54174. };
  54175. this.createLabelStyle = (text) => {
  54176. let style = new ol.style.Style({
  54177. image: new ol.style.Circle({
  54178. radius: 6,
  54179. stroke: new ol.style.Stroke({
  54180. color: 'white',
  54181. width: 2
  54182. }),
  54183. fill: new ol.style.Fill({
  54184. color: 'green'
  54185. })
  54186. }),
  54187. text: new ol.style.Text({
  54188. font: '12px helvetica,sans-serif',
  54189. text: text,
  54190. fill: new ol.style.Fill({
  54191. color: '#000'
  54192. }),
  54193. stroke: new ol.style.Stroke({
  54194. color: '#fff',
  54195. width: 2
  54196. })
  54197. })
  54198. });
  54199. return style;
  54200. };
  54201. }
  54202. showSources (show) {
  54203. this.sourcesLayer.setVisible(show);
  54204. this.sourcesLabelLayer.setVisible(show);
  54205. }
  54206. init () {
  54207. if(typeof ol === "undefined"){
  54208. return;
  54209. }
  54210. this.elMap = $('#potree_map');
  54211. this.elMap.draggable({ handle: $('#potree_map_header') });
  54212. this.elMap.resizable();
  54213. this.elTooltip = $(`<div style="position: relative; z-index: 100"></div>`);
  54214. this.elMap.append(this.elTooltip);
  54215. let extentsLayer = this.getExtentsLayer();
  54216. let cameraLayer = this.getCameraLayer();
  54217. this.getToolLayer();
  54218. let sourcesLayer = this.getSourcesLayer();
  54219. this.images360Layer = this.getImages360Layer();
  54220. this.getSourcesLabelLayer();
  54221. this.getAnnotationsLayer();
  54222. let mousePositionControl = new ol.control.MousePosition({
  54223. coordinateFormat: ol.coordinate.createStringXY(5),
  54224. projection: 'EPSG:4326',
  54225. undefinedHTML: '&nbsp;'
  54226. });
  54227. let _this = this;
  54228. let DownloadSelectionControl = function (optOptions) {
  54229. let options = optOptions || {};
  54230. // TOGGLE TILES
  54231. let btToggleTiles = document.createElement('button');
  54232. btToggleTiles.innerHTML = 'T';
  54233. btToggleTiles.addEventListener('click', () => {
  54234. let visible = sourcesLayer.getVisible();
  54235. _this.showSources(!visible);
  54236. }, false);
  54237. btToggleTiles.style.float = 'left';
  54238. btToggleTiles.title = 'show / hide tiles';
  54239. // DOWNLOAD SELECTED TILES
  54240. let link = document.createElement('a');
  54241. link.href = '#';
  54242. link.download = 'list.txt';
  54243. link.style.float = 'left';
  54244. let button = document.createElement('button');
  54245. button.innerHTML = 'D';
  54246. link.appendChild(button);
  54247. let handleDownload = (e) => {
  54248. let features = selectedFeatures.getArray();
  54249. let url = [document.location.protocol, '//', document.location.host, document.location.pathname].join('');
  54250. if (features.length === 0) {
  54251. alert('No tiles were selected. Select area with ctrl + left mouse button!');
  54252. e.preventDefault();
  54253. e.stopImmediatePropagation();
  54254. return false;
  54255. } else if (features.length === 1) {
  54256. let feature = features[0];
  54257. if (feature.source) {
  54258. let cloudjsurl = feature.pointcloud.pcoGeometry.url;
  54259. let sourceurl = new URL(url + '/../' + cloudjsurl + '/../source/' + feature.source.name);
  54260. link.href = sourceurl.href;
  54261. link.download = feature.source.name;
  54262. }
  54263. } else {
  54264. let content = '';
  54265. for (let i = 0; i < features.length; i++) {
  54266. let feature = features[i];
  54267. if (feature.source) {
  54268. let cloudjsurl = feature.pointcloud.pcoGeometry.url;
  54269. let sourceurl = new URL(url + '/../' + cloudjsurl + '/../source/' + feature.source.name);
  54270. content += sourceurl.href + '\n';
  54271. }
  54272. }
  54273. let uri = 'data:application/octet-stream;base64,' + btoa(content);
  54274. link.href = uri;
  54275. link.download = 'list_of_files.txt';
  54276. }
  54277. };
  54278. button.addEventListener('click', handleDownload, false);
  54279. // assemble container
  54280. let element = document.createElement('div');
  54281. element.className = 'ol-unselectable ol-control';
  54282. element.appendChild(link);
  54283. element.appendChild(btToggleTiles);
  54284. element.style.bottom = '0.5em';
  54285. element.style.left = '0.5em';
  54286. element.title = 'Download file or list of selected tiles. Select tile with left mouse button or area using ctrl + left mouse.';
  54287. ol.control.Control.call(this, {
  54288. element: element,
  54289. target: options.target
  54290. });
  54291. };
  54292. ol.inherits(DownloadSelectionControl, ol.control.Control);
  54293. this.map = new ol.Map({
  54294. controls: ol.control.defaults({
  54295. attributionOptions: ({
  54296. collapsible: false
  54297. })
  54298. }).extend([
  54299. // this.controls.zoomToExtent,
  54300. new DownloadSelectionControl(),
  54301. mousePositionControl
  54302. ]),
  54303. layers: [
  54304. new ol.layer.Tile({source: new ol.source.OSM()}),
  54305. this.toolLayer,
  54306. this.annotationsLayer,
  54307. this.sourcesLayer,
  54308. this.sourcesLabelLayer,
  54309. this.images360Layer,
  54310. extentsLayer,
  54311. cameraLayer
  54312. ],
  54313. target: 'potree_map_content',
  54314. view: new ol.View({
  54315. center: this.olCenter,
  54316. zoom: 9
  54317. })
  54318. });
  54319. // DRAGBOX / SELECTION
  54320. this.dragBoxLayer = new ol.layer.Vector({
  54321. source: new ol.source.Vector({}),
  54322. style: new ol.style.Style({
  54323. stroke: new ol.style.Stroke({
  54324. color: 'rgba(0, 0, 255, 1)',
  54325. width: 2
  54326. })
  54327. })
  54328. });
  54329. this.map.addLayer(this.dragBoxLayer);
  54330. let select = new ol.interaction.Select();
  54331. this.map.addInteraction(select);
  54332. let selectedFeatures = select.getFeatures();
  54333. let dragBox = new ol.interaction.DragBox({
  54334. condition: ol.events.condition.platformModifierKeyOnly
  54335. });
  54336. this.map.addInteraction(dragBox);
  54337. // this.map.on('pointermove', evt => {
  54338. // let pixel = evt.pixel;
  54339. // let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
  54340. // return feature;
  54341. // });
  54342. // // console.log(feature);
  54343. // // this.elTooltip.css("display", feature ? '' : 'none');
  54344. // this.elTooltip.css('display', 'none');
  54345. // if (feature && feature.onHover) {
  54346. // feature.onHover(evt);
  54347. // // overlay.setPosition(evt.coordinate);
  54348. // // tooltip.innerHTML = feature.get('name');
  54349. // }
  54350. // });
  54351. this.map.on('click', evt => {
  54352. let pixel = evt.pixel;
  54353. let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
  54354. return feature;
  54355. });
  54356. if (feature && feature.onClick) {
  54357. feature.onClick(evt);
  54358. }
  54359. });
  54360. dragBox.on('boxend', (e) => {
  54361. // features that intersect the box are added to the collection of
  54362. // selected features, and their names are displayed in the "info"
  54363. // div
  54364. let extent = dragBox.getGeometry().getExtent();
  54365. this.getSourcesLayer().getSource().forEachFeatureIntersectingExtent(extent, (feature) => {
  54366. selectedFeatures.push(feature);
  54367. });
  54368. });
  54369. // clear selection when drawing a new box and when clicking on the map
  54370. dragBox.on('boxstart', (e) => {
  54371. selectedFeatures.clear();
  54372. });
  54373. this.map.on('click', () => {
  54374. selectedFeatures.clear();
  54375. });
  54376. this.viewer.addEventListener('scene_changed', e => {
  54377. this.setScene(e.scene);
  54378. });
  54379. this.onPointcloudAdded = e => {
  54380. this.load(e.pointcloud);
  54381. };
  54382. this.on360ImagesAdded = e => {
  54383. this.addImages360(e.images);
  54384. };
  54385. this.onAnnotationAdded = e => {
  54386. if (!this.sceneProjection) {
  54387. return;
  54388. }
  54389. let annotation = e.annotation;
  54390. let position = annotation.position;
  54391. let mapPos = this.toMap.forward([position.x, position.y]);
  54392. let feature = new ol.Feature({
  54393. geometry: new ol.geom.Point(mapPos),
  54394. name: annotation.title
  54395. });
  54396. feature.setStyle(this.createAnnotationStyle(annotation.title));
  54397. feature.onHover = evt => {
  54398. let coordinates = feature.getGeometry().getCoordinates();
  54399. let p = this.map.getPixelFromCoordinate(coordinates);
  54400. this.elTooltip.html(annotation.title);
  54401. this.elTooltip.css('display', '');
  54402. this.elTooltip.css('left', `${p[0]}px`);
  54403. this.elTooltip.css('top', `${p[1]}px`);
  54404. };
  54405. feature.onClick = evt => {
  54406. annotation.clickTitle();
  54407. };
  54408. this.getAnnotationsLayer().getSource().addFeature(feature);
  54409. };
  54410. this.setScene(this.viewer.scene);
  54411. }
  54412. setScene (scene) {
  54413. if (this.scene === scene) {
  54414. return;
  54415. };
  54416. if (this.scene) {
  54417. this.scene.removeEventListener('pointcloud_added', this.onPointcloudAdded);
  54418. this.scene.removeEventListener('360_images_added', this.on360ImagesAdded);
  54419. this.scene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  54420. }
  54421. this.scene = scene;
  54422. this.scene.addEventListener('pointcloud_added', this.onPointcloudAdded);
  54423. this.scene.addEventListener('360_images_added', this.on360ImagesAdded);
  54424. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  54425. for (let pointcloud of this.viewer.scene.pointclouds) {
  54426. this.load(pointcloud);
  54427. }
  54428. this.viewer.scene.annotations.traverseDescendants(annotation => {
  54429. this.onAnnotationAdded({annotation: annotation});
  54430. });
  54431. for(let images of this.viewer.scene.images360){
  54432. this.on360ImagesAdded({images: images});
  54433. }
  54434. }
  54435. getExtentsLayer () {
  54436. if (this.extentsLayer) {
  54437. return this.extentsLayer;
  54438. }
  54439. this.gExtent = new ol.geom.LineString([[0, 0], [0, 0]]);
  54440. let feature = new ol.Feature(this.gExtent);
  54441. let featureVector = new ol.source.Vector({
  54442. features: [feature]
  54443. });
  54444. this.extentsLayer = new ol.layer.Vector({
  54445. source: featureVector,
  54446. style: new ol.style.Style({
  54447. fill: new ol.style.Fill({
  54448. color: 'rgba(255, 255, 255, 0.2)'
  54449. }),
  54450. stroke: new ol.style.Stroke({
  54451. color: '#0000ff',
  54452. width: 2
  54453. }),
  54454. image: new ol.style.Circle({
  54455. radius: 3,
  54456. fill: new ol.style.Fill({
  54457. color: '#0000ff'
  54458. })
  54459. })
  54460. })
  54461. });
  54462. return this.extentsLayer;
  54463. }
  54464. getAnnotationsLayer () {
  54465. if (this.annotationsLayer) {
  54466. return this.annotationsLayer;
  54467. }
  54468. this.annotationsLayer = new ol.layer.Vector({
  54469. source: new ol.source.Vector({
  54470. }),
  54471. style: new ol.style.Style({
  54472. fill: new ol.style.Fill({
  54473. color: 'rgba(255, 0, 0, 1)'
  54474. }),
  54475. stroke: new ol.style.Stroke({
  54476. color: 'rgba(255, 0, 0, 1)',
  54477. width: 2
  54478. })
  54479. })
  54480. });
  54481. return this.annotationsLayer;
  54482. }
  54483. getCameraLayer () {
  54484. if (this.cameraLayer) {
  54485. return this.cameraLayer;
  54486. }
  54487. // CAMERA LAYER
  54488. this.gCamera = new ol.geom.LineString([[0, 0], [0, 0], [0, 0], [0, 0]]);
  54489. let feature = new ol.Feature(this.gCamera);
  54490. let featureVector = new ol.source.Vector({
  54491. features: [feature]
  54492. });
  54493. this.cameraLayer = new ol.layer.Vector({
  54494. source: featureVector,
  54495. style: new ol.style.Style({
  54496. stroke: new ol.style.Stroke({
  54497. color: '#0000ff',
  54498. width: 2
  54499. })
  54500. })
  54501. });
  54502. return this.cameraLayer;
  54503. }
  54504. getToolLayer () {
  54505. if (this.toolLayer) {
  54506. return this.toolLayer;
  54507. }
  54508. this.toolLayer = new ol.layer.Vector({
  54509. source: new ol.source.Vector({
  54510. }),
  54511. style: new ol.style.Style({
  54512. fill: new ol.style.Fill({
  54513. color: 'rgba(255, 0, 0, 1)'
  54514. }),
  54515. stroke: new ol.style.Stroke({
  54516. color: 'rgba(255, 0, 0, 1)',
  54517. width: 2
  54518. })
  54519. })
  54520. });
  54521. return this.toolLayer;
  54522. }
  54523. getImages360Layer(){
  54524. if(this.images360Layer){
  54525. return this.images360Layer;
  54526. }
  54527. let style = new ol.style.Style({
  54528. image: new ol.style.Circle({
  54529. radius: 4,
  54530. stroke: new ol.style.Stroke({
  54531. color: [255, 0, 0, 1],
  54532. width: 2
  54533. }),
  54534. fill: new ol.style.Fill({
  54535. color: [255, 100, 100, 1]
  54536. })
  54537. })
  54538. });
  54539. let layer = new ol.layer.Vector({
  54540. source: new ol.source.Vector({}),
  54541. style: style,
  54542. });
  54543. this.images360Layer = layer;
  54544. return this.images360Layer;
  54545. }
  54546. getSourcesLayer () {
  54547. if (this.sourcesLayer) {
  54548. return this.sourcesLayer;
  54549. }
  54550. this.sourcesLayer = new ol.layer.Vector({
  54551. source: new ol.source.Vector({}),
  54552. style: new ol.style.Style({
  54553. fill: new ol.style.Fill({
  54554. color: 'rgba(0, 0, 150, 0.1)'
  54555. }),
  54556. stroke: new ol.style.Stroke({
  54557. color: 'rgba(0, 0, 150, 1)',
  54558. width: 1
  54559. })
  54560. })
  54561. });
  54562. return this.sourcesLayer;
  54563. }
  54564. getSourcesLabelLayer () {
  54565. if (this.sourcesLabelLayer) {
  54566. return this.sourcesLabelLayer;
  54567. }
  54568. this.sourcesLabelLayer = new ol.layer.Vector({
  54569. source: new ol.source.Vector({
  54570. }),
  54571. style: new ol.style.Style({
  54572. fill: new ol.style.Fill({
  54573. color: 'rgba(255, 0, 0, 0.1)'
  54574. }),
  54575. stroke: new ol.style.Stroke({
  54576. color: 'rgba(255, 0, 0, 1)',
  54577. width: 2
  54578. })
  54579. }),
  54580. minResolution: 0.01,
  54581. maxResolution: 20
  54582. });
  54583. return this.sourcesLabelLayer;
  54584. }
  54585. setSceneProjection (sceneProjection) {
  54586. this.sceneProjection = sceneProjection;
  54587. this.toMap = proj4(this.sceneProjection, this.mapProjection);
  54588. this.toScene = proj4(this.mapProjection, this.sceneProjection);
  54589. };
  54590. getMapExtent () {
  54591. let bb = this.viewer.getBoundingBox();
  54592. let bottomLeft = this.toMap.forward([bb.min.x, bb.min.y]);
  54593. let bottomRight = this.toMap.forward([bb.max.x, bb.min.y]);
  54594. let topRight = this.toMap.forward([bb.max.x, bb.max.y]);
  54595. let topLeft = this.toMap.forward([bb.min.x, bb.max.y]);
  54596. let extent = {
  54597. bottomLeft: bottomLeft,
  54598. bottomRight: bottomRight,
  54599. topRight: topRight,
  54600. topLeft: topLeft
  54601. };
  54602. return extent;
  54603. };
  54604. getMapCenter () {
  54605. let mapExtent = this.getMapExtent();
  54606. let mapCenter = [
  54607. (mapExtent.bottomLeft[0] + mapExtent.topRight[0]) / 2,
  54608. (mapExtent.bottomLeft[1] + mapExtent.topRight[1]) / 2
  54609. ];
  54610. return mapCenter;
  54611. };
  54612. updateToolDrawings () {
  54613. this.toolLayer.getSource().clear();
  54614. let profiles = this.viewer.profileTool.profiles;
  54615. for (let i = 0; i < profiles.length; i++) {
  54616. let profile = profiles[i];
  54617. let coordinates = [];
  54618. for (let j = 0; j < profile.points.length; j++) {
  54619. let point = profile.points[j];
  54620. let pointMap = this.toMap.forward([point.x, point.y]);
  54621. coordinates.push(pointMap);
  54622. }
  54623. let line = new ol.geom.LineString(coordinates);
  54624. let feature = new ol.Feature(line);
  54625. this.toolLayer.getSource().addFeature(feature);
  54626. }
  54627. let measurements = this.viewer.measuringTool.measurements;
  54628. for (let i = 0; i < measurements.length; i++) {
  54629. let measurement = measurements[i];
  54630. let coordinates = [];
  54631. for (let j = 0; j < measurement.points.length; j++) {
  54632. let point = measurement.points[j].position;
  54633. let pointMap = this.toMap.forward([point.x, point.y]);
  54634. coordinates.push(pointMap);
  54635. }
  54636. if (measurement.closed && measurement.points.length > 0) {
  54637. coordinates.push(coordinates[0]);
  54638. }
  54639. let line = new ol.geom.LineString(coordinates);
  54640. let feature = new ol.Feature(line);
  54641. this.toolLayer.getSource().addFeature(feature);
  54642. }
  54643. }
  54644. addImages360(images){
  54645. let transform = this.toMap.forward;
  54646. let layer = this.getImages360Layer();
  54647. for(let pano of images.panos){
  54648. let p = transform([pano.position.x, pano.position.y]);
  54649. let feature = new ol.Feature({
  54650. 'geometry': new ol.geom.Point(p),
  54651. });
  54652. feature.onClick = () => {
  54653. //images.focus(pano);
  54654. images.flyToPano({
  54655. pano
  54656. });
  54657. };
  54658. layer.getSource().addFeature(feature);
  54659. }
  54660. }
  54661. async load (pointcloud) {
  54662. if (!pointcloud) {
  54663. return;
  54664. }
  54665. /* if (!pointcloud.projection) {
  54666. return;
  54667. }
  54668. */
  54669. if (!this.sceneProjection) {
  54670. try {
  54671. this.setSceneProjection(proj4.defs("NAVVIS:TMERC") || pointcloud.projection);
  54672. }catch (e) {
  54673. console.log('Failed projection:', e);
  54674. if (pointcloud.fallbackProjection) {
  54675. try {
  54676. console.log('Trying fallback projection...');
  54677. this.setSceneProjection(pointcloud.fallbackProjection);
  54678. console.log('Set projection from fallback');
  54679. }catch (e) {
  54680. console.log('Failed fallback projection:', e);
  54681. return;
  54682. }
  54683. }else {
  54684. return;
  54685. };
  54686. }
  54687. }
  54688. let mapExtent = this.getMapExtent();
  54689. let mapCenter = this.getMapCenter();
  54690. let view = this.map.getView();
  54691. view.setCenter(mapCenter);
  54692. this.gExtent.setCoordinates([
  54693. mapExtent.bottomLeft,
  54694. mapExtent.bottomRight,
  54695. mapExtent.topRight,
  54696. mapExtent.topLeft,
  54697. mapExtent.bottomLeft
  54698. ]);
  54699. view.fit(this.gExtent, [300, 300], {
  54700. constrainResolution: false
  54701. });
  54702. if (pointcloud.pcoGeometry.type == 'ept'){
  54703. return;
  54704. }
  54705. let url = `${pointcloud.pcoGeometry.url}/../sources.json`;
  54706. //let response = await fetch(url);
  54707. fetch(url).then(async (response) => {
  54708. let data = await response.json();
  54709. let sources = data.sources;
  54710. for (let i = 0; i < sources.length; i++) {
  54711. let source = sources[i];
  54712. let name = source.name;
  54713. let bounds = source.bounds;
  54714. let mapBounds = {
  54715. min: this.toMap.forward([bounds.min[0], bounds.min[1]]),
  54716. max: this.toMap.forward([bounds.max[0], bounds.max[1]])
  54717. };
  54718. let mapCenter = [
  54719. (mapBounds.min[0] + mapBounds.max[0]) / 2,
  54720. (mapBounds.min[1] + mapBounds.max[1]) / 2
  54721. ];
  54722. let p1 = this.toMap.forward([bounds.min[0], bounds.min[1]]);
  54723. let p2 = this.toMap.forward([bounds.max[0], bounds.min[1]]);
  54724. let p3 = this.toMap.forward([bounds.max[0], bounds.max[1]]);
  54725. let p4 = this.toMap.forward([bounds.min[0], bounds.max[1]]);
  54726. // let feature = new ol.Feature({
  54727. // 'geometry': new ol.geom.LineString([p1, p2, p3, p4, p1])
  54728. // });
  54729. let feature = new ol.Feature({
  54730. 'geometry': new ol.geom.Polygon([[p1, p2, p3, p4, p1]])
  54731. });
  54732. feature.source = source;
  54733. feature.pointcloud = pointcloud;
  54734. this.getSourcesLayer().getSource().addFeature(feature);
  54735. feature = new ol.Feature({
  54736. geometry: new ol.geom.Point(mapCenter),
  54737. name: name
  54738. });
  54739. feature.setStyle(this.createLabelStyle(name));
  54740. this.sourcesLabelLayer.getSource().addFeature(feature);
  54741. }
  54742. }).catch(() => {
  54743. });
  54744. }
  54745. toggle () {
  54746. if (this.elMap.is(':visible')) {
  54747. this.elMap.css('display', 'none');
  54748. this.enabled = false;
  54749. } else {
  54750. this.elMap.css('display', 'block');
  54751. this.enabled = true;
  54752. }
  54753. }
  54754. update (delta) {
  54755. if (!this.sceneProjection) {
  54756. return;
  54757. }
  54758. let pm = $('#potree_map');
  54759. if (!this.enabled) {
  54760. return;
  54761. }
  54762. // resize
  54763. let mapSize = this.map.getSize();
  54764. let resized = (pm.width() !== mapSize[0] || pm.height() !== mapSize[1]);
  54765. if (resized) {
  54766. this.map.updateSize();
  54767. }
  54768. //
  54769. let camera = this.viewer.scene.getActiveCamera();
  54770. let scale = this.map.getView().getResolution();
  54771. let campos = camera.position;
  54772. let camdir = camera.getWorldDirection(new Vector3());
  54773. let sceneLookAt = camdir.clone().multiplyScalar(30 * scale).add(campos);
  54774. let geoPos = camera.position;
  54775. let geoLookAt = sceneLookAt;
  54776. let mapPos = new Vector2$1().fromArray(this.toMap.forward([geoPos.x, geoPos.y]));
  54777. let mapLookAt = new Vector2$1().fromArray(this.toMap.forward([geoLookAt.x, geoLookAt.y]));
  54778. let mapDir = new Vector2$1().subVectors(mapLookAt, mapPos).normalize();
  54779. mapLookAt = mapPos.clone().add(mapDir.clone().multiplyScalar(30 * scale));
  54780. let mapLength = mapPos.distanceTo(mapLookAt);
  54781. let mapSide = new Vector2$1(-mapDir.y, mapDir.x);
  54782. let p1 = mapPos.toArray();
  54783. let p2 = mapLookAt.clone().sub(mapSide.clone().multiplyScalar(0.3 * mapLength)).toArray();
  54784. let p3 = mapLookAt.clone().add(mapSide.clone().multiplyScalar(0.3 * mapLength)).toArray();
  54785. this.gCamera.setCoordinates([p1, p2, p3, p1]);
  54786. }
  54787. get sourcesVisible () {
  54788. return this.getSourcesLayer().getVisible();
  54789. }
  54790. set sourcesVisible (value) {
  54791. this.getSourcesLayer().setVisible(value);
  54792. }
  54793. }
  54794. let texLoader$1 = new TextureLoader();
  54795. texLoader$1.crossOrigin = "anonymous";
  54796. let createErrorMaterial = function() {
  54797. var t = new MeshBasicMaterial({
  54798. transparent: !0,
  54799. depthWrite: !1,
  54800. depthTest: !0,
  54801. opacity: 1,
  54802. side: DoubleSide
  54803. });
  54804. return t.color = new Color(3355443),
  54805. t
  54806. };
  54807. let tempVector = new Vector3, //sharedata
  54808. face1 = new Face3(0,1,2),
  54809. face2 = new Face3(2,3,0),
  54810. errorMaterial = createErrorMaterial(),
  54811. uv00 = new Vector2$1(0,0),
  54812. uv01 = new Vector2$1(0,1),
  54813. uv10 = new Vector2$1(1,0),
  54814. uv11 = new Vector2$1(1,1),
  54815. face1UV = [uv00, uv10, uv11],
  54816. face2UV = [uv11, uv01, uv00];
  54817. const HALF_WORLD_SIZE = 21e6;
  54818. const MAX_VERTICAL_DIST = 2;
  54819. const MAX_VERTICAL_DIST_TO_BEST = 1;
  54820. //高德坐标拾取工具 : https://lbs.amap.com/tools/picker
  54821. class MapLayer extends EventDispatcher{ // 包括了 MapLayerBase SceneLayer
  54822. constructor(viewer_, viewport){
  54823. super();
  54824. this.sceneGroup = new Object3D;
  54825. this.sceneGroup.name = "MapLayer";
  54826. this.loadingInProgress = 0;
  54827. this.maps = [];
  54828. this.frustum = new Frustum;
  54829. this.frustumMatrix = new Matrix4;
  54830. this.tileColor = /* i && i.tileColor ? i.tileColor : */new Color(16777215);
  54831. this.viewport = viewport;
  54832. this.changeViewer(viewer_);
  54833. //添加地图
  54834. var map = new TiledMapOpenStreetMap(this, this.tileColor );
  54835. this.addMap(map);
  54836. //map.setEnable(false)
  54837. /* this.on('needUpdate',()=>{
  54838. this.mapLayer.update()
  54839. })
  54840. */
  54841. }
  54842. addMapEntity(data, datasetId){
  54843. if(!data || !data[0]){
  54844. Potree.Log('平面图无数据','red');
  54845. return
  54846. }
  54847. var floorplan = new TiledMapFromEntity(this, this.tileColor, data[0] );//[0]?
  54848. if(floorplan){
  54849. floorplan.name += "_"+ datasetId;
  54850. this.addMap(floorplan);
  54851. floorplan.updateProjection();
  54852. floorplan.updateObjectGroup();
  54853. let visible = false;
  54854. if(datasetId in Potree.settings.floorplanEnables){
  54855. visible = Potree.settings.floorplanEnables[datasetId];
  54856. }else {
  54857. visible = Potree.settings.floorplanEnable;
  54858. }
  54859. if(visible){
  54860. this.needUpdate = true;
  54861. }else {
  54862. floorplan.setEnable(false);
  54863. }
  54864. this.dispatchEvent({type:'floorplanLoaded', floorplan});
  54865. }
  54866. return floorplan
  54867. }
  54868. getFloorplan(datasetId){
  54869. return this.maps.find(e=>e.name == 'floorplan'+"_"+ datasetId )
  54870. }
  54871. addMap(t){
  54872. this.maps.push(t);
  54873. //this.view.invalidateScene()
  54874. this.needUpdate = true;
  54875. }
  54876. removeMap(t){
  54877. var e = this.maps.indexOf(t);
  54878. if(e >= 0){
  54879. t.removeFromSceneGroup(this.sceneGroup);
  54880. this.maps.splice(e, 1);
  54881. }
  54882. /* this.view.invalidateScene() */
  54883. this.needUpdate = true;
  54884. this.viewer.dispatchEvent({
  54885. type:'content_changed'
  54886. });
  54887. }
  54888. changeViewer(viewer_){//add
  54889. this.viewer = viewer_;
  54890. }
  54891. initProjection(){
  54892. this.maps.forEach(map=>{
  54893. map.updateProjection();
  54894. map.updateObjectGroup();
  54895. });
  54896. }
  54897. visibilityChanged(){
  54898. if (!this.visible)
  54899. for (var t = 0, e = this.maps; t < e.length; t++){
  54900. e[t].removeFromSceneGroup(this.sceneGroup);
  54901. }
  54902. }
  54903. onAfterRenderViewport(e){
  54904. var n = this;
  54905. /* this.isVisibleInViewport(e) && (this.updateTimer || this.loadingInProgress || (this.updateTimer = window.setTimeout((function(){
  54906. n.update(e).then((function (t){
  54907. t && n.loadComplete.emit(!0)
  54908. }
  54909. )).catch(u.handleWarning)
  54910. }
  54911. ), 100))) */
  54912. }
  54913. update(){
  54914. this.needUpdate = false;
  54915. if(this.disabled || !this.maps.find(e=>!e.disabled) || !this.maps.find(e=>e.objectGroup.visible) )return //add
  54916. var e, n, i, r, o;
  54917. this.updateTimer = void 0,
  54918. e = this.viewport.camera,
  54919. n = e.projectionMatrix.clone(),
  54920. n.elements[0] /= 1.5,
  54921. n.elements[5] /= 1.5,
  54922. this.frustumMatrix.multiplyMatrices(n, e.matrixWorldInverse),
  54923. this.frustum.setFromProjectionMatrix(this.frustumMatrix),
  54924. this.frustum.planes[4].setComponents(0, 0, 0, 0),
  54925. this.frustum.planes[5].setComponents(0, 0, 0, 0),
  54926. i = !0;
  54927. for (r = 0; r < this.maps.length; r++){
  54928. var map = this.maps[r];
  54929. i = map.update(this.frustum, this.sceneGroup) && i;
  54930. }
  54931. return [2, i]
  54932. }
  54933. getAttributions(){
  54934. for (var t = {}, e = 0, n = this.maps; e < n.length; e++){
  54935. n[e].fillAttributions(t);
  54936. }
  54937. return t
  54938. }
  54939. updateProjection(){
  54940. for (var t = 0, e = this.maps; t < e.length; t++){
  54941. var n = e[t];
  54942. n.clearProjection(),
  54943. n.updateObjectGroup();
  54944. }
  54945. }
  54946. }
  54947. class TiledMapBase extends EventDispatcher{
  54948. constructor(/* t, */name, mapLayer, tileColor, projection){
  54949. super();
  54950. this.name = name;
  54951. //this.TransformService = t,
  54952. this.mapLayer = mapLayer,
  54953. this.tileColor = tileColor,
  54954. this.bias = 0;
  54955. this.zIndex = -1;
  54956. this.objectGroup = new Object3D;
  54957. this.objectGroup.name = name;
  54958. this.objectGroupAdded = !1,
  54959. this.baseTile = new MapTile(this,/* this.mapLayer, */this.objectGroup,this.tileColor),
  54960. this.isTileVisibleBox = new Box3,
  54961. this.isTileVisibleVec = new Vector3;
  54962. this.projection = projection;
  54963. this._zoomLevel = 0;//1-20
  54964. }
  54965. get zoomLevel(){
  54966. return this._zoomLevel
  54967. }
  54968. set zoomLevel(zoomLevel){
  54969. if(this._zoomLevel != zoomLevel){
  54970. this._zoomLevel = zoomLevel;
  54971. //this.dispatchEvent('zoomLevelChange',zoomLevel)
  54972. //if(this.name == 'map')console.log(zoomLevel,viewer.mapViewer.camera.zoom)
  54973. }
  54974. }
  54975. updateObjectGroup(){
  54976. this.position && this.objectGroup.position.copy(this.position),
  54977. this.quaternion && this.objectGroup.quaternion.copy(this.quaternion),
  54978. this.objectGroup.updateMatrixWorld(!0);
  54979. }
  54980. updateProjection(){
  54981. //this.transformMapToLocal || (this.transformMapToLocal = this.TransformService.getTransform(this.projection, this.TransformService.crsLocal))
  54982. if(!this.transformMapToLocal){
  54983. if(proj4.defs("NAVVIS:TMERC")){
  54984. if(this.projection == "EPSG:4550"){
  54985. this.transformMapToLocal = {
  54986. forward:(e)=>{
  54987. var a = viewer.transform.lonlatTo4550.inverse(e);
  54988. return viewer.transform.lonlatToLocal.forward(a)
  54989. },
  54990. };
  54991. }else {
  54992. this.transformMapToLocal = proj4(this.projection, "NAVVIS:TMERC");
  54993. }
  54994. //this.transformMapToLocal = proj4(this.projection, "NAVVIS:TMERC")
  54995. }
  54996. }
  54997. }
  54998. setEnable(enable){//add
  54999. if(!this.disabled == enable)return
  55000. if(enable){
  55001. console.log('setEnable',true);
  55002. }
  55003. this.disabled = !enable;
  55004. viewer.updateVisible(this.objectGroup, 'setEnable', enable);
  55005. if(!enable){
  55006. this.baseTile.remove();
  55007. }else {
  55008. this.mapLayer.needUpdate = true;
  55009. }
  55010. this.mapLayer.viewer.dispatchEvent({
  55011. type:'content_changed'
  55012. });
  55013. }
  55014. /* clearProjection(){
  55015. this.transformMapToLocal = void 0,
  55016. this.projection.name !== this.TransformService.NAVVIS_LOCAL && this.baseTile.remove()
  55017. } */
  55018. update(e, n){
  55019. var unavailable = (this.disabled || !this.objectGroup.visible);//地图即使不显示也要获得zoomlevel
  55020. if(this.name != 'map' && unavailable)return
  55021. this.updateProjection();
  55022. if(!this.transformMapToLocal)return
  55023. if (!this.isTileVisible(new Vector3(0,0,0), this.mapSizeM, e))
  55024. return this.removeFromSceneGroup(n), !0;
  55025. let viewport = this.mapLayer.viewport;
  55026. var i = new Vector3(-.5 * this.mapSizeM,0,0);
  55027. i.applyMatrix4(this.objectGroup.matrixWorld),
  55028. i.project(viewport.camera);
  55029. var o = new Vector3(.5 * this.mapSizeM,0,0);
  55030. o.applyMatrix4(this.objectGroup.matrixWorld),
  55031. o.project(viewport.camera);
  55032. var a = viewport.resolution.x
  55033. , s = viewport.resolution.y;
  55034. if (a <= 0 || s <= 0 || isNaN(i.x) || isNaN(o.x)) return !1;
  55035. i.sub(o),
  55036. i.x *= a / 2,
  55037. i.y *= s / 2;
  55038. var c = this.tileSizePx / i.length()
  55039. , level = Math.ceil(-Math.log(c) / Math.log(2) - this.bias);
  55040. level = Math.max(level, 0);
  55041. level = Math.min(level, void 0 === this.maxDepth ? 1 / 0 : this.maxDepth);
  55042. this.zoomLevel = level;//add
  55043. //console.log(level)
  55044. if(!unavailable){
  55045. this.addToSceneGroup(n);
  55046. return this.baseTile.update(this, e, level, this.mapSizeM, 0, 0, "")
  55047. }
  55048. }
  55049. isTileVisible(e, n, i){
  55050. if (n > HALF_WORLD_SIZE) return !0;
  55051. var r = .5 * n;
  55052. this.transformMapToLocal.forward(e);
  55053. this.isTileVisibleBox.makeEmpty();
  55054. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55055. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55056. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55057. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55058. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55059. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55060. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55061. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55062. return i.intersectsBox(this.isTileVisibleBox)
  55063. }
  55064. addToSceneGroup(t){
  55065. this.objectGroupAdded || (t.add(this.objectGroup),
  55066. this.objectGroupAdded = !0);
  55067. }
  55068. removeFromSceneGroup(t){
  55069. this.baseTile.remove(),
  55070. this.objectGroupAdded && (t.remove(this.objectGroup),
  55071. this.objectGroupAdded = !1);
  55072. }
  55073. }
  55074. class MapTile{
  55075. constructor(map,/* t, */ e, n){
  55076. this.map = map;
  55077. //this.mapLayer = t,
  55078. this.objectGroup = e,
  55079. this.tileColor = n,
  55080. this.meshAdded = !1,
  55081. this.textureLoaded = !1,
  55082. this.children = [];
  55083. }
  55084. update(e, n, i, r, o, a, s){
  55085. return !!this.doesNotContainTilesToBeDisplayed(e) || (0 === i ? this.updateTile(e, r, o, a) : this.updateSubTiles(e, n, i, r, o, a, s))
  55086. }
  55087. doesNotContainTilesToBeDisplayed(t){
  55088. return t.tilePresenceMap && t.tilePresenceMap.empty
  55089. }
  55090. updateTile(t, e, n, i){
  55091. if(!this.mesh){
  55092. this.createTileObject(t, e, n, i);
  55093. }
  55094. if(!this.meshAdded){
  55095. this.objectGroup.add(this.mesh);
  55096. this.meshAdded = !0;
  55097. }
  55098. if(this.textureLoaded){
  55099. this.removeChildren();
  55100. }
  55101. return this.textureLoaded
  55102. }
  55103. updateSubTiles(entity, n, level, o, a, s, c){
  55104. for (var l = !0, u = [-.25 * o, .25 * o, -.25 * o, .25 * o], d = [.25 * o, .25 * o, -.25 * o, -.25 * o], p = 0; p < 4; ++p){
  55105. var h = c + p.toString(10);
  55106. //一级(512):0 1 2 3分别为左上、右上、左下、右下。二级(1024)就是把一级的每一块分裂,如00 01 02 03分别是0的左上、右上、左下、右下……
  55107. /* if(entity.name == 'floorplan'){
  55108. console.log(1)
  55109. } */
  55110. if (!entity.tilePresenceMap || entity.tilePresenceMap[h]){
  55111. //去掉判断,直接显示
  55112. var f = a + u[p]
  55113. , m = s + d[p];
  55114. tempVector.set(f, m, 0);
  55115. if (entity.isTileVisible(tempVector, .5 * o, n)){
  55116. this.children[p] || (this.children[p] = new MapTile(this.map, this.objectGroup,this.tileColor));
  55117. l = this.children[p].update(entity, n, level - 1, .5 * o, f, m, h) && l;
  55118. } else {
  55119. if (this.children[p]){
  55120. this.children[p].remove();
  55121. delete this.children[p];
  55122. }
  55123. }
  55124. }
  55125. }
  55126. return l && this.removeObject3D(),
  55127. l
  55128. }
  55129. createTileObject(t, e, n, a){
  55130. var s = this;
  55131. this.mesh = this.createMesh(t.transformMapToLocal, e, n, a),
  55132. this.textureLoaded = !1;
  55133. var c = t.mapSizeM / e
  55134. , l = Math.log(c) / Math.log(2)
  55135. , u = n / e + .5 * (c - 1)
  55136. , d = -a / e + .5 * (c - 1)
  55137. , p = t.getTileUrl(Math.round(l), Math.round(u), Math.round(d));
  55138. viewer.setObjectLayers(this.mesh, 'map' );
  55139. this.mesh.renderOrder = -(1e6 - l - 100 * (t.zIndex || 0));
  55140. var h = this.mesh.material;
  55141. var loadDone = ()=>{
  55142. this.map.mapLayer.loadingInProgress--;
  55143. if(this.map.mapLayer.loadingInProgress == 0){
  55144. this.map.mapLayer.dispatchEvent('loadDone');
  55145. }
  55146. };
  55147. h.map = texLoader$1.load(p, (tex)=>{
  55148. if(this.mesh){//如果还要显示的话
  55149. this.textureLoaded = true;
  55150. this.mesh.material.opacity = 1;
  55151. //this.mapLayer.view.invalidateScene()
  55152. this.map.mapLayer.viewer.dispatchEvent({
  55153. type:'content_changed'
  55154. });
  55155. this.map.mapLayer.needUpdate = true; //表示还要继续update(以removeChildren)
  55156. }else {
  55157. tex.dispose();
  55158. }
  55159. loadDone();
  55160. } , void 0, (()=>{//error
  55161. this.textureLoaded = !0;
  55162. if(this.mesh){
  55163. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh)
  55164. this.mesh.material = errorMaterial;
  55165. //this.map.mapLayer.view.invalidateScene())
  55166. this.map.mapLayer.viewer.dispatchEvent({
  55167. type:'content_changed'
  55168. });
  55169. }
  55170. loadDone();
  55171. }));
  55172. h.map.anisotropy = 0,
  55173. h.map.generateMipmaps = !1,
  55174. h.map.minFilter = LinearFilter,
  55175. h.map.magFilter = LinearFilter,
  55176. this.map.mapLayer.loadingInProgress++;
  55177. }
  55178. createMesh(t, e, n, o){
  55179. var a = new Geometry;
  55180. return tempVector.set(n - e / 2, o - e / 2, 0),
  55181. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55182. tempVector.set(n + e / 2, o - e / 2, 0),
  55183. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55184. tempVector.set(n + e / 2, o + e / 2, 0),
  55185. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55186. tempVector.set(n - e / 2, o + e / 2, 0),
  55187. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55188. a.faces.push(face1),
  55189. a.faces.push(face2),
  55190. a.faceVertexUvs[0].push(face1UV),
  55191. a.faceVertexUvs[0].push(face2UV),
  55192. new Mesh(a,this.createMaterial())
  55193. }
  55194. createMaterial(){
  55195. var t = new MeshBasicMaterial({
  55196. transparent: !0,
  55197. depthWrite: !1,
  55198. depthTest: !0,
  55199. opacity: 0,
  55200. side: DoubleSide
  55201. });
  55202. return t.color = this.tileColor ? this.tileColor : new Color(16777215),
  55203. t
  55204. }
  55205. remove(){
  55206. this.removeObject3D(),
  55207. this.removeChildren();
  55208. }
  55209. removeObject3D(){
  55210. if (this.mesh){
  55211. if (this.objectGroup.remove(this.mesh),
  55212. this.textureLoaded){
  55213. var t = this.mesh.material.map;
  55214. t && t.dispose();
  55215. }
  55216. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh),
  55217. this.mesh.geometry.dispose();
  55218. this.mesh = void 0;
  55219. }
  55220. this.meshAdded = !1,
  55221. this.textureLoaded = !1;
  55222. }
  55223. removeChildren(){
  55224. for (var t = 0, e = this.children; t < e.length; t++){
  55225. var n = e[t];
  55226. n && (n.removeObject3D(),
  55227. n.removeChildren());
  55228. }
  55229. this.children.length = 0;
  55230. }
  55231. }
  55232. proj4.defs("EPSG:3857", "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");
  55233. //这里地图世界的中心是不是lon:0,lat:0
  55234. class TiledMapOpenStreetMap extends TiledMapBase{
  55235. constructor(mapLayer, tileColor){
  55236. super('map', mapLayer, tileColor, /* "EPSG:4550" */ "EPSG:3857" ); //EPSG projection
  55237. //this.baseUrl = "https://wprd03.is.autonavi.com/appmaptile?style=7&x=${x}&y=${y}&z=${z}",
  55238. //this.baseUrl = "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}" //最高只到18 level
  55239. this.baseUrl = "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&style=7&x=${x}&y=${y}&z=${z}"; //最高只到19
  55240. this.attribution = "© PopSmart, © 高德地图",
  55241. this.tileSizePx = 256;
  55242. this.mapSizeM = 40075017;
  55243. this.maxDepth = 19;//20
  55244. this.bias = 0.5;
  55245. }
  55246. getTileUrl(t, e, n){
  55247. return this.baseUrl.replace(/\${z}/, t.toString(10)).replace(/\${x}/, e.toString(10)).replace(/\${y}/, n.toString(10))
  55248. }
  55249. fillAttributions(t){
  55250. t[this.attribution] = {
  55251. score: 50
  55252. };
  55253. }
  55254. }
  55255. class TiledMapFromEntity extends TiledMapBase{
  55256. constructor(mapLayer, tileColor, data){
  55257. super('floorplan', mapLayer, tileColor, "NAVVIS:TMERC" /* "EPSG:3857" *//* "WGS84" */); //直接就是本地坐标,没有projec
  55258. let entity = this.tiledMapEntity = this.fillFromData(data);
  55259. let time = entity.updateTime || entity.createTime;
  55260. this.tileSizePx = entity.tileSizePx,
  55261. this.mapSizeM = entity.mapSizeM,
  55262. this.maxDepth = entity.maxDepth;
  55263. this.postStamp = time ? time.replace(/[^0-9]/ig,'') : (new Date).getTime();
  55264. //this.projection = n.crsLocal,
  55265. this.zIndex = 0,
  55266. this.tilePresenceMap = this.decodeBitStream(this.tiledMapEntity.quadtree); //包含tile分裂信息,如果写错了会造成tile显示不全
  55267. }
  55268. fillFromData(e){
  55269. let data = {};
  55270. data.id = e.id;
  55271. data.globalLocation = Potree.Utils.VectorFactory.fromArray3(e.location),
  55272. data.orientation = Potree.Utils.QuaternionFactory.fromArray(e.orientation);
  55273. if(Potree.fileServer){
  55274. data.filePath = `${Potree.settings.urls.prefix}${e.file_path}`;
  55275. }else {
  55276. data.filePath = `${Potree.settings.urls.prefix}/data/${Potree.settings.number}/${e.file_path}`;
  55277. }
  55278. //if(!data.filePath.includes('building_1'))data.filePath = data.filePath.replace('building','building_1')//暂时
  55279. data.fileName = '$DEPTH/$X/$Y.png',//e.file_name,
  55280. data.type = e.type,
  55281. data.mapSizeM = e.map_size_m,
  55282. data.tileSizePx = e.tile_size_px,
  55283. data.maxDepth = e.max_depth,
  55284. data.quadtree = e.quadtree,
  55285. data.floorId = e.floor_id,
  55286. data.bundleId = e.bundle_id;
  55287. //this.computeLocalCoordinates()
  55288. return data
  55289. }
  55290. computeLocalCoordinates(){
  55291. if(proj4.defs("NAVVIS:TMERC")){
  55292. this.tiledMapEntity.location = new Vector3().copy(viewer.transform.lonlatToLocal.forward(this.tiledMapEntity.globalLocation));
  55293. }
  55294. }
  55295. updateProjection() {
  55296. super.updateProjection();
  55297. if(!this.position){
  55298. this.computeLocalCoordinates();
  55299. }
  55300. /* this.projection = this.TransformService.crsLocal,
  55301. t.prototype.updateProjection.call(this) */
  55302. }
  55303. get position(){
  55304. return this.tiledMapEntity.location
  55305. /* enumerable: !0,
  55306. configurable: !0 */
  55307. }
  55308. get quaternion(){
  55309. return this.tiledMapEntity.orientation
  55310. /* enumerable: !0,
  55311. configurable: !0 */
  55312. }
  55313. getTileUrl(t, e, n) {
  55314. var i = (this.tiledMapEntity.filePath + "/" + this.tiledMapEntity.fileName).replace(/\$DEPTH/g, t.toString(10)).replace(/\$X/g, e.toString(10)).replace(/\$Y/g, n.toString(10));
  55315. return i += "?t=" + this.postStamp
  55316. //this.RestService.addAuthorizationQueryParameter(i) //????
  55317. }
  55318. fillAttributions(t) {
  55319. t.NavVis = {
  55320. score: 100
  55321. };
  55322. }
  55323. decodeBitStream(t) {
  55324. if (!t)
  55325. return {
  55326. empty: !0
  55327. };
  55328. for (var e = {}, n = [e], i = 0; i < t.length; i++) {
  55329. var r = n.shift()
  55330. , o = parseInt(t.substr(i, 1), 16);
  55331. if (1 & o) {
  55332. var a = {};
  55333. r[0] = a,
  55334. n.push(a);
  55335. }
  55336. 2 & o && (a = {},
  55337. r[1] = a,
  55338. n.push(a)),
  55339. 4 & o && (a = {},
  55340. r[2] = a,
  55341. n.push(a)),
  55342. 8 & o && (a = {},
  55343. r[3] = a,
  55344. n.push(a));
  55345. }
  55346. var s = {
  55347. empty: !0
  55348. };
  55349. return this.computeHashes(s, e, ""),
  55350. s
  55351. }
  55352. computeHashes(t, e, n) {
  55353. for (var i = 0; i < 4; i++)
  55354. e[i] && (t[n + i.toString(10)] = !0,
  55355. t.empty = !1,
  55356. this.computeHashes(t, e[i], n + i.toString(10)));
  55357. }
  55358. }
  55359. /* {
  55360. "bundle_id": 1, //t-CwfhfqJ
  55361. "file_name": "$DEPTH/$X/$Y.png",
  55362. "file_path": "data/bundle_t-CwfhfqJ/building_1/map_tiles/11",
  55363. "floor_id": 11,
  55364. "id": 1,
  55365. "location": [
  55366. 113.5957510575092,
  55367. 22.366605927999239,
  55368. 0.0
  55369. ],
  55370. "map_size_m": 61.44,
  55371. "max_depth": 3,
  55372. "orientation": [
  55373. 0.7071067811865476,
  55374. 0.0,
  55375. 0.0,
  55376. 0.7071067811865475
  55377. ],
  55378. "quadtree": "fe5f7c7fcffff7f53",
  55379. "sceneCode": "t-CwfhfqJ",
  55380. "tile_size_px": 256,
  55381. "type": "TILED_PYRAMID"
  55382. }
  55383. */
  55384. var MathLight = {};
  55385. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  55386. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  55387. MathLight.Vector3 = function(e, t, i) {
  55388. this.x = e || 0,
  55389. this.y = t || 0,
  55390. this.z = i || 0;
  55391. };
  55392. MathLight.Matrix4 = function() {
  55393. this.elements = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
  55394. arguments.length > 0 && console.error("MathLight.Matrix4: the constructor no longer reads arguments. use .set() instead.");
  55395. };
  55396. MathLight.Matrix4.prototype = {
  55397. identity: function() {
  55398. return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
  55399. this
  55400. },
  55401. copy: function(e) {
  55402. return this.elements.set(e.elements),
  55403. this
  55404. },
  55405. applyToVector3: function(e) {
  55406. var t = e.x
  55407. , i = e.y
  55408. , n = e.z
  55409. , r = this.elements;
  55410. return e.x = r[0] * t + r[4] * i + r[8] * n + r[12],
  55411. e.y = r[1] * t + r[5] * i + r[9] * n + r[13],
  55412. e.z = r[2] * t + r[6] * i + r[10] * n + r[14],
  55413. this
  55414. },
  55415. getInverse: function(e, t) {
  55416. var i = this.elements
  55417. , n = e.elements
  55418. , r = n[0]
  55419. , o = n[1]
  55420. , a = n[2]
  55421. , s = n[3]
  55422. , l = n[4]
  55423. , c = n[5]
  55424. , h = n[6]
  55425. , u = n[7]
  55426. , d = n[8]
  55427. , p = n[9]
  55428. , f = n[10]
  55429. , g = n[11]
  55430. , m = n[12]
  55431. , v = n[13]
  55432. , A = n[14]
  55433. , y = n[15]
  55434. , C = p * A * u - v * f * u + v * h * g - c * A * g - p * h * y + c * f * y
  55435. , I = m * f * u - d * A * u - m * h * g + l * A * g + d * h * y - l * f * y
  55436. , E = d * v * u - m * p * u + m * c * g - l * v * g - d * c * y + l * p * y
  55437. , b = m * p * h - d * v * h - m * c * f + l * v * f + d * c * A - l * p * A
  55438. , w = r * C + o * I + a * E + s * b;
  55439. if (0 === w) {
  55440. var _ = "MathLight.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  55441. if (t)
  55442. throw new Error(_);
  55443. return console.warn(_),
  55444. this.identity()
  55445. }
  55446. var T = 1 / w;
  55447. return i[0] = C * T,
  55448. i[1] = (v * f * s - p * A * s - v * a * g + o * A * g + p * a * y - o * f * y) * T,
  55449. i[2] = (c * A * s - v * h * s + v * a * u - o * A * u - c * a * y + o * h * y) * T,
  55450. i[3] = (p * h * s - c * f * s - p * a * u + o * f * u + c * a * g - o * h * g) * T,
  55451. i[4] = I * T,
  55452. i[5] = (d * A * s - m * f * s + m * a * g - r * A * g - d * a * y + r * f * y) * T,
  55453. i[6] = (m * h * s - l * A * s - m * a * u + r * A * u + l * a * y - r * h * y) * T,
  55454. i[7] = (l * f * s - d * h * s + d * a * u - r * f * u - l * a * g + r * h * g) * T,
  55455. i[8] = E * T,
  55456. i[9] = (m * p * s - d * v * s - m * o * g + r * v * g + d * o * y - r * p * y) * T,
  55457. i[10] = (l * v * s - m * c * s + m * o * u - r * v * u - l * o * y + r * c * y) * T,
  55458. i[11] = (d * c * s - l * p * s - d * o * u + r * p * u + l * o * g - r * c * g) * T,
  55459. i[12] = b * T,
  55460. i[13] = (d * v * a - m * p * a + m * o * f - r * v * f - d * o * A + r * p * A) * T,
  55461. i[14] = (m * c * a - l * v * a - m * o * h + r * v * h + l * o * A - r * c * A) * T,
  55462. i[15] = (l * p * a - d * c * a + d * o * h - r * p * h - l * o * f + r * c * f) * T,
  55463. this
  55464. },
  55465. makeRotationFromQuaternion: function(e) {
  55466. var t = this.elements
  55467. , i = e.x
  55468. , n = e.y
  55469. , r = e.z
  55470. , o = e.w
  55471. , a = i + i
  55472. , s = n + n
  55473. , l = r + r
  55474. , c = i * a
  55475. , h = i * s
  55476. , u = i * l
  55477. , d = n * s
  55478. , p = n * l
  55479. , f = r * l
  55480. , g = o * a
  55481. , m = o * s
  55482. , v = o * l;
  55483. return t[0] = 1 - (d + f),
  55484. t[4] = h - v,
  55485. t[8] = u + m,
  55486. t[1] = h + v,
  55487. t[5] = 1 - (c + f),
  55488. t[9] = p - g,
  55489. t[2] = u - m,
  55490. t[6] = p + g,
  55491. t[10] = 1 - (c + d),
  55492. t[3] = 0,
  55493. t[7] = 0,
  55494. t[11] = 0,
  55495. t[12] = 0,
  55496. t[13] = 0,
  55497. t[14] = 0,
  55498. t[15] = 1,
  55499. this
  55500. }
  55501. };
  55502. MathLight.Quaternion = function(e, t, i, n) {
  55503. this._x = e || 0,
  55504. this._y = t || 0,
  55505. this._z = i || 0,
  55506. this._w = void 0 !== n ? n : 1;
  55507. };
  55508. MathLight.Quaternion.prototype = {
  55509. get x() {
  55510. return this._x
  55511. },
  55512. set x(e) {
  55513. this._x = e;
  55514. },
  55515. get y() {
  55516. return this._y
  55517. },
  55518. set y(e) {
  55519. this._y = e;
  55520. },
  55521. get z() {
  55522. return this._z
  55523. },
  55524. set z(e) {
  55525. this._z = e;
  55526. },
  55527. get w() {
  55528. return this._w
  55529. },
  55530. set w(e) {
  55531. this._w = e;
  55532. },
  55533. copy: function(e) {
  55534. this._x = e.x,
  55535. this._y = e.y,
  55536. this._z = e.z,
  55537. this._w = e.w;
  55538. },
  55539. inverse: function() {
  55540. return this.conjugate().normalize()
  55541. },
  55542. conjugate: function() {
  55543. return this._x *= -1,
  55544. this._y *= -1,
  55545. this._z *= -1,
  55546. this
  55547. },
  55548. length: function() {
  55549. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
  55550. },
  55551. normalize: function() {
  55552. var e = this.length();
  55553. return 0 === e ? (this._x = 0,
  55554. this._y = 0,
  55555. this._z = 0,
  55556. this._w = 1) : (e = 1 / e,
  55557. this._x = this._x * e,
  55558. this._y = this._y * e,
  55559. this._z = this._z * e,
  55560. this._w = this._w * e),
  55561. this
  55562. },
  55563. setFromAxisAngle: function(e, t) {
  55564. var i = t / 2
  55565. , n = Math.sin(i);
  55566. return this._x = e.x * n,
  55567. this._y = e.y * n,
  55568. this._z = e.z * n,
  55569. this._w = Math.cos(i),
  55570. this
  55571. },
  55572. setFromUnitVectors: function() {
  55573. var e, t, i = 1e-6;
  55574. return function(n, o) {
  55575. return void 0 === e && (e = new MathLight.Vector3),
  55576. t = MathLight.dot(n, o) + 1,
  55577. t < i ? (t = 0,
  55578. Math.abs(n.x) > Math.abs(n.z) ? MathLight.setVector(e, -n.y, n.x, 0) : MathLight.setVector(e, 0, -n.z, n.y)) : MathLight.cross(n, o, e),
  55579. this._x = e.x,
  55580. this._y = e.y,
  55581. this._z = e.z,
  55582. this._w = t,
  55583. this.normalize()
  55584. }
  55585. }(),
  55586. multiply: function(e) {
  55587. return this.multiplyQuaternions(this, e)
  55588. },
  55589. premultiply: function(e) {
  55590. return this.multiplyQuaternions(e, this)
  55591. },
  55592. multiplyQuaternions: function(e, t) {
  55593. var i = e._x
  55594. , n = e._y
  55595. , r = e._z
  55596. , o = e._w
  55597. , a = t._x
  55598. , s = t._y
  55599. , l = t._z
  55600. , c = t._w;
  55601. return this._x = i * c + o * a + n * l - r * s,
  55602. this._y = n * c + o * s + r * a - i * l,
  55603. this._z = r * c + o * l + i * s - n * a,
  55604. this._w = o * c - i * a - n * s - r * l,
  55605. this
  55606. }
  55607. };
  55608. MathLight.convertWorkshopVector = function(e) {
  55609. return new MathLight.Vector3(-e.x,e.y,e.z)
  55610. };
  55611. MathLight.convertWorkshopQuaternion = function(e) {
  55612. return new MathLight.Quaternion(-e.x,e.y,e.z,-e.w).multiply(new MathLight.Quaternion(Math.sqrt(2) / 2,Math.sqrt(2) / 2,0,0))
  55613. };
  55614. MathLight.convertWorkshopOrthoZoom = function(e) {
  55615. //return e === -1 ? -1 : e / 16 * ($('#player').width() / $('#player').height()) / n.workshopApsect
  55616. return e === -1 ? -1 : e * ($("#player").width() / $("#player").height()) ;
  55617. };
  55618. MathLight.convertWorkshopPanoramaQuaternion = function(e) {
  55619. return new MathLight.Quaternion(e.x,-e.y,-e.z,e.w).normalize().multiply((new MathLight.Quaternion).setFromAxisAngle(new MathLight.Vector3(0,1,0), 270 * MathLight.RADIANS_PER_DEGREE))
  55620. };
  55621. MathLight.normalize = function(e) {
  55622. var t = e.x * e.x + e.y * e.y + e.z * e.z
  55623. , i = Math.sqrt(t);
  55624. e.x /= i,
  55625. e.y /= i,
  55626. e.z /= i;
  55627. };
  55628. MathLight.dot = function(e, t) {
  55629. return e.x * t.x + e.y * t.y + e.z * t.z
  55630. };
  55631. MathLight.cross = function(e, t, i) {
  55632. var n = e.x
  55633. , r = e.y
  55634. , o = e.z;
  55635. i.x = r * t.z - o * t.y,
  55636. i.y = o * t.x - n * t.z,
  55637. i.z = n * t.y - r * t.x;
  55638. };
  55639. MathLight.setVector = function(e, t, i, n) {
  55640. e.x = t,
  55641. e.y = i,
  55642. e.z = n;
  55643. };
  55644. MathLight.copyVector = function(e, t) {
  55645. t.x = e.x,
  55646. t.y = e.y,
  55647. t.z = e.z;
  55648. };
  55649. MathLight.addVector = function(e, t) {
  55650. e.x += t.x,
  55651. e.y += t.y,
  55652. e.z += t.z;
  55653. };
  55654. MathLight.subVector = function(e, t) {
  55655. e.x -= t.x,
  55656. e.y -= t.y,
  55657. e.z -= t.z;
  55658. };
  55659. MathLight.applyQuaternionToVector = function(e, t) {
  55660. var i = t.x
  55661. , n = t.y
  55662. , r = t.z
  55663. , o = e.x
  55664. , a = e.y
  55665. , s = e.z
  55666. , l = e.w
  55667. , c = l * i + a * r - s * n
  55668. , h = l * n + s * i - o * r
  55669. , u = l * r + o * n - a * i
  55670. , d = -o * i - a * n - s * r;
  55671. t.x = c * l + d * -o + h * -s - u * -a,
  55672. t.y = h * l + d * -a + u * -o - c * -s,
  55673. t.z = u * l + d * -s + c * -a - h * -o;
  55674. };
  55675. MathLight.angleBetweenVectors = function(e, t) {
  55676. return Math.acos(MathLight.dot(e, t))
  55677. };
  55678. var cameraLight = {
  55679. clampVFOV: function(currentFov, maxHFov, width, height) {//限制currentFov, 使之造成的横向fov不大于指定值maxHFov
  55680. var r = cameraLight.getHFOVFromVFOV(currentFov, width, height);
  55681. return r > maxHFov ? cameraLight.getVFOVFromHFOV(maxHFov, width, height) : currentFov
  55682. },
  55683. getHFOVForCamera: function(camera, getRad) {
  55684. return cameraLight.getHFOVByScreenPrecent(camera.fov, camera.aspect, getRad)
  55685. },
  55686. //add
  55687. getHFOVByScreenPrecent: function(fov, percent, getRad) { //当fov为占比百分百时,percent代表在屏幕上从中心到边缘的占比
  55688. let rad = 2 * Math.atan(percent * Math.tan(fov * MathLight.RADIANS_PER_DEGREE / 2));
  55689. if(getRad)return rad
  55690. else return rad * MathLight.DEGREES_PER_RADIAN;
  55691. }
  55692. };
  55693. /**
  55694. * @author mschuetz / http://mschuetz.at
  55695. *
  55696. * adapted from THREE.OrbitControls by
  55697. *
  55698. * @author qiao / https://github.com/qiao
  55699. * @author mrdoob / http://mrdoob.com
  55700. * @author alteredq / http://alteredqualia.com/
  55701. * @author WestLangley / http://github.com/WestLangley
  55702. * @author erich666 / http://erichaines.com
  55703. *
  55704. *
  55705. *
  55706. */
  55707. class FirstPersonControls extends EventDispatcher {
  55708. constructor (viewer, viewport) {
  55709. super();
  55710. this.viewer = viewer;
  55711. this.renderer = viewer.renderer;
  55712. this.scene = viewer.scene;
  55713. this.rotationSpeed = 200;
  55714. this.moveSpeed = 10;
  55715. this.setCurrentViewport({hoverViewport:viewport, force:true}); //this.currentViewport = viewport
  55716. this.keys = {
  55717. FORWARD: ['W'.charCodeAt(0), 38],
  55718. BACKWARD: ['S'.charCodeAt(0), 40],
  55719. LEFT: ['A'.charCodeAt(0), 37],
  55720. RIGHT: ['D'.charCodeAt(0), 39],
  55721. UP: ['Q'.charCodeAt(0)],
  55722. DOWN: ['E'.charCodeAt(0)],
  55723. //SHIFT : [16],
  55724. ALT : [18],
  55725. Rotate_LEFT : ['L'.charCodeAt(0)],
  55726. Rotate_RIGHT : ['J'.charCodeAt(0)],
  55727. Rotate_UP : ['K'.charCodeAt(0)],
  55728. Rotate_DOWN : ['I'.charCodeAt(0)],
  55729. };
  55730. this.fadeFactor = 20;
  55731. this.yawDelta = 0;
  55732. this.pitchDelta = 0;
  55733. this.translationDelta = new Vector3(0, 0, 0);
  55734. this.translationWorldDelta = new Vector3(0, 0, 0);
  55735. this.tweens = [];
  55736. this.dollyStart = new Vector2$1;
  55737. this.dollyEnd = new Vector2$1;
  55738. //this.enableChangePos = true
  55739. this.viewer.addEventListener('camera_changed',(e)=>{
  55740. this.setFPCMoveSpeed(e.viewport);
  55741. });
  55742. let drag = (e) => {
  55743. if(!this.enabled)return
  55744. let viewport = e.dragViewport;
  55745. if(!viewport)return
  55746. let camera = viewport.camera;
  55747. let mode;
  55748. if(e.isTouch){
  55749. if(e.touches.length == 1){
  55750. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan';
  55751. }else if(e.touches.length == 2){
  55752. mode = 'scale';
  55753. }else {
  55754. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'pan' : 'scale';
  55755. }
  55756. }else {
  55757. //mode = e.buttons === Buttons.LEFT && (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan'
  55758. mode = e.buttons === Buttons.LEFT && camera.type != 'OrthographicCamera' ? 'rotate' : 'pan';
  55759. }
  55760. //console.log('mode ', mode )
  55761. let moveSpeed = this.currentViewport.getMoveSpeed();
  55762. if (e.drag.startHandled === undefined) {///???????
  55763. e.drag.startHandled = true;
  55764. this.dispatchEvent({type: 'start'});
  55765. }
  55766. if (mode.includes('rotate')) {//旋转
  55767. //来自panoramaControl updateRotation
  55768. if(!this.pointerDragStart){
  55769. return this.pointerDragStart = e.pointer.clone()
  55770. }
  55771. let view = this.scene.view;
  55772. if(Potree.settings.rotAroundPoint && this.intersectStart && this.canMovePos(viewport) && !viewer.images360.isAtPano() && !this.viewer.inputHandler.pressedKeys[17]){//定点旋转: 以当前intersect的点为target旋转,不改点在屏幕中的位置
  55773. let distance = camera.position.distanceTo(this.intersectStart.location); //不按下ctrl的话
  55774. //按照orbitControl的方式旋转:
  55775. let rotationSpeed = 2.5;
  55776. this.yawDelta -= e.drag.pointerDelta.x * rotationSpeed;
  55777. this.pitchDelta += e.drag.pointerDelta.y * rotationSpeed;
  55778. //先更新一下相机:
  55779. this.update();
  55780. view.applyToCamera(camera);
  55781. //然后得到新的相机角度下,原先点在屏幕中的位置所对应的3d点现在的坐标。只需要平移一下新旧坐标差值即可。
  55782. let newPointerDir = viewer.inputHandler.getMouseDirection(this.intersectStart.pointer).direction.clone().multiplyScalar(distance);
  55783. let pivot = new Vector3().addVectors(camera.position, newPointerDir); //新的3d点
  55784. let moveVec = new Vector3().subVectors(pivot, this.intersectStart.location);
  55785. this.translationWorldDelta.copy(moveVec.negate());
  55786. //立即更新下,防止因update和此drag频率不同而打滑。
  55787. this.update();
  55788. view.applyToCamera(camera);
  55789. }else {
  55790. let _matrixWorld = camera.matrixWorld;
  55791. camera.matrixWorld = new Matrix4;//unproject 前先把相机置于原点
  55792. var e1 = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y,-1).unproject(camera)
  55793. , t = new Vector3(e.pointer.x,e.pointer.y,-1).unproject(camera)
  55794. , i = Math.sqrt(e1.x * e1.x + e1.z * e1.z)
  55795. , n = Math.sqrt(t.x * t.x + t.z * t.z)
  55796. , o = Math.atan2(e1.y, i)
  55797. , a = Math.atan2(t.y, n);
  55798. this.pitchDelta += o - a; //上下旋转
  55799. e1.y = 0,
  55800. t.y = 0;
  55801. var s = Math.acos(e1.dot(t) / e1.length() / t.length());
  55802. if(!isNaN(s)){
  55803. var yawDelta = s; //左右旋转
  55804. this.pointerDragStart.x > e.pointer.x && (yawDelta *= -1);
  55805. this.yawDelta += yawDelta;
  55806. }
  55807. //console.log('rotate:', this.pitchDelta, e.pointer.toArray(), this.pointerDragStart.toArray())
  55808. this.pointerDragStart.copy(e.pointer);
  55809. camera.matrixWorld = _matrixWorld ;
  55810. }
  55811. }
  55812. if (mode.includes('pan')) {//平移
  55813. if(!this.canMovePos(viewport)){
  55814. return
  55815. }
  55816. if(camera.type == "OrthographicCamera"){
  55817. //console.log(e.drag.pointerDelta, e.pointer, e.drag.end)
  55818. let moveVec = Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, camera );//最近一次移动向量
  55819. let pointclouds;
  55820. let Alignment = window.viewer.modules.Alignment;
  55821. let MergeEditor = window.viewer.modules.MergeEditor;
  55822. let handleState = Alignment.handleState;
  55823. let a = e.buttons === Buttons.LEFT && viewport.alignment && handleState && viewport.alignment[handleState];
  55824. if(Potree.settings.editType == 'pano'){//右键平移视图、左键操作点云
  55825. let PanoEditor = window.viewer.modules.PanoEditor;
  55826. if(a && PanoEditor.selectedPano){
  55827. if(!PanoEditor.selectedGroup || !PanoEditor.checkIfAllLinked({group:PanoEditor.selectedGroup}) ){
  55828. if(handleState == 'translate' && ( e.drag.intersectStart.pointclouds && Common.getMixedSet(PanoEditor.selectedClouds, e.drag.intersectStart.pointclouds).length || PanoEditor.selectedPano.hovered)//拖拽到点云上 或 circle
  55829. || handleState == 'rotate' )
  55830. {
  55831. pointclouds = PanoEditor.selectedClouds;
  55832. }
  55833. }else {
  55834. PanoEditor.dispatchEvent('needToDisConnect');
  55835. console.warn('选中的漫游点连通了整个数据集,不允许移动');
  55836. }
  55837. }
  55838. if(!pointclouds && e.buttons === Buttons.LEFT && viewport.rotateSide){
  55839. return PanoEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  55840. }
  55841. }else if(Potree.settings.editType == 'merge'){
  55842. if(e.buttons === Buttons.LEFT && viewport.rotateSide){
  55843. return MergeEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  55844. }
  55845. }else {
  55846. /* if(Alignment.selectedClouds && Alignment.selectedClouds.length){
  55847. pointclouds = a && e.drag.intersectStart.pointclouds && Common.getMixedSet(Alignment.selectedClouds, e.drag.intersectStart.pointclouds).length && Alignment.selectedClouds
  55848. }else{ */
  55849. pointclouds = a && e.drag.intersectStart.pointcloud && [e.drag.intersectStart.pointcloud];
  55850. //}
  55851. }
  55852. if(pointclouds){
  55853. this.dispatchEvent({
  55854. type : "transformPointcloud",
  55855. intersect: e.intersect.orthoIntersect,
  55856. intersectStart: e.drag.intersectStart.orthoIntersect,
  55857. moveVec,
  55858. pointclouds,
  55859. camera
  55860. });
  55861. }else {
  55862. this.translationWorldDelta.add(moveVec.negate());
  55863. }
  55864. }else {
  55865. if(e.drag.intersectStart){//如果拖拽着点云
  55866. if(e.drag.z == void 0){//拖拽开始
  55867. let pointerStartPos2d = e.drag.intersectStart.location.clone().project(camera);//识别到的点云点的位置
  55868. e.drag.z = pointerStartPos2d.z; //记录z,保持拖拽物体到屏幕距离不变,所以z深度不变
  55869. e.drag.projectionMatrixInverse = camera.projectionMatrixInverse.clone();
  55870. //防止吸附到最近点上(因为鼠标所在位置并非识别到的点云点的位置,需要得到鼠标所在位置的3d坐标。)
  55871. let pointerStartPos2dReal = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y, e.drag.z);
  55872. e.drag.translateStartPos = pointerStartPos2dReal.clone().unproject(camera);
  55873. /* this.viewer.dispatchEvent({
  55874. type: 'dragPanBegin',
  55875. projectionMatrixInverse : e.drag.projectionMatrixInverse
  55876. }); */
  55877. //console.log('开始拖拽', e.pointer.clone())
  55878. }
  55879. //拖拽的过程中将projectionMatrixInverse替换成开始拖拽时的,因为near、far一直在变,会导致unproject计算出的3d坐标改变很大而闪烁。
  55880. var _projectionMatrixInverse = camera.projectionMatrixInverse;
  55881. camera.projectionMatrixInverse = e.drag.projectionMatrixInverse;
  55882. let newPos2d = new Vector3(e.pointer.x,e.pointer.y, e.drag.z );
  55883. let newPos3d = newPos2d.clone().unproject(camera);
  55884. let moveVec = newPos3d.clone().sub( e.drag.translateStartPos /* e.drag.intersectStart.location */ );//移动相机,保持鼠标下的位置永远不变,所以用鼠标下的新位置减去鼠标下的原始位置
  55885. camera.projectionMatrixInverse = _projectionMatrixInverse;
  55886. this.translationWorldDelta.copy(moveVec.negate()); //这里没法用add,原因未知,会跳动
  55887. //console.log('pan 1', this.translationWorldDelta.clone())
  55888. //四指松开剩三指时会偏移一下,暂不知道哪里的问题,或许跟开头防止点云吸附有关?
  55889. }else { //如果鼠标没有找到和点云的交点,就假设移动整个模型(也可以去扩大范围寻找最近点云)
  55890. /* let center = viewer.scene.pointclouds[0].position;
  55891. let radius = camera.position.distanceTo(center);
  55892. let ratio = radius * Math.tan(THREE.Math.degToRad(camera.fov)/2) / 1000 */
  55893. /* let speed = this.currentViewport.getMoveSpeed()
  55894. if(FirstPersonControls.boundPlane){
  55895. speed = FirstPersonControls.boundPlane.distanceToPoint(this.currentViewport.position)
  55896. speed = Math.max(1 , speed)
  55897. } */
  55898. let lastIntersect = viewport.lastIntersect ? (viewport.lastIntersect.location || viewport.lastIntersect) : viewer.bound.center; //该viewport的最近一次鼠标和点云的交点
  55899. let speed = camera.position.distanceTo(lastIntersect);
  55900. let fov = cameraLight.getHFOVForCamera(camera, true);
  55901. let ratio = speed * Math.tan(fov/2);
  55902. this.translationDelta.x -= e.drag.pointerDelta.x * ratio;
  55903. this.translationDelta.z -= e.drag.pointerDelta.y * ratio;
  55904. //console.log('pan2', e.drag.pointerDelta)
  55905. }
  55906. }
  55907. this.useAttenuation = false;
  55908. }
  55909. if(mode.includes('scale')){
  55910. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  55911. //if(!this.dollyStart)return
  55912. var scale = this.dollyEnd.length() / this.dollyStart.length();
  55913. //console.log('scale ',scale)
  55914. let pointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  55915. dolly({
  55916. pointer,
  55917. scale, camera
  55918. });
  55919. this.dollyStart.copy(this.dollyEnd);
  55920. }
  55921. //最好按ctrl可以变为dollhouse的那种旋转
  55922. };
  55923. let drop = e => {
  55924. if(!this.enabled)return
  55925. this.dispatchEvent({type: 'end'});
  55926. };
  55927. let dolly = (e={})=>{
  55928. if(Potree.settings.displayMode == 'showPanos' && this.currentViewport == viewer.mainViewport/* this.currentViewport.unableChangePos */){//全景时
  55929. this.dispatchEvent({type:'dollyStopCauseUnable',delta:e.delta, scale:e.scale});
  55930. return
  55931. }
  55932. let camera = e.camera;
  55933. if(camera.type == "OrthographicCamera"){
  55934. let ratio;
  55935. if(e.delta != void 0){//滚轮缩放
  55936. if(e.delta == 0){//mac
  55937. return
  55938. }else if (e.delta < 0) {
  55939. ratio = 0.9;
  55940. } else if (e.delta > 0) {
  55941. ratio = 1.1;
  55942. }
  55943. }else {
  55944. ratio = e.scale; //触屏缩放
  55945. }
  55946. let zoom = camera.zoom * ratio;
  55947. let limit = camera.zoomLimit;
  55948. if(limit) zoom = MathUtils.clamp(zoom, limit.min,limit.max );
  55949. let pointerPos = new Vector3(e.pointer.x, e.pointer.y,0.5);
  55950. let oldPos = pointerPos.clone().unproject(camera);
  55951. if(camera.zoom != zoom){
  55952. camera.zoom = zoom;
  55953. camera.updateProjectionMatrix();
  55954. }
  55955. let newPos = pointerPos.clone().unproject(camera);
  55956. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  55957. let moveVec = new Vector3().subVectors(newPos,oldPos);
  55958. this.translationWorldDelta.add(moveVec.negate());
  55959. this.useAttenuation = false;
  55960. }else {
  55961. let speed , direction;
  55962. if(e.delta != void 0){//滚轮缩放
  55963. speed = this.currentViewport.getMoveSpeed() * 15;
  55964. //var direction = this.currentViewport.view.direction.clone();
  55965. direction = this.viewer.inputHandler.getMouseDirection().direction; //定点缩放
  55966. if(e.delta == 0){//mac
  55967. return
  55968. }else if (e.delta < 0) {
  55969. speed *= -1;
  55970. }
  55971. }else {
  55972. const constantDis = this.currentViewport.getMoveSpeed() * 200; //constantDis = 10;//常量系数,当放大一倍时前进的距离。可以调整
  55973. speed = (e.scale-1)*constantDis; //触屏缩放
  55974. //pointer = new THREE.Vector2().addVectors().multiplyScalar(0.5);//两个指头的中心点
  55975. direction = this.viewer.inputHandler.getMouseDirection(e.pointer).direction; //定点缩放
  55976. }
  55977. this.useAttenuation = true;
  55978. var vec = direction.multiplyScalar(speed );
  55979. this.translationWorldDelta.copy(vec);
  55980. }
  55981. };
  55982. let scroll = (e) => {
  55983. if(!this.enabled || !e.hoverViewport)return
  55984. this.setCurrentViewport(e);
  55985. e.camera = e.hoverViewport.camera;
  55986. dolly(e);
  55987. };
  55988. let dblclick = (e) => {
  55989. if(!this.enabled)return
  55990. if(!Potree.settings.dblToFocusPoint)return;//调试时才可双击
  55991. if(Potree.settings.displayMode == 'showPointCloud'/* !viewer.images360.isAtPano() */) this.zoomToLocation(e.mouse);
  55992. };
  55993. this.viewer.addEventListener('global_drag', drag);
  55994. /* this.viewer.addEventListener('global_touchmove', (e)=>{
  55995. if(!this.enabled)return
  55996. if(e.touches.length>1){//单指的就触发上一句
  55997. //console.log('global_touchmove' )
  55998. drag(e)
  55999. }
  56000. }); */
  56001. this.viewer.addEventListener('global_drop', drop);
  56002. this.viewer.addEventListener('global_mousewheel', scroll);
  56003. this.viewer.addEventListener('global_dblclick', dblclick);
  56004. let prepareScale = (e)=>{//触屏的scale
  56005. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  56006. };
  56007. let prepareRotate = (e)=>{
  56008. this.pointerDragStart = e.pointer.clone();
  56009. this.intersectStart = e.intersect && e.intersect.location && {
  56010. location : e.intersect.location,
  56011. pointer : e.intersect.location.clone().project(e.dragViewport.camera) //intersect点在屏幕中的位置
  56012. };
  56013. //console.log('prepareRotate' )
  56014. };
  56015. let preparePan = (e)=>{//触屏的pan点云 还是会偏移
  56016. this.pointerDragStart = e.pointer.clone();
  56017. e.drag.z = void 0; //清空
  56018. drag(e); //触屏点击时更新的pointer直接用一次drag
  56019. //console.log('preparePan ' )
  56020. };
  56021. this.viewer.addEventListener('global_mousedown'/* 'startDragging' */, (e)=>{
  56022. if(!this.enabled)return
  56023. this.setCurrentViewport(e);
  56024. prepareRotate(e);
  56025. });
  56026. //注意,每次增减指头都会修改pointer,需要更新下状态
  56027. this.viewer.addEventListener('global_touchstart', (e)=>{
  56028. if(!this.enabled)return
  56029. if(e.touches.length==2){//只监听开头两个指头
  56030. prepareScale(e);
  56031. }else if(e.touches.length>=3){
  56032. preparePan(e);
  56033. }
  56034. });
  56035. this.viewer.addEventListener('global_touchend', (e)=>{
  56036. if(!this.enabled)return
  56037. if(e.touches.length==2){//停止平移,开始scale
  56038. prepareScale(e);
  56039. }else if(e.touches.length==1){//停止scale,开始rotate
  56040. prepareRotate(e);
  56041. }else if(e.touches.length>=3){//重新准备下平移(因为抬起的指头可能包含平移使用的数据),否则抬起时漂移
  56042. preparePan(e);
  56043. }
  56044. });
  56045. /* this.viewer.addEventListener('enableChangePos', (e)=>{
  56046. if(!this.enabled)return
  56047. this.enableChangePos = e.canLeavePano
  56048. }) */
  56049. }
  56050. canMovePos(viewport){
  56051. if(viewport == viewer.mainViewport && (Potree.settings.displayMode == 'showPanos'
  56052. || viewer.images360.bumping || viewer.images360.latestToPano))return false
  56053. else return true
  56054. }
  56055. setEnable(enabled){
  56056. this.enabled = enabled;
  56057. }
  56058. setFPCMoveSpeed(viewport){
  56059. if(viewport.camera.type == 'OrthographicCamera'){
  56060. let s = 1 / viewport.camera.zoom;
  56061. viewport.setMoveSpeed(s);
  56062. }else {
  56063. if(viewport == viewer.mainViewport && FirstPersonControls.boundPlane){
  56064. let s = FirstPersonControls.boundPlane.distanceToPoint(viewer.mainViewport.view.position);
  56065. s = Math.sqrt(s) / 10;
  56066. s = Math.max(FirstPersonControls.standardSpeed , s);
  56067. s *= Potree.config.moveSpeedAdujust;
  56068. viewer.setMoveSpeed(s);
  56069. }
  56070. }
  56071. }
  56072. setCurrentViewport(o={}){//add
  56073. if(!this.enabled && !o.force )return
  56074. if(o.hoverViewport && this.currentViewport != o.hoverViewport ){
  56075. this.currentViewport = o.hoverViewport;
  56076. //this.viewer.setMoveSpeed(this.currentViewport.radius/100);
  56077. this.setFPCMoveSpeed(this.currentViewport);
  56078. }
  56079. if(this.currentViewport.camera.type == 'OrthographicCamera'){
  56080. this.lockElevationOri = true;
  56081. this.lockRotation = true;
  56082. }else {
  56083. this.lockElevationOri = false;
  56084. this.lockRotation = false;
  56085. }
  56086. }
  56087. setScene (scene) {
  56088. this.scene = scene;
  56089. }
  56090. stop(){
  56091. this.yawDelta = 0;
  56092. this.pitchDelta = 0;
  56093. this.translationDelta.set(0, 0, 0);
  56094. }
  56095. zoomToLocation(mouse){
  56096. if(!this.enabled)return
  56097. let camera = this.scene.getActiveCamera();
  56098. /* let I = Utils.getMousePointCloudIntersection(
  56099. mouse,
  56100. camera,
  56101. this.viewer,
  56102. this.scene.pointclouds); */
  56103. var I = this.viewer.inputHandler.intersect;
  56104. if (!I) {
  56105. return;
  56106. }
  56107. let targetRadius = 0;
  56108. {
  56109. let minimumJumpDistance = 0.2;
  56110. let domElement = this.renderer.domElement;
  56111. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer, camera);
  56112. let {origin, direction} = this.viewer.inputHandler.getMouseDirection();
  56113. let raycaster = new Raycaster();
  56114. raycaster.ray.set(origin, direction);
  56115. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  56116. let nodes2 = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, raycaster.ray);
  56117. let lastNode = nodes[nodes.length - 1];
  56118. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  56119. targetRadius = Math.min(this.scene.view.radius, radius);
  56120. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  56121. }
  56122. let d = this.scene.view.direction.multiplyScalar(-1);
  56123. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  56124. // TODO Unused: let controlsTargetPosition = I.location;
  56125. let animationDuration = 600;
  56126. let easing = TWEEN.Easing.Quartic.Out;
  56127. { // animate
  56128. let value = {x: 0};
  56129. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  56130. tween.easing(easing);
  56131. this.tweens.push(tween);
  56132. let startPos = this.scene.view.position.clone();
  56133. let targetPos = cameraTargetPosition.clone();
  56134. let startRadius = this.scene.view.radius;
  56135. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  56136. tween.onUpdate(() => {
  56137. let t = value.x;
  56138. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  56139. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  56140. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  56141. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  56142. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  56143. });
  56144. tween.onComplete(() => {
  56145. this.tweens = this.tweens.filter(e => e !== tween);
  56146. });
  56147. tween.start();
  56148. }
  56149. }
  56150. update (delta=1) {
  56151. if(!this.enabled)return
  56152. //console.log('update')
  56153. let view = this.currentViewport.view;
  56154. { // cancel move animations on user input
  56155. let changes = [ this.yawDelta,
  56156. this.pitchDelta,
  56157. this.translationDelta.length(),
  56158. this.translationWorldDelta.length() ];
  56159. let changeHappens = changes.some(e => Math.abs(e) > 0.001);
  56160. if (changeHappens && this.tweens.length > 0) {
  56161. this.tweens.forEach(e => e.stop());
  56162. this.tweens = [];
  56163. }
  56164. }
  56165. { // accelerate while input is given
  56166. let ih = this.viewer.inputHandler;
  56167. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  56168. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  56169. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  56170. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  56171. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  56172. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  56173. let rotateLeft = this.keys.Rotate_LEFT.some(e => ih.pressedKeys[e]);
  56174. let rotateRight = this.keys.Rotate_RIGHT.some(e => ih.pressedKeys[e]);
  56175. let rotateUp = this.keys.Rotate_UP.some(e => ih.pressedKeys[e]);
  56176. let rotateDown = this.keys.Rotate_DOWN.some(e => ih.pressedKeys[e]);
  56177. this.lockElevation = this.lockElevationOri || this.keys.ALT.some(e => ih.pressedKeys[e]);
  56178. if(!this.lockRotation){
  56179. if(rotateLeft){
  56180. this.yawDelta -= 0.01;
  56181. }else if(rotateRight){
  56182. this.yawDelta += 0.01;
  56183. }
  56184. if(rotateUp){
  56185. this.pitchDelta -= 0.01;
  56186. }else if(rotateDown){
  56187. this.pitchDelta += 0.01;
  56188. }
  56189. }
  56190. if(this.canMovePos(this.currentViewport) && !this.lockKey){
  56191. if(this.lockElevation){
  56192. let dir = view.direction;
  56193. dir.z = 0;
  56194. dir.normalize();
  56195. if (moveForward && moveBackward) {
  56196. this.translationWorldDelta.set(0, 0, 0);
  56197. } else if (moveForward) {
  56198. this.translationWorldDelta.copy(dir.multiplyScalar(this.currentViewport.getMoveSpeed()));
  56199. } else if (moveBackward) {
  56200. this.translationWorldDelta.copy(dir.multiplyScalar(-this.currentViewport.getMoveSpeed()));
  56201. }
  56202. }else {
  56203. if (moveForward && moveBackward) {
  56204. this.translationDelta.y = 0;
  56205. } else if (moveForward) {
  56206. this.translationDelta.y = this.currentViewport.getMoveSpeed();
  56207. } else if (moveBackward) {
  56208. this.translationDelta.y = -this.currentViewport.getMoveSpeed();
  56209. }
  56210. }
  56211. if (moveLeft && moveRight) {
  56212. this.translationDelta.x = 0;
  56213. } else if (moveLeft) {
  56214. this.translationDelta.x = -this.currentViewport.getMoveSpeed();
  56215. } else if (moveRight) {
  56216. this.translationDelta.x = this.currentViewport.getMoveSpeed();
  56217. }
  56218. if (moveUp && moveDown) {
  56219. this.translationWorldDelta.z = 0;
  56220. } else if (moveUp) {
  56221. this.translationWorldDelta.z = this.currentViewport.getMoveSpeed();
  56222. } else if (moveDown) {
  56223. this.translationWorldDelta.z = -this.currentViewport.getMoveSpeed();
  56224. }
  56225. if(moveUp || moveDown || moveForward || moveBackward){
  56226. this.useAttenuation = false;
  56227. }
  56228. }
  56229. }
  56230. { // apply rotation
  56231. let yaw = view.yaw;
  56232. let pitch = view.pitch;
  56233. yaw += this.yawDelta; /* * delta; */
  56234. pitch += this.pitchDelta;/* * delta; */
  56235. view.yaw = yaw;
  56236. view.pitch = pitch;
  56237. this.yawDelta = 0;
  56238. this.pitchDelta = 0;
  56239. }
  56240. if(this.translationWorldDelta.length()>0) {
  56241. // console.log('translationDelta')
  56242. }
  56243. { // apply translation
  56244. view.translate(
  56245. this.translationDelta.x, /* * delta, */
  56246. this.translationDelta.y, /* * delta, */
  56247. this.translationDelta.z, /* * delta */
  56248. );
  56249. this.translationDelta.set(0,0,0);
  56250. //if(this.translationWorldDelta.length())console.log(translationWorldDelta)
  56251. view.translateWorld(
  56252. this.translationWorldDelta.x /* * delta */,
  56253. this.translationWorldDelta.y /* * delta */,
  56254. this.translationWorldDelta.z /* * delta */
  56255. );
  56256. //this.translationWorldDelta.set(0,0,0)
  56257. }
  56258. { // set view target according to speed
  56259. //view.radius = 1 * this.currentViewport.getMoveSpeed();
  56260. /* if(viewer.bound) view.radius = view.position.distanceTo(viewer.bound.center)
  56261. let speed = view.radius/100;
  56262. this.viewer.setMoveSpeed(speed); */
  56263. //this.setMoveSpeed()
  56264. }
  56265. if(this.useAttenuation){ //只有滚轮缩放时开启
  56266. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  56267. /*this.yawDelta *= attenuation;
  56268. this.pitchDelta *= attenuation;
  56269. this.translationDelta.multiplyScalar(attenuation);*/
  56270. this.translationWorldDelta.multiplyScalar(attenuation);
  56271. }else {
  56272. this.translationWorldDelta.set(0,0,0);
  56273. }
  56274. }
  56275. };
  56276. class Viewport{
  56277. constructor( view, camera, prop={}){//目前不支持换camera
  56278. this.left = prop.left;
  56279. this.bottom = prop.bottom;
  56280. this.width = prop.width;
  56281. this.height = prop.height;
  56282. this.name = prop.name;
  56283. this.view = view;
  56284. this.camera = camera;
  56285. this.active = true;
  56286. this.unableChangePos = false;
  56287. this.noPointcloud;
  56288. //this.keys = [...] firstPersonCtl....
  56289. this.resolution = new Vector2$1;
  56290. this.resolution2 = new Vector2$1;
  56291. this.offset = new Vector2$1; //viewportOffset 范围从0-整个画布的像素
  56292. this.extraEnableLayers = prop.extraEnableLayers || [];//额外可展示的层
  56293. this.cameraLayers = prop.cameraLayers;
  56294. this.pixelRatio = prop.pixelRatio; //如果规定pixelRatio的话要传,这样就覆盖devicePicelRatio, 如magnifier
  56295. }
  56296. clone(){
  56297. return Common.CloneClassObject(this)
  56298. }
  56299. getMoveSpeed(){
  56300. return this.moveSpeed
  56301. }
  56302. setMoveSpeed(e){
  56303. this.moveSpeed = e;
  56304. }
  56305. layersAdd(name){
  56306. this.extraEnableLayers.includes(name) || this.extraEnableLayers.push(name);
  56307. }
  56308. layersRemove(name){
  56309. let index = this.extraEnableLayers.indexOf(name);
  56310. if(index > -1){
  56311. this.extraEnableLayers.splice(index, 1);
  56312. }
  56313. }
  56314. cameraChanged() {
  56315. var copy = ()=>{
  56316. this.previousState = {
  56317. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在this.control时归零了所以不用了吧,用position和qua也一样
  56318. position: this.camera.position.clone(),
  56319. quaternion: this.camera.quaternion.clone()
  56320. };
  56321. };
  56322. let projectionChanged = true;
  56323. let positionChanged = true;
  56324. let quaternionChanged = true;
  56325. let getChanged = ()=>{
  56326. return {
  56327. projectionChanged,positionChanged,quaternionChanged,
  56328. changed:projectionChanged || positionChanged || quaternionChanged
  56329. }
  56330. };
  56331. if (this.previousState){
  56332. projectionChanged = !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix);
  56333. positionChanged = !this.camera.position.equals(this.previousState.position);
  56334. quaternionChanged = !this.camera.quaternion.equals(this.previousState.quaternion);
  56335. }
  56336. copy();
  56337. return getChanged()
  56338. }
  56339. setResolution(w,h, wholeW=0, wholeH=0){
  56340. this.resolution.set(w,h);//是client的width height
  56341. this.resolution2.copy(this.resolution).multiplyScalar(this.pixelRatio || window.devicePixelRatio);
  56342. this.offset.set(wholeW,wholeH).multiply(new Vector2$1(this.left,this.bottom)).multiplyScalar(window.devicePixelRatio);
  56343. }
  56344. }
  56345. /**
  56346. * @author mschuetz / http://mschuetz.at
  56347. *
  56348. *
  56349. */
  56350. class InputHandler extends EventDispatcher {
  56351. constructor (viewer,scene) {
  56352. super();
  56353. this.viewer = viewer;
  56354. this.renderer = viewer.renderer;
  56355. this.domElement = this.renderer.domElement;
  56356. this.enabled = true;
  56357. this.scene = scene;
  56358. this.interactiveScenes = [];
  56359. this.interactiveObjects = new Set();
  56360. this.inputListeners = [];
  56361. this.blacklist = new Set();
  56362. this.drag = null;
  56363. this.mouse = new Vector2$1(0, 0);
  56364. //add:
  56365. this.pointer = new Vector2$1(0, 0); //交互点的屏幕坐标,有别于DOM坐标,在此存放NDC坐标。(NDC,三维常用坐标系,二维坐标,整个屏幕映射范围(-1,1),屏幕中心为原点,+Y朝上,+X朝右)
  56366. this.mouseDownMouse = new Vector2$1(0, 0);
  56367. this.selection = [];
  56368. this.hoveredElements = [];
  56369. this.pressedKeys = {};
  56370. this.wheelDelta = 0;
  56371. this.speed = 1;
  56372. this.logMessages = false;
  56373. if (this.domElement.tabIndex === -1) {
  56374. this.domElement.tabIndex = 2222;
  56375. }
  56376. this.lastPointerUpTime = 0;
  56377. this.touches = [];
  56378. this.hoverViewport = viewer.viewports[0];
  56379. this.domElement.addEventListener('contextmenu', (event) => { event.preventDefault(); }, false);
  56380. this.domElement.addEventListener('click', this.onMouseClick.bind(this), false);
  56381. this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false);
  56382. window.addEventListener('mouseup', this.onMouseUp.bind(this), false);
  56383. this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this), false);
  56384. //add
  56385. /* this.domElement.addEventListener("pointerout", this.onMouseUp.bind(this)),
  56386. this.domElement.addEventListener("pointercancel", this.onMouseUp.bind(this)),
  56387. */
  56388. this.domElement.addEventListener('mousewheel', this.onMouseWheel.bind(this), false);
  56389. this.domElement.addEventListener('DOMMouseScroll', this.onMouseWheel.bind(this), false); // Firefox
  56390. //this.domElement.addEventListener('dblclick', this.onDoubleClick.bind(this)); //因为双击时间间隔是跟随系统的所以不好判断
  56391. this.domElement.addEventListener('keydown', this.onKeyDown.bind(this));
  56392. window.addEventListener('keyup', this.onKeyUp.bind(this));
  56393. //window.addEventListener('focus',()=>{
  56394. window.addEventListener('blur',this.onKeyUp.bind(this)); //add
  56395. this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this));
  56396. this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this));
  56397. this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this));
  56398. {
  56399. this.addEventListener('isMeasuring',(e)=>{
  56400. //console.log('isMeasuring',e.v,e.cause)
  56401. this.isMeasuring = e.v;
  56402. });
  56403. }
  56404. }
  56405. /* addInputListener (listener) {
  56406. this.inputListeners.push(listener);
  56407. }
  56408. removeInputListener (listener) {
  56409. this.inputListeners = this.inputListeners.filter(e => e !== listener);
  56410. }
  56411. getSortedListeners(){
  56412. return this.inputListeners.sort( (a, b) => {
  56413. let ia = (a.importance !== undefined) ? a.importance : 0;
  56414. let ib = (b.importance !== undefined) ? b.importance : 0;
  56415. return ib - ia;
  56416. });
  56417. } */
  56418. //统一跟第一个触碰的viewport相同
  56419. updateTouchesInfo(e){
  56420. var viewport, pointer, camera;
  56421. let oldTouches = this.touches;
  56422. let changedTouches = Array.from(e.changedTouches);
  56423. let touches = Array.from(e.touches);
  56424. this.touches = touches.map(touch=>{
  56425. let touch_ = oldTouches.find(a=>a.touch.identifier == touch.identifier);
  56426. let pointer = touch_ && touch_.pointer; //复制原先的值
  56427. return {
  56428. touch, pointer,
  56429. }
  56430. });
  56431. if(e.touches.length > 0){
  56432. let newTouches = touches.filter(e=>!
  56433. oldTouches.some(a=>a.touch.identifier == e.identifier) && !changedTouches.some(a=>a.identifier == e.identifier)
  56434. ); //从按钮处划过时e.touches中会出现this.touches和changedTouches中都没有的identifier
  56435. if(newTouches.length>0){
  56436. console.warn('has new',newTouches.map(e=>e.identifier));
  56437. }
  56438. newTouches.concat(changedTouches).forEach(touch=>{ //修改changedTouches的
  56439. let touch_ = this.touches.find(a=>a.touch.identifier == touch.identifier);
  56440. if(touch_){
  56441. let a = this.getPointerInViewport(touch.pageX, touch.pageY, this.dragViewport||viewport, new Vector2$1);
  56442. touch_.pointer = a.pointer.clone();
  56443. viewport = a.viewport; camera = a.camera;
  56444. }
  56445. });
  56446. //使用当前touches的平均
  56447. if(e.touches.length > 1){
  56448. let pageX = Common.average(e.touches, "pageX");
  56449. let pageY = Common.average(e.touches, "pageY");
  56450. let a = this.getPointerInViewport(pageX, pageY, viewport, new Vector2$1);
  56451. this.pointer.copy(a.pointer);
  56452. //console.log('updateTouchesInfo', this.pointer.clone())
  56453. }else {
  56454. this.pointer = this.touches[0].pointer.clone(); //更新,使用当前touches中的第一个
  56455. }
  56456. /* if(this.touches.find(e=>!e.pointer)){
  56457. console.error(' touches has no pointer', oldTouches.map(e=>e.touch.identifier),
  56458. Array.from(e.touches).map(e=>e.identifier), Array.from(e.changedTouches).map(e=>e.identifier) )
  56459. } */
  56460. //console.log(this.touches)
  56461. //console.log('更新pointer1',this.pointer.toArray())
  56462. return {viewport, camera/* , pointer:this.pointer */}
  56463. }
  56464. }
  56465. onTouchStart (e) {
  56466. if (this.logMessages) console.log(this.constructor.name + ': onTouchStart');
  56467. e.preventDefault();
  56468. /* if (e.touches.length === 1 || !this.drag) { //!this.drag代表一次性下了两个指头
  56469. let rect = this.domElement.getBoundingClientRect();
  56470. let x = e.touches[0].pageX
  56471. let y = e.touches[0].pageY
  56472. this.dealPointerDown(x,y,e,true)
  56473. }else{
  56474. this.updateTouchesInfo(e)
  56475. this.drag.end.copy(this.pointer)
  56476. } */
  56477. this.dealPointerDown(e,true);
  56478. this.viewer.dispatchEvent($.extend(
  56479. this.getEventDesc(e,true),
  56480. {
  56481. type: 'global_' + e.type,
  56482. changedTouches: e.changedTouches
  56483. }
  56484. ));
  56485. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  56486. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  56487. ) */
  56488. //console.log('')
  56489. }
  56490. onTouchMove (e) {
  56491. if (this.logMessages) console.log(this.constructor.name + ': onTouchMove');
  56492. e.preventDefault();
  56493. /* if (e.touches.length === 1) {
  56494. let rect = this.domElement.getBoundingClientRect();
  56495. let x = e.touches[0].pageX;
  56496. let y = e.touches[0].pageY;
  56497. }else{
  56498. this.updateTouchesInfo(e)
  56499. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end)
  56500. this.drag.end.copy(this.pointer)
  56501. }
  56502. */
  56503. this.dealPointerMove(e, true);
  56504. this.viewer.dispatchEvent($.extend(
  56505. this.getEventDesc(e,true),
  56506. {
  56507. type: 'global_' + e.type,
  56508. changedTouches: e.changedTouches
  56509. }
  56510. ));
  56511. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  56512. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  56513. ) */
  56514. }
  56515. onTouchEnd (e) {
  56516. if (this.logMessages) console.log(this.constructor.name + ': onTouchEnd');
  56517. e.preventDefault();
  56518. //console.log('onTouchEnd')
  56519. this.updateTouchesInfo(e);
  56520. /* if (e.touches.length === 0) {
  56521. let rect = this.domElement.getBoundingClientRect();
  56522. let x = e.changedTouches[0].pageX //万一一次松开两个指头的怎么办
  56523. let y = e.changedTouches[0].pageY
  56524. this.dealPointerUp(x,y,e,true)
  56525. }else {
  56526. this.drag.end.copy(this.pointer)
  56527. } */
  56528. this.dealPointerUp(e,true);
  56529. this.viewer.dispatchEvent($.extend(
  56530. this.getEventDesc(e,true),
  56531. {
  56532. type: 'global_' + e.type,
  56533. }
  56534. ));
  56535. //console.log('touchend length '+e.touches.length, this.touches.length)
  56536. }
  56537. onKeyDown (e) {
  56538. if (this.logMessages) console.log(this.constructor.name + ': onKeyDown');
  56539. // DELETE
  56540. if (e.keyCode === KeyCodes.DELETE && this.selection.length > 0) {
  56541. this.dispatchEvent({
  56542. type: 'delete',
  56543. selection: this.selection
  56544. });
  56545. this.deselectAll();
  56546. }
  56547. this.dispatchEvent({
  56548. type: 'keydown',
  56549. keyCode: e.keyCode,
  56550. event: e
  56551. });
  56552. // for(let l of this.getSortedListeners()){
  56553. // l.dispatchEvent({
  56554. // type: "keydown",
  56555. // keyCode: e.keyCode,
  56556. // event: e
  56557. // });
  56558. // }
  56559. this.pressedKeys[e.keyCode] = true;
  56560. // e.preventDefault();
  56561. }
  56562. onKeyUp (e) {
  56563. if (this.logMessages) console.log(this.constructor.name + ': onKeyUp');
  56564. if(e.keyCode != void 0){
  56565. delete this.pressedKeys[e.keyCode];
  56566. }else {
  56567. this.pressedKeys = {};
  56568. }
  56569. e.preventDefault();
  56570. }
  56571. onDoubleClick (e) {
  56572. if (this.logMessages) console.log(this.constructor.name + ': onDoubleClick');
  56573. let consumed = false;
  56574. for (let hovered of this.hoveredElements) {
  56575. if (hovered._listeners && hovered._listeners['dblclick']) {
  56576. hovered.object.dispatchEvent({
  56577. type: 'dblclick',
  56578. mouse: this.mouse,
  56579. object: hovered.object
  56580. });
  56581. consumed = true;
  56582. break;
  56583. }
  56584. }
  56585. if (!consumed) {
  56586. /* for (let inputListener of this.getSortedListeners()) {
  56587. inputListener. */this.viewer.dispatchEvent({
  56588. type: 'global_dblclick',
  56589. mouse: this.mouse,
  56590. object: null
  56591. });
  56592. //}
  56593. }
  56594. this.needSingleClick = false;//add
  56595. e.preventDefault();
  56596. }
  56597. onMouseClick (e) {
  56598. if (this.logMessages) console.log(this.constructor.name + ': onMouseClick');
  56599. e.preventDefault();
  56600. }
  56601. dealPointerDown(e,isTouch){
  56602. e.preventDefault();
  56603. //重新获取一下pointer, 因点击了浏览器的按钮展开列表时 move回来不会触发onmousemove,所以pointer是旧的
  56604. if(isTouch){
  56605. var { camera, viewport } = this.updateTouchesInfo(e);
  56606. if(this.drag){
  56607. //因为触屏在按下前缺少pointermove所以要更新下
  56608. this.drag.end = this.pointer.clone();
  56609. }
  56610. }else {
  56611. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  56612. }
  56613. this.dragViewport = this.hoverViewport = viewport;
  56614. if(isTouch || !Potree.settings.intersectWhenHover ){
  56615. this.hoveredElements = this.getHoveredElements();
  56616. this.intersect = this.getIntersect(viewport);
  56617. //this.intersect = this.getWholeIntersect()
  56618. }
  56619. if(!viewport)return
  56620. if(!isTouch || e.touches.length == 1){
  56621. let consumed = false;
  56622. let consume = () => { return consumed = true; };
  56623. //if (this.hoveredElements.length === 0) {
  56624. this.viewer.dispatchEvent($.extend(
  56625. this.getEventDesc(e,isTouch),
  56626. {
  56627. type: 'global_mousedown'
  56628. }
  56629. ));
  56630. for(let hovered of this.hoveredElements){
  56631. let object = hovered.object;
  56632. object.dispatchEvent({
  56633. type: 'mousedown',
  56634. viewer: this.viewer,
  56635. consume: consume
  56636. });
  56637. if(consumed){
  56638. break;
  56639. }
  56640. }
  56641. }
  56642. if (!this.drag) {
  56643. let target = (isTouch||e.button == MOUSE.LEFT) && this.hoveredElements.find(el => (//只有左键能拖拽
  56644. el.object._listeners &&
  56645. el.object._listeners['drag'] &&
  56646. el.object._listeners['drag'].length > 0));
  56647. if (target) {
  56648. this.startDragging(target.object, {location: target.point});
  56649. } else {
  56650. this.startDragging(null);
  56651. }
  56652. }
  56653. this.drag.intersectStart = this.intersect;
  56654. this.mouseDownMouse = this.mouse.clone();
  56655. this.pointerDownTime = Date.now();
  56656. }
  56657. onMouseDown (e) {
  56658. if (this.logMessages) console.log(this.constructor.name + ': onMouseDown');
  56659. this.dealPointerDown(e);
  56660. }
  56661. /* getWholeIntersect(hoveredElements, intersectPoint){//add
  56662. hoveredElements = hoveredElements || this.hoveredElements
  56663. intersectPoint = intersectPoint || this.intersectPoint
  56664. if(Potree.settings.intersectOnObjs && hoveredElements[0] && hoveredElements[0].object.isModel){
  56665. return {//模拟点云的intersectPoint的结构写法
  56666. hoveredElement : hoveredElements[0] ,
  56667. location: hoveredElements[0].point,
  56668. point: {normal: hoveredElements[0].face.normal },
  56669. distance: hoveredElements[0].distance,
  56670. object: hoveredElements[0].object
  56671. }
  56672. }else return intersectPoint
  56673. } */
  56674. getEventDesc(e,isTouch){//搜集dispatchEvent要给的一般数据
  56675. let o = {
  56676. viewer: this.viewer,
  56677. mouse: this.mouse,
  56678. pointer:this.pointer,
  56679. drag :this.drag,
  56680. isTouch,
  56681. dragViewport : this.dragViewport,
  56682. hoverViewport: this.hoverViewport,
  56683. // button: isTouch ? 0 : e.button,
  56684. //intersectPoint:this.intersectPoint,
  56685. hoveredElement: this.hoveredElements[0],
  56686. intersect: this.intersect//this.getWholeIntersect() , //可能包含mesh上的,针对融合页面
  56687. };
  56688. if(e){
  56689. o.isAtDomElement = e.target == this.domElement;
  56690. }
  56691. if(isTouch){
  56692. o.touches = this.touches;
  56693. }else if(e){
  56694. o.button = e.button;
  56695. o.buttons = e.buttons;
  56696. }
  56697. return o;
  56698. }
  56699. dealPointerUp(e,isTouch){
  56700. if(!this.drag){// 在canvas外mousedown
  56701. return
  56702. }
  56703. this.drag.end.copy(this.pointer);
  56704. if(isTouch && e.touches.length >= 1){
  56705. return
  56706. }
  56707. let now = Date.now();
  56708. if (this.logMessages) console.log(this.constructor.name + ': onMouseUp');
  56709. e.preventDefault();
  56710. let pressDistance = this.mouseDownMouse.distanceTo(this.mouse);
  56711. let pressTime = now - this.pointerDownTime;
  56712. let noMovement = this.drag.pointerDelta.length() == 0;//this.getNormalizedDrag().length() === 0;
  56713. let consumed = false;
  56714. let consume = () => { return consumed = true; };
  56715. //if (this.hoveredElements.length === 0) {
  56716. /* for (let inputListener of this.getSortedListeners()) {
  56717. inputListener */this.viewer.dispatchEvent($.extend(
  56718. this.getEventDesc(e,isTouch),
  56719. {
  56720. type: 'global_mouseup',
  56721. pressDistance,
  56722. consume,
  56723. }
  56724. ));
  56725. /* if(consumed){//??
  56726. break;
  56727. } */
  56728. //}
  56729. //}
  56730. if (this.hoveredElements.length > 0) {
  56731. let hovered = this.hoveredElements
  56732. .map(e => e.object)
  56733. .find(e => (e._listeners && e._listeners['mouseup']));
  56734. if(hovered){
  56735. hovered.dispatchEvent({
  56736. type: 'mouseup',
  56737. viewer: this.viewer,
  56738. consume: consume
  56739. });
  56740. }
  56741. }
  56742. if (this.drag) {
  56743. //拖拽结束
  56744. if (this.drag.object/* && e.button == THREE.MOUSE.LEFT */) {//add LEFT
  56745. if (this.logMessages) console.log(`${this.constructor.name}: drop ${this.drag.object.name}`);
  56746. this.drag.object.dispatchEvent($.extend(
  56747. this.getEventDesc(e,isTouch),
  56748. {
  56749. type: 'drop',
  56750. pressDistance,
  56751. }
  56752. ));
  56753. } else {
  56754. this.viewer.dispatchEvent($.extend(
  56755. this.getEventDesc(e,isTouch),
  56756. {
  56757. type: 'global_drop',
  56758. pressDistance
  56759. }
  56760. ));
  56761. }
  56762. // check for a click
  56763. if(pressDistance < Potree.config.clickMaxDragDis && pressTime<Potree.config.clickMaxPressTime){
  56764. let clickElement;
  56765. if(this.hoveredElements){
  56766. clickElement = this.hoveredElements.find(e=>e.object._listeners['click']);
  56767. if(clickElement){
  56768. //console.log('clickElement',clickElement)
  56769. if (this.logMessages) console.log(`${this.constructor.name}: click ${clickElement.name}`);
  56770. clickElement.object.dispatchEvent($.extend(
  56771. this.getEventDesc(e,isTouch),
  56772. {
  56773. type: 'click',
  56774. pressDistance
  56775. }
  56776. ));
  56777. }
  56778. }
  56779. let consumed = false;
  56780. let consume = () => { return consumed = true; };
  56781. let desc = this.getEventDesc(e,isTouch);
  56782. //if(!clickElement){
  56783. this.viewer.dispatchEvent($.extend(
  56784. desc,
  56785. {
  56786. type: 'global_click',
  56787. pressDistance,
  56788. clickElement,
  56789. consume
  56790. }
  56791. ));
  56792. //}
  56793. //增加 单击:
  56794. this.needSingleClick = true;
  56795. consumed || setTimeout(()=>{
  56796. if(this.needSingleClick){
  56797. this.viewer.dispatchEvent($.extend(
  56798. desc,
  56799. {
  56800. type: 'global_single_click',
  56801. pressDistance,
  56802. clickElement
  56803. }
  56804. ));
  56805. }
  56806. }, Potree.config.doubleClickTime+1);
  56807. //自行执行双击:
  56808. if(now - this.lastClickTime < Potree.config.doubleClickTime){
  56809. this.onDoubleClick(e);
  56810. }
  56811. this.lastClickTime = now;
  56812. }
  56813. this.drag = null;
  56814. }
  56815. this.dragViewport = null;
  56816. if(!consumed && !this.fixSelection){
  56817. if (e.button === MOUSE.LEFT) {
  56818. if (noMovement) {
  56819. let selectable = this.hoveredElements
  56820. .find(el => el.object._listeners && el.object._listeners['select']);
  56821. if (selectable) {
  56822. selectable = selectable.object;
  56823. if (this.isSelected(selectable)) {
  56824. this.selection
  56825. .filter(e => e !== selectable)
  56826. .forEach(e => this.toggleSelection(e));
  56827. } else {
  56828. this.deselectAll();
  56829. this.toggleSelection(selectable);
  56830. }
  56831. } else {
  56832. this.deselectAll();
  56833. }
  56834. }
  56835. } else if ((e.button === MOUSE.RIGHT) && noMovement) {
  56836. this.deselectAll();
  56837. }
  56838. }
  56839. }
  56840. onMouseUp (e) {
  56841. this.dealPointerUp( e );
  56842. }
  56843. getPointerInViewport(clientX, clientY, viewForceAt, pointer ){
  56844. let rect = this.domElement.getBoundingClientRect();
  56845. let x = clientX - rect.left;
  56846. let y = clientY - rect.top;
  56847. let camera;
  56848. let viewport;
  56849. pointer = pointer ||this.pointer;
  56850. //if(this.viewer.viewports || viewForceAt){
  56851. var getDimension = (view)=>{
  56852. var left = Math.ceil(this.domElement.clientWidth * view.left)
  56853. , bottom = Math.ceil(this.domElement.clientHeight * view.bottom)
  56854. , width = Math.ceil(this.domElement.clientWidth * view.width)
  56855. , height = Math.ceil(this.domElement.clientHeight * view.height)
  56856. , top = this.domElement.clientHeight - bottom - height;
  56857. return {left, bottom, width, height, top}
  56858. };
  56859. var getView = (view, left, bottom, width, height, top)=>{
  56860. this.mouse.set(x-left, y - top );
  56861. Utils.convertScreenPositionToNDC(pointer, this.mouse, width, height);
  56862. //console.log('更新pointer2',this.pointer.toArray())
  56863. camera = view.camera;
  56864. viewport = view;
  56865. };
  56866. if(viewForceAt){
  56867. let {left, bottom, width, height, top} = getDimension(viewForceAt);
  56868. getView(viewForceAt, left, bottom, width, height, top);
  56869. }else {
  56870. var length = this.viewer.viewports.length;
  56871. //var getif = false
  56872. for(var i=0;i<length;i++){
  56873. var view = this.viewer.viewports[i];
  56874. if(!view.active)continue
  56875. var {left, bottom, width, height, top} = getDimension(view);
  56876. if(x >= left && x <= left + width && y >= top && y <= top + height){
  56877. getView(view, left, bottom, width, height, top);
  56878. //getif = true
  56879. break;
  56880. }
  56881. }
  56882. }
  56883. return {
  56884. camera, viewport, pointer
  56885. }
  56886. }
  56887. ifBlockedByIntersect(point, margin=0, usePointcloud, cameraPos, pickWindowSize, pano){//某点是否被遮挡(不允许camera修改位置, 因为depthTex不好置换)
  56888. if(cameraPos){
  56889. usePointcloud = true; //只有使用点云才允许换位置
  56890. }
  56891. let intersect = this.getIntersect(this.hoverViewport, true, pickWindowSize, null, usePointcloud, {point, cameraPos, pano});
  56892. let cameraPos_ = (!usePointcloud && pano) ? pano.position : (cameraPos||this.hoverViewport.view.position);
  56893. if(intersect && intersect.distance+margin <= point.distanceTo(cameraPos_)){
  56894. return intersect //被遮挡
  56895. }
  56896. //点云模式,对没加载出的点云不准确。 尤其是需要修改相机位置时,因临时修改并不能使点云加载。
  56897. }
  56898. getIntersect(viewport, onlyGetIntersect, pickWindowSize, dontIntersect, usePointcloud, prop={}){
  56899. let intersectPoint;
  56900. let camera = viewport.camera;
  56901. let raycaster;
  56902. if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && !usePointcloud && !this.isMeasuring && viewport == viewer.mainViewport ){
  56903. /* if(prop.point){
  56904. raycaster = new THREE.Raycaster()
  56905. var dir = new THREE.Vector3().subVectors(prop.point, camera.position).normalize()
  56906. raycaster.set(camera.position, dir) //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  56907. } */
  56908. let intersect;
  56909. if(prop.point){
  56910. let cameraPos = prop.pano ? prop.pano.position : camera.position;
  56911. let dir = new Vector3().subVectors(prop.point, cameraPos).normalize();
  56912. intersect = {dir};
  56913. }else {
  56914. intersect = Utils.getIntersect(camera, [viewer.images360.cube], this.pointer, raycaster);
  56915. }
  56916. intersectPoint = viewer.images360.depthSampler.sample(intersect, prop.pano, !!prop.point); //可能不准确, 因pano可能未加载depthTex
  56917. }else {
  56918. if(prop.point){
  56919. prop.cameraPos && camera.position.copy(prop.cameraPos);
  56920. camera.lookAt(prop.point);
  56921. camera.updateMatrixWorld();
  56922. prop.pointer = this.pointer.clone();
  56923. prop.mouse = this.mouse.clone();
  56924. this.pointer.set(0,0); //画布中心
  56925. this.mouse.set(Math.round(viewport.resolution.x/2), Math.round(viewport.resolution.y/2));
  56926. }
  56927. intersectPoint = (viewport.noPointcloud || dontIntersect)? null : Utils.getMousePointCloudIntersection(
  56928. viewport,
  56929. this.mouse,
  56930. this.pointer,
  56931. camera,
  56932. this.viewer,
  56933. this.viewer.scene.pointclouds,
  56934. {pickClipped: true, isMeasuring: this.isMeasuring, pickWindowSize, cameraChanged: !!prop.point }
  56935. );
  56936. //恢复
  56937. if(prop.point){
  56938. viewport.view.applyToCamera(camera);
  56939. this.pointer.copy(prop.pointer);
  56940. this.mouse.copy(prop.mouse);
  56941. }
  56942. }
  56943. //console.log(viewport.name , intersectPoint && intersectPoint.location )
  56944. let intersect;
  56945. let intersectOnModel, allElements;
  56946. if(Potree.settings.intersectOnObjs && !dontIntersect){
  56947. if(prop.point){
  56948. raycaster = new Raycaster();
  56949. var dir = new Vector3().subVectors(prop.point, camera.position).normalize();
  56950. raycaster.set(camera.position, dir); //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  56951. }
  56952. allElements = this.getHoveredElements(viewer.objs.children, true, raycaster);
  56953. if(allElements[0]){
  56954. intersectOnModel = {//模拟点云的intersectPoint的结构写法
  56955. hoveredElement : allElements[0] ,
  56956. location: allElements[0].point,
  56957. //point: {normal: allElements[0].face.normal },
  56958. normal: allElements[0].face.normal,
  56959. distance: allElements[0].distance,
  56960. object: allElements[0].object
  56961. };
  56962. }
  56963. }
  56964. if(intersectPoint && intersectOnModel){
  56965. if(intersectPoint.distance < intersectOnModel.distance){
  56966. intersect = intersectPoint;
  56967. }else {
  56968. intersect = intersectOnModel;
  56969. }
  56970. }else {
  56971. intersect = intersectOnModel || intersectPoint;
  56972. }
  56973. if(viewport.camera.type == 'OrthographicCamera'/* == 'mapViewport' */){
  56974. let pos3d = new Vector3(this.pointer.x,this.pointer.y,-1).unproject(viewport.camera); //z:-1朝外
  56975. if(!intersect){
  56976. intersect = {};
  56977. }
  56978. intersect.orthoIntersect = pos3d.clone();
  56979. }
  56980. //记录全部hover到的:
  56981. if(intersect){
  56982. intersect.allElements = allElements;
  56983. intersect.pointclouds = intersectPoint ? intersectPoint.pointclouds : [];
  56984. }
  56985. if(onlyGetIntersect){
  56986. return intersect
  56987. }
  56988. if (intersect) {
  56989. if(viewer.showCoordType){ //显示坐标位置时
  56990. let pos = intersect.point.position.toArray();
  56991. if(viewer.showCoordType == "local"){
  56992. }else if(viewer.showCoordType == "lonlat"){
  56993. pos = viewer.transform.lonlatToLocal.inverse(pos);
  56994. }else {
  56995. pos = viewer.transform.lonlatToLocal.inverse(pos);
  56996. pos = viewer.transform.lonlatTo4550.forward(pos);
  56997. }
  56998. viewer.dispatchEvent({
  56999. type : "coordinateChange", pos
  57000. });
  57001. }
  57002. }
  57003. //console.log('getIntersect', !!intersectPoint)
  57004. this.intersect = intersect;
  57005. intersect && (this.hoverViewport.lastIntersect = intersect);
  57006. return intersect
  57007. }
  57008. onMouseMove (e) {
  57009. return this.dealPointerMove( e )
  57010. }
  57011. dealPointerMove(e, isTouch){
  57012. if(isTouch){
  57013. var { camera, viewport } = this.updateTouchesInfo(e);
  57014. }else {
  57015. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY, this.dragViewport);
  57016. }
  57017. this.hoverViewport = viewport;
  57018. if(!viewport)return//刚变化viewport时会找不到
  57019. let isFlying = this.viewer.viewports.some(e=>e.view.isFlying()) || viewer.scene.cameraAnimations.some(c=>c.onUpdate);
  57020. let intersect;
  57021. if(e.onlyGetIntersect || Potree.settings.intersectWhenHover && (!this.drag || this.drag.object || viewport.alignment ) ){ //没有拖拽物体,但按下鼠标了的话,不intersect
  57022. let dontIntersect = this.drag && viewport.alignment/* && Potree.settings.editType == 'pano' */|| isFlying;/* viewer.images360.flying */ // flying 时可能卡顿
  57023. //console.log('dontIntersectPointcloud',dontIntersectPointcloud)
  57024. intersect = this.getIntersect(viewport, e.onlyGetIntersect, e.pickWindowSize, !!dontIntersect, e.whichPointcloud); //数据集多的时候卡顿
  57025. //console.log('intersectPoint', intersectPoint)
  57026. }
  57027. if(e.onlyGetIntersect){
  57028. /* if(Potree.settings.intersectOnObjs){
  57029. let hoveredElements = this.getHoveredElements() //应该不用发送mouseover事件吧
  57030. let intersect = this.getWholeIntersect(hoveredElements, intersectPoint)
  57031. return intersect
  57032. }
  57033. return intersectPoint */
  57034. return intersect
  57035. }
  57036. e.preventDefault();
  57037. /* if(intersectPoint && intersectPoint.pointcloud){
  57038. console.log(intersectPoint.pointcloud.name)
  57039. } */
  57040. if (this.drag) {//有拖拽(不一定拖拽了物体, 也不一定按下了鼠标)
  57041. this.drag.mouse = isTouch ? 1 : e.buttons;
  57042. //add:
  57043. //this.drag.pointer = this.pointer.clone();
  57044. //this.drag.hoverViewport = this.hoverViewport
  57045. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end);
  57046. this.drag.end.copy(this.pointer);
  57047. if (this.drag.object && (e.buttons == Buttons.NONE || !this.drag.notPressMouse )){//如果是本不需要按鼠标的拖拽,但按下了鼠标,就不执行这段(改为拖拽场景,如添加测量时突然拖拽画面)
  57048. if (this.logMessages) console.log(this.constructor.name + ': drag: ' + this.drag.object.name);
  57049. this.drag.object.dispatchEvent($.extend(
  57050. this.getEventDesc(e,isTouch),
  57051. {
  57052. type: 'drag', //拖拽物体
  57053. }
  57054. ));
  57055. } else {
  57056. if (this.logMessages) console.log(this.constructor.name + ': drag: ');
  57057. let dragConsumed = false;
  57058. this.viewer.dispatchEvent($.extend(
  57059. this.getEventDesc(e,isTouch),
  57060. {
  57061. type: 'global_drag', //拖拽画面
  57062. consume: () => {dragConsumed = true;}
  57063. }
  57064. ));
  57065. }
  57066. }
  57067. if(!isTouch || e.touches.length == 1){
  57068. if((!this.drag || this.drag.notPressMouse || Potree.settings.intersectOnObjs && this.drag.object) && !isFlying){
  57069. /* let blacklist = this.drag && this.drag */
  57070. let hoveredElements = this.getHoveredElements( );
  57071. if(hoveredElements.length > 0){
  57072. let names = hoveredElements.map(h => h.object.name).join(", ");
  57073. if (this.logMessages) console.log(`${this.constructor.name}: onMouseMove; hovered: '${names}'`);
  57074. }
  57075. let curr = hoveredElements.map(a => a.object).find(a => true);//只取第一个
  57076. let prev = this.lastMouseoverElement; //this.hoveredElements.map(a => a.object).find(a => true);
  57077. if(curr !== prev){
  57078. if(curr){
  57079. if (this.logMessages) console.log(`${this.constructor.name}: mouseover: ${curr.name}`);
  57080. curr.dispatchEvent({
  57081. type: 'mouseover',
  57082. object: curr,
  57083. });
  57084. }
  57085. if(prev){
  57086. if (this.logMessages) console.log(`${this.constructor.name}: mouseleave: ${prev.name}`);
  57087. prev.dispatchEvent({
  57088. type: 'mouseleave',
  57089. object: prev,
  57090. });
  57091. }
  57092. this.lastMouseoverElement = curr;
  57093. }
  57094. if(hoveredElements.length > 0){
  57095. let object = hoveredElements
  57096. .map(e => e.object)
  57097. .find(e => (e._listeners && e._listeners['mousemove']));
  57098. if(object){
  57099. object.dispatchEvent({
  57100. type: 'mousemove',
  57101. object: object
  57102. });
  57103. }
  57104. }
  57105. this.hoveredElements = hoveredElements;
  57106. }
  57107. //this.intersect = this.getWholeIntersect()
  57108. this.viewer.dispatchEvent($.extend(
  57109. this.getEventDesc(e,isTouch),
  57110. {
  57111. type: 'global_mousemove',
  57112. }
  57113. ));
  57114. }
  57115. }
  57116. onMouseWheel(e){
  57117. if(!this.enabled) return;
  57118. if(this.logMessages) console.log(this.constructor.name + ": onMouseWheel");
  57119. e.preventDefault();
  57120. let delta = 0;
  57121. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  57122. delta = e.wheelDelta;
  57123. } else if (e.detail !== undefined) { // Firefox
  57124. delta = -e.detail;
  57125. }
  57126. let ndelta = Math.sign(delta);
  57127. // this.wheelDelta += Math.sign(delta);
  57128. if(!this.hoverViewport){//调试手机版时会无
  57129. var { viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  57130. this.hoverViewport = viewport;
  57131. }
  57132. if (this.hoveredElement) {
  57133. this.hoveredElement.object.dispatchEvent($.extend(
  57134. this.getEventDesc(e,isTouch),
  57135. {
  57136. type: 'mousewheel',
  57137. delta: ndelta,
  57138. object: this.hoveredElement.object
  57139. }
  57140. ));
  57141. } else {
  57142. this.viewer.dispatchEvent($.extend(
  57143. this.getEventDesc(e),
  57144. {
  57145. type: 'global_mousewheel',
  57146. delta: ndelta,
  57147. }
  57148. ));
  57149. }
  57150. }
  57151. startDragging (object, args = null) {
  57152. let name = object ? object.name : "no name";
  57153. if (this.logMessages) console.log(`${this.constructor.name}: startDragging: '${name}'`);
  57154. this.drag = {
  57155. start: this.pointer.clone(),
  57156. end: this.pointer.clone(),
  57157. pointerDelta: new Vector2$1(0, 0),
  57158. object: object,
  57159. hoverViewport: this.hoverViewport, //会变化
  57160. dragViewport: this.hoverViewport, //不变
  57161. };
  57162. if (args) {
  57163. for (let key of Object.keys(args)) {
  57164. this.drag[key] = args[key];
  57165. }
  57166. }
  57167. if(object){
  57168. object.dispatchEvent($.extend(
  57169. this.getEventDesc(),
  57170. {
  57171. type: 'startDragging'
  57172. }
  57173. ));
  57174. }
  57175. }
  57176. /* getMousePointCloudIntersection (mouse) {
  57177. return Utils.getMousePointCloudIntersection(
  57178. this.mouse,
  57179. this.scene.getActiveCamera(),
  57180. this.viewer,
  57181. this.scene.pointclouds);
  57182. } */
  57183. toggleSelection (object) {
  57184. let oldSelection = this.selection;
  57185. let index = this.selection.indexOf(object);
  57186. if (index === -1) {
  57187. this.selection.push(object);
  57188. object.dispatchEvent({
  57189. type: 'select'
  57190. });
  57191. } else {
  57192. this.selection.splice(index, 1);
  57193. object.dispatchEvent({
  57194. type: 'deselect'
  57195. });
  57196. }
  57197. this.dispatchEvent({
  57198. type: 'selection_changed',
  57199. oldSelection: oldSelection,
  57200. selection: this.selection
  57201. });
  57202. }
  57203. deselect(object){
  57204. let oldSelection = this.selection;
  57205. let index = this.selection.indexOf(object);
  57206. if(index >= 0){
  57207. this.selection.splice(index, 1);
  57208. object.dispatchEvent({
  57209. type: 'deselect'
  57210. });
  57211. this.dispatchEvent({
  57212. type: 'selection_changed',
  57213. oldSelection: oldSelection,
  57214. selection: this.selection
  57215. });
  57216. }
  57217. }
  57218. deselectAll () {
  57219. for (let object of this.selection) {
  57220. object.dispatchEvent({
  57221. type: 'deselect'
  57222. });
  57223. }
  57224. let oldSelection = this.selection;
  57225. if (this.selection.length > 0) {
  57226. this.selection = [];
  57227. this.dispatchEvent({
  57228. type: 'selection_changed',
  57229. oldSelection: oldSelection,
  57230. selection: this.selection
  57231. });
  57232. }
  57233. }
  57234. isSelected (object) {
  57235. let index = this.selection.indexOf(object);
  57236. return index !== -1;
  57237. }
  57238. registerInteractiveObject(object){
  57239. this.interactiveObjects.add(object);
  57240. }
  57241. removeInteractiveObject(object){
  57242. this.interactiveObjects.delete(object);
  57243. }
  57244. registerInteractiveScene (scene) {
  57245. let index = this.interactiveScenes.indexOf(scene);
  57246. if (index === -1) {
  57247. this.interactiveScenes.push(scene);
  57248. }
  57249. }
  57250. unregisterInteractiveScene (scene) {
  57251. let index = this.interactiveScenes.indexOf(scene);
  57252. if (index > -1) {
  57253. this.interactiveScenes.splice(index, 1);
  57254. }
  57255. }
  57256. getHoveredElement () {
  57257. let hoveredElements = this.getHoveredElements();
  57258. if (hoveredElements.length > 0) {
  57259. return hoveredElements[0];
  57260. } else {
  57261. return null;
  57262. }
  57263. }
  57264. getHoveredElements (interactables, dontCheckDis, raycaster) {
  57265. if(!interactables){
  57266. let scenes = this.hoverViewport.interactiveScenes || this.interactiveScenes.concat(this.scene);
  57267. let interactableListeners = ['mouseup', 'mousemove', 'mouseover', 'mouseleave', 'drag', 'drop', 'click', 'select', 'deselect'];
  57268. interactables = [];
  57269. for (let scene of scenes) {
  57270. scene.traverseVisible(node => {//检测加了侦听的object
  57271. if (node._listeners && node.visible && !this.blacklist.has(node) ) {
  57272. let hasInteractableListener = interactableListeners.filter((e) => {
  57273. return node._listeners[e] !== undefined;
  57274. }).length > 0;
  57275. if (hasInteractableListener) {
  57276. interactables.push(node);
  57277. }
  57278. }
  57279. });
  57280. }
  57281. }
  57282. let camera = this.hoverViewport.camera;
  57283. if(!raycaster){
  57284. let ray = Utils.mouseToRay(this.pointer, camera );
  57285. raycaster = new Raycaster();
  57286. raycaster.ray.set(ray.origin, ray.direction);
  57287. raycaster.camera = camera; //add
  57288. }
  57289. if(camera.type == "OrthographicCamera"){//使无论多远,threshold区域都是一样宽的
  57290. raycaster.params.Line.threshold = 20/camera.zoom;
  57291. }else {
  57292. raycaster.params.Line.threshold = 0.2;
  57293. }
  57294. raycaster.params.Line2 = {threshold :20 }; //拓宽的lineWidth
  57295. //raycaster.layers.enableAll()//add
  57296. viewer.setCameraLayers(raycaster, //设置能识别到的layers(如空间模型里只有mapViewer能识别到marker)
  57297. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  57298. this.hoverViewport && this.hoverViewport.extraEnableLayers
  57299. );
  57300. //this.hoverViewport.beforeRender && this.hoverViewport.beforeRender()
  57301. viewer.dispatchEvent( {type:'raycaster', viewport: this.hoverViewport});//add
  57302. let intersections = raycaster.intersectObjects(interactables.filter(o => o.visible), true); //原本是false 检测不到children
  57303. let intersectionsCopy = intersections.slice();
  57304. if(this.intersect && this.intersect.distance != void 0 && !dontCheckDis){//add
  57305. intersections = intersections.filter(e=>{
  57306. let material = e.object.material;
  57307. return (e.object.pickDontCheckDis || material.depthTest == false || material.depthWrite == false) && !material.useDepth //!material.depthTestWhenPick
  57308. || ( material.useDepth ? e.distance < this.intersect.distance + material.uniforms.occlusionDistance.value : e.distance < this.intersect.distance )
  57309. });
  57310. }
  57311. intersections = intersections.map(e=>{//add 转化为interactables
  57312. var object = e.object;
  57313. do{
  57314. if(interactables.includes(object)) {
  57315. e.oriObject = e.object;
  57316. e.object = object;
  57317. break
  57318. }
  57319. object = object.parent;
  57320. }while(object)
  57321. return e
  57322. });
  57323. //add for测量线,在检测到sphere时优先选中sphere而非线
  57324. //intersections = intersections.sort(function(a,b){return b.object.renderOrder-a.object.renderOrder}) // 降序
  57325. intersections = intersections.sort(function(a,b){
  57326. let order2 = b.object.pickOrder || 0;
  57327. let order1 = a.object.pickOrder || 0;
  57328. return order2-order1
  57329. }); // 降序
  57330. //console.log('getHoveredElement ', intersections)
  57331. return intersections;
  57332. }
  57333. /* setScene (scene) {
  57334. this.deselectAll();
  57335. this.scene = scene;
  57336. } */
  57337. update (delta) {
  57338. }
  57339. /*getNormalizedDrag () {
  57340. if (!this.drag) {
  57341. return new THREE.Vector2(0, 0);
  57342. }
  57343. let diff = new THREE.Vector2().subVectors(this.drag.end, this.drag.start);
  57344. diff.x = diff.x / this.domElement.clientWidth;
  57345. diff.y = diff.y / this.domElement.clientHeight;
  57346. return diff;
  57347. }
  57348. getNormalizedLastDrag () {
  57349. if (!this.drag) {
  57350. return new THREE.Vector2(0, 0);
  57351. }
  57352. let mouseDelta = this.drag.mouseDelta.clone();
  57353. mouseDelta.x = mouseDelta.x / this.domElement.clientWidth;
  57354. mouseDelta.y = mouseDelta.y / this.domElement.clientHeight;
  57355. return mouseDelta;
  57356. } */
  57357. getMouseDirection(pointer) {//add
  57358. pointer = pointer || this.pointer;
  57359. let camera = this.hoverViewport.camera;
  57360. var t = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  57361. i = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  57362. return {origin: t, direction:i.clone().sub(t).normalize() }
  57363. }
  57364. }
  57365. class ViewerBase extends EventDispatcher{
  57366. constructor(domElement, args = {}){
  57367. super();
  57368. this.name = args.name;
  57369. this.renderArea = domElement;
  57370. this.oldResolution = new Vector2$1();
  57371. this.screenSizeInfo = {
  57372. W:0, H:0, pixelRatio:1 , windowWidth:0, windowHeight:0
  57373. };
  57374. this.initContext(args);
  57375. this.addEventListener('content_changed', ()=>{//画面改变,需要渲染
  57376. this.needRender = true;
  57377. });
  57378. }
  57379. initContext(args){
  57380. //console.log(`initializing three.js ${THREE.REVISION}`);
  57381. let width = this.renderArea.clientWidth;
  57382. let height = this.renderArea.clientHeight;
  57383. let contextAttributes = {
  57384. alpha: true,
  57385. depth: true,
  57386. stencil: false,
  57387. antialias: true,
  57388. preserveDrawingBuffer: true,
  57389. powerPreference: "high-performance",
  57390. };
  57391. let canvas = document.createElement("canvas");
  57392. let context = canvas.getContext('webgl', contextAttributes );
  57393. this.renderer = new WebGLRenderer({
  57394. alpha: true, //支持透明
  57395. premultipliedAlpha: false,
  57396. canvas: canvas,
  57397. context: context,
  57398. });
  57399. this.renderer.sortObjects = true; //原先false 打开了renderOrder才奏效
  57400. //this.renderer.setSize(width, height);
  57401. this.renderer.autoClear = args.autoClear || false;
  57402. //args.clearColor = args.clearColor || '#aa0033'
  57403. args.clearColor && this.renderer.setClearColor(args.clearColor);
  57404. this.renderArea.appendChild(this.renderer.domElement);
  57405. this.renderer.domElement.tabIndex = '2222';
  57406. this.renderer.domElement.style.position = 'absolute';
  57407. this.renderer.domElement.addEventListener('mousedown', () => {
  57408. this.renderer.domElement.focus();
  57409. });
  57410. //this.renderer.domElement.focus();
  57411. // NOTE: If extension errors occur, pass the string into this.renderer.extensions.get(x) before enabling
  57412. // enable frag_depth extension for the interpolation shader, if available
  57413. let gl = this.renderer.getContext();
  57414. gl.getExtension('EXT_frag_depth');
  57415. gl.getExtension('WEBGL_depth_texture');
  57416. gl.getExtension('WEBGL_color_buffer_float'); // Enable explicitly for more portability, EXT_color_buffer_float is the proper name in WebGL 2
  57417. if(gl.createVertexArray == null){
  57418. let extVAO = gl.getExtension('OES_vertex_array_object');
  57419. if(!extVAO){
  57420. throw new Error("OES_vertex_array_object extension not supported");
  57421. }
  57422. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  57423. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  57424. }
  57425. /* let oldClear = gl.clear;
  57426. gl.clear = (bits)=>{
  57427. console.error('clear')
  57428. }
  57429. */
  57430. }
  57431. updateScreenSize(o={}) { //有可能需要让viewport来判断,当窗口大小不变但viewport大小变时
  57432. var render = false, ratio, w, h;
  57433. //记录应当render的大小
  57434. if (o.width != void 0 && o.height != void 0) {
  57435. w = o.width;
  57436. h = o.height;
  57437. render = true;
  57438. ratio = 1;
  57439. }else {
  57440. w = this.renderArea.clientWidth;
  57441. h = this.renderArea.clientHeight;
  57442. if(w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || o.forceUpdateSize || this.screenSizeInfo.pixelRatio != window.devicePixelRatio){
  57443. this.screenSizeInfo.W = w;
  57444. this.screenSizeInfo.H = h;
  57445. render = true;
  57446. this.screenSizeInfo.pixelRatio = window.devicePixelRatio; //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  57447. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  57448. ratio = window.devicePixelRatio;
  57449. }
  57450. }
  57451. if (render) {
  57452. this.setSize(w, h, ratio);
  57453. }
  57454. }
  57455. /* updateScreenSize(o={}) { //容易出错。。
  57456. var render = false, ratio, w, h;
  57457. //记录应当render的大小
  57458. if (o.width != void 0 && o.height != void 0) {
  57459. w = o.width
  57460. h = o.height
  57461. render = true
  57462. ratio = 1
  57463. }else {
  57464. w = this.renderArea.clientWidth;
  57465. h = this.renderArea.clientHeight
  57466. let refreshWin = ()=>{
  57467. this.screenSizeInfo.windowWidth = window.innerWidth
  57468. this.screenSizeInfo.windowHeight = window.innerHeight
  57469. }
  57470. let prepareToRender = ()=>{
  57471. w = this.renderArea.clientWidth;
  57472. h = this.renderArea.clientHeight
  57473. this.screenSizeInfo.W = w
  57474. this.screenSizeInfo.H = h
  57475. refreshWin() //render后才refreshWin
  57476. render = true
  57477. this.screenSizeInfo.pixelRatio = window.devicePixelRatio //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  57478. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  57479. ratio = window.devicePixelRatio
  57480. //console.log('setSize11', w)
  57481. o.forceUpdateSize = false ;//防止再次render
  57482. }
  57483. let ifNeedUpdate = ()=>{
  57484. w = this.renderArea.clientWidth;
  57485. h = this.renderArea.clientHeight
  57486. return o.forceUpdateSize || w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || this.screenSizeInfo.pixelRatio != window.devicePixelRatio
  57487. }
  57488. if(ifNeedUpdate()){
  57489. //当只有一个有效viewport时,且因为改变整个窗口大小而触发的话,延时
  57490. let canInterval = !o.forceUpdateSize && this.viewports.filter(e=>e.active).length==1 && (this.screenSizeInfo.windowWidth != window.innerWidth || this.screenSizeInfo.windowHeight != window.innerHeight )
  57491. if(canInterval){
  57492. Common.intervalTool.isWaiting('updateScreenSize', ()=>{ //延时update,防止崩溃 , 未到时间就拦截(第一次直接执行)
  57493. if(ifNeedUpdate()){
  57494. prepareToRender()
  57495. return true
  57496. }
  57497. }, 500)
  57498. }else{
  57499. //console.log('soon', window.innerWidth, this.screenSizeInfo.windowWidth)
  57500. prepareToRender()
  57501. }
  57502. }
  57503. }
  57504. if (render) {
  57505. this.setSize(w, h, ratio);
  57506. }
  57507. } */
  57508. setSize(width, height, devicePixelRatio, onlyForTarget){
  57509. //console.log('setSize', width)
  57510. if(!onlyForTarget){//onlyForTarget表示不更改当前renderer,只是为了rendertarget才要改变viewport
  57511. this.renderer.setSize(width, height, null, devicePixelRatio); // resize之后会自动clear(似乎因为setScissor ),所以一定要立刻绘制,所以setSize要在cameraChanged、update之前
  57512. }
  57513. this.composer && this.composer.setSize(width, height);
  57514. if(this.viewports){
  57515. this.viewports.forEach((view,i)=>{
  57516. if(!view.active)return
  57517. var width_ = width * view.width;
  57518. var height_ = height * view.height;
  57519. if(height_ == 0)return //avoid NAN
  57520. view.setResolution(Math.ceil(width_), Math.ceil(height_), width, height ); //本来应该是floor,但是这样奇数时会少一个像素,导致向左移一个像素且宽度少1。现在则多绘制1个像素,超出的1个像素应该不会绘制出来(但不知道其他地方是否有偏差,比如pick时)
  57521. let aspect = width_ / height_; //camera的参数精确些,不用视口的归整的resolution像素值,否则hasChange无法为true, 导致canvasResize了但map没update从而闪烁
  57522. view.camera.aspect = aspect;
  57523. if(view.camera.type == "OrthographicCamera"){
  57524. /* //不改宽度 同4dkk
  57525. var heightHalf = view.camera.right / aspect
  57526. view.camera.top = heightHalf
  57527. view.camera.bottom = -heightHalf */
  57528. //高宽都改 使大小不随视口大小改变 navvis (直接和视口大小一致即可,通过zoom来定大小)
  57529. view.camera.left = -width_/2;
  57530. view.camera.right = width_/2;
  57531. view.camera.bottom = -height_/2;
  57532. view.camera.top = height_/2;
  57533. }else {
  57534. }
  57535. view.camera.updateProjectionMatrix();
  57536. });
  57537. }
  57538. if(!onlyForTarget){//因为onlyForTarget不传递devicePixelRatio所以不发送了
  57539. this.emitResizeMsg({viewport:this.viewports[0], deviceRatio:devicePixelRatio});
  57540. }
  57541. }
  57542. emitResizeMsg(e){//切换viewport渲染时就发送一次, 通知一些材质更新resolution。
  57543. if(!e.viewport.resolution.equals(this.oldResolution)){
  57544. this.dispatchEvent($.extend(e, {type:'resize'}));
  57545. this.oldResolution.copy(e.viewport.resolution);
  57546. }
  57547. }
  57548. cameraChanged() {//判断相机是否改变
  57549. var changed = false;
  57550. /* if(this.needRender){
  57551. this.needRender = false
  57552. return true
  57553. } */
  57554. for(let i=0,j=this.viewports.length;i<j;i++){
  57555. let changeInfo = this.viewports[i].cameraChanged();
  57556. if(changeInfo.changed){
  57557. changed = true;
  57558. //if(!this.changeTime ||this.changeTime<100){
  57559. this.dispatchEvent({
  57560. type: "camera_changed",
  57561. camera: this.viewports[i].camera,
  57562. viewport : this.viewports[i],
  57563. changeInfo
  57564. });
  57565. //this.changeTime = (this.changeTime || 0) +1
  57566. //}
  57567. }
  57568. }
  57569. return changed
  57570. }
  57571. makeScreenshot( size, viewports, compressRatio){//暂时不要指定viewports渲染,但也可以
  57572. let {width, height} = size;
  57573. /* let oldBudget = Potree.pointBudget;
  57574. Potree.pointBudget = Math.max(10 * 1000 * 1000, 2 * oldBudget);
  57575. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, size );
  57576. Potree.pointBudget = oldBudget;
  57577. this.dispatchEvent({ //resize everything such as lines targets
  57578. type: 'resize',
  57579. resolution: new THREE.Vector2(width,height),
  57580. });*/
  57581. let target = new WebGLRenderTarget(width, height, {
  57582. format: RGBAFormat,
  57583. });
  57584. this.setSize(width, height,1,true);
  57585. this.render({
  57586. target ,
  57587. //camera ,
  57588. viewports: viewports || this.viewports,
  57589. screenshot : true,
  57590. width ,
  57591. height,
  57592. resize :true //需要resize
  57593. });
  57594. let dataUrl = Potree.Utils.renderTargetToDataUrl(target, width, height, this.renderer, compressRatio);
  57595. /* let pixelCount = width * height;
  57596. let buffer = new Uint8Array(4 * pixelCount);
  57597. this.renderer.readRenderTargetPixels(target, 0, 0, width, height, buffer);
  57598. let dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio) */
  57599. target.dispose();
  57600. //resize back
  57601. //this.updateScreenSize({forceUpdateSize:true})
  57602. return {
  57603. width,
  57604. height,
  57605. dataUrl
  57606. };
  57607. }
  57608. }
  57609. const prefixVertex ="precision highp float;\nprecision highp int;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\n";
  57610. const prefixFragment ="precision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n";
  57611. let shader = {
  57612. uniforms: {
  57613. opacity: {
  57614. type: "f",
  57615. value: 1
  57616. },
  57617. progress: {
  57618. type: "f",
  57619. value: 0
  57620. },
  57621. pano0Map: {
  57622. type: "t",
  57623. value: null
  57624. },
  57625. pano1Map: {
  57626. type: "t",
  57627. value: null
  57628. },
  57629. depthMap0: {
  57630. type: "t",
  57631. value: null
  57632. },
  57633. depthMap1: {
  57634. type: "t",
  57635. value: null
  57636. },
  57637. pano0Position: {
  57638. type: "v3",
  57639. value: new Vector3
  57640. },
  57641. pano0Matrix: {
  57642. type: "m4",
  57643. value: new Matrix4
  57644. },
  57645. pano1Position: {
  57646. type: "v3",
  57647. value: new Vector3
  57648. },
  57649. pano1Matrix: {
  57650. type: "m4",
  57651. value: new Matrix4
  57652. },
  57653. /* pano1Matrix2: {
  57654. type: "m4",
  57655. value: new THREE.Matrix4
  57656. },
  57657. */
  57658. inverseProjectionMatrix: {
  57659. value: new Matrix4
  57660. },
  57661. /* projectionMatrix:{//需要再写一遍吗
  57662. value: new THREE.Matrix4
  57663. }, */
  57664. viewport: {
  57665. value: new Vector4
  57666. },
  57667. //如 {x: 0, y: 0, z: 428, w: 969} xy应该是offset, zw是宽高
  57668. cameraHeight0: {
  57669. type: "f",
  57670. value: 1
  57671. },
  57672. cameraHeight1: {
  57673. type: "f",
  57674. value: 1
  57675. },
  57676. },
  57677. vertexShader: prefixVertex + `
  57678. uniform vec3 pano0Position;
  57679. uniform mat4 pano0Matrix;
  57680. uniform vec3 pano1Position;
  57681. uniform mat4 pano1Matrix;
  57682. //uniform mat4 pano1Matrix2;
  57683. varying vec2 vUv;
  57684. varying vec3 vWorldPosition0;
  57685. varying vec3 vWorldPosition1;
  57686. varying vec3 vWorldPosition12;
  57687. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  57688. {
  57689. float y = direction.y;
  57690. direction.y = direction.z;
  57691. direction.z = -y;
  57692. return direction;
  57693. }
  57694. void main() {
  57695. vUv = uv;
  57696. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  57697. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  57698. vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  57699. vWorldPosition0.x *= -1.0;
  57700. vWorldPosition0 = transformAxis(vWorldPosition0);
  57701. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  57702. vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  57703. vWorldPosition1.x *= -1.0;
  57704. vWorldPosition1 = transformAxis(vWorldPosition1);
  57705. /*
  57706. vec3 positionLocalToPanoCenter12 = worldPosition.xyz - pano1Position;
  57707. vWorldPosition12 = (vec4(positionLocalToPanoCenter12, 1.0) * pano1Matrix2).xyz;
  57708. vWorldPosition12.x *= -1.0;
  57709. vWorldPosition12 = transformAxis(vWorldPosition12);
  57710. */
  57711. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  57712. }
  57713. `,
  57714. fragmentShader: prefixFragment + `
  57715. #define PI 3.141592653
  57716. uniform float modelAlpha;
  57717. uniform float opacity;
  57718. uniform float progress;
  57719. uniform int blackout;
  57720. uniform vec3 pano0Position;
  57721. uniform vec3 pano1Position;
  57722. uniform float maxDistance;
  57723. uniform float minDistance;
  57724. uniform float minOpa;
  57725. uniform float cameraHeight0;
  57726. uniform float cameraHeight1;
  57727. /* uniform sampler2D pano0Map;
  57728. uniform sampler2D pano1Map; */
  57729. uniform samplerCube pano0Map;
  57730. uniform samplerCube pano1Map;
  57731. varying vec2 vUv;
  57732. varying vec3 vWorldPosition0;
  57733. varying vec3 vWorldPosition1;
  57734. //varying vec3 vWorldPosition12;
  57735. /* vec2 getSamplerCoord( vec3 direction )
  57736. {
  57737. direction = normalize(direction);
  57738. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  57739. float ty=acos(direction.z)/PI;
  57740. return vec2(tx,ty);
  57741. } */
  57742. vec2 getSamplerCoord2( vec3 direction )
  57743. {
  57744. direction = normalize(direction);
  57745. float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;
  57746. float ty=acos(direction.y)/PI;
  57747. return vec2(tx,ty);
  57748. }
  57749. #extension GL_EXT_frag_depth : enable
  57750. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  57751. uniform sampler2D depthMap0;
  57752. uniform sampler2D depthMap1;
  57753. uniform mat4 inverseProjectionMatrix;
  57754. uniform mat4 projectionMatrix;
  57755. uniform vec4 viewport;
  57756. vec2 getDepth(vec3 dir, sampler2D depthMap, float height, vec4 eyePos){
  57757. vec2 depthValue = vec2(0.0, 0.0);
  57758. vec2 uv2 = getSamplerCoord2(/* vWorldPosition12 */dir.xyz); //暂时只用基于目标漫游点的方向
  57759. uv2.x -= 0.25; //全景图和Cube的水平采样起始坐标相差90度,这里矫正 0.25 个采样偏移
  57760. vec4 depth = texture2D(depthMap, uv2);
  57761. //float distance = depth.r + 256. * (depth.g + 256. * depth.b);
  57762. //distance *= 255. * .001; // distance is now in meters
  57763. //更改
  57764. float distance = (depth.g + depth.r / 256.) * 255.; //为什么要乘以255
  57765. if(distance == 0.0){//漫游点底部识别不到的区域,给一个地板高度
  57766. if(uv2.y > 0.75)distance = height / dir.y;
  57767. else distance = 100000.0;//给个超级远的值
  57768. }
  57769. depthValue.x = distance;
  57770. // return r[1] + r[0] / 256
  57771. distance += .1; // add a safety margin
  57772. vec4 eyePos2 = vec4(normalize(eyePos.xyz) * distance, 1.);
  57773. vec4 clipPos2 = projectionMatrix * eyePos2;
  57774. vec4 ndcPos2 = clipPos2 * 1. / clipPos2.w;
  57775. depthValue.y = 0.5 * ((gl_DepthRange.far - gl_DepthRange.near) * ndcPos2.z
  57776. + gl_DepthRange.near + gl_DepthRange.far);
  57777. return depthValue;
  57778. }
  57779. //注:未加载好的话,depth为0,导致第一次漫游过去的时候许多mesh会立刻被遮挡,所以要确保加载完
  57780. #endif
  57781. void main()
  57782. {
  57783. /* vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  57784. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  57785. vec4 colorFromPano0=texture2D(pano0Map,samplerCoord0);
  57786. vec4 colorFromPano1=texture2D(pano1Map,samplerCoord1); */
  57787. vec4 colorFromPano0 = vec4(0.0,0.0,0.0,0.0);
  57788. if(progress < 1.0){//通常是1
  57789. colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  57790. }
  57791. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  57792. gl_FragColor=mix(colorFromPano0,colorFromPano1,progress);
  57793. //深度图修改深度
  57794. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  57795. vec4 ndcPos;
  57796. ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.;
  57797. ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
  57798. (gl_DepthRange.far - gl_DepthRange.near);
  57799. ndcPos.w = 1.0;
  57800. vec4 clipPos = ndcPos / gl_FragCoord.w;
  57801. vec4 eyePos = inverseProjectionMatrix * clipPos;
  57802. vec2 depth0 = vec2(0.0,0.0);
  57803. if(progress < 1.0){
  57804. depth0 = getDepth(vWorldPosition0, depthMap0, cameraHeight0, eyePos);
  57805. }
  57806. vec2 depth1 = getDepth(vWorldPosition1, depthMap1, cameraHeight1, eyePos);
  57807. /* if(progress < 1.0 && depth1.x == 0.0 && depth0.x > 0.0){
  57808. gl_FragDepthEXT = depth0.y;
  57809. }else{ */
  57810. gl_FragDepthEXT = mix(depth0.y,depth1.y,progress);
  57811. //}
  57812. #endif
  57813. }
  57814. `
  57815. };
  57816. class ModelTextureMaterial extends RawShaderMaterial {
  57817. constructor( ){
  57818. let defines = {};
  57819. super({
  57820. fragmentShader: shader.fragmentShader,
  57821. vertexShader: shader.vertexShader,
  57822. uniforms: UniformsUtils.clone(shader.uniforms),
  57823. side:DoubleSide,
  57824. name: "ModelTextureMaterial",
  57825. defines
  57826. });
  57827. let setSize = (e)=>{
  57828. let viewport = e.viewport;
  57829. let viewportOffset = viewport.offset || new Vector2();
  57830. let resolution = viewport.resolution2;
  57831. this.uniforms.viewport.value.set(viewportOffset.x, viewportOffset.y, resolution.x, resolution.y);
  57832. };
  57833. let viewport = viewer.mainViewport;
  57834. setSize({viewport});
  57835. viewer.addEventListener('resize',(e)=>{
  57836. setSize(e);
  57837. });
  57838. //var supportExtDepth = !!Features.EXT_DEPTH.isSupported()
  57839. {
  57840. //add
  57841. viewer.addEventListener('camera_changed', (e)=>{
  57842. //this.uniforms.projectionMatrix.value.copy(e.camera.projectionMatrix)
  57843. this.uniforms.inverseProjectionMatrix.value.copy(e.camera.projectionMatrixInverse);
  57844. });
  57845. }
  57846. //-------------------------------------
  57847. }
  57848. /**
  57849. *
  57850. * @param {Panorama} pano0
  57851. * @param {Panorama} pano1
  57852. * @param {boolean} flag
  57853. 更新全景图的材质uniforms
  57854. */
  57855. setProjectedPanos(pano0, pano1, progressValue ){
  57856. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  57857. //pano0.ensureSkyboxReadyForRender();
  57858. if(pano0){
  57859. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();//pano0.texture
  57860. this.uniforms.pano0Position.value.copy(pano0.position);
  57861. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix/* pano0.mesh.matrixWorld */ );
  57862. this.uniforms.cameraHeight0.value = pano0.floorPosition.distanceTo(pano0.position);
  57863. //pano1.ensureSkyboxReadyForRender();
  57864. }
  57865. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();//pano1.texture;
  57866. this.uniforms.pano1Position.value.copy(pano1.position);
  57867. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix /* pano1.mesh.matrixWorld */ );
  57868. this.uniforms.cameraHeight1.value = pano1.floorPosition.distanceTo(pano1.position);
  57869. this.pano0 = pano0;
  57870. this.pano1 = pano1;
  57871. this.updateDepthTex(pano0);
  57872. this.updateDepthTex(pano1);
  57873. //console.log('setProjectedPanos', pano0&&pano0.id, pano1&&pano1.id)
  57874. this.needsUpdate = true;
  57875. }
  57876. updateDepthTex(pano){
  57877. if( !Potree.settings.useDepthTex || !pano || !pano.depthTex || pano!=this.pano0 && pano!=this.pano1)return
  57878. //console.log('updateDepthTex', pano.id, this.pano0 && this.pano0.id, this.pano1 && this.pano1.id)
  57879. this.uniforms.depthMap0.value = this.pano0 && this.pano0.depthTex;
  57880. this.uniforms.depthMap1.value = this.pano1 && this.pano1.depthTex;
  57881. this.updateDepthTexEnable();
  57882. }
  57883. updateDepthTexEnable(){
  57884. let hasDepthTex = this.pano0 && this.pano1 && this.pano0.pointcloud.hasDepthTex && this.pano1.pointcloud.hasDepthTex; //暂时不知道一个有图一个没图怎么写所以
  57885. Common.addOrRemoveDefine(this, 'hasDepthTex', hasDepthTex?'add':'remove' );
  57886. }
  57887. /* EnableDepthTex(){//开启DepthTex
  57888. if(this.defines['hasDepthTex']){
  57889. return
  57890. }
  57891. this.defines['hasDepthTex'] = ''
  57892. this.needsUpdate = true;
  57893. } */
  57894. }
  57895. var TileUtils = {};
  57896. TileUtils.TILE_SIZE = 512,
  57897. TileUtils.FACES_PER_PANO = 6,
  57898. TileUtils.LocationOnTile = {
  57899. Center: 0,
  57900. UpperLeft: 1,
  57901. UpperRight: 2,
  57902. LowerRight: 3,
  57903. LowerLeft: 4
  57904. },
  57905. /*
  57906. * 获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的指定位置)。spherical通过先求uv,再直接得到dir
  57907. * @param {*} size 面分辨率
  57908. * @param {*} cubeFace 所在面
  57909. * @param {*} Center 在tile上的目标位置,默认为中心,其他位置就是四个顶点
  57910. * @param {*} c 似乎是在tile的缩进百分比,根据所在面的不同,分别向不同方向缩进,但都是向tile的中心
  57911. * @param {*} dir 所求方向
  57912. */
  57913. TileUtils.getTileVector = function() {//获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的中心)
  57914. return function(size, tileSize, cubeFace, tileX, tileY, Center, c, dir) {//c似乎是缩进百分比
  57915. Center = Center || TileUtils.LocationOnTile.Center;
  57916. //假设该cube边长为2:
  57917. var u = size / tileSize
  57918. , d = tileX / u;
  57919. tileY = -tileY + (u - 1);
  57920. var p = tileY / u
  57921. , f = tileSize / size
  57922. , g = 2 * f //一个tile的宽度 (乘以2是因为cube边长是2)
  57923. , m = g / 2
  57924. , v = 2 * d - 1 + m
  57925. , A = 2 * p - 1 + m;
  57926. switch (Center) {//计算在tile中指定位置带来的偏移
  57927. case TileUtils.LocationOnTile.UpperLeft: //1
  57928. v -= m,
  57929. A += m,
  57930. v += c * g; //似乎是向内缩进
  57931. break;
  57932. case TileUtils.LocationOnTile.UpperRight:
  57933. v += m,
  57934. A += m,
  57935. A -= c * g;
  57936. break;
  57937. case TileUtils.LocationOnTile.LowerRight:
  57938. v += m,
  57939. A -= m,
  57940. v -= c * g;
  57941. break;
  57942. case TileUtils.LocationOnTile.LowerLeft:
  57943. v -= m,
  57944. A -= m,
  57945. A += c * g;
  57946. break;
  57947. case TileUtils.LocationOnTile.Center: //0
  57948. }
  57949. switch (cubeFace) {
  57950. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  57951. MathLight.setVector(dir, -1, A, -v);
  57952. break;
  57953. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  57954. MathLight.setVector(dir, 1, A, v);
  57955. break;
  57956. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: //顶面
  57957. MathLight.setVector(dir, -v, 1, -A);
  57958. break;
  57959. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  57960. MathLight.setVector(dir, -v, -1, A);
  57961. break;
  57962. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  57963. MathLight.setVector(dir, -v, A, 1);
  57964. break;
  57965. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  57966. MathLight.setVector(dir, v, A, -1);
  57967. }
  57968. MathLight.normalize(dir);
  57969. }
  57970. }(),
  57971. /*
  57972. * 获取该tile在第几个面(简易装载法)
  57973. */
  57974. TileUtils.getFaceForTile = function(size, index) {//获取该tile在第几个面
  57975. var tileSize = TileUtils.TILE_SIZE;
  57976. size < TileUtils.TILE_SIZE && (tileSize = size);
  57977. var n = Math.floor(size / tileSize)
  57978. , sum = n * n; //得每个面tile总数
  57979. return Math.floor(index / sum)
  57980. }
  57981. ,
  57982. TileUtils.getTileLocation = function(size, t, result) {
  57983. var tileSize = TileUtils.TILE_SIZE;
  57984. size < TileUtils.TILE_SIZE && (tileSize = size);
  57985. var r = TileUtils.getFaceForTile(size, t)
  57986. , a = Math.floor(size / tileSize)
  57987. , s = a * a
  57988. , l = t - r * s;
  57989. result.tileX = l % a;
  57990. result.tileY = Math.floor(l / a);
  57991. result.face = r;
  57992. result.faceTileIndex = l;
  57993. return result
  57994. }
  57995. ,
  57996. /*
  57997. * 求size分辨率需要多少张tile
  57998. */
  57999. TileUtils.getTileCountForSize = function(e) {
  58000. if (e <= TileUtils.TILE_SIZE)
  58001. return TileUtils.FACES_PER_PANO;
  58002. var t = Math.floor(e / TileUtils.TILE_SIZE)
  58003. , i = t * t
  58004. , n = i * TileUtils.FACES_PER_PANO;
  58005. return n
  58006. }
  58007. ,
  58008. TileUtils.getRelativeDirection = function() {
  58009. var e = new MathLight.Matrix4
  58010. , t = new MathLight.Quaternion;
  58011. return function(i, n) {//i是pano.quaternion, n是camera的direction
  58012. t.copy(i),
  58013. t.inverse(),
  58014. e.makeRotationFromQuaternion(t),
  58015. e.applyToVector3(n),
  58016. MathLight.normalize(n);
  58017. }
  58018. }(),
  58019. /*
  58020. * 根据方向寻找合适的tile加载
  58021. */
  58022. TileUtils.matchingTilesInDirection = function() {
  58023. var e = new MathLight.Vector3
  58024. , t = new MathLight.Vector3(0,0,-1)
  58025. , i = new MathLight.Quaternion
  58026. , n = function(e, t) {
  58027. e.push({
  58028. face: t.face,
  58029. faceTileIndex: t.faceTileIndex,
  58030. tileX: t.tileX,
  58031. tileY: t.tileY
  58032. });
  58033. }
  58034. , a = function() {
  58035. var e = {
  58036. face: -1,
  58037. faceTileIndex: -1,
  58038. tileX: -1,
  58039. tileY: -1
  58040. };
  58041. return function(size, i, r) {
  58042. for (var a = TileUtils.getTileCountForSize(size), s = 0, l = 0; l < a; l++)
  58043. TileUtils.getTileLocation(size, l, e),
  58044. i && !i(e) || (s++,
  58045. r && n(r, e));
  58046. return s
  58047. }
  58048. }();
  58049. return function(pano, size, dir, hFov, vFov, result) {
  58050. var d = size < TileUtils.TILE_SIZE ? size : TileUtils.TILE_SIZE;
  58051. //TileUtils.getTileCountForSize(size);
  58052. if (!hFov && !vFov)
  58053. return a(size, null, result);
  58054. var p = !!vFov;
  58055. vFov = vFov || hFov,
  58056. vFov = Math.max(0, Math.min(vFov, 360)),
  58057. hFov = Math.max(0, Math.min(hFov, 360)),
  58058. MathLight.copyVector(dir, e),
  58059. TileUtils.getRelativeDirection(pano.quaternion4dkk, e);
  58060. if(p){//如果有vFov hFov
  58061. i.setFromUnitVectors(e, t);
  58062. var f = function(e) {
  58063. return TileUtils.isTileWithinFrustum(size, d, e.face, e.tileX, e.tileY, i, hFov, vFov)//在视野中的
  58064. };
  58065. return a(size, f, result)
  58066. }
  58067. var g = function(t) {//如果仅有hFov
  58068. return TileUtils.isTileWithinFOV(size, d, t.face, t.tileX, t.tileY, e, hFov)
  58069. };
  58070. return a(size, g, result)
  58071. }
  58072. }(),
  58073. /*
  58074. * 是否在屏幕范围内
  58075. */
  58076. TileUtils.isTileWithinFrustum = function() {
  58077. var e = new MathLight.Vector3
  58078. , t = 1e-5;
  58079. return function(i, n, a, s, l, c, h, u) {
  58080. for (var d = Math.tan(.5 * u * MathLight.RADIANS_PER_DEGREE), p = -d, f = Math.tan(.5 * h * MathLight.RADIANS_PER_DEGREE), g = -f, m = TileUtils.mapFaceToCubemapFace(a), v = 0, A = 0, y = 0, C = 0, I = 0, E = 0, b = TileUtils.LocationOnTile.Center; b <= TileUtils.LocationOnTile.LowerLeft; b++){
  58081. TileUtils.getTileVector(i, n, m, s, l, b, 0, e),//get e // size, tileSize, cubeFace, tileX, tileY, Center, c, dir
  58082. MathLight.applyQuaternionToVector(c, e);
  58083. if (e.z >= -t)//似乎是在相机背面
  58084. I++;
  58085. else {
  58086. var w = -1 / e.z
  58087. , _ = e.x * w
  58088. , T = e.y * w;
  58089. T > d ? v++ : T < p && A++, //这四种似乎代表在这个画框之外,如在左、在上、在下、在右
  58090. _ > f ? y++ : _ < g && C++,
  58091. E++;
  58092. }
  58093. }
  58094. return A !== E && v !== E && y !== E && C !== E //如果有一项和E相等代表要么是在相机背面要么是tile的四个顶点都画在画布的同一边,所以肯定不在画布上
  58095. }
  58096. }(),
  58097. /*
  58098. * 是否在FOV范围内
  58099. */
  58100. TileUtils.isTileWithinFOV = function() {
  58101. var e = new MathLight.Vector3
  58102. , t = new MathLight.Vector3(0,1,0)
  58103. , i = new MathLight.Vector3(1,0,0);
  58104. return function(panoSize, tileSize, face, tileX, tileY, direction, fov) {//direction是作用了pano.quaternion的camera.direction
  58105. var d = TileUtils.mapFaceToCubemapFace(face);
  58106. MathLight.cross(direction, t, i); //get i 好像没用到
  58107. TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, TileUtils.LocationOnTile.Center, 0, e);
  58108. if (TileUtils.isWithinFOV(e, direction, fov, null))//先判断tile中心在不在FOV内
  58109. return !0;
  58110. for (var p = fov / 360, f = Math.floor(1 / p), g = 0, m = 0; m < f; m++) {
  58111. for (var v = TileUtils.LocationOnTile.UpperLeft; v <= TileUtils.LocationOnTile.LowerLeft; v++)
  58112. if (TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, v, g, e),
  58113. TileUtils.isWithinFOV(e, direction, fov, null))
  58114. return !0;
  58115. g += p; //可能是考虑到有可能tile比fov覆盖了fov(虽然一般不可能,除非fov特别小),所以将tile分成若干段,取tile中的点再检测下
  58116. }
  58117. return !1
  58118. }
  58119. }(),
  58120. TileUtils.isWithinFOV = function() {
  58121. var e = new MathLight.Vector3
  58122. , t = new MathLight.Vector3;
  58123. return function(dir, cameraDir, fov, a) {
  58124. if (MathLight.copyVector(dir, t),
  58125. a) {
  58126. MathLight.copyVector(a, e),
  58127. MathLight.normalize(e);
  58128. var s = MathLight.dot(e, dir);
  58129. e.x *= s,
  58130. e.y *= s,
  58131. e.z *= s,
  58132. MathLight.subVector(t, e);
  58133. }
  58134. var l = fov / 2 * MathLight.RADIANS_PER_DEGREE
  58135. , c = Math.cos(l)
  58136. , h = MathLight.dot(t, cameraDir);
  58137. return h >= c
  58138. }
  58139. }(),
  58140. TileUtils.mapFaceToCubemapFace = function() {
  58141. var e = {
  58142. 0: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  58143. 1: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  58144. 2: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  58145. 3: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  58146. 4: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  58147. 5: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
  58148. };
  58149. return function(t) {
  58150. return e[t]
  58151. }
  58152. }();
  58153. var texLoader$2 = new TextureLoader();
  58154. const labelProp = {
  58155. sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  58156. backgroundColor:{r: 255, g: 255, b: 255, a: 0.4 },
  58157. textColor:{r: 0, g: 0, b: 0, a: 1 },
  58158. borderRadius: 15,
  58159. renderOrder:10
  58160. };
  58161. let standardMarkerMat;
  58162. let markerTex;
  58163. let getMarerMat = function(){
  58164. if(!markerTex) {
  58165. markerTex = {
  58166. default:texLoader$2.load( Potree.resourcePath+'/textures/marker.png' ),
  58167. ring:texLoader$2.load( Potree.resourcePath+'/textures/marker2.png' )
  58168. };
  58169. markerTex.default.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  58170. markerTex.ring.anisotropy = 4;
  58171. //有可能被点云遮住吗。
  58172. }
  58173. return new DepthBasicMaterial({opacity:0.7, side: DoubleSide , map:markerTex.default ,transparent:true,
  58174. clipDistance: 2, occlusionDistance:1, //不能设置太短,因为过渡时深度不准确
  58175. //depthTest: !!Potree.settings.useDepthTex,
  58176. useDepth: !!Potree.settings.useDepthTex
  58177. //改为DepthBasicMaterial是因为原Basic的材质过渡时会先隐藏后出现
  58178. })
  58179. };
  58180. //显示全景图时marker没有被遮挡,如果需要,要换成depthBasicMaterial 或者直接把skybox的深度修改(拿到深度贴图后更如此)
  58181. let planeGeo$1 = new PlaneBufferGeometry(0.2,0.2);
  58182. let sg = new SphereGeometry(0.1, 8, 8);
  58183. let smHovered = new MeshBasicMaterial({/* side: THREE.BackSide, */color: 0xff0000});
  58184. let sm = new MeshBasicMaterial({/* side: THREE.BackSide */});
  58185. var rot90 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  58186. //var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI/2 ); //4dkk->navvis
  58187. //var rot901 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/2 ); //整张球幕图要旋转下
  58188. //rot90 = new THREE.Quaternion().multiplyQuaternions( rot901, rot90)
  58189. var old = null;
  58190. /*
  58191. 转成四维看看的axis:
  58192. var a = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), THREE.Math.degToRad(-90)) 因为四维的要绕y转90
  58193. 这里的quaternion.multiply(a);
  58194. 先乘再换顺序 w : q.w, x:q.x , y:-q.z, z:q.y
  58195. */
  58196. //暂时直接用4dkkconsole输出的数据
  58197. class Panorama extends EventDispatcher{
  58198. constructor(o, images360){//file, time, longitude, latitude, altitude, course, pitch, roll
  58199. super();
  58200. this.id = o.id; //唯一标识
  58201. this.images360 = images360;
  58202. this.visible = true; //for viewer updateVisible
  58203. this.enabled = true;//是否可以走
  58204. this.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  58205. //console.log('pano isVisible', this.id, e.visible)
  58206. viewer.updateVisible(this.marker, 'panoVisi', e.visible);
  58207. Potree.settings.showPanoMesh && (this.mesh.visible = e.visible);
  58208. if(e.reason == 'screenshot' || e.visible){
  58209. this.label && (this.label.visible = e.visible);//截图时隐藏下
  58210. }
  58211. viewer.updateVisible(this.label2, 'panoVisi', e.visible);
  58212. });
  58213. /*
  58214. 漫游点可见性:旧
  58215. level reason 类型
  58216. 2(最高)buildingChange(不在此楼层) unvisible
  58217. 1 modeIsShowPanos(漫游模式) visible //不记得为什么加这个了,所以重写
  58218. 0 pointcloudVisi(隐藏了数据集) unvisible
  58219. */
  58220. /*
  58221. 漫游点可见性:新
  58222. level reason 类型
  58223. 2(最高)buildingChange(不在此楼层) unvisible
  58224. 1 ifShowMarker(marker显示开关) unvisible
  58225. 0 pointcloudVisi(隐藏了数据集) unvisible
  58226. */
  58227. if(Potree.settings.editType == 'pano'){//漫游点拼合编辑
  58228. this.uuid = o.uuid; //因为有多个数据集 所以会重复
  58229. this.index = o.index; //下标, 用于visibles
  58230. this.pointcloud = viewer.scene.pointclouds.find(e=>e.panoUuid == o.uuid);
  58231. this.pointcloud.panos.push(this);
  58232. this.sid = this.pointcloud.dataset_id + '|' + this.uuid; //不会更改的标记 用于entity.panos里的标记
  58233. this.panosData = o;
  58234. //数据中原本的位置朝向
  58235. this.dataPosition = new Vector3().copy(o.pose.translation);
  58236. this.dataQuaternion = new Quaternion().copy(o.pose.rotation);
  58237. this.dataRotation = new Euler().setFromQuaternion(this.dataQuaternion);
  58238. //因为位置朝向随着点云位置改变,所以直接运用到点云上,这里清零
  58239. this.originPosition = new Vector3(); //{x: 0, y: 0, z: 0}
  58240. this.quaternion = new Quaternion(); //{w: 0, x: 0, y: 0, z: 1}
  58241. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  58242. this.visibles = o.visibles;
  58243. const height = 1.4; //相机高度
  58244. this.originFloorPosition = this.originPosition.clone();
  58245. this.originFloorPosition.z -= height;
  58246. /* this.originPosition = new THREE.Vector3().copy(o.pose.translation) //{x: 0, y: 0, z: 0}
  58247. this.quaternion = new THREE.Quaternion().copy(o.pose.rotation) //{w: 0, x: 0, y: 0, z: 1}
  58248. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  58249. this.visibles = o.visibles
  58250. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.uuid)
  58251. this.pointcloud.panos.push(this)
  58252. const height = 1.5; //相机高度
  58253. this.originFloorPosition = this.originPosition.clone()
  58254. this.originFloorPosition.z -= height
  58255. */
  58256. }else {
  58257. this.originPosition = new Vector3().fromArray(o.dataset_location);
  58258. this.originFloorPosition = new Vector3().fromArray(o.dataset_floor_location);
  58259. this.originID = parseInt(o.file_id);//"file_id":"00022"对应是原本的4dkk的id --来自vision.txt
  58260. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.dataset_id) || viewer.scene.pointclouds[0];
  58261. this.pointcloud.panos.push(this);
  58262. //this.sid = this.pointcloud.sceneCode + '|' + this.originID //不会更改的标记
  58263. this.sid = this.pointcloud.dataset_id + '|' + this.originID; //不会更改的标记
  58264. //全景图和Cube的水平采样起始坐标相差90度
  58265. /* if(from4dkk){
  58266. var qua = o.dataset_orientation
  58267. var quaternion = new THREE.Quaternion().fromArray(qua)
  58268. quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion, rot901);//整张球幕图要旋转下 因为在4dkk里转过,还原。如果是tiles的不用
  58269. this.quaternion = new THREE.Quaternion(quaternion.x, -quaternion.z, quaternion.y, quaternion.w) //转化坐标
  58270. }else{ */
  58271. var qua = o.dataset_orientation;
  58272. qua = [qua[1], qua[2], qua[3], qua[0]];
  58273. this.quaternion = new Quaternion().fromArray(qua);
  58274. this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion);//4dkk内使用的quaternion
  58275. this.quaternion2 = this.quaternion.clone();
  58276. this.quaternion = new Quaternion().multiplyQuaternions(this.quaternion, rot90);//全景图和Cube的水平采样起始坐标相差90度,cubeTex转90度
  58277. this.rotation4dkk = new Euler().setFromQuaternion(this.quaternion4dkk);
  58278. //}
  58279. //this.quaternion1 = Potree.Utils.QuaternionFactory.fromArray(o.dataset_orientation)
  58280. //同quaternion
  58281. //let xy = this.transform.forward([this.longitude, this.latitude]);
  58282. this.file = `https://4dkk.4dage.com/images/images${Potree.settings.number}/pan/high/${this.id}.jpg`;
  58283. }
  58284. this.rotation = new Euler().setFromQuaternion(this.quaternion);
  58285. this.build();
  58286. this.transformByPointcloud(); //初始化位移
  58287. {//tile
  58288. this.minimumTiledPanoLoaded = !1;
  58289. this.highestPartialTileRenderOpCompleted = 0;
  58290. this.highestFullTileRenderOpCompleted = 0;
  58291. this.shouldRedrawOnBaseLoaded = !1;
  58292. this.resolutionPromise = {};
  58293. this.tiledPanoRenderTarget = null;
  58294. this.zoomed = !1;
  58295. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderSuccess, this.onTileRendered.bind(this));
  58296. images360.panoRenderer.addEventListener(PanoRendererEvents.PanoRenderComplete, this.onPanoRendered.bind(this));
  58297. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderFailure, this.onTileRenderFail.bind(this));
  58298. images360.panoRenderer.addEventListener(PanoRendererEvents.UploadAttemptedForAllTiles, this.onUploadAttemptedForAllTiles.bind(this));
  58299. }
  58300. this.addEventListener('hoverOn', (e)=>{//from Map
  58301. if(!e.byMainView){
  58302. this.hoverOn(e);
  58303. }
  58304. });
  58305. this.addEventListener('hoverOff', (e)=>{
  58306. if(!e.byMainView){
  58307. this.hoverOff(e);
  58308. }
  58309. });
  58310. }
  58311. setEnable(enable){//是否可以走
  58312. viewer.updateVisible(this, 'isEnabled', enable); //令所有marker不可见
  58313. this.enabled = enable;
  58314. //如果当前在全景模式且在这个点,需要切换显示吗? 目前用不到
  58315. }
  58316. loadDepthImg(){
  58317. if(!this.pointcloud.hasDepthTex || this.depthTex || this.depthTexLoading)return
  58318. this.depthTexLoading = true;
  58319. let src = Potree.settings.number == 'SS-t-7DUfWAUZ3V' ? `${Potree.scriptPath}/data/${Potree.settings.number}/depthMap/${this.originID}.png`
  58320. : `https://laser-oss.4dkankan.com/${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png`;
  58321. let texture = texLoader$2.load( src, ()=>{
  58322. this.depthTex = texture;
  58323. this.images360.dispatchEvent({type:'loadedDepthImg', pano:this, loaded:true});
  58324. this.depthTexLoading = false;
  58325. },(e)=>{//error
  58326. console.error('loadDepthImg失败, 数据集sceneCode'+ this.pointcloud.sceneCode, this.id );
  58327. this.pointcloud.hasDepthTex = false;
  58328. this.images360.dispatchEvent({type:'loadedDepthImg', pano:this, });
  58329. });
  58330. texture.wrapS = RepeatWrapping;
  58331. texture.flipY = false;
  58332. texture.magFilter = LinearFilter;
  58333. texture.minFilter = LinearFilter;
  58334. }
  58335. build(){
  58336. /* let mesh = new THREE.Mesh(sg, sm);
  58337. mesh.scale.set(1, 1, 1);
  58338. mesh.material.transparent = true;
  58339. mesh.material.opacity = 0.75;
  58340. mesh.pano = this;
  58341. mesh.name = 'panoSphere'
  58342. mesh.addEventListener('mouseover',(e)=>{
  58343. mesh.material = smHovered
  58344. })
  58345. mesh.addEventListener('mouseleave',(e)=>{
  58346. mesh.material = sm
  58347. })
  58348. mesh.addEventListener('click',(e)=>{
  58349. this.images360.focusPano(this)
  58350. })
  58351. this.mesh = mesh;
  58352. if(!Potree.settings.showPanoMesh) mesh.visible = false
  58353. this.images360.node.add(mesh)
  58354. */
  58355. { // orientation
  58356. //var {course, pitch, roll} = this;
  58357. //mesh.quaternion.copy(this.quaternion)
  58358. //add
  58359. //var quaternion = new THREE.Quaternion().multiplyQuaternions(this.quaternion, rot901);//改 为球目全
  58360. //quaternion.premultiply(rot90)
  58361. this.panoMatrix = new Matrix4().makeRotationFromQuaternion(this.quaternion);
  58362. this.oriPanoMatrix = this.panoMatrix.clone();
  58363. if(this.quaternion2)this.oriPanoMatrix2 = new Matrix4().makeRotationFromQuaternion(this.quaternion2);
  58364. //console.log(this.quaternion)
  58365. //this.quaternion = quaternion
  58366. }
  58367. let marker = new Mesh(planeGeo$1, getMarerMat() );
  58368. marker.name = 'marker_'+this.id;
  58369. marker.up.set(0,0,1);
  58370. marker.lookAt(marker.up);
  58371. marker.scale.set(2,2,2);
  58372. this.addEventListener('changeMarkerTex',(e)=>{
  58373. marker.material.map = markerTex[e.name];
  58374. });
  58375. this.marker = marker;
  58376. if(Potree.settings.editType == 'pano'){
  58377. viewer.updateVisible(marker, 'panoEdit', false, 4);
  58378. }
  58379. this.images360.node.add(marker);
  58380. Potree.settings.isTest && this.createTextLabel();
  58381. this.createTextLabel2();
  58382. /* let mouseover = (e)=>{
  58383. if(!e.byMap){
  58384. pano.mapMarker.material = panoMarkerMats.selected
  58385. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true})
  58386. this.needRender = true
  58387. }
  58388. }
  58389. let mouseleave = (e)=>{
  58390. if(!e.byMap){
  58391. pano.mapMarker.material = panoMarkerMats.default
  58392. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true})
  58393. this.needRender = true
  58394. }
  58395. } */
  58396. marker.addEventListener('mouseover', this.hoverOn.bind(this));
  58397. marker.addEventListener('mouseleave', this.hoverOff.bind(this));
  58398. }
  58399. transformByPointcloud(){
  58400. let position = this.originPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);//也可以用datasetPosTransform算
  58401. let floorPosition = this.originFloorPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);
  58402. this.setPosition(position, floorPosition);
  58403. this.panoMatrix = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix );
  58404. //this.panoMatrix2 = Potree.Utils.datasetRotTransform({fromDataset:true, pointcloud:this.pointcloud, matrix:this.oriPanoMatrix, getMatrix:true}) //和上一行结果一样
  58405. //quaternion也变下
  58406. if(this.oriPanoMatrix2){
  58407. this.panoMatrix2 = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix2 );//供DepthImageSampler使用
  58408. this.panoMatrix2Inverse = this.panoMatrix2.clone().invert();
  58409. }
  58410. this.dispatchEvent('rePos');
  58411. }
  58412. setPosition(position, floorPosition){
  58413. this.position = position;
  58414. this.floorPosition = floorPosition;
  58415. //this.mesh.position.copy(this.position)
  58416. this.marker.position.copy(this.floorPosition);
  58417. this.marker.position.z+=0.04;//会被点云遮住
  58418. if(this.label){
  58419. if(Potree.settings.editType == 'pano'){
  58420. this.label.position.copy(this.position);
  58421. }else {
  58422. this.label.position.copy(this.floorPosition);
  58423. }
  58424. this.label.position.z+=0.14;
  58425. this.label.update();
  58426. }
  58427. if(this.label2){
  58428. if(Potree.settings.editType == 'pano'){
  58429. this.label2.position.copy(this.position);
  58430. }else {
  58431. this.label2.position.copy(this.floorPosition);
  58432. }
  58433. this.label2.position.copy(this.marker.position);
  58434. this.label2.update();
  58435. }
  58436. }
  58437. hoverOn(e={}) {
  58438. //console.log("hoverOn " + this.id )
  58439. transitions.start(lerp.property(this.marker.material, "opacity", 1), 250);
  58440. if(!e.byMap) this.dispatchEvent({type:'hoverOn', byMainView:true});
  58441. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:true, pano:this});
  58442. }
  58443. hoverOff(e={}){
  58444. //console.log("hoverOff " + this.id )
  58445. transitions.start(lerp.property(this.marker.material, "opacity", 0.5), 250);
  58446. if(!e.byMap) this.dispatchEvent({type:'hoverOff', byMainView:true});
  58447. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:false, pano:this});
  58448. }
  58449. setZoomed(zoomed){
  58450. this.zoomed = zoomed;
  58451. Potree.settings.displayMode == 'showPanos' && this.updateSkyboxForZoomLevel(); //放大后换成zoomTarget贴图
  58452. viewer.dispatchEvent({type:'panoSetZoom', zoomed});
  58453. }
  58454. enter(){
  58455. this.setZoomed(!1),
  58456. viewer.dispatchEvent({type:PanoramaEvents.Enter, oldPano:old, newPano:this } );
  58457. old = this;
  58458. //console.log("enter pano "+ this.id)
  58459. }
  58460. exit(){
  58461. /* if(this.tiled)
  58462. { */
  58463. this.clearWaitDeferreds();
  58464. this.minimumTiledPanoLoaded = !1;
  58465. this.tiledPanoRenderTarget = null;
  58466. this.setZoomed(!1);
  58467. this.images360.panoRenderer.deactivateTiledPano(this);
  58468. this.highestPartialTileRenderOpCompleted = 0;
  58469. this.highestFullTileRenderOpCompleted = 0;
  58470. /*}
  58471. else
  58472. {
  58473. this.solidSkybox.dispose();
  58474. this.solidSkybox.loaded = !1;
  58475. this.solidSkybox.version = 0;
  58476. } */
  58477. //console.log("exit pano "+ this.id)
  58478. viewer.dispatchEvent({type:PanoramaEvents.Exit, pano:this});
  58479. }
  58480. updateSkyboxForZoomLevel(){
  58481. if(this.minimumTiledPanoLoaded){
  58482. this.images360.updateProjectedPanos();
  58483. }
  58484. }
  58485. getSkyboxTexture(){
  58486. if(this.minimumTiledPanoLoaded)
  58487. {
  58488. if(this.zoomed && this.images360.qualityManager.maxRenderTargetSize > this.images360.qualityManager.maxNavPanoSize)//change 如果放大后和不放大都是2k就不用这个
  58489. {
  58490. return this.images360.panoRenderer.zoomRenderTarget.texture;
  58491. }
  58492. else
  58493. {
  58494. this.tiledPanoRenderTarget.texture.mapping = UVMapping;//add
  58495. return this.tiledPanoRenderTarget.texture;
  58496. }
  58497. }
  58498. else
  58499. {
  58500. return null;
  58501. }
  58502. }
  58503. isLoaded(e){
  58504. if (e && "string" == typeof e)
  58505. console.error("Wrong panoSize given to Panorama.isLoaded(); a tiled pano uses PanoSizeClass");
  58506. return !!this.minimumTiledPanoLoaded && (!e || this.highestFullTileRenderOpCompleted >= e)//改:原本是:this.highestPartialTileRenderOpCompleted >= e, 希望这代表全部加载完
  58507. }
  58508. getWaitDeferred(size){//获取不同size的tile贴图的promiss
  58509. var t = this.resolutionPromise[this.id];
  58510. t || (t = {}, this.resolutionPromise[this.id] = t);
  58511. var i = t[size];
  58512. return i || (i = {
  58513. deferred: $.Deferred(),
  58514. active: !1
  58515. },
  58516. t[size] = i),
  58517. i
  58518. }
  58519. clearWaitDeferreds(){
  58520. var e = this.resolutionPromise[this.id];
  58521. e || (e = {},
  58522. this.resolutionPromise[this.id] = e);
  58523. for (var t in e)
  58524. if (e.hasOwnProperty(t)) {
  58525. var i = e[t];
  58526. i.active = !1,
  58527. i.deferred = $.Deferred();
  58528. }
  58529. }
  58530. resetWaitDeferred(e){
  58531. var t = this.getWaitDeferred(e);
  58532. t.active = !1;
  58533. t.deferred = $.Deferred();
  58534. }
  58535. onTileRendered(ev){
  58536. ev.id === this.id && this.dispatchEvent({
  58537. type:PanoramaEvents.TileLoaded,
  58538. size:ev.panoSize, index:ev.tileIndex, count:ev.totalTiles
  58539. });
  58540. }
  58541. onPanoRendered(ev) {
  58542. if(ev.id === this.id)
  58543. {
  58544. this.minimumTiledPanoLoaded = !0;
  58545. this.updateSkyboxForZoomLevel();//更新贴图 setProjected
  58546. ev.panoSize > this.highestPartialTileRenderOpCompleted && (this.highestPartialTileRenderOpCompleted = ev.panoSize);//应该是更新最高获取到的Partial size
  58547. ev.updateFullComplete && ev.panoSize > this.highestFullTileRenderOpCompleted && (this.highestFullTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Full size
  58548. //this.dispatchEvent("load", ev.panoSize);
  58549. viewer.ifAllLoaded( this);
  58550. this.dispatchEvent({type:PanoramaEvents.LoadComplete, size:ev.panoSize, count:ev.totalTiles});
  58551. }
  58552. }
  58553. onTileRenderFail(ev) {
  58554. ev.id === this.id && this.dispatchEvent({type:PanoramaEvents.LoadFailed });
  58555. }
  58556. onUploadAttemptedForAllTiles(ev) {
  58557. if (ev.id === this.id) {
  58558. var n = this.images360.qualityManager.getPanoSize(PanoSizeClass.BASE);
  58559. if(ev.panoSize === n && this.shouldRedrawOnBaseLoaded) //shouldRedrawOnBaseLoaded一直是false。在4dkk里只有初始点在quickstart后变为true。
  58560. {
  58561. this.shouldRedrawOnBaseLoaded = !1;
  58562. this.panoRenderer.resetRenderStatus(this.id, !0, !1);
  58563. this.panoRenderer.renderPanoTiles(this.id, null, !0, !0);
  58564. }
  58565. }
  58566. }
  58567. createTextLabel(){
  58568. this.removeTextLabel();
  58569. this.label = new TextSprite(Object.assign({},
  58570. labelProp, {text: this.id }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  58571. );
  58572. this.images360.node.add(this.label);
  58573. this.floorPosition && this.label.position.copy(this.floorPosition);
  58574. }
  58575. createTextLabel2(){
  58576. let labelProp2 = {
  58577. //sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  58578. backgroundColor:{r: 255, g: 255, b: 255, a: 0 },
  58579. textColor:{r:255 , g: 255, b: 255, a: 1 },
  58580. textBorderColor:{r:30 , g:30, b: 30, a: 1 },
  58581. textBorderThick:3,
  58582. dontFixOrient:true,
  58583. renderOrder:10,
  58584. fontsize:30,
  58585. };
  58586. this.label2 = new TextSprite(Object.assign({},
  58587. labelProp2, {text: /* this.originID */ parseInt(this.id)+1 }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  58588. );
  58589. this.images360.node.add(this.label2);
  58590. this.floorPosition && this.label2.position.copy(this.floorPosition);
  58591. let s = 0.4;
  58592. this.label2.scale.set(s,s,s);
  58593. viewer.updateVisible(this.label2, 'notDisplay', false);
  58594. }
  58595. removeTextLabel(){
  58596. if(this.label){
  58597. this.label.parent.remove(this.label);
  58598. }
  58599. }
  58600. dispose(){
  58601. let i = viewer.images360.panos.indexOf(this);
  58602. if(i==-1)return
  58603. this.marker.parent.remove(this.marker);
  58604. this.removeTextLabel();
  58605. if(this.depthTex) this.depthTex.dispose();
  58606. viewer.images360.panos.splice(i,1);
  58607. this.dispatchEvent('dispose');
  58608. //删除tile贴图、depthTex等以后再写
  58609. }
  58610. };
  58611. Panorama.prototype.loadTiledPano = function() {
  58612. //var downloads = [] , t = [];
  58613. var downloaded = {} , eventAdded = {}, latestPartialRequest = {}; //每个pano对应一组这些
  58614. return function(size, dirs, fov, o, a, download) {
  58615. var dir = dirs.datasetsLocal.find(e=>e.datasetId == this.pointcloud.dataset_id).direction;
  58616. //var dir = dirs
  58617. null !== o && void 0 !== o || (o = !0),
  58618. null !== a && void 0 !== a || (a = !0);
  58619. var l = this.getWaitDeferred(size)
  58620. , c = l.deferred
  58621. , h = null
  58622. , u = null;
  58623. fov && ("number" == typeof fov ? h = fov : (h = fov.hFov, u = fov.vFov));
  58624. if (!this.isLoaded(size)) {
  58625. //console.log('loadTiledPano', this.id, size, fov)
  58626. if (!l.active) {
  58627. l.active = !0;
  58628. let name = this.id + ":" + size;
  58629. downloaded[name] = downloaded[name] || [];
  58630. /*
  58631. this.downloaded = downloaded
  58632. this.latestPartialRequest = latestPartialRequest
  58633. */
  58634. latestPartialRequest[name] = null;
  58635. if (fov) {
  58636. let tileArr = [];//add
  58637. var d = TileUtils.matchingTilesInDirection(this, size, dir, h, u, tileArr);
  58638. latestPartialRequest[name] = tileArr;
  58639. downloaded[name].forEach((e)=>{
  58640. let item = latestPartialRequest[name].find(a=>e.faceTileIndex == a.faceTileIndex && e.face == a.face);
  58641. if(item){
  58642. item.loaded = true;
  58643. }
  58644. });
  58645. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的全部加载成功
  58646. //let total = TileUtils.getTileCountForSize(size)
  58647. //this.onPanoRendered(this.id, size, total, !0);
  58648. c.resolve(size/* , total */);
  58649. this.resetWaitDeferred(size);
  58650. //console.log('该部分早已经加载好了'+size, this.id)
  58651. latestPartialRequest[name] = null;
  58652. }
  58653. //console.log("Loading partial pano: " + this.id + " with " + d + " tiles")
  58654. }
  58655. if(!eventAdded[this.id]) {
  58656. eventAdded[this.id] = !0;
  58657. this.addEventListener(PanoramaEvents.LoadComplete, function(ev/* e, t */) {//本次任务全部加载完毕
  58658. //console.warn('点位(可能部分)下载完成 ', 'id:'+this.id, 'size:'+ev.size )
  58659. var i = this.getWaitDeferred(ev.size).deferred;//"pending"为还未完成
  58660. i && "pending" === i.state() && this.highestPartialTileRenderOpCompleted >= ev.size && (i.resolve(ev.size, ev.count),
  58661. this.resetWaitDeferred(ev.size));//恢复active为false
  58662. }.bind(this));
  58663. this.addEventListener(PanoramaEvents.LoadFailed, function(ev) {
  58664. var t = this.getWaitDeferred(e).deferred;
  58665. t && "pending" === t.state() && this.highestPartialTileRenderOpCompleted >= ev.t && (t.reject(ev.t),
  58666. this.resetWaitDeferred(ev.t));//恢复active为false
  58667. }.bind(this));
  58668. this.addEventListener(PanoramaEvents.TileLoaded, function(ev/* t, i, n */) {//每张加载完时
  58669. //console.log('tileLoaded', 'id:'+this.id, 'size:'+ev.size, 'tileIndex:'+ev.index )
  58670. let tileIndex = ev.index;
  58671. let total = ev.count;
  58672. let size = ev.size;
  58673. let name = this.id + ":" + size;
  58674. downloaded[name] = downloaded[name] || []; //不是所有的加载都是从loadTiledPano获取的所以会有未定义的情况
  58675. let {faceTileIndex,face} = TileUtils.getTileLocation(size, tileIndex, {});
  58676. downloaded[name].push({faceTileIndex,face});
  58677. var r = this.getWaitDeferred(size).deferred;
  58678. if (r && "pending" === r.state()) {
  58679. r.notify(size, tileIndex, total);
  58680. if(latestPartialRequest[name]){
  58681. let item = latestPartialRequest[name].find(e=>e.faceTileIndex == faceTileIndex && e.face == face);
  58682. item && (item.loaded = true );
  58683. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的局部tiles全部加载成功
  58684. this.onPanoRendered(this.id, size, total, !0); //onPanoRendered还会触发 PanoramaEvents.LoadComplete
  58685. r.resolve(size, total);
  58686. this.resetWaitDeferred(size);
  58687. //console.log('该部分加载好了'+size, this.id)
  58688. latestPartialRequest[name] = null;
  58689. }
  58690. }
  58691. }
  58692. /* var r = this.getWaitDeferred(ev.size).deferred;
  58693. if (r && "pending" === r.state()) {
  58694. r.notify(ev.size, ev.index, ev.count);
  58695. var o = downloads[this.id + ":" + ev.size];
  58696. if(o){//如果有规定下载哪些tile,只需要下载这些tile则LoadComplete
  58697. o.tileCount++
  58698. if(o.tileCount === o.targetTileCount){//达到下载目标数
  58699. this.onPanoRendered(this.id, ev.size, ev.count, !0);
  58700. r.resolve(ev.size, ev.count);
  58701. this.resetWaitDeferred(ev.size)
  58702. }
  58703. }
  58704. } */
  58705. }.bind(this));
  58706. }
  58707. }
  58708. this.images360.tileDownloader.clearForceQueue(),
  58709. this.images360.tileDownloader.forceQueueTilesForPano(this, size, dir, h, u, download);
  58710. this.tiledPanoRenderTarget = this.images360.panoRenderer.activateTiledPano(this, this.images360.qualityManager.getMaxNavPanoSize(), o);
  58711. this.images360.panoRenderer.renderPanoTiles(this.id, dirs, a);
  58712. }else {
  58713. //console.log('早已经全加载好了' +size, this.id)
  58714. c.resolve(size);
  58715. }
  58716. return c.promise()
  58717. }
  58718. }();
  58719. class QualityManager {
  58720. constructor(e, t, i) {
  58721. this.maxNavPanoSize = -1;
  58722. this.maxZoomPanoSize = -1;
  58723. this.devicePixelDensity = e;
  58724. this.deviceScreenSize = t;
  58725. this.clientBandwidth = i;
  58726. this.panoSizeClassMap = {};
  58727. this.useHighResolutionPanos = !0; //是否能够使用2k及以上图
  58728. this.useUltraHighResolutionPanos = !1;
  58729. this.modelHasUltraHighPanos = !1;
  58730. this.qualityManager = this;
  58731. this.maxRenderTargetSize = browser.isMobile() ? 2048 : 4096; //add
  58732. this.init();
  58733. }
  58734. init(e ) {
  58735. //var metadata = store.getters['scene/metadata'] ;//有时候请求不到
  58736. //if(metadata.sceneSource == 11 || metadata.sceneScheme == 12){
  58737. /* if(config.tileClass == '1k'){
  58738. this.useHighResolutionPanos = false //xzw add 只加载1k
  58739. } */
  58740. this.buildPanoSizeClassMap(this.devicePixelDensity, this.deviceScreenSize, this.clientBandwidth);
  58741. this.ultraHighSize = this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58742. this.highSize = this.getPanoSize(PanoSizeClass.HIGH);
  58743. this.standardSize = this.getPanoSize(PanoSizeClass.STANDARD);
  58744. this.baseSize = this.getPanoSize(PanoSizeClass.BASE);
  58745. config$1.tiling.maxZoomPanoQuality && this.ultraHighSize <= config$1.tiling.maxZoomPanoQuality && (config$1.tiling.allowUltraHighResolution = !0);
  58746. this.highQualityThreshold = browser.valueFromHash("threshold2k", config$1.windowHeightHighQualityThreshold);
  58747. this.updateMaximums();
  58748. //e.on(ModelManagerEvents.ActiveModelChanged, this.onModelChanged.bind(this));
  58749. }
  58750. updateFromModel(e) {
  58751. //this.updateHighResolutionSettings(e)
  58752. this.updateUltraHighResolutionSettings(e);
  58753. }
  58754. /* updateHighResolutionSettings(e) {
  58755. this.useHighResolutionPanos = !0
  58756. this.updateMaximums()
  58757. } */
  58758. updateUltraHighResolutionSettings(e) {
  58759. if (config$1.tiling.allowUltraHighResolution && this.modelHasUltraHighPanos) {
  58760. this.useUltraHighResolutionPanos = !0;
  58761. } else {
  58762. this.useUltraHighResolutionPanos = !1;
  58763. }
  58764. this.updateMaximums();
  58765. }
  58766. enableUltraHighQualityMode() {
  58767. this.modelHasUltraHighPanos = !0;
  58768. this.updateUltraHighResolutionSettings(null);
  58769. }
  58770. ultraHighQualityModeEnabled() {
  58771. return this.modelHasUltraHighPanos
  58772. }
  58773. onModelChanged(e) {
  58774. this.updateFromModel(e.model),
  58775. this.updateMaximums();
  58776. }
  58777. updateMaximums() {
  58778. this.maxNavPanoSize = config$1.tiling.maxNavPanoQuality || this.detectMaxNavPanoSize(),
  58779. this.maxZoomPanoSize = config$1.tiling.maxZoomPanoQuality || this.detectMaxZoomPanoSize(),
  58780. this.maxZoomPanoSize < this.maxNavPanoSize && (this.maxNavPanoSize = this.maxZoomPanoSize);
  58781. }
  58782. buildPanoSizeClassMap() {
  58783. this.panoSizeClassMap[PanoSizeClass.BASE] = 512,
  58784. this.panoSizeClassMap[PanoSizeClass.STANDARD] = 1024,
  58785. this.panoSizeClassMap[PanoSizeClass.HIGH] = 2048,
  58786. this.panoSizeClassMap[PanoSizeClass.ULTRAHIGH] = 4096;
  58787. }
  58788. getPanoSize(e) {
  58789. return this.panoSizeClassMap[e]
  58790. }
  58791. getMaxPossiblePanoSize() {
  58792. return this.getPanoSize(PanoSizeClass.ULTRAHIGH)
  58793. }
  58794. getMaxPanoSize() {
  58795. return this.maxZoomPanoSize
  58796. }
  58797. getMaxNavPanoSize() {
  58798. return this.maxNavPanoSize
  58799. }
  58800. getMaxZoomPanoSize() {
  58801. return this.maxZoomPanoSize
  58802. }
  58803. detectMaxNavPanoSizeClass() {
  58804. //return this.useHighResolutionPanos ? browser.isMobile() ? PanoSizeClass.STANDARD : window.innerHeight < this.highQualityThreshold ? PanoSizeClass.STANDARD : PanoSizeClass.HIGH : PanoSizeClass.STANDARD
  58805. /* if(config.name == 'decor'){
  58806. return PanoSizeClass.STANDARD
  58807. }
  58808. return PanoSizeClass.HIGH */
  58809. switch(Potree.settings.navTileClass){
  58810. case '1k':
  58811. return PanoSizeClass.STANDARD;
  58812. break;
  58813. case '2k':
  58814. default:
  58815. return PanoSizeClass.HIGH;
  58816. }
  58817. }
  58818. detectMaxNavPanoSize() {
  58819. var e = this.detectMaxNavPanoSizeClass();
  58820. return this.getPanoSize(e)
  58821. }
  58822. detectMaxZoomPanoSize() {
  58823. if(this.zoomLevelResolution){
  58824. if(this.zoomLevelResolution == '4k' && this.useUltraHighResolutionPanos){
  58825. return this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58826. }else if(this.zoomLevelResolution == '1k' || !this.useHighResolutionPanos){
  58827. return this.getPanoSize(PanoSizeClass.STANDARD);
  58828. }else {
  58829. return this.getPanoSize(PanoSizeClass.HIGH);
  58830. }
  58831. }else {
  58832. if (this.useHighResolutionPanos) {
  58833. /* if (browser.isMobile()) {//手机版如果要2k的将这里去掉
  58834. if (settings.tiling.mobileHighQualityOverride) {
  58835. return this.getPanoSize(PanoSizeClass.HIGH);
  58836. } else {
  58837. return this.getPanoSize(PanoSizeClass.STANDARD);
  58838. }
  58839. } else */if (this.useUltraHighResolutionPanos ) {
  58840. return this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58841. } else {
  58842. return this.getPanoSize(PanoSizeClass.HIGH);
  58843. }
  58844. } else {
  58845. return this.getPanoSize(PanoSizeClass.STANDARD);
  58846. }
  58847. }
  58848. }
  58849. }
  58850. var h = Object.freeze({
  58851. None: 0,
  58852. DirectionalFOV: 1
  58853. });
  58854. var u = function () {
  58855. var e = function e(t, i) {
  58856. var n = e._panoSpaceDir,
  58857. r = e._fovThreshold,
  58858. o = e._fovThresholdNarrow,
  58859. a = Math.max(Math.min(n.dot(t.direction), 1), -1),
  58860. s = Math.max(Math.min(n.dot(i.direction), 1), -1);
  58861. return t._dot = a,
  58862. i._dot = s,
  58863. a >= r && s < r ? -1 : a < r && s >= r ? 1 : a >= o && s < o ? -1 : a < o && s >= o ? 1 : t.panoSize > i.panoSize ? 1 : i.panoSize > t.panoSize ? -1 : -(a - s)
  58864. };
  58865. return e._panoSpaceDir = new Vector3,
  58866. e._fovThreshold = -1,
  58867. e._fovThresholdNarrow = -1,
  58868. e
  58869. }();
  58870. class TilePrioritizer {//优先级处理序列
  58871. constructor(e,t, i, o, a) {
  58872. this.qualityManager = e;
  58873. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize();
  58874. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  58875. this.baseSize = t;
  58876. this.standardSize = i;
  58877. this.highSize = o;
  58878. this.ultraHighSize = a;
  58879. this.priorityCriteria = new TilePrioritizer.PriorityCriteria(null, new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 0, -1));
  58880. }
  58881. updateCriteria(e, t, i, n) {//由player更新
  58882. this.priorityCriteria.pano = e,
  58883. this.priorityCriteria.cameraPosition.copy(t),
  58884. //this.priorityCriteria.cameraDir.copy(i),
  58885. this.priorityCriteria.cameraDirs = i;
  58886. this.priorityCriteria.upcomingPanos = n,
  58887. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(),
  58888. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  58889. }
  58890. canDownloadSize(e) {
  58891. return this.maxNavQuality >= e || this.maxZoomQuality >= e && this.zoomingActive
  58892. }
  58893. /* populateNeighborPanos(e, t, i) {
  58894. i = i || [],
  58895. i.length = 0;
  58896. var n = t.getNeighbours(e);
  58897. for (var r in n)
  58898. if (n.hasOwnProperty(r)) {
  58899. var o = t.get(r);
  58900. if(!o){
  58901. console.log(1)
  58902. }
  58903. i.push(o)
  58904. }
  58905. return i
  58906. } */
  58907. populateScoredPanos(e, t, i, dirs, a) {
  58908. i = i || [],
  58909. i.length = 0;
  58910. var s = [Images360.filters.inPanoDirection(e.position, dirs, TilePrioritizer.DIRECTION_SCORE_STRICTNESS), Images360.filters.not(e)],
  58911. l = [Images360.scoreFunctions.distanceSquared(e), Images360.scoreFunctions.direction(e.position, dirs)],
  58912. c = Common.sortByScore(t, s, l);
  58913. if (c)
  58914. for (var h = 0; h < c.length && h < a; h++) {
  58915. var u = c[h].item;
  58916. i.push(u);
  58917. }
  58918. return i
  58919. }
  58920. queueTilesForPanos(e, t, i, n, r) {
  58921. for (var o = 0, a = 0; a < t.length; a++) {
  58922. var s = t[a],
  58923. l = this.queueTilesForPano(e, i, s, n);
  58924. if (o += l > 0 ? 1 : 0,
  58925. r && o >= r)
  58926. break
  58927. }
  58928. return o
  58929. }
  58930. /* queueTilesInDirectionForPanos(e, t, i, n, r, o, a, s) {//没用到
  58931. for (var l = 0, c = 0; c < i.length; c++) {
  58932. var h = i[c],
  58933. u = this.queueTilesInDirectionForPano(e, t, h, n, o, a);
  58934. if (l += u > 0 ? 1 : 0,
  58935. s && l >= s)
  58936. break
  58937. }
  58938. return l
  58939. }
  58940. */
  58941. canIncludeDescriptor(e) {
  58942. return e.status !== DownloadStatus.Downloading && e.status !== DownloadStatus.Downloaded
  58943. }
  58944. canIncludePano(e, t) {
  58945. return !e.isLoaded(t)
  58946. }
  58947. getFOVDotThreshold(e) {
  58948. return Math.cos(MathUtils.degToRad(e / 2))
  58949. }
  58950. setZoomingActive(e) {
  58951. e !== this.zoomingActive && (this.zoomingActive = e);
  58952. }
  58953. }
  58954. TilePrioritizer.PriorityCriteria = function (e, t, i, n, o) {
  58955. this.pano = e,
  58956. this.cameraPosition = (new Vector3).copy(t),
  58957. //this.cameraDir = (new THREE.Vector3).copy(i),
  58958. this.cameraDirs = [], //
  58959. this.panoSpaceDir = (new Vector3).copy(n),
  58960. this.upcomingPanos = o,
  58961. this.copy = function (e) {
  58962. this.pano = e.pano,
  58963. this.cameraPosition.copy(e.cameraPosition),
  58964. //this.cameraDir.copy(e.cameraDir),
  58965. this.cameraDirs = e.cameraDirs;
  58966. this.panoSpaceDir.copy(e.panoSpaceDir),
  58967. this.upcomingPanos = o;
  58968. },
  58969. this.zoomingActive = !1;
  58970. };
  58971. TilePrioritizer.DIRECTIONAL_FOV = 180;
  58972. TilePrioritizer.DIRECTIONAL_FOV_NARROW = 120;
  58973. TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER = 6;
  58974. TilePrioritizer.MAX_SCORED_PANOS_TOADD = 2;
  58975. TilePrioritizer.MAX_UPCOMING_PANOS_TOADD = 3;
  58976. TilePrioritizer.DIRECTION_SCORE_STRICTNESS = .75;
  58977. TilePrioritizer.appendQueue = function (e, t) {
  58978. if (e && t)
  58979. for (var i = 0; i < t.length; i++){
  58980. e.push(t[i]);
  58981. //console.log(t[i])
  58982. }
  58983. };
  58984. TilePrioritizer.sortPanoTiles = function (descriptors, pano, dir) {
  58985. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  58986. u._panoSpaceDir.copy(dir);
  58987. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir); //应该是将dir根据quaternion转化下
  58988. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  58989. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  58990. descriptors.sort(u);
  58991. };
  58992. TilePrioritizer.insertSortedPanoTile = function (e, t, pano, dir) {
  58993. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  58994. u._panoSpaceDir.copy(dir),
  58995. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir),
  58996. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW),
  58997. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  58998. for (var o = -1, a = 0; a < e.length; a++) {
  58999. var s = u(t, e[a]);
  59000. if (s <= 0) {
  59001. o = a;
  59002. break
  59003. }
  59004. }
  59005. if (o === -1)
  59006. e[e.length] = t;
  59007. else {
  59008. for (var h = e.length; h > o; h--)
  59009. e[h] = e[h - 1];
  59010. e[o] = t;
  59011. }
  59012. };
  59013. TilePrioritizer.prototype.filterDepthTex = function (panos ) {//仅下载depthTex
  59014. if(!Potree.settings.useDepthTex || !this.priorityCriteria.pano)return
  59015. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  59016. let t = [];
  59017. //获得视野范围内的邻近点位序列t
  59018. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  59019. t.forEach(p=>p.loadDepthImg());
  59020. };
  59021. TilePrioritizer.prototype.filterAndPrioritize = function () {//挑选出优先加载的 pano和tile (有点复杂,没看很懂)
  59022. var e = [],
  59023. t = [],
  59024. i = [];
  59025. return function (queue, panos, tileDownloader) {
  59026. //this.populateNeighborPanos(this.priorityCriteria.pano, panos, e);
  59027. /* let cameraDirLocals = this.priorityCriteria.cameraDirs.map(e=>{ //add
  59028. var dataset = viewer.scene.pointclouds.find(u=>u.dataset_id == e.datasetId)
  59029. var matrix = new THREE.Matrix4().copy(dataset.rotateMatrix)
  59030. var direction = math.convertVector.YupToZup(e.direction)
  59031. return {
  59032. datasetId:e.datasetId,
  59033. direction: direction.clone().applyMatrix4(matrix)
  59034. }
  59035. }) */
  59036. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  59037. //获得视野范围内的邻近点位序列t
  59038. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  59039. t.forEach(p=>p.loadDepthImg()); //add
  59040. var s = this.baseSize //512
  59041. ,
  59042. l = this.standardSize //1024
  59043. ,
  59044. c = this.highSize //2048
  59045. ,
  59046. h = this.ultraHighSize; //4096
  59047. this.queueTilesForPano(queue, tileDownloader, this.priorityCriteria.pano, s); //把当前pano的512下载了
  59048. if (this.priorityCriteria.upcomingPanos) {// 添加即将走到的点(之前用于导览路线)512 tiles
  59049. this.queueTilesForPanos(queue, this.priorityCriteria.upcomingPanos, tileDownloader, s, TilePrioritizer.MAX_UPCOMING_PANOS_TOADD);
  59050. }
  59051. i.length = 0;
  59052. //把当前pano角度范围内的tile按照分辨率从低到高加入队列
  59053. if (this.canDownloadSize(l)) {//1024如果在限制范围内的话
  59054. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59055. }
  59056. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  59057. TilePrioritizer.appendQueue(queue, i);
  59058. //添加邻近点t 512的tiles
  59059. this.queueTilesForPanos(queue, t, tileDownloader, s, TilePrioritizer.MAX_SCORED_PANOS_TOADD);
  59060. i.length = 0;
  59061. //NARROW :
  59062. if (this.canDownloadSize(c)) {//2048
  59063. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59064. }
  59065. if (this.canDownloadSize(h)) {//4096
  59066. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59067. }
  59068. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  59069. TilePrioritizer.appendQueue(queue, i);
  59070. i.length = 0;
  59071. if (this.canDownloadSize(l)) {//1024
  59072. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  59073. }
  59074. if (this.canDownloadSize(c)) {//2048
  59075. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  59076. }
  59077. if (this.canDownloadSize(h)) {//4096
  59078. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  59079. }
  59080. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  59081. TilePrioritizer.appendQueue(queue, i);
  59082. this.queueTilesForPanos(queue, e, tileDownloader, s); // 如果前面有populateNeighborPanos的话,这步就是加neibour
  59083. }
  59084. }();
  59085. TilePrioritizer.prototype.queueTilesInDirectionForPano = function () {
  59086. var e = {
  59087. filter: h.DirectionalFOV,
  59088. direction: new Vector3,
  59089. fov: 60
  59090. },
  59091. t = new Vector3;
  59092. return function (i, n, pano, o, a, dirs, c) {
  59093. var dir = dirs.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  59094. //var dir = dirs
  59095. t.copy(dir);
  59096. TileUtils.getRelativeDirection(pano.quaternion4dkk, t);
  59097. e.direction.copy(t);
  59098. e.fov = c;
  59099. return this.filterAndQueueTileDownloadDescriptors(i, n, pano, o, e)
  59100. }
  59101. }();
  59102. TilePrioritizer.prototype.filterAndQueueTileDownloadDescriptors = function () {
  59103. var e = [];
  59104. return function (t, i, n, r, o) {
  59105. var a = i.getTileDownloadDescriptors(n, r);
  59106. e.length = 0,
  59107. this.filterTileDownloadDescriptors(n, a, e, o);
  59108. for (var s = 0, l = 0; l < e.length; l++) {
  59109. var c = e[l];
  59110. if (c) {
  59111. t.push(c);
  59112. s++;
  59113. }
  59114. }
  59115. return s
  59116. }
  59117. }();
  59118. TilePrioritizer.prototype.filterTileDownloadDescriptors = function () {
  59119. new Vector3;
  59120. return function (e, t, i, n) {
  59121. var r, o;
  59122. switch (n.filter) {
  59123. case h.DirectionalFOV:
  59124. for (r = 0; r < t.length; r++)
  59125. o = t[r],
  59126. TileUtils.isTileWithinFOV(o.panoSize, o.tileSize, o.face, o.tileX, o.tileY, n.direction, n.fov) && i.push(o);
  59127. break;
  59128. default:
  59129. for (r = 0; r < t.length; r++)
  59130. o = t[r],
  59131. i.push(o);
  59132. }
  59133. for (r = 0; r < i.length; r++)
  59134. o = i[r],
  59135. this.canIncludeDescriptor(o) || (i[r] = null);
  59136. }
  59137. }();
  59138. TilePrioritizer.prototype.queueTilesForPano = function () {
  59139. var e = {
  59140. filter: h.None
  59141. };
  59142. return function (t, i, n, r) {
  59143. return this.filterAndQueueTileDownloadDescriptors(t, i, n, r, e)
  59144. }
  59145. }();
  59146. /* TilePrioritizer.prototype.queueTilesForPanosInDirection = function () { //没用到
  59147. var e = new THREE.Vector3;
  59148. return function (t, i, n, r, o, a, s, l) {
  59149. for (var h = 0, u = 0; u < n.length; u++) {
  59150. var d = n[u];
  59151. e.copy(d.position),
  59152. e.sub(o),
  59153. e.normalize();
  59154. var p = Math.max(Math.min(a.dot(e), 1), -1),
  59155. f = c.getFOVDotThreshold(s);
  59156. if (p >= f) {
  59157. var g = this.queueTilesInDirectionForPano(t, i, d, r, o, a, s);
  59158. if (h += g > 0 ? 1 : 0,
  59159. l && h >= l)
  59160. break
  59161. }
  59162. }
  59163. return h
  59164. }
  59165. }() */
  59166. //import { i18n } from "@/lang/index"
  59167. // 媒体名称
  59168. /* export const mediaTypes = {
  59169. image: i18n.t("common.photo"),
  59170. video: i18n.t("common.video"),
  59171. audio: i18n.t("common.voice"),
  59172. } */
  59173. // 媒体扩展类型
  59174. const mediaMimes = {
  59175. image: ["jpg", "png", "jpeg", "bmp", "gif"],
  59176. audio: ["mp3", "aac", "ogg", "wav" /* , "m4a" */],
  59177. video: ["mp4", "mov", "quicktime", "webm" /* "rmvb", "wmv" */], //ios:mov
  59178. };
  59179. // 媒体大小显示(MB)
  59180. const mediaMaxSize = {
  59181. image: 10,
  59182. video: 20,
  59183. audio: 5,
  59184. };
  59185. /**
  59186. * 获取媒体扩展类型
  59187. * @param {Stirng} filename 文件名称
  59188. */
  59189. const getMime = filename => {
  59190. if (!filename || filename.indexOf(".") === -1) {
  59191. return ""
  59192. }
  59193. return filename
  59194. .split(".")
  59195. .pop()
  59196. .toLowerCase()
  59197. };
  59198. /**
  59199. * 在路径中获取文件名
  59200. * @param {*} path
  59201. */
  59202. const getFilename = path => {
  59203. const segment = (path || "").split("/");
  59204. return segment[segment.length - 1]
  59205. };
  59206. /**
  59207. * 检测媒体文件是否超过预设限制
  59208. * @param {String} type 媒体类型
  59209. * @param {Number} size 文件大小
  59210. */
  59211. const checkSizeLimit = (type, size) => {
  59212. size = size / 1024 / 1024;
  59213. return size <= mediaMaxSize[type]
  59214. };
  59215. const checkSizeLimitFree = (size, limit) => {
  59216. size = size / 1024 / 1024;
  59217. return size <= limit
  59218. };
  59219. /**
  59220. * 检测媒体类型
  59221. * @param {String} type 媒体类型
  59222. * @param {String} filename 文件名称
  59223. */
  59224. const checkMediaMime = (type, filename) => {
  59225. const mime = getMime(filename);
  59226. const find = mediaMimes[type];
  59227. if (!find) {
  59228. return false
  59229. }
  59230. return find.indexOf(mime) !== -1
  59231. };
  59232. const checkMediaMimeByAccept = (accept, filename) => {
  59233. let mime = getMime(filename);
  59234. let type = accept;
  59235. if (type && type.indexOf("jpg") == -1 && type.indexOf("jpeg") != -1) {
  59236. type += ",image/jpg";
  59237. }
  59238. return (type || "").indexOf(mime) != -1
  59239. };
  59240. const base64ToBlob = base64 => {
  59241. let arr = base64.split(","),
  59242. mime = arr[0].match(/:(.*?);/)[1],
  59243. bstr = atob(arr[1]),
  59244. n = bstr.length,
  59245. u8arr = new Uint8Array(n);
  59246. while (n--) {
  59247. u8arr[n] = bstr.charCodeAt(n);
  59248. }
  59249. return new Blob([u8arr], { type: mime })
  59250. };
  59251. const base64ToDataURL = base64 => {
  59252. return window.URL.createObjectURL(base64ToBlob(base64))
  59253. };
  59254. const blobToBase64 = function(blob) {
  59255. return new Promise(resolve => {
  59256. var reader = new FileReader();
  59257. reader.onload = function() {
  59258. resolve(reader.result);
  59259. };
  59260. reader.readAsDataURL(blob);
  59261. })
  59262. };
  59263. /*
  59264. * @Author: Rindy
  59265. * @Date: 2019-08-06 16:25:08
  59266. * @LastEditors: Rindy
  59267. * @LastEditTime: 2021-08-27 12:33:49
  59268. * @Description: Request
  59269. */
  59270. //import { $alert, $confirm, $loginTips } from "@/components/shared/message"
  59271. //import { $waiting } from "@/components/shared/loading"
  59272. //import { checkLogin } from "@/api"
  59273. //import { LoginDetector } from "@/core/starter"
  59274. //import { i18n } from "@/lang"
  59275. //import { password } from "@/utils/string"
  59276. //import store from "../Store"
  59277. // 空函数
  59278. const noop = function() {};
  59279. // 请求回调队列
  59280. let postQueue = [];
  59281. /**
  59282. * @property {number} NEXT - 继续执行
  59283. * @property {number} SUCCESS - 成功
  59284. * @property {number} EXCEPTION - 异常错误
  59285. * @property {number} FAILURE_CODE_3001 - 缺少必要参数
  59286. * @property {number} FAILURE_CODE_3002 - 访问异常
  59287. * @property {number} FAILURE_CODE_3003 - 非法访问
  59288. * @property {number} FAILURE_CODE_3004 - 用户未登录
  59289. * @property {number} FAILURE_CODE_3005 - 验证码已过期
  59290. * @property {number} FAILURE_CODE_3006 - 验证码错误
  59291. * @property {number} FAILURE_CODE_3007 - 昵称已存在
  59292. * @property {number} FAILURE_CODE_3008 - 该手机已被注册
  59293. * @property {number} FAILURE_CODE_3009 - 两次输入的密码不一致
  59294. * @property {number} FAILURE_CODE_3010 - 昵称长度错误
  59295. * @property {number} FAILURE_CODE_3011 - 密码长度错误
  59296. * @property {number} FAILURE_CODE_3012 - 昵称包含敏感词
  59297. * @property {number} FAILURE_CODE_3013 - 手机号码格式错误
  59298. * @property {number} FAILURE_CODE_3014 - 账号或密码不正确
  59299. * @property {number} FAILURE_CODE_3015 - 用户不存在
  59300. * @property {number} FAILURE_CODE_3016 - 您没有权限,请联系管理员
  59301. * @property {number} FAILURE_CODE_3017 - 空文件
  59302. * @property {number} FAILURE_CODE_3018 - 需要上传或使用的文件不存在
  59303. * @property {number} FAILURE_CODE_5010 - 找不到该场景对应的相机
  59304. * @property {number} FAILURE_CODE_5012 - 数据不正常
  59305. * @property {number} FAILURE_CODE_5014 - 无权操作该场景
  59306. * @property {number} FAILURE_CODE_5005 - 场景不存在
  59307. */
  59308. const statusCode = {
  59309. NEXT: -999,
  59310. SUCCESS: 0,
  59311. EXCEPTION: -1,
  59312. FAILURE_CODE_3001: 3001,
  59313. FAILURE_CODE_3002: 3002,
  59314. FAILURE_CODE_3003: 3003,
  59315. FAILURE_CODE_3004: 3004,
  59316. FAILURE_CODE_3005: 3005,
  59317. FAILURE_CODE_3006: 3006,
  59318. FAILURE_CODE_3007: 3007,
  59319. FAILURE_CODE_3008: 3008,
  59320. FAILURE_CODE_3009: 3009,
  59321. FAILURE_CODE_3010: 3010,
  59322. FAILURE_CODE_3011: 3011,
  59323. FAILURE_CODE_3012: 3012,
  59324. FAILURE_CODE_3013: 3013,
  59325. FAILURE_CODE_3014: 3014,
  59326. FAILURE_CODE_3015: 3015,
  59327. FAILURE_CODE_3016: 3016,
  59328. FAILURE_CODE_3017: 3017,
  59329. FAILURE_CODE_3018: 3018,
  59330. FAILURE_CODE_5010: 5010,
  59331. FAILURE_CODE_5012: 5012,
  59332. FAILURE_CODE_5014: 5014,
  59333. FAILURE_CODE_5005: 5005,
  59334. };
  59335. /**
  59336. * 获取Token
  59337. * @function
  59338. */
  59339. function getToken() {
  59340. var urlToken = browser.urlHasValue("token", true);
  59341. if (urlToken) {
  59342. // 设置token共享给用户中心
  59343. localStorage.setItem("token", urlToken);
  59344. }
  59345. return urlToken || localStorage.getItem("token") || ""
  59346. }
  59347. /**
  59348. * 根据状态码的结果处理后续操作
  59349. * @function
  59350. * @param {number} code - 状态码
  59351. * @param {function} callback - 回调
  59352. */
  59353. function statusCodesHandler(code, callback) {
  59354. if (code == statusCode.EXCEPTION) {
  59355. return $alert({ content: i18n.t("tips.exception") })
  59356. }
  59357. if (
  59358. code == statusCode.FAILURE_CODE_3002 ||
  59359. code == statusCode.FAILURE_CODE_3003 ||
  59360. code == statusCode.FAILURE_CODE_3004
  59361. ) {
  59362. callback(code);
  59363. return showLoginTips()
  59364. }
  59365. if (code == statusCode.FAILURE_CODE_3001) {
  59366. callback(code);
  59367. return $alert({ content: i18n.t("tips.params_notfound") })
  59368. }
  59369. if (code == statusCode.FAILURE_CODE_3017) {
  59370. callback(code);
  59371. return $alert({ content: i18n.t("tips.file_notfound") })
  59372. }
  59373. if (code == statusCode.FAILURE_CODE_5005) {
  59374. /* if (!config.isEdit) {
  59375. return (location.href = config.pages.NotFound)
  59376. } */
  59377. callback(code);
  59378. return $alert({ content: i18n.t("tips.scene_notfound") })
  59379. }
  59380. if (code == statusCode.FAILURE_CODE_5010) {
  59381. callback(code);
  59382. return $alert({ content: i18n.t("tips.camera_notfound") })
  59383. }
  59384. if (code == statusCode.FAILURE_CODE_5012) {
  59385. callback(code);
  59386. return $alert({ content: i18n.t("tips.data_error") })
  59387. }
  59388. if (code == statusCode.FAILURE_CODE_5014) {
  59389. callback(code);
  59390. return $alert({ content: i18n.t("tips.auth_deny") })
  59391. }
  59392. return statusCode.NEXT
  59393. }
  59394. $.ajaxSetup({
  59395. headers: {},
  59396. beforeSend: function(xhr) {
  59397. const token = getToken();
  59398. if (token) {
  59399. xhr.setRequestHeader("token", token);
  59400. } else if (!token && this.url.indexOf("isLogin") != -1) {
  59401. showLoginTips();
  59402. }
  59403. /* if (config.oem == "localshow") {
  59404. // 本地版本兼容当前目录
  59405. if (this.url.indexOf("http") == -1 && this.url.indexOf("/") == 0) {
  59406. this.url = this.url.substr(1)
  59407. }
  59408. } */
  59409. // if(this.url.indexOf('http')==-1 && this.url.indexOf('/') !=0){
  59410. // this.url = '/'+this.url
  59411. // }
  59412. },
  59413. error: function(xhr, status, error) {
  59414. // 出错时默认的处理函数
  59415. if (this.url.indexOf("/scene.json") != -1 && xhr.status == 404) {
  59416. return $alert({ content: i18n.t("tips.scene_notfound") })
  59417. } else if (this.type === "POST") {
  59418. return $alert({ content: i18n.t("tips.network_error") })
  59419. }
  59420. },
  59421. success: function(result) {},
  59422. complete: function() {
  59423. // Post类型请求无论成功或失败都关闭等待提示
  59424. if (this.type === "POST") {
  59425. http.__loading && $waiting.hide();
  59426. }
  59427. http.__loading = true;
  59428. },
  59429. });
  59430. /**
  59431. * @namespace http
  59432. * @type {Object}
  59433. */
  59434. const http = {
  59435. statusCode,
  59436. __loading: true,
  59437. __request(xhr, method, url, data, done, fail) {
  59438. if (typeof done != "function") {
  59439. done = noop;
  59440. }
  59441. if (typeof fail != "function") {
  59442. fail = noop;
  59443. }
  59444. xhr.done(result => {
  59445. if (typeof result.code !== "undefined") {
  59446. const flag = statusCodesHandler(result.code, function(code) {
  59447. // 需要登录的状态
  59448. if (
  59449. code == statusCode.FAILURE_CODE_3001 ||
  59450. code == statusCode.FAILURE_CODE_3002 ||
  59451. code == statusCode.FAILURE_CODE_3003 ||
  59452. code == statusCode.FAILURE_CODE_3004
  59453. ) {
  59454. if (url.indexOf("isLogin") == -1 && url.indexOf("openSceneBykey") == -1) {
  59455. postQueue.push(function() {
  59456. http[method](url, data, done, fail);
  59457. });
  59458. }
  59459. }
  59460. fail();
  59461. });
  59462. if (flag === statusCode.NEXT) {
  59463. done(result, result.code == 0);
  59464. }
  59465. } else {
  59466. done(result);
  59467. }
  59468. });
  59469. xhr.fail(fail);
  59470. xhr.always(() => (xhr = null));
  59471. return xhr
  59472. },
  59473. /**
  59474. * Get请求
  59475. * @param {String} url 请求地址
  59476. * @param {Object?} data 请求参数
  59477. * @param {Function?} done 成功回调
  59478. * @param {Function?} fail 失败回调
  59479. */
  59480. get(url, data = {}, done, fail) {
  59481. if (/\.json/.test(url)) {
  59482. // json文件格式自动调用getJson方法
  59483. return this.getJson(url, data, done, fail)
  59484. }
  59485. return this.__request($.get(url, data), "get", url, data, done, fail)
  59486. },
  59487. /**
  59488. * Get Blob请求
  59489. * @param {String} url 请求地址
  59490. * @param {Object?} data 请求参数
  59491. * @param {Function?} done 成功回调
  59492. * @param {Function?} fail 失败回调
  59493. */
  59494. getText(url, data = {}, done, fail) {
  59495. return this.__request(
  59496. $.ajax({
  59497. url: url,
  59498. dataType: "text",
  59499. }),
  59500. "getText",
  59501. url,
  59502. data,
  59503. done,
  59504. fail
  59505. )
  59506. },
  59507. /**
  59508. * GetJson请求 读取json文件数据
  59509. * @param {String} url 请求地址
  59510. * @param {Object?} data 请求参数
  59511. * @param {Function?} done 成功回调
  59512. * @param {Function?} fail 失败回调
  59513. */
  59514. getJson(url, data = {}, done, fail) {
  59515. return this.__request($.getJSON(url, data), "get", url, data, done, fail)
  59516. },
  59517. /**
  59518. * Get Blob请求
  59519. * @param {String} url 请求地址
  59520. * @param {Object?} data 请求参数
  59521. * @param {Function?} done 成功回调
  59522. * @param {Function?} fail 失败回调
  59523. */
  59524. getBlob(url, data = {}, done, fail) {
  59525. return this.__request(
  59526. $.ajax({
  59527. url: url,
  59528. dataType: "blob",
  59529. }),
  59530. "getBlob",
  59531. url,
  59532. data,
  59533. done,
  59534. fail
  59535. )
  59536. },
  59537. /**
  59538. * Get Arraybuffer请求
  59539. * @param {String} url 请求地址
  59540. * @param {Object?} data 请求参数
  59541. * @param {Function?} done 成功回调
  59542. * @param {Function?} fail 失败回调
  59543. */
  59544. getArraybuffer(url, data = {}, done, fail) {
  59545. return this.__request(
  59546. $.ajax({
  59547. url: url,
  59548. dataType: "arraybuffer",
  59549. }),
  59550. "getArraybuffer",
  59551. url,
  59552. data,
  59553. done,
  59554. fail
  59555. )
  59556. },
  59557. /**
  59558. * Post 请求
  59559. * @param {String} url 请求地址
  59560. * @param {Object?} data 请求参数
  59561. * @param {Function?} done 成功回调
  59562. * @param {Function?} fail 失败回调
  59563. */
  59564. post(url, data = {}, done, fail) {
  59565. if (url.indexOf("isLogin") == -1) {
  59566. http.__loading && $waiting.show();
  59567. }
  59568. return this.__request($.post(url, data), "post", url, data, done, fail)
  59569. },
  59570. /**
  59571. * PostJson 请求
  59572. * @param {String} url 请求地址
  59573. * @param {Object?} data 请求参数
  59574. * @param {Function?} done 成功回调
  59575. * @param {Function?} fail 失败回调
  59576. */
  59577. postJson(url, data = {}, done, fail) {
  59578. http.__loading && $waiting.show();
  59579. return this.__request(
  59580. $.ajax({
  59581. type: "POST",
  59582. url: url,
  59583. contentType: "application/json",
  59584. data: JSON.stringify(data),
  59585. }),
  59586. "postJson",
  59587. url,
  59588. data,
  59589. done,
  59590. fail
  59591. )
  59592. },
  59593. /**
  59594. * Post 表单 支持文件上传
  59595. * @param {String} url 请求地址
  59596. * @param {FormData?} formData 请求参数
  59597. * @param {Function?} done 成功回调
  59598. * @param {Function?} fail 失败回调
  59599. */
  59600. postForm(url, formData, done, fail, onProgress) {
  59601. if (typeof onProgress === "function") {
  59602. return this.__request(
  59603. $.ajax({
  59604. type: "POST",
  59605. url: url,
  59606. processData: false,
  59607. contentType: false,
  59608. data: formData,
  59609. xhr: function() {
  59610. const xhr = new XMLHttpRequest();
  59611. xhr.upload.addEventListener("progress", function(e) {
  59612. onProgress((e.loaded / e.total) * 100 + "%");
  59613. });
  59614. return xhr
  59615. },
  59616. }),
  59617. "postForm",
  59618. url,
  59619. formData,
  59620. done,
  59621. fail
  59622. )
  59623. } else {
  59624. http.__loading && $waiting.show();
  59625. return this.__request(
  59626. $.ajax({
  59627. type: "POST",
  59628. url: url,
  59629. processData: false,
  59630. contentType: false,
  59631. data: formData,
  59632. }),
  59633. "postForm",
  59634. url,
  59635. formData,
  59636. done,
  59637. fail
  59638. )
  59639. }
  59640. },
  59641. /**
  59642. * 加载图片
  59643. * @param {String} url 请求地址
  59644. * @param {Number?} retry 重试次数,默认为3
  59645. */
  59646. loadImage(url, retry = 3) {
  59647. const def = $.Deferred();
  59648. const img = new Image();
  59649. /* if (process.env.VUE_APP_REGION == "AWS" && url.indexOf("x-oss-process=image") != -1) {
  59650. var arr = url.split("?")
  59651. url = arr[0] + encodeURIComponent("?" + arr[1].replace(/\//g, "@"))
  59652. } */
  59653. const load = () => {
  59654. console.warn("Retrying load image: " + url);
  59655. this.loadImage(url, retry - 1)
  59656. .done(def.resolve.bind(def))
  59657. .progress(def.notify.bind(def))
  59658. .fail(def.reject.bind(def));
  59659. };
  59660. img.onerror = function() {
  59661. retry > 0 ? setTimeout(() => load(), 1e3) : def.reject(`[${url}]加载失败`);
  59662. };
  59663. img.onload = function() {
  59664. def.resolve(img);
  59665. };
  59666. img.crossOrigin = "anonymous";
  59667. img.src = url;
  59668. return def
  59669. },
  59670. /**
  59671. * 上传文件
  59672. * @param {String} url 请求地址
  59673. * @param {Object?} data 请求参数
  59674. * @param {Function?} done 成功回调
  59675. * @param {Function?} fail 失败回调
  59676. */
  59677. uploadFile(url, data = {}, done, fail, onProgress) {
  59678. const form = new FormData();
  59679. // if (file.needTransfer) { //ie和苹果都不支持dataURLtoFile得传送,所以只能用blob
  59680. // form.append("file", common.dataURLtoBlob(file.file), file.name || file.file.name);
  59681. // } else {
  59682. // form.append("file", file.file, file.name || file.file.name);
  59683. // }
  59684. for (let key in data) {
  59685. if (key == "file") {
  59686. form.append("file", data[key], data.filename || data[key].name);
  59687. } else if (key != "filename") {
  59688. form.append(key, data[key]);
  59689. }
  59690. }
  59691. return this.postForm(url, form, done, fail, onProgress)
  59692. },
  59693. /**
  59694. * 上传文件
  59695. * @param {String} url 请求地址
  59696. * @param {Object?} data 请求参数 {file:'base64 string',filename:'image.jpg',...}
  59697. * @param {Function?} done 成功回调
  59698. * @param {Function?} fail 失败回调
  59699. */
  59700. uploadBlobFile(url, data = {}, done, fail) {
  59701. const form = new FormData();
  59702. for (let key in data) {
  59703. if (key === "file") {
  59704. form.append("file", base64ToBlob(data.file), data.filename);
  59705. } else if (key != "filename") {
  59706. form.append(key, data[key]);
  59707. }
  59708. }
  59709. return this.postForm(url, form, done, fail)
  59710. },
  59711. };
  59712. window.downloaded = {};
  59713. window.startdownloads = [];
  59714. class TileDownloader extends EventDispatcher{
  59715. constructor( ) {
  59716. super();
  59717. this.panos = null;
  59718. this.retryMinimumTime = 1e4;
  59719. this.panoLoadCallbacks = {};
  59720. this.downloadDescriptors = {};
  59721. this.priorityQueue = [];
  59722. this.forceQueue = [];
  59723. this.activeDownloads = [];
  59724. this.tilePrioritizer = null;
  59725. this.refreshInterval = null;
  59726. this.processPriorityQueue = !1;
  59727. this.concurrentDownloads = 6;//e.concurrentDownloads || 1;
  59728. this.downloadTestResults = {};
  59729. this.freeze = Object.freeze({
  59730. Testing: 1,
  59731. Success: 2,
  59732. Fail: 3
  59733. });
  59734. this.visible = true; //add 借用viewer.updateVisible来判断是否start
  59735. viewer.addEventListener('pageVisible', (e)=>{//不可见时不refreshUpdateInterval
  59736. //console.log('visibilitychange:', state)
  59737. viewer.updateVisible(this, 'pageVisible', e.v);
  59738. this.judgeStart();
  59739. });
  59740. }
  59741. setPanoData(e, t /* , i */) {
  59742. this.panos = e,
  59743. this.imagePanos = t;
  59744. // this.panoGroupId = i
  59745. }
  59746. start() {
  59747. this.downloadCubeTex = true;
  59748. if(!Potree.settings.useDepthTex){
  59749. viewer.updateVisible(this,'pano', true );
  59750. this.judgeStart();
  59751. }else {
  59752. this.refreshInterval || this.judgeStart();
  59753. }
  59754. }
  59755. stop() {
  59756. this.downloadCubeTex = false;
  59757. if(!Potree.settings.useDepthTex){
  59758. viewer.updateVisible(this,'pano', false );
  59759. this.judgeStart();
  59760. }
  59761. }
  59762. judgeStart(){//add
  59763. if(this.visible){
  59764. //console.log('judgeStart true')
  59765. this.started = true;
  59766. this.refreshUpdateInterval(0);
  59767. }else {
  59768. //console.log('judgeStart false')
  59769. this.started = false;
  59770. window.clearTimeout(this.refreshInterval);
  59771. }
  59772. }
  59773. refreshUpdateInterval(e) {
  59774. e || (e = 0),
  59775. this.refreshInterval = window.setTimeout(function() {
  59776. var e = this.update();
  59777. e ? this.refreshUpdateInterval(TileDownloader.ACTIVE_REFRESH_DELAY) : this.refreshUpdateInterval(TileDownloader.IDLE_REFRESH_DELAY);
  59778. }
  59779. .bind(this), e);
  59780. }
  59781. update() {
  59782. if(this.downloadCubeTex){ //可以下载贴图
  59783. var e = this.forceQueue.length > 0;
  59784. this.processQueueForDownloading(this.forceQueue);
  59785. if (this.processPriorityQueue) {
  59786. this.queuePrioritizedTilesForPanos(this.panos);
  59787. this.priorityQueue.length > 0 && (e = !0);
  59788. this.processQueueForDownloading(this.priorityQueue);
  59789. }
  59790. return e
  59791. }else {//仅下载depthTex
  59792. this.tilePrioritizer.filterDepthTex(this.panos);
  59793. }
  59794. }
  59795. queuePrioritizedTilesForPanos(e) {
  59796. this.tilePrioritizer && (this.clearQueue(this.priorityQueue),
  59797. this.tilePrioritizer.filterAndPrioritize(this.priorityQueue, e, this),
  59798. this.clearFromQueue(this.priorityQueue, DownloadStatus.None, !0), //去除state为DownloadStatus.None的(可能是去除已经在下载的)
  59799. this.setStatusOrRemoveForAllDescriptors(this.priorityQueue, DownloadStatus.Queued));
  59800. }
  59801. clearQueue(e) {//停止下载并清空
  59802. this.setStatusForAllDescriptors(e, DownloadStatus.None),
  59803. e.length = 0;
  59804. }
  59805. clearForceQueue() {
  59806. this.clearQueue(this.forceQueue);
  59807. }
  59808. clearFromQueue(e, t, i) {
  59809. for (var n = 0; n < e.length; n++) {
  59810. var r = e[n];
  59811. r && (t === r.status && !i || t !== r.status && i) && (e[n] = null);
  59812. }
  59813. }
  59814. setStatusForAllDescriptors(e, t) {
  59815. for (var i = 0; i < e.length; i++) {
  59816. var n = e[i];
  59817. n && (n.status = t);
  59818. }
  59819. }
  59820. setStatusOrRemoveForAllDescriptors(e, t) {
  59821. for (var i = 0; i < e.length; i++) {
  59822. var n = e[i];
  59823. n && (n.status !== t ? n.status = t : e[i] = null);
  59824. }
  59825. }
  59826. getTileDownloadDescriptors(pano, size) {//获取该pano的该size的全部的tile的descriptor
  59827. var i = this.getAllTileDownloadDescriptorsForPano(pano),
  59828. n = i[size];
  59829. return n || (n = this.buildDownloadDescriptorArray(size),//创建的全部是空的
  59830. i[size] = n,
  59831. this.initTileDownloadDescriptors(n, pano, size)),//绑定到该pano size
  59832. n
  59833. }
  59834. getAllTileDownloadDescriptorsForPano(pano) {//新建空Descriptors
  59835. var t = this.downloadDescriptors[pano.id];
  59836. return t || (t = {},
  59837. this.downloadDescriptors[pano.id] = t),
  59838. t
  59839. }
  59840. processQueueForDownloading(e, t) {//执行下载任务
  59841. this.cleanupActiveDownloads();
  59842. if (this.activeDownloads.length < this.concurrentDownloads || t) {
  59843. var i = t ? e.length : this.concurrentDownloads - this.activeDownloads.length;
  59844. for (var n = 0, r = 0; n < i && e.length > 0; r++) {
  59845. var o = e.shift();
  59846. if(o){
  59847. //add 为了防止1024的在512前下载完,这里强行等待512下载完毕再开始下载
  59848. if(o.panoSize > 512 && !this.isPanoDownloaded(o.pano, 512) ){
  59849. //console.log('512的还没下载好呢!')
  59850. e.push(o);
  59851. break;//一般512的都是连续下载的,所以后面就都不是512了直接中断
  59852. }
  59853. this.startDownload(o);
  59854. n++;
  59855. }
  59856. }
  59857. }
  59858. }
  59859. testDownload(panoSize, tileSize, callback) {
  59860. var n = this.downloadTestResults[panoSize];
  59861. if (n)
  59862. return void(n === this.freeze.Success ? callback(!0) : n === this.freeze.Fail && callback(!1));
  59863. this.downloadTestResults[panoSize] = this.freeze.Testing;
  59864. var r = this.panos[0],
  59865. o = this.getTileUrl({pano:r, panoSize, tileSize, tileIndex:0} /* r.id, panoSize, tileSize, 0 */),
  59866. a = function(t) {
  59867. this.downloadTestResults[panoSize] = this.freeze.Success,
  59868. callback(!0);
  59869. }
  59870. .bind(this),
  59871. s = function() {
  59872. this.downloadTestResults[panoSize] = this.freeze.Fail,
  59873. callback(!1);
  59874. }
  59875. .bind(this);
  59876. this.loadImage(o, 0, a, s);
  59877. }
  59878. startDownload(e) {//开始下载啦
  59879. //console.log('startDownload')
  59880. startdownloads.push(e);
  59881. e.status = DownloadStatus.Downloading;
  59882. var t = this.getTileUrl(e/* e.pano.id, e.panoSize, e.tileSize, e.tileIndex, e.pano.alignmentType */);//xzw add alignmentType
  59883. if(!t)return;
  59884. this.activeDownloads.push(e);
  59885. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  59886. }
  59887. downloadFailed(e, t) {}
  59888. downloadComplete(e, t) {//下载成功时
  59889. //if (e.panoGroupId === this.panoGroupId) {
  59890. var i = this.getPanoLoadCallbacks(e.pano, e.panoSize);
  59891. e.status = DownloadStatus.Downloaded,
  59892. i && i.onProgress && i.onProgress(e.pano, e.panoSize);
  59893. var n = {
  59894. panoId: e.pano.id,
  59895. image: t,
  59896. tileSize: e.tileSize,
  59897. panoSize: e.panoSize,
  59898. tileIndex: e.tileIndex,
  59899. faceTileIndex: e.faceTileIndex,
  59900. totalTiles: e.totalTiles,
  59901. face: e.face,
  59902. tileX: e.tileX,
  59903. tileY: e.tileY,
  59904. direction: e.direction
  59905. };
  59906. downloaded[e.pano.id] || (downloaded[e.pano.id]={512:[],1024:[],2048:[]});
  59907. downloaded[e.pano.id][e.panoSize] || (downloaded[e.pano.id][e.panoSize] = []);
  59908. downloaded[e.pano.id][e.panoSize].push(e);
  59909. if(e.panoSize != 512 && downloaded[e.pano.id][512].length<6){
  59910. console.warn('没下完');
  59911. }
  59912. e.image = t,
  59913. this.dispatchEvent({type:TileDownloaderEvents.TileDownloadSuccess, desc:n} );
  59914. this.isPanoDownloaded(e.pano, e.panoSize) && (n = {
  59915. panoId: e.pano.id,
  59916. tileSize: e.tileSize,
  59917. panoSize: e.panoSize
  59918. },
  59919. this.dispatchEvent({type:TileDownloaderEvents.PanoDownloadComplete, desc:n}),
  59920. i && i.onLoad && i.onLoad(e.pano, e.panoSize));
  59921. //}
  59922. }
  59923. isPanoDownloaded(e, t) {
  59924. var i = this.getTileDownloadDescriptors(e, t);
  59925. if (i.length <= 0)
  59926. return !1;
  59927. for (var n = 0; n < i.length; n++) {
  59928. var r = i[n];
  59929. if (r.status !== DownloadStatus.Downloaded)
  59930. return !1
  59931. }
  59932. return !0
  59933. }
  59934. setPanoLoadCallbacks(e, t, i, n, r) {
  59935. var o = e.id + ":" + this.qualityManager.getPanoSize(t);
  59936. this.panoLoadCallbacks[o] = {
  59937. onLoad: i,
  59938. onFail: n,
  59939. onProgress: r
  59940. };
  59941. }
  59942. getPanoLoadCallbacks(e, t) {
  59943. var i = e.id + ":" + t;
  59944. return this.panoLoadCallbacks[i]
  59945. }
  59946. buildDownloadDescriptorArray(e) {
  59947. for (var t = TileUtils.getTileCountForSize(e), i = [], n = 0; n < t; n++) {
  59948. var r = this.buildDownloadDescriptor();
  59949. i.push(r);
  59950. }
  59951. return i
  59952. }
  59953. buildDownloadDescriptor() {//Descriptor!
  59954. var e = {
  59955. panoGroupId: null,
  59956. pano: null,
  59957. panoSize: -1,
  59958. tileSize: -1,
  59959. tileIndex: -1,
  59960. totalTiles: -1,
  59961. faceTileIndex: -1,
  59962. status: DownloadStatus.None,
  59963. url: null,
  59964. image: null,
  59965. direction: new Vector3, //该tile在cube中的方向
  59966. face: -1,
  59967. cubeFace: -1,
  59968. tileX: -1,
  59969. tileY: -1
  59970. };
  59971. return e
  59972. }
  59973. initTileDownloadDescriptors(e, t, i) {
  59974. for (var n = 0; n < e.length; n++) {
  59975. var r = e[n];
  59976. this.initTileDownloadDescriptor(r, t, i, n);
  59977. }
  59978. }
  59979. initTileDownloadDescriptor(desc, pano, size, index) {
  59980. var r = size >= TileUtils.TILE_SIZE ? TileUtils.TILE_SIZE : size;
  59981. desc.face = TileUtils.getFaceForTile(size, index);//根据顺序得到的face的index
  59982. desc.cubeFace = TileUtils.mapFaceToCubemapFace(desc.face);//为了贴图而转化的face index
  59983. //desc.panoGroupId = this.panoGroupId;//就是场景号
  59984. desc.pano = pano;
  59985. desc.panoSize = size;
  59986. desc.tileSize = r; //瓦片图size 512
  59987. desc.tileIndex = index;
  59988. desc.totalTiles = TileUtils.getTileCountForSize(size);
  59989. desc.status = DownloadStatus.None;
  59990. desc.image = null;
  59991. TileUtils.getTileLocation(desc.panoSize, desc.tileIndex, desc);//得到该tile在这个face中的具体位置(tileX等)
  59992. TileUtils.getTileVector(desc.panoSize, desc.tileSize, desc.cubeFace, desc.tileX, desc.tileY, TileUtils.LocationOnTile.Center, 0, desc.direction);
  59993. }
  59994. getTiles(d, sceneNum){
  59995. if(Potree.settings.isLocal2){//新的地址 scene_view_data/场景码/images/tiles
  59996. return `${Potree.settings.urls.prefix3}/scene_view_data/${sceneNum}/images/${d}`
  59997. }
  59998. return `${Potree.settings.urls.prefix3}/images/images${sceneNum}/${d}`
  59999. }
  60000. loadImage(e, t, i, n) {
  60001. //自己修改了ajax,把getImage改成了loadImg
  60002. http.loadImage(e, t).then(function(e) {
  60003. i(e);
  60004. }).fail(n);
  60005. }
  60006. }
  60007. TileDownloader.prototype.forceQueueTilesForPano = function() {//根据条件开始加载tile
  60008. var e = [],
  60009. t = [];
  60010. return function(pano, size, dir, hFov, vFov, download) {
  60011. e.length = 0;
  60012. for (var u = this.getTileDownloadDescriptors(pano, size), d = 0; d < u.length; d++) {
  60013. var p = u[d];
  60014. p.status !== DownloadStatus.None && p.status !== DownloadStatus.Queued || e.push(p);
  60015. }
  60016. if (dir && e.length > 0) {
  60017. TilePrioritizer.sortPanoTiles(e, pano, dir); //按最佳方向排序e
  60018. t.length = 0;
  60019. TileUtils.matchingTilesInDirection(pano, size, dir, hFov, vFov, t);//得到在符合视野标准的集合t
  60020. for (var f = 0, g = function(e) {
  60021. return e.face === m.face && e.faceTileIndex === m.faceTileIndex
  60022. }; f < e.length;) { //过滤掉不符合角度要求的
  60023. var m = e[f],
  60024. v = t.findIndex(g);
  60025. v < 0 ? e.splice(f, 1) : f++;
  60026. }
  60027. }
  60028. for (var A = 0; A < e.length; A++){
  60029. this.forceQueue.push(e[A]); //装载
  60030. }
  60031. /* if(e.length){
  60032. console.log(e)
  60033. } */
  60034. this.setStatusForAllDescriptors(this.forceQueue, DownloadStatus.ForceQueued);
  60035. this.clearFromQueue(this.priorityQueue, DownloadStatus.ForceQueued, !1);
  60036. download && this.processQueueForDownloading(this.forceQueue, !0);
  60037. }
  60038. }();
  60039. TileDownloader.prototype.cleanupActiveDownloads = function() {
  60040. var e = [];
  60041. return function() {
  60042. e.length = 0;
  60043. for (var t = 0; t < this.activeDownloads.length; t++) {
  60044. var i = this.activeDownloads[t];
  60045. i.status !== DownloadStatus.Downloaded && i.status !== DownloadStatus.Failed && e.push(i);
  60046. }
  60047. this.activeDownloads.length = 0,
  60048. this.activeDownloads.push.apply(this.activeDownloads, e);
  60049. }
  60050. }();
  60051. TileDownloader.prototype.getTileUrl = function() {
  60052. var e = {
  60053. 256: "256",
  60054. 512: "512",
  60055. 1024: "1k",
  60056. 2048: "2k",
  60057. 4096: "4k"
  60058. },
  60059. t = {
  60060. face: -1,
  60061. faceTileIndex: -1,
  60062. tileX: -1,
  60063. tileY: -1
  60064. };
  60065. return function(o={} ) {
  60066. var id = o.pano.originID, ////////
  60067. panoSize = o.panoSize,
  60068. tileSize = o.tileSize,
  60069. tileIndex = o.tileIndex,
  60070. sceneCode = o.pano.pointcloud.sceneCode;
  60071. var metadata = {sceneScheme:10};
  60072. TileUtils.getTileLocation(panoSize, tileIndex, t);
  60073. var s = Math.floor(panoSize / tileSize),
  60074. l = s * s,
  60075. h = Math.floor(tileIndex / l),
  60076. u = "",
  60077. d = '', g = '';
  60078. if(Potree.settings.isLocal){//原始规则
  60079. //1 === config.tiling.customCompression && (u = "_" + config.tiling["q" + e[panoSize]]);
  60080. //1 === o.tiling.customCompression && (u = "_" + o.tiling["q" + e[n]]);
  60081. d = "tiles/" + id + "/" + e[panoSize] + u + "_face" + h + "_" + t.tileX + "_" + t.tileY + ".jpg";
  60082. d = this.getTiles(d, sceneCode);
  60083. g = "?";
  60084. }else {//阿里云oss的规则 if (metadata.sceneScheme == 10)
  60085. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=';
  60086. if (e[panoSize] == '512') {
  60087. d += 'image/resize,h_512';
  60088. } else {
  60089. //4k的图,移动端是1k,pc端是2k,放大才是4k
  60090. if (e[panoSize] == '1k' || e[panoSize] == '2k') { //https://4dkk.4dage.com/images/imagesx4iqYDG3/tiles/4k/122_skybox0.jpg?x-oss-process=image/resize,m_lfit,w_1024/crop,w_512,h_512,x_511,y_0
  60091. d += 'image/resize,m_lfit,w_' + panoSize + '/crop,w_512,h_512,';
  60092. } else {
  60093. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=image/crop,w_512,h_512,';
  60094. }
  60095. //起始位置
  60096. if (t.tileX == 0) {
  60097. d += 'x_0,';
  60098. } else {
  60099. d += 'x_' + (512 * t.tileX - 1) + ',';
  60100. }
  60101. if (t.tileY == 0) {
  60102. d += 'y_0';
  60103. } else {
  60104. d += 'y_' + (512 * t.tileY - 1);
  60105. }
  60106. }
  60107. d = this.getTiles(d, sceneCode);
  60108. g = "&";
  60109. }
  60110. d += g + 'time='+o.pano.pointcloud.timeStamp; //加后缀
  60111. return d;
  60112. }
  60113. }();
  60114. TileDownloader.tilegen = true;
  60115. TileDownloader.IDLE_REFRESH_DELAY = 500;
  60116. TileDownloader.ACTIVE_REFRESH_DELAY = 16;
  60117. TileDownloader.DOWNLOAD_RETRIES = 4;
  60118. function Node$1(e, t) {
  60119. this.tree = e, //所属树(TileTree)
  60120. this.parent = t,
  60121. this.children = [],
  60122. this.id = ++u$1;
  60123. }
  60124. function o(e, t, i, r, a, s, l, h) {
  60125. if (e) {
  60126. l = l || TileTree.TraversalType.PreOrder;
  60127. var u = r * c + i;
  60128. if (l === TileTree.TraversalType.PreOrder && (a && a(e, t, u, i, r),
  60129. s && s.push(e)),
  60130. e.children && 0 !== e.children.length) {
  60131. for (var d = r * c, p = i * c, f = 0; f < c; f++)
  60132. for (var g = 0; g < c; g++)
  60133. o(e.children[g * c + f], t + 1, p + f, d + g, a, s, l, h);
  60134. l === TileTree.TraversalType.PostOrder && (a && a(e, t, u, i, r),
  60135. s && s.push(e));
  60136. }
  60137. }
  60138. }
  60139. function Plant(seed) {
  60140. seed.root = Branch(seed, null, 0);
  60141. }
  60142. function Branch(seed, parent, level) {
  60143. if (level > seed.levels)
  60144. return null;
  60145. var node = new Node$1(seed, parent);
  60146. seed.allNodes.push(node);
  60147. for (var o = 0; o < h$1; o++)
  60148. node.children[o] = Branch(seed, node, level + 1);
  60149. return node
  60150. }
  60151. function l(parent, t, level, n, r) {
  60152. if (!parent)
  60153. return null;
  60154. if (0 === level)
  60155. return parent;
  60156. if (!parent.children || 0 === parent.children.length)
  60157. return null;
  60158. var o = Math.pow(c, level),
  60159. a = o / c,
  60160. s = n % a,
  60161. h = r % a,
  60162. u = Math.floor(r / a),
  60163. d = Math.floor(n / a),
  60164. p = u * c + d,
  60165. f = parent.children[p];
  60166. return l(f, t + 1, level - 1, s, h)
  60167. }
  60168. /* cube每个面都有一个分层树 用于代表瓦片图的细分?
  60169. 树4096的分为三层,每层有4个子节点。(最后一层的四个子节点都是null)
  60170. */
  60171. var c = 2,
  60172. h$1 = c * c; //4个子节点
  60173. var u$1 = 0;
  60174. class TileTree {
  60175. constructor(e, t) {
  60176. this.levels = t,
  60177. this.tileSize = e,
  60178. this.root = null,
  60179. this.allNodes = [],
  60180. Plant(this);
  60181. }
  60182. getSubNode(e, t, i) {
  60183. (!t || e < this.tileSize) && (t = 0),
  60184. (!i || e < this.tileSize) && (i = 0),
  60185. e < this.tileSize && (e = this.tileSize);
  60186. var level = TileTree.getLevelCountForSize(this.tileSize, e),
  60187. o = l(this.root, 0, level, t, i);
  60188. return o
  60189. }
  60190. breadthFirst(e) {//广度优先搜索
  60191. e = e || {};
  60192. var t = !!e.nullLevelEnd,
  60193. i = e.maxLevel,
  60194. n = e.minLevel,
  60195. r = e.callback,
  60196. o = e.saveVisited,
  60197. a = [],
  60198. s = {},
  60199. l = 0,
  60200. c = 0;
  60201. for (a.push(this.root),
  60202. a.push(s); a.length > 0 && !(i && l > i);) {
  60203. var h = a.shift();
  60204. if (h === s)
  60205. (!n || l >= n) && (r && t && r(null),
  60206. o && t && o.push(null)),
  60207. a.length > 0 && a.push(s),
  60208. l++,
  60209. c = 0;
  60210. else {
  60211. if (h.children)
  60212. for (var u = 0; u < h.children.length; u++) {
  60213. var d = h.children[u];
  60214. d && a.push(h.children[u]);
  60215. }
  60216. var p = this.getFaceIndexFromNode(h);
  60217. (!n || l >= n) && (r && r(h, l, p),
  60218. o && o.push(h)),
  60219. c++;
  60220. }
  60221. }
  60222. }
  60223. getFaceIndexFromNode(e) {
  60224. if (!e)
  60225. return -1;
  60226. for (var t = 1, i = e, n = 0, r = 0;;) {
  60227. var o = i.parent;
  60228. if (!o)
  60229. break;
  60230. for (var a = -1, s = 0; s < o.children.length; s++)
  60231. o.children[s] === i && (a = s);
  60232. var l = a % c,
  60233. h = Math.floor(a / c);
  60234. n = l * t + n,
  60235. r = h * t + r,
  60236. t *= c,
  60237. i = o;
  60238. }
  60239. return r * t + n
  60240. }
  60241. depthFirst(e, t, i) {
  60242. o(this.root, 0, 0, 0, e, t, i, this.tileSize);
  60243. }
  60244. }
  60245. TileTree.TraversalType = Object.freeze({
  60246. PreOrder: 0,
  60247. PostOrder: 1
  60248. });
  60249. TileTree.getLevelCountForSize = function(tileSize, size) {//512->0 2024->1
  60250. var i = 0;
  60251. for (size < tileSize && (size = tileSize);;) {
  60252. if (size /= c,
  60253. size < tileSize)
  60254. break;
  60255. i++;
  60256. }
  60257. return i
  60258. };
  60259. TileTree.getSizeForLevel = function(e, t) {
  60260. return Math.pow(c, t) * e
  60261. };
  60262. function createDescriptor() {
  60263. var e = {
  60264. renderTarget: null,
  60265. inUse: !1,
  60266. size: -1,
  60267. pano: null
  60268. };
  60269. return e
  60270. }
  60271. function c$1() {
  60272. if (!this.uploadIntervalCancelled) {
  60273. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  60274. b = !0,
  60275. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  60276. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(w) : this.uploadInterval = null;
  60277. } else {
  60278. this.refreshUploadInterval(this.uploadIntervalDelay);
  60279. }
  60280. }
  60281. }
  60282. var b = !1,
  60283. w = config$1.tiling.uploadIntervalDelay,
  60284. _ = config$1.tiling.initialIntervalDelay,
  60285. T = config$1.tiling.maxNonBaseUploadsPerFrame,
  60286. x$1 = config$1.tiling.maxBaseUploadsPerFrame,
  60287. S = {
  60288. Base: 0,
  60289. Remaining: 1
  60290. };/* ,
  60291. M = []; */
  60292. class PanoRenderer extends EventDispatcher{
  60293. constructor(viewer, tileDownloader, qualityManager) {
  60294. super();
  60295. this.tileDirectory = {};
  60296. this.activeRenderTargetDescriptors = {};
  60297. this.activePanos = [];
  60298. this.panoLODDescriptors = {};
  60299. this.panoDescriptors = {};
  60300. this.tileTrees = {};
  60301. this.forceQueue = [];
  60302. this.uploadQueues = {};
  60303. this.uploadInterval = null;
  60304. this.uploadIntervalCancelled = !1;
  60305. this.usingTileOverlay = !1;
  60306. this.overlayTilesLoaded = !1;
  60307. this.overlayTileBase = null;
  60308. this.overlayTilesBasic = {};
  60309. this.overlayTilesEnhanced = {};
  60310. this.zoomRenderTarget = null; //用于缩放的rendertarget
  60311. this.zoomPano = null;
  60312. this.zoomingActive = !1;
  60313. this.zoomPanoId = null;
  60314. this.zoomPanoRenderingDisabled = !1;
  60315. this.direction = [];//new THREE.Vector3;
  60316. this.maxBaseUploadsPerFrame = x$1;
  60317. this.maxNonBaseUploadsPerFrame = T;
  60318. this.M = [];//move M to here 似乎列表里会有两个
  60319. this.viewer = viewer;
  60320. this.tileDownloader = tileDownloader;
  60321. this.qualityManager = qualityManager;
  60322. this.initTime = performance.now();
  60323. this.bindEvents();
  60324. }
  60325. getActivePanoTextures(e) {
  60326. e = e || [];
  60327. for (var t = 0; t < M.length; t++) {
  60328. var i = M[t];
  60329. i.renderTarget && i.renderTarget.texture && e.push(i.renderTarget.texture);
  60330. }
  60331. }
  60332. hasQueuedTiles() {
  60333. var e = this.peekNextFromUploadQueue();
  60334. return null !== e && void 0 !== e
  60335. }
  60336. getActiveRenderTargetDescriptor(e) {
  60337. return this.activeRenderTargetDescriptors[e]
  60338. }
  60339. setActiveRenderTargetDescriptor(e, t) {
  60340. this.activeRenderTargetDescriptors[e] = t;
  60341. }
  60342. bindEvents() {
  60343. this.tileDownloader.addEventListener(TileDownloaderEvents.TileDownloadSuccess, this.onTileDownloaded.bind(this));
  60344. }
  60345. enableUltraHighQualityMode(e) {
  60346. if(config$1.tileClass == "2k"||config$1.tileClass == "1k")return this.enableHighQuality(e)//xzw add 濡傛灉鏈€澶氬彧瑕?k鐨勮瘽
  60347. if (!this.qualityManager.ultraHighQualityModeEnabled()) {
  60348. var t = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
  60349. this.tileDownloader.testDownload(t, TileUtils.TILE_SIZE, function (t) {
  60350. t && (this.qualityManager.enableUltraHighQualityMode(),
  60351. this.setupZoomRenderTarget(),
  60352. e());
  60353. }
  60354. .bind(this));
  60355. }
  60356. }
  60357. activateTiledPano(pano, size, i) {
  60358. i && this.clearAllQueuedUploads();
  60359. for (var n = 0; n < TileUtils.FACES_PER_PANO; n++)
  60360. this.initTileTree(pano.id, n, this.qualityManager.getMaxPossiblePanoSize()); //得到this.tileTrees[pano.id],arr[6]
  60361. this.linkAllTilesAndNodes(pano);
  60362. var r = this.getActiveRenderTargetDescriptor(pano.id),
  60363. l = size;
  60364. l > this.qualityManager.getMaxNavPanoSize() && (l = this.qualityManager.getMaxNavPanoSize());
  60365. if ( !r || l !== r.size) {
  60366. r && this.deactiveDescripor(r.renderTarget);
  60367. r = this.activeDescripor(l);
  60368. if (!r) {
  60369. var ren = this.initTiledPano(l, !1);
  60370. r = this.initDescriptor(ren.width);
  60371. r.renderTarget = ren;
  60372. }
  60373. r.pano = pano;
  60374. this.resetPanoDescriptor(pano.id);
  60375. this.resetPanoLODDescriptors(pano.id);
  60376. this.resetRenderStatus(pano.id, !0, !0);
  60377. }
  60378. this.setActiveRenderTargetDescriptor(pano.id, r);
  60379. var h = i ? 0 : 1;
  60380. this.updateActivePanos(pano, h);
  60381. //console.log(`index:${this.viewer.index} ${r.renderTarget.texture.id} ${pano.id}`)
  60382. return r.renderTarget
  60383. }
  60384. deactivateTiledPano(e) {
  60385. var t = this.getActiveRenderTargetDescriptor(e.id);
  60386. if(this.isRenderTargetDescriptorValid(t)){
  60387. this.deactiveDescripor(t.renderTarget);
  60388. this.setActiveRenderTargetDescriptor(e.id, null);
  60389. }
  60390. var i = this.getUploadQueueForPano(e.id);
  60391. this.clearUploadQueue(i);
  60392. this.updateActivePanos();
  60393. }
  60394. getActivePanoCount() {
  60395. return this.activePanos.length
  60396. }
  60397. resetRenderStatus(e, t, i, n) {
  60398. var r = null;
  60399. n && (r = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, n) + 1);
  60400. for (var o = function (e, n, r, o) {
  60401. i && (n.tile.zoomUploaded = !1),
  60402. t && (n.tile.uploaded = !1);
  60403. }, a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  60404. var s = this.getTileTree(e, a);
  60405. s.breadthFirst({
  60406. callback: o.bind(this, a),
  60407. minLevel: r
  60408. });
  60409. }
  60410. }
  60411. copyBaseRenderStatusToZoomed(e) {
  60412. for (var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, this.qualityManager.getMaxNavPanoSize()), i = function (e, t, i, n) {
  60413. t.tile.zoomUploaded = t.tile.uploaded,
  60414. t.zoomCovered = t.covered;
  60415. }, n = 0; n < TileUtils.FACES_PER_PANO; n++) {
  60416. var r = this.getTileTree(e, n);
  60417. r.breadthFirst({
  60418. callback: i.bind(this, n),
  60419. maxLevel: t
  60420. });
  60421. }
  60422. }
  60423. isRenderTargetDescriptorValid(e) {
  60424. return e && e.renderTarget
  60425. }
  60426. isPanoActive(e) {
  60427. var t = this.getActiveRenderTargetDescriptor(e);
  60428. return this.isRenderTargetDescriptorValid(t)
  60429. }
  60430. isPanoZoomed(e) {
  60431. return this.zoomingActive && this.zoomPanoId === e
  60432. }
  60433. initTileTree(e, t, i) {
  60434. var n = this.tileTrees[e];
  60435. n || (n = [],
  60436. this.tileTrees[e] = n);
  60437. var r = n[t];
  60438. if (!r) {
  60439. var o = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i);
  60440. r = new TileTree(TileUtils.TILE_SIZE, o),
  60441. n[t] = r;
  60442. }
  60443. }
  60444. getTileTree(e, t) {
  60445. var i = this.tileTrees[e];
  60446. if (!i)
  60447. console.error("PanoRenderer.getTileTree() -> Tree array not yet initialized!");
  60448. var n = i[t];
  60449. if (!n)
  60450. console.error("PanoRenderer.getTileTree() -> Tree not yet initialized!");
  60451. return n
  60452. }
  60453. /*
  60454. * 创建tile的renderTarget, 包括pano.tiledPanoRenderTarget和zoomRenderTarget
  60455. * @param {number} size 当前的panoSize,每个面的分辨率
  60456. */
  60457. initTiledPano(size, t) {//创建 RenderTargetCube
  60458. var renderer = this.viewer.renderer;
  60459. var renderTarget, texture;
  60460. renderTarget = new WebGLCubeRenderTarget(size,{ //THREE.WebGLRenderTargetCube(size, size, {
  60461. stencilBuffer: !1
  60462. });
  60463. texture = new CubeTexture([]);
  60464. texture.image = [null, null, null, null, null, null];
  60465. texture.flipY = !0,
  60466. texture.format = RGBAFormat;
  60467. t ? (texture.generateMipmaps = !0,
  60468. texture.magFilter = LinearFilter,
  60469. texture.minFilter = LinearMipMapLinearFilter)
  60470. : (texture.generateMipmaps = !1,
  60471. texture.magFilter = LinearFilter,
  60472. texture.minFilter = LinearFilter);
  60473. renderer.setRenderTarget(renderTarget);
  60474. renderer.setRenderTarget(null);
  60475. var o = renderer.properties.get(texture);
  60476. o.__image__webglTextureCube = o.__webglTexture;
  60477. //window.tex[r.id] = {texture:r, index:this.viewer.index }
  60478. return renderTarget
  60479. }
  60480. getUploadQueueForPano(e) {
  60481. var t = this.uploadQueues[e];
  60482. return t || (t = [],
  60483. this.uploadQueues[e] = t),
  60484. t
  60485. }
  60486. isTileUploaded(e) {
  60487. return this.isPanoZoomed(e.panoId) ? e.zoomUploaded : e.uploaded
  60488. }
  60489. setUploaded(e, t) {
  60490. this.isPanoZoomed(e.panoId) ? e.zoomUploaded = t : e.uploaded = t;
  60491. }
  60492. queueTileUpload(e, t, i) {
  60493. var n = this.getActiveRenderTargetDescriptor(e.panoId);
  60494. if (this.isRenderTargetDescriptorValid(n) && e.downloaded && !this.isTileUploaded(e) && (!e.uploadQueued || i)
  60495. && (!(e.panoSize > this.qualityManager.getMaxNavPanoSize())|| this.zoomingActive)) {
  60496. var r = this.getUploadQueueForPano(e.panoId);
  60497. if(i){
  60498. this.uploadTile(e, !1);//提交
  60499. }else {
  60500. if(this.shoulPushToFrontOfQueue(e)){//如果是512的优先
  60501. this.forceQueue.push(e);
  60502. }else {
  60503. if(t && this.direction){
  60504. TilePrioritizer.insertSortedPanoTile(r, e, n.pano, this.direction);
  60505. }else r.push(e);
  60506. }
  60507. e.uploadQueued = !0;
  60508. this.uploadInterval || this.uploadIntervalCancelled || this.refreshUploadInterval(0);
  60509. }
  60510. }
  60511. }
  60512. shoulPushToFrontOfQueue(e) {
  60513. return 0 === TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize)
  60514. }
  60515. getTopUploadQueue() {
  60516. for (var e = null, t = null, i = S.Base; i <= S.Remaining; i++)
  60517. for (var n = 0; n < this.activePanos.length; n++)
  60518. if (e = this.activePanos[n],
  60519. t = this.getUploadQueueForPano(e.id),
  60520. t.length > 0)
  60521. switch (i) {
  60522. case S.Base:
  60523. if (0 === t[0].level)
  60524. return t;
  60525. break;
  60526. case S.Remaining:
  60527. return t
  60528. }
  60529. return null
  60530. }
  60531. peekNextFromUploadQueue() {
  60532. if (this.forceQueue.length > 0)
  60533. return this.forceQueue[0];
  60534. var e = this.getTopUploadQueue();
  60535. return e && e.length > 0 ? e[0] : null
  60536. }
  60537. clearAllQueuedUploads() {
  60538. this.clearAllUploadQueues(null, 0);
  60539. }
  60540. clearAllQueuedUploadsForPano(e) {
  60541. this.clearAllUploadQueues(e, 0);
  60542. }
  60543. clearAllUploadQueues(e, t) {
  60544. if (e)
  60545. this.clearUploadQueue(this.getUploadQueueForPano(e), t),
  60546. this.clearUploadQueue(this.forceQueue, t, e);
  60547. else {
  60548. for (var i = 0; i < this.activePanos.length; i++) {
  60549. var n = this.activePanos[i];
  60550. this.clearUploadQueue(this.getUploadQueueForPano(n.id), t);
  60551. }
  60552. this.clearUploadQueue(this.forceQueue, t);
  60553. }
  60554. }
  60555. clearUploadQueue(e, t, i) {
  60556. void 0 !== t && null !== t || (t = 0);
  60557. for (var n = 0; n < e.length;) {
  60558. var r = e[n];
  60559. (!i || i && i === r.tile.panoId) && r.level >= t ? (r.uploadQueued = !1,
  60560. e.splice(n, 1)) : n++;
  60561. }
  60562. //若报错, r.tile.panoId改为 r.panoId
  60563. }
  60564. updateUploadQueue(maxNPF,maxPF/* e, t */) {//参数是 maxNonBaseUploadsPerFrame and maxBaseUploadsPerFrame, 优先上传512
  60565. maxNPF || (maxNPF = 1);
  60566. for (var i = 0, n = 0;;) {
  60567. let old = this.forceQueue.slice(0);
  60568. if (n >= maxPF || i >= maxNPF)
  60569. break;
  60570. var r = this.getNextFromUploadQueue();
  60571. if (!r)
  60572. break;
  60573. //r.panoSize <2048 && console.log('panoId', r.panoId, 'panoSize', r.panoSize , old)
  60574. 0 !== r.level ? i++ : n++;
  60575. if (!(r.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive) {
  60576. var o = this.getActiveRenderTargetDescriptor(r.panoId);
  60577. this.isRenderTargetDescriptorValid(o) && this.uploadTile(r, r.forceUpload);
  60578. }
  60579. }
  60580. }
  60581. updateDirection(e) {
  60582. if (e = e || this.direction) {
  60583. this.direction = e;
  60584. for (var t = 0; t < this.activePanos.length; t++) {
  60585. var i = this.activePanos[t],
  60586. n = this.getUploadQueueForPano(i.id);
  60587. TilePrioritizer.sortPanoTiles(n, i, this.direction);
  60588. }
  60589. }
  60590. }
  60591. anyUploaded(e) {
  60592. if (!e)
  60593. return !1;
  60594. if (e.tile && this.isTileUploaded(e.tile))
  60595. return !0;
  60596. if (e.children)
  60597. for (var t = 0; t < e.children.length; t++) {
  60598. var i = e.children[t];
  60599. if (this.anyUploaded(i))
  60600. return !0
  60601. }
  60602. return !1
  60603. }
  60604. setNodeCovered(e, t) {
  60605. this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered = t : e.covered = t;
  60606. }
  60607. isNodeCovered(e) {
  60608. return !!e && (this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered : e.covered)
  60609. }
  60610. addCoverageForNode(e) {
  60611. if (this.setNodeCovered(e, !0),
  60612. e.parent && e.covered) {
  60613. var t = e.parent;
  60614. this.nodeSubcovered(t) && this.addCoverageForNode(t, !0);
  60615. }
  60616. }
  60617. calcFullCoverage(e) {
  60618. var t = !1;
  60619. if (e.children)
  60620. for (var i = 0; i < e.children.length; i++) {
  60621. var n = e.children[i];
  60622. t = t || this.calcFullCoverage(n);
  60623. }
  60624. e.covered = e.tile.uploaded || t;
  60625. }
  60626. nodeSubcovered(e) {
  60627. if (!e.children)
  60628. return !1;
  60629. for (var t = 0; t < e.children.length; t++)
  60630. if (!e.children[t] || !this.isNodeCovered(e.children[t]))
  60631. return !1;
  60632. return !0
  60633. }
  60634. resetPanoDescriptor(e) {
  60635. this.getPanoDescriptor(e);
  60636. }
  60637. getPanoDescriptor(e) {
  60638. var t = this.panoDescriptors[e];
  60639. return t || (t = {},
  60640. this.panoDescriptors[e] = t),
  60641. t
  60642. }
  60643. resetPanoLODDescriptors(e) {
  60644. var t = this.getPanoLODDescriptors(e);
  60645. for (var i in t)
  60646. if (t.hasOwnProperty(i)) {
  60647. var n = t[i];
  60648. n.uploadCount = 0,
  60649. n.uploadAttempts = 0;
  60650. n.uploaded = [];
  60651. }
  60652. }
  60653. getPanoLODDescriptor(e, t) {
  60654. var i = this.getPanoLODDescriptors(e),
  60655. n = i[t];
  60656. return n || (n = {
  60657. uploadCount: 0,
  60658. uploadAttempts: 0,
  60659. uploaded:[],//add
  60660. },
  60661. i[t] = n),
  60662. n
  60663. }
  60664. getPanoLODDescriptors(e) {
  60665. var t = this.panoLODDescriptors[e];
  60666. return t || (t = {},
  60667. this.panoLODDescriptors[e] = t),
  60668. t
  60669. }
  60670. onTileDownloaded(o) {
  60671. var e = o.desc;
  60672. var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize),
  60673. i = this.getTileDirectoryEntry(e.panoId, e.face, t, e.faceTileIndex);
  60674. i.downloaded = !0;
  60675. i.image = e.image;
  60676. i.panoSize = e.panoSize;
  60677. i.tileX = e.tileX;
  60678. i.tileY = e.tileY;
  60679. i.totalTiles = e.totalTiles;
  60680. i.tileIndex = e.tileIndex;
  60681. i.faceTileIndex = e.faceTileIndex;
  60682. i.face = e.face;
  60683. i.cubeFace = TileUtils.mapFaceToCubemapFace(e.face);
  60684. i.panoId = e.panoId;
  60685. i.tileSize = e.tileSize;
  60686. i.direction = (new Vector3).copy(e.direction);
  60687. i.node = null;
  60688. i.level = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i.panoSize);
  60689. if (this.isPanoActive(i.panoId)) {
  60690. var n = this.getTileTree(i.panoId, i.face);
  60691. var r = n.getSubNode(i.panoSize, i.tileX, i.tileY);
  60692. this.linkTileAndNode(i, r);
  60693. this.queueTileUpload(i, !0);
  60694. }
  60695. }
  60696. getTileDirectoryEntry(panoId, t, i, n) {
  60697. var r = this.tileDirectory[panoId];
  60698. r || (r = {}, this.tileDirectory[panoId] = r);
  60699. var o = 16384 * t + 1024 * i + n, //t:4096级别
  60700. a = r[o];
  60701. return a || (a = {
  60702. downloaded: !1,
  60703. uploaded: !1,
  60704. zoomUploaded: !1
  60705. },
  60706. r[o] = a),
  60707. a._key = panoId + ":" + t + ":" + i + ":" + n,//panoId : face : level : faceTileIndex
  60708. a._tileKey = o,
  60709. a
  60710. }
  60711. setZoomingActive(active, pano, i) {//设置当前正在zoom的pano
  60712. this.zoomPanoRenderingDisabled || active === this.zoomingActive && this.zoomPanoId === pano.id || (this.zoomingActive = active,
  60713. this.zoomPanoId = pano.id,
  60714. this.zoomingActive && (this.zoomPanoId !== pano.id || i) && this.updateZoomedPanoFromBase(pano));
  60715. }
  60716. updateZoomedPanoFromBase(pano) {//因更换pano所以将pano的rendertarget渲染到panoRenderer的zoomRenderTarget上
  60717. if (!this.zoomPanoRenderingDisabled && this.zoomRenderTarget) {
  60718. var t = this.getActiveRenderTargetDescriptor(pano.id);
  60719. if (t && t.renderTarget ) {
  60720. var i = Math.min(this.qualityManager.maxRenderTargetSize, this.qualityManager.getMaxZoomPanoSize()), //change
  60721. n = t.renderTarget,
  60722. r = t.size;
  60723. this.copyCubeMap(n.texture, this.zoomRenderTarget, r, r, i, i),
  60724. this.copyBaseRenderStatusToZoomed(pano.id);
  60725. }
  60726. }
  60727. }
  60728. add(e) {
  60729. this.M.push(e);
  60730. }
  60731. initDescriptor(size) {
  60732. var t = createDescriptor();
  60733. t.inUse = !0;
  60734. t.size = size;
  60735. this.add(t);
  60736. return t
  60737. }
  60738. activeDescripor(e) {
  60739. for (var t = 0; t < this.M.length; t++) {
  60740. var i = this.M[t];
  60741. if (!i.inUse && i.size === e){
  60742. i.inUse = !0;
  60743. return i
  60744. }
  60745. }
  60746. return null
  60747. }
  60748. deactiveDescripor(e) {
  60749. for (var t = 0; t < this.M.length; t++) {
  60750. var i = this.M[t];
  60751. if (i.renderTarget === e){
  60752. i.inUse = !1;
  60753. return !0
  60754. }
  60755. }
  60756. return !1
  60757. }
  60758. enableHighQuality(e){//xzw add 如果最多只要2k图的话enableUltraHighQualityMode替换成这个
  60759. if (!this.qualityManager.highQualityModeStarted) {
  60760. this.setupZoomRenderTarget();
  60761. e();
  60762. //this.qualityManager.updateHighResolutionSettings(e)////////?
  60763. this.qualityManager.highQualityModeStarted = true;
  60764. }
  60765. }
  60766. linkTileAndNode(e, t) {
  60767. t.tile = e,
  60768. e.node = t;
  60769. }
  60770. linkAllTilesAndNodes(e) {
  60771. var t = function (t, i, n, r, o) {
  60772. var a = this.getTileDirectoryEntry(e.id, i, r, o);
  60773. this.linkTileAndNode(a, n);
  60774. };
  60775. for (var i = 0; i < TileUtils.FACES_PER_PANO; i++) {
  60776. var n = this.getTileTree(e.id, i);
  60777. n.breadthFirst({
  60778. callback: t.bind(this, n, i)
  60779. });
  60780. }
  60781. }
  60782. //--------------sceneRenderer
  60783. initSizedTexture2D(e, t, i) {
  60784. var renderer = this.viewer.renderer,
  60785. o = renderer.getContext(),
  60786. a = renderer.state,
  60787. s = new Texture(null);
  60788. s.flipY = !1,
  60789. i !== !0 && (i = !1),
  60790. s.generateMipmaps = i;
  60791. var l = renderer.paramThreeToGL(s.format),
  60792. c = renderer.paramThreeToGL(s.type),
  60793. h = renderer.properties.get(s),
  60794. u = o.createTexture();
  60795. a.bindTexture(o.TEXTURE_2D, u),
  60796. o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL, s.flipY),
  60797. o.texImage2D(o.TEXTURE_2D, 0, l, e, e, 0, l, c, null),
  60798. s.wrapS = t,
  60799. s.wrapT = t;
  60800. var d = renderer.paramThreeToGL(t);
  60801. return o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, d),
  60802. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, d),
  60803. i ? (s.magFilter = LinearFilter,
  60804. s.minFilter = LinearMipMapLinearFilter,
  60805. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  60806. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR_MIPMAP_NEAREST),
  60807. o.generateMipmap(o.TEXTURE_2D)) : (s.magFilter = LinearFilter,
  60808. s.minFilter = LinearFilter,
  60809. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  60810. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR)),
  60811. a.bindTexture(o.TEXTURE_2D, null),
  60812. h.__webglTexture = u,
  60813. s
  60814. }
  60815. deallocateCubeTexture(e) {
  60816. var t = this.viewer.renderer,
  60817. i = t.getContext(),
  60818. renderer = t.properties.get(e);
  60819. i.deleteTexture(renderer.__image__webglTextureCube);
  60820. }
  60821. uploadTexture2D(img, tex, startX, startY, width, height) {
  60822. var renderer = this.viewer.renderer,
  60823. gl = renderer.getContext(),
  60824. webglState = renderer.state,
  60825. c = renderer.properties.get(tex);
  60826. webglState.bindTexture(gl.TEXTURE_2D, c.__webglTexture),
  60827. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, tex.flipY),
  60828. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, tex.premultiplyAlpha),
  60829. gl.pixelStorei(gl.UNPACK_ALIGNMENT, tex.unpackAlignment),
  60830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, renderer.paramThreeToGL(tex.wrapS)),
  60831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, renderer.paramThreeToGL(tex.wrapT)),
  60832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, renderer.paramThreeToGL(tex.magFilter)),
  60833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, renderer.paramThreeToGL(tex.minFilter)),
  60834. gl.texSubImage2D(gl.TEXTURE_2D, 0, startX, startY, gl.RGBA, gl.UNSIGNED_BYTE, img),
  60835. tex.generateMipmaps && gl.generateMipmap(gl.TEXTURE_2D),
  60836. webglState.bindTexture(gl.TEXTURE_2D, null);
  60837. }
  60838. getCubeOrientationForCubeFace(e, t) {
  60839. switch (e) {
  60840. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  60841. t.set(0, -Math.PI / 2, 0);
  60842. break;
  60843. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  60844. t.set(0, Math.PI / 2, 0);
  60845. break;
  60846. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  60847. t.set(Math.PI / 2, Math.PI, 0);
  60848. break;
  60849. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  60850. t.set(-Math.PI / 2, Math.PI, 0);
  60851. break;
  60852. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  60853. t.set(0, -Math.PI, 0);
  60854. break;
  60855. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  60856. t.set(0, 0, 0);
  60857. }
  60858. }
  60859. }
  60860. PanoRenderer.prototype.setupZoomRenderTarget = function(){
  60861. var targets = {};
  60862. return function(){
  60863. if(this.qualityManager.maxRenderTargetSize == '2k' && this.qualityManager.getMaxNavPanoSize()=='2k')return; //不使用zoomTarget 直接用pano的tiledPanoRenderTarget,防崩溃
  60864. if (this.qualityManager.getMaxZoomPanoSize() >= this.qualityManager.getMaxNavPanoSize() /* && (config.tileClass != "2k" ||config.tileClass != "1k") */) {
  60865. //部分手机2k时copyCubeMap会重载 , 所以如果没有超出当前分辨率,就不使用zoomRenderTarget。但在微信依旧会重载,只是优化了些,safari几乎不会。
  60866. if (this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize())
  60867. return;
  60868. var e = this.zoomRenderTarget;
  60869. var size = this.qualityManager.getMaxZoomPanoSize();
  60870. if(size > this.qualityManager.maxRenderTargetSize){
  60871. return
  60872. }
  60873. if(targets[size]){
  60874. this.zoomRenderTarget = targets[size];
  60875. }else {
  60876. this.zoomRenderTarget = this.initTiledPano(size, !1);
  60877. targets[size] = this.zoomRenderTarget;
  60878. }
  60879. if (e) {//将旧的zoomRenderTarget渲染到新zoomRenderTarget上
  60880. var t = e.width,
  60881. i = this.zoomRenderTarget.width;
  60882. this.copyCubeMap(e.texture, this.zoomRenderTarget, t, t, i, i),
  60883. e.texture.dispose(),
  60884. e.texture.loaded = !1,
  60885. e.texture.version = 0,
  60886. this.deallocateCubeTexture(e.texture),
  60887. e.texture = null;
  60888. }
  60889. this.zoomPanoRenderingDisabled = !1;
  60890. } else
  60891. this.zoomPanoRenderingDisabled = !0;
  60892. }
  60893. }();
  60894. PanoRenderer.prototype.updateActivePanos = function () {
  60895. var e = [];
  60896. return function (t, i) {
  60897. e.length = 0;
  60898. for (var n = 0; n < this.activePanos.length; n++) {
  60899. t && e.length === i && e.push(t);
  60900. var r = this.activePanos[n],
  60901. o = this.getActiveRenderTargetDescriptor(r.id);
  60902. t && r.id === t.id || !this.isRenderTargetDescriptorValid(o) || e.push(r);
  60903. }
  60904. t && i >= e.length && e.push(t),
  60905. this.activePanos.length = 0,
  60906. this.activePanos.push.apply(this.activePanos, e);
  60907. }
  60908. }();
  60909. PanoRenderer.prototype.renderPanoTiles = function () {
  60910. var e = [];
  60911. return function (panoId, i, n, r) {
  60912. this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize() || this.zoomPanoRenderingDisabled || this.setupZoomRenderTarget(),//如果ZoomRenderTarget大小需要变动就重新创建
  60913. i = i || this.direction || Vectors.FORWARD; // [{1:Vectors.FORWARD}]?
  60914. var o = this.getActiveRenderTargetDescriptor(panoId);
  60915. if (!this.isRenderTargetDescriptorValid(o))
  60916. console.error("PanoRenderer.renderPanoTiles() -> Cannot render to a pano that is not activated.");
  60917. for (var a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  60918. var s = this.getTileTree(panoId, a);
  60919. e.length = 0;
  60920. s.breadthFirst({//获取所有node? 85个
  60921. saveVisited: e
  60922. });
  60923. for (var l = 0; l < e.length; l++) {
  60924. var c = e[l];
  60925. this.queueTileUpload(c.tile, !1, r || 0 === l && n);//为什么第0个会直接uploadTile??
  60926. }
  60927. }
  60928. this.updateDirection(i);
  60929. }
  60930. }();
  60931. PanoRenderer.prototype.getNextFromUploadQueue = function () {
  60932. var e = function (e) {
  60933. var t = e.shift();
  60934. return t.uploadQueued = !1,
  60935. t
  60936. };
  60937. return function () {
  60938. if (this.forceQueue.length > 0)
  60939. return e(this.forceQueue);
  60940. var t = this.getTopUploadQueue();
  60941. return t && t.length > 0 ? e(t) : null
  60942. }
  60943. }();
  60944. PanoRenderer.prototype.refreshUploadInterval = function () {
  60945. var e = null;
  60946. return function (t) {
  60947. this.uploadIntervalCancelled || (e || (e = c$1.bind(this)),
  60948. null !== t && void 0 !== t || (t = w),
  60949. b || (t = _),
  60950. this.uploadInterval = window.setTimeout(e, t),
  60951. this.uploadIntervalDelay = t);
  60952. }
  60953. }();
  60954. PanoRenderer.prototype.update = function () {
  60955. var e = performance.now(),
  60956. t = 0;
  60957. return function () {
  60958. this.uploadIntervalCancelled = !0;
  60959. window.clearTimeout(this.uploadInterval);
  60960. this.uploadInterval = null;
  60961. var i = performance.now() - e;
  60962. //!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay || (this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  60963. //e = performance.now()),
  60964. if (!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay) {} else {
  60965. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame);
  60966. e = performance.now();
  60967. }
  60968. t++;
  60969. }
  60970. }();
  60971. PanoRenderer.prototype.uploadTile = function () {//重写
  60972. var collection = {},
  60973. overlayStyle = config$1.tiling.overlayStyle;
  60974. var failHistory = {};
  60975. return function (info, n) {
  60976. var id = info.panoId,
  60977. img = info.image,
  60978. tileSize = info.tileSize,
  60979. panoSize = info.panoSize,
  60980. tileIndex = info.tileIndex,
  60981. totalTiles = info.totalTiles,
  60982. tileX = info.tileX,
  60983. tileY = info.tileY,
  60984. p = !0,
  60985. g = !1,
  60986. ignore = false, //add
  60987. LodDescripor = (this.getPanoDescriptor(id), this.getPanoLODDescriptor(id, panoSize)),
  60988. activeDescripor = this.getActiveRenderTargetDescriptor(id),
  60989. renderTarget = activeDescripor.renderTarget,
  60990. size = activeDescripor.size;//当前要渲染的面的分辨率,也就是MaxNavPanoSize
  60991. if (this.isPanoZoomed(id) && this.zoomRenderTarget) {
  60992. renderTarget = this.zoomRenderTarget;
  60993. size = this.zoomRenderTarget.width; //this.qualityManager.getMaxZoomPanoSize(); //放大后可能2048或4096
  60994. }
  60995. let done = ()=>{
  60996. if(!LodDescripor.uploaded.includes(tileIndex)){//已经upload过(本来这时候直接返回,但发现缩放后这不会归零,导致清晰度不更新,所以还是redraw且emit吧)
  60997. //console.log('try to reupload and return',tileIndex)
  60998. LodDescripor.uploaded.push(tileIndex);
  60999. LodDescripor.uploadCount++;
  61000. }
  61001. this.dispatchEvent({type:PanoRendererEvents.TileRenderSuccess, id, panoSize, tileIndex, totalTiles});
  61002. LodDescripor.uploadCount === totalTiles && this.dispatchEvent({type:PanoRendererEvents.PanoRenderComplete, id, panoSize, totalTiles, updateFullComplete:true});
  61003. this.setUploaded(info, !0);
  61004. this.addCoverageForNode(info.node);
  61005. };
  61006. {//已经uploadTile过了不再uploadTile
  61007. if(!this.isRenderTargetDescriptorValid(activeDescripor)){
  61008. p = !1; g = !1;
  61009. }
  61010. if(!n){
  61011. this.anyUploaded(info.node) && (p = !1, g = !0,ignore = true ); //包括子集也uploadTile了
  61012. this.isTileUploaded(info) && (p = !1, g = !1,ignore = true ); //当前tile uploadTile了
  61013. }
  61014. }
  61015. if (p) {
  61016. /*if(failHistory[id+':'+ panoSize+ ':' +tileIndex]){
  61017. console.log('uploadTile retry',id, panoSize, tileIndex)
  61018. }
  61019. console.log('uploadTile 成功', id, panoSize, tileIndex) */
  61020. var C = tileX * tileSize,
  61021. I = tileY * tileSize,
  61022. E = tileSize / panoSize * size, // tile在renderTarget上渲染出的宽度
  61023. b = C / panoSize * size, // tile在renderTarget上渲染的startX
  61024. w = I / panoSize * size; // tile在renderTarget上渲染的startY
  61025. collection[tileSize] || (collection[tileSize] = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping));
  61026. if(panoSize > this.qualityManager.maxRenderTargetSize ){ //4096 改
  61027. var tex = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping);
  61028. var loaded = this.viewer.images360.isHighMapLoaded(info.cubeFace, tileX,tileY);
  61029. }else {
  61030. var tex = collection[tileSize];
  61031. }
  61032. this.uploadTexture2D(img, tex, 0, 0, tileSize, tileSize);//只替换tex对应的img,不新建
  61033. if(panoSize > this.qualityManager.maxRenderTargetSize){
  61034. loaded || this.viewer.images360.updateHighMap(tex, info.cubeFace, tileX,tileY);
  61035. }else {
  61036. if (1 === overlayStyle || 2 === overlayStyle) {
  61037. var T = 1 === overlayStyle ? this.overlayTilesBasic : this.overlayTilesEnhanced;
  61038. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  61039. this.renderToCubeMap(T[panoSize], renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace, NormalBlending, !0, .5);
  61040. } else {
  61041. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  61042. }
  61043. }
  61044. done();
  61045. }else if(ignore){
  61046. //console.log('finish because anyUploaded',id,panoSize,tileIndex)
  61047. done(); //改: 如果因为这部分更高清的贴图已加载所以才不绘制的话,直接完成
  61048. }else {
  61049. //console.log('uploadTile 失败', id, panoSize, tileIndex)
  61050. if(panoSize == 512){
  61051. //console.log("!!!!!!!!!!!!!")
  61052. }
  61053. failHistory[id+':'+ panoSize+ ':' +tileIndex] = true;
  61054. this.setUploaded(info, !1);
  61055. }
  61056. info.uploadAttempted || (LodDescripor.uploadAttempts++, this.dispatchEvent({type:PanoRendererEvents.TileUploadAttempted, id, panoSize, tileIndex, totalTiles})),
  61057. info.uploadAttempted = !0;
  61058. LodDescripor.uploadAttempts === totalTiles && this.dispatchEvent({type:PanoRendererEvents.UploadAttemptedForAllTiles, id, panoSize, totalTiles});
  61059. return g;
  61060. }
  61061. }();
  61062. /*
  61063. 注:tileY的方向同UV,从下到上
  61064. renderToCubeMap里的画布or镜头的xy范围是-0.5到0.5
  61065. */
  61066. PanoRenderer.prototype.renderToCubeMap = function() {
  61067. var inited = !1,
  61068. scene = null,
  61069. camera = null,
  61070. material = null,
  61071. geo = null,
  61072. plane = null,
  61073. l = 1;
  61074. return function(texture, renderTarget, tileWidth, tileHeight, startXinTile, startYinTile, widthinTile, heightinTile, startX, startY, width, height, cubeFace, E, b, w) {
  61075. var renderer = this.viewer.renderer;
  61076. inited || (camera = new OrthographicCamera(l / -2, l / 2, l / 2, l / -2, -200, 200),
  61077. camera.position.z = 150,
  61078. scene = new Scene,
  61079. scene.add(camera),
  61080. material = new ShaderMaterial({
  61081. uniforms: {
  61082. tDiffuse: {
  61083. type: "scene",
  61084. value: null
  61085. },
  61086. alpha: {
  61087. type: "startYinTile",
  61088. value: 1
  61089. }
  61090. },
  61091. vertexShader: Shaders['basicTextured.vs'],
  61092. fragmentShader: Shaders['basicTextured.fs'],
  61093. depthWrite: !1,
  61094. depthTest: !1,
  61095. side: DoubleSide
  61096. }),
  61097. geo = new PlaneBufferGeometry(l, l),
  61098. plane = new Mesh(geo, material),
  61099. plane.position.z = 0,
  61100. scene.add(plane),
  61101. inited = !0);
  61102. var uv = geo.getAttribute("uv");
  61103. uv.setDynamic(!0), //setUsage
  61104. uv.needsUpdate = !0;
  61105. var uvArr = uv.array,
  61106. S = startXinTile / tileWidth, //uv这几个值基本是固定的startXinTile:0,startYinTile:0,widthinTile:512,widthinTile:512,tileWidth:512,tileHeight:512 也就是说uv不会变、每张tile的有效范围是100%
  61107. M = startYinTile / tileHeight,
  61108. R = widthinTile / tileWidth,
  61109. P = heightinTile / tileHeight;
  61110. uvArr[0] = S,
  61111. uvArr[1] = M + P,
  61112. uvArr[2] = S + R,
  61113. uvArr[3] = M + P,
  61114. uvArr[4] = S,
  61115. uvArr[5] = M,
  61116. uvArr[6] = S + R,
  61117. uvArr[7] = M;
  61118. //修改posistion,使该plane只占据需要绘制的部分。类似拼图。
  61119. //startX startY width height 都是在画布上的大小,比如画布大小为2048*2048,此tile为16分之一,tileX是1,tileY是1,则startX=2048/4,startY=2048/4
  61120. var pos = geo.getAttribute("position");
  61121. pos.setDynamic(!0),
  61122. pos.needsUpdate = !0;
  61123. var posArr = pos.array,
  61124. D = startX / renderTarget.width - l / 2 // 起始x
  61125. ,
  61126. N = startY / renderTarget.height - l / 2 // 起始y
  61127. ,
  61128. B = width / renderTarget.width // 宽
  61129. ,
  61130. F = height / renderTarget.height; // 高
  61131. posArr[0] = D,
  61132. posArr[1] = N + F,
  61133. posArr[3] = D + B,
  61134. posArr[4] = N + F,
  61135. posArr[6] = D,
  61136. posArr[7] = N,
  61137. posArr[9] = D + B,
  61138. posArr[10] = N;
  61139. renderer.properties.get(scene);
  61140. material.uniforms.tDiffuse.value = texture;
  61141. material.blending = E || NoBlending,
  61142. material.transparent = !!b;
  61143. void 0 !== w && null !== w || (w = 1),
  61144. material.uniforms.alpha.value = w,
  61145. material.needUpdate = !0;
  61146. //renderTarget.activeCubeFace = cubeFace, //0-5 应该是指定渲染h中的面 失效
  61147. /* renderer.setScissorTest(!0)
  61148. //指定绘制区域,类似遮罩(相对于屏幕)
  61149. renderer.setScissor(startX,startY,width,height) //加上这个会不会快一些,尤其是spherical
  61150. //指定绘制视口位置和大小(相对于屏幕)
  61151. */
  61152. renderTarget.viewport.set(0, 0, renderTarget.width, renderTarget.height);
  61153. var V = renderer.autoClear;
  61154. var oldTarget = renderer.getRenderTarget();
  61155. renderer.autoClear = !1;
  61156. renderer.setRenderTarget(renderTarget, cubeFace);
  61157. renderer.render(scene, camera/* , renderTarget, !1 */);
  61158. renderer.setRenderTarget(oldTarget);
  61159. renderer.autoClear = V;
  61160. //renderer.setScissorTest(!1)
  61161. /* this.renderer.render(scene, camera, this.planeTargets[cubeFace], !1),//针对有的场景app第一个点图加载不成功的问题
  61162. console.log(`图index ${cubeFace} , ${startX}, ${startY}, ${width}, ${height}`)
  61163. this.targetList[cubeFace] || (this.targetList[cubeFace] = [])
  61164. this.targetList[cubeFace].push([startX,startY,width,height])*/
  61165. }
  61166. }();
  61167. /*
  61168. * 将texture渲染到zoomRenderTarget上(目的是复制贴图到zoomRenderTarget)
  61169. */
  61170. PanoRenderer.prototype.copyCubeMap = function() {//将texture渲染到zoomRenderTarget上
  61171. var inited = !1,
  61172. scene = null,
  61173. camera = null,
  61174. material = null,
  61175. geo = null,
  61176. mesh = null,
  61177. testCube = null, //add
  61178. c = new Euler;
  61179. return function(texture, renderTarget, tWidth, tHeight, rWidth, rHeight, m, v, A) {
  61180. if(rWidth > this.qualityManager.maxRenderTargetSize) return; //add
  61181. if (!inited) {
  61182. var w = 2;
  61183. camera = new OrthographicCamera(w / -2, w / 2, w / 2, w / -2, 0, 200),
  61184. camera.position.set(0, 0, 0),
  61185. scene = new Scene,
  61186. scene.add(camera);
  61187. material = new ShaderMaterial({
  61188. uniforms: {
  61189. tDiffuse: {
  61190. type: "t",
  61191. value: null
  61192. },
  61193. alpha: {
  61194. type: "f",
  61195. value: 1
  61196. }
  61197. },
  61198. vertexShader: Shaders['copyCubeMap.vs'],
  61199. fragmentShader:Shaders['copyCubeMap.fs'],
  61200. depthWrite: !1,
  61201. depthTest: !1,
  61202. side: DoubleSide
  61203. });
  61204. geo = new BoxGeometry(w, w, w),
  61205. mesh = new Mesh(geo, material),
  61206. scene.add(mesh);
  61207. inited = !0;
  61208. /* testCube = mesh.clone();
  61209. viewer.scene.scene.add(testCube);
  61210. viewer.setObjectLayers(testCube, 'sceneObjects')
  61211. */
  61212. }
  61213. let autoClear = this.viewer.renderer.autoClear;
  61214. let oldTarget = this.viewer.renderer.getRenderTarget();
  61215. this.viewer.renderer.autoClear = false;
  61216. material.uniforms.tDiffuse.value = texture;
  61217. material.blending = m || NoBlending;
  61218. material.transparent = !!v;
  61219. void 0 !== A && null !== A || (A = 1);
  61220. material.uniforms.alpha.value = A;
  61221. material.needUpdate = !0;
  61222. for (var C = 0; C < 6; C++){
  61223. this.getCubeOrientationForCubeFace(C, c);
  61224. mesh.rotation.copy(c);
  61225. mesh.matrixWorldNeedsUpdate = !0;
  61226. mesh.updateMatrixWorld();
  61227. renderTarget.viewport.set(0, 0, rWidth, rHeight);
  61228. this.viewer.renderer.setRenderTarget(renderTarget, C ); //renderTarget.activeCubeFace = C//失效
  61229. this.viewer.renderer.render(scene, camera);
  61230. }
  61231. //console.warn('copyCubeMap' + rWidth)
  61232. this.viewer.renderer.autoClear = autoClear;
  61233. this.viewer.renderer.setRenderTarget(oldTarget);
  61234. }
  61235. }();
  61236. class DepthImageSampler {
  61237. constructor(){
  61238. var canvas = document.createElement("canvas");
  61239. this.canvas = canvas;
  61240. this.context = canvas.getContext("2d");
  61241. /* document.getElementsByTagName('body')[0].appendChild(canvas);
  61242. canvas.style.position = 'fixed';
  61243. canvas.style.width = '1024px';
  61244. canvas.style.top = canvas.style.left = 0
  61245. canvas.style['z-index'] = 100
  61246. */
  61247. }
  61248. changeImg(img){
  61249. if(this.img == img)return
  61250. this.canvas.width = img.width;
  61251. this.canvas.height = img.height;
  61252. this.context.drawImage(img, 0, 0);
  61253. this.img = img;
  61254. }
  61255. getDepth(UVx, UVy) {//根据图片像素获取深度值
  61256. var x = Math.round(UVx * (this.canvas.width - 1))
  61257. , y = Math.round(UVy * (this.canvas.height - 1));
  61258. if (!(x < 0 || y < 0 || x >= this.width || y >= this.height)) {
  61259. var r = this.context.getImageData(x, y, 1, 1).data;
  61260. //console.log('color', r, x,y)
  61261. return r[1] + r[0] / 256
  61262. }
  61263. }
  61264. sample( intersect, currentPano, onlyPos ) {//通过和skybox的intersect得到真实的intersect的位置
  61265. if(!intersect)return
  61266. let location = new THREE.Vector3;
  61267. let normal;
  61268. currentPano = currentPano || viewer.images360.currentPano;
  61269. if(currentPano != this.currentPano){
  61270. if(!currentPano.depthTex/* || !currentPano.depthTex.image */) return //未加载
  61271. this.changeImg(currentPano.depthTex.image);
  61272. this.currentPano = currentPano;
  61273. }
  61274. let origin = currentPano.position;
  61275. let dir = intersect.dir || new THREE.Vector3().subVectors(intersect.point, origin).normalize();
  61276. //var uv = intersect.uv
  61277. //let dirInPano = math.getNormalDir(dir, currentPano)//转化为考虑漫游点旋转的方向
  61278. let dirInPano = dir.clone().applyMatrix4(currentPano.panoMatrix2Inverse).normalize(); //转化为考虑漫游点旋转的方向
  61279. let uv = math.getUVfromDir(dirInPano);//转化为uv
  61280. let distance = this.getDepth(uv.x, uv.y);
  61281. //console.log('depth', depth, uv.y)
  61282. if (!distance){
  61283. if(uv.y > 0.75){//漫游点底部识别不到的区域,给一个地板高度
  61284. //let height = origin.distanceTo(currentPano.floorPosition);
  61285. const margin = 0.1;
  61286. distance = (currentPano.floorPosition.z - origin.z - margin) / dir.z;
  61287. location.copy(dir).multiplyScalar(distance).add(origin);
  61288. let normal = new THREE.Vector3(0,0,1);
  61289. return {location, normal, distance}
  61290. }
  61291. else return !1; //应该是天空或模型外 , 因为很少有漫游点的地方还拍不到地板
  61292. }
  61293. //this.mainDepth = depth
  61294. location.copy(dir).multiplyScalar(distance).add(origin);
  61295. if(!onlyPos){
  61296. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  61297. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  61298. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  61299. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  61300. normal = this.planeFit(dir,location, pL,pR,pB,pT );
  61301. }
  61302. /* if(normal.x != normal.x ){
  61303. console.log('NAN', normal)
  61304. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  61305. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  61306. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  61307. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  61308. } */
  61309. //console.log('normal',normal)
  61310. return {location, normal, distance}
  61311. }
  61312. getNearbyPoint( origin, uv, x, y) { //获取附近的若干像素距离的点
  61313. let uv2 = uv.clone();
  61314. uv2.x += x/(this.canvas.width-1);
  61315. uv2.x = this.clampUV(uv2.x);
  61316. uv2.y += y/(this.canvas.height-1);
  61317. uv2.y = this.clampUV(uv2.y);
  61318. /* if(uv2.x < 0 || uv2.y < 0 || uv2.x > 1 || uv2.y > 1){
  61319. console.log('will nan')
  61320. } */
  61321. let dir = math.getDirFromUV(uv2);//从uv获取到方向
  61322. dir.applyMatrix4(viewer.images360.currentPano.panoMatrix2);
  61323. let depth = this.getDepth(uv2.x, uv2.y);
  61324. /* if(Math.abs(depth - this.mainDepth) > 0.3){
  61325. console.log('Math.abs(depth - this.mainDepth) > 0.3')
  61326. } */
  61327. //let dir = new THREE.Vector3().subVectors(intersect.point, origin).normalize()
  61328. let position = new THREE.Vector3().copy(dir).multiplyScalar(depth).add(origin);
  61329. //console.log('getNearbyPoint', uv2, depth, dir, position )
  61330. return position
  61331. }
  61332. clampUV(v){
  61333. return (v + 1) % 1; // 使输出在 0-1
  61334. }
  61335. planeFit(dir, position, pL,pR,pB,pT ) {//求平均法线
  61336. let normal = new THREE.Vector3;
  61337. let plane = new THREE.Plane;
  61338. function addNormal(p1, p2) {//根据临接的四个点,分别求法线,然后法线相加能得到平均法线
  61339. if(!p1 || !p2)return
  61340. plane.setFromCoplanarPoints(position, p1, p2);
  61341. //console.log('normalSub', plane.normal)
  61342. normal.addScaledVector(plane.normal, dir.dot(plane.normal) < 0 ? 1 : -1);//根据面的朝向判断加还是减
  61343. }
  61344. addNormal(pL, pB);
  61345. addNormal(pL, pT);
  61346. addNormal(pR, pB);
  61347. addNormal(pR, pT);
  61348. if(0 !== normal.x || 0 !== normal.y || 0 !== normal.z){
  61349. normal.normalize();
  61350. //console.log(normal)
  61351. return normal
  61352. }
  61353. /* 四个面拼成一个菱形 */
  61354. }
  61355. /* makeUvToPosMap(intersect, matrix1, vec1, vec2) {
  61356. var o = intersect.object.geometry
  61357. , a = o.attributes.position.array
  61358. , s = new THREE.Vector3(a[3 * intersect.face.a],a[3 * intersect.face.a + 1],a[3 * intersect.face.a + 2]).applyMatrix4(intersect.object.matrixWorld)
  61359. , c = new THREE.Vector3(a[3 * intersect.face.b],a[3 * intersect.face.b + 1],a[3 * intersect.face.b + 2]).applyMatrix4(intersect.object.matrixWorld)
  61360. , l = new THREE.Vector3(a[3 * intersect.face.c],a[3 * intersect.face.c + 1],a[3 * intersect.face.c + 2]).applyMatrix4(intersect.object.matrixWorld);
  61361. vec1.subVectors(s, c),
  61362. vec2.subVectors(l, c);
  61363. var u = o.attributes.uv.array
  61364. , d = new THREE.Vector2(u[2 * intersect.face.a],u[2 * intersect.face.a + 1])
  61365. , p = new THREE.Vector2(u[2 * intersect.face.b],u[2 * intersect.face.b + 1])
  61366. , h = new THREE.Vector2(u[2 * intersect.face.c],u[2 * intersect.face.c + 1])
  61367. , f = d.sub(p)
  61368. , g = h.sub(p);
  61369. matrix1.set(f.x, g.x, 0, f.y, g.y, 0, 0, 0, 1),
  61370. matrix1.getInverse(matrix1)
  61371. } */
  61372. /* getNearbyPoint( point, origin, uv, o, a, s, x, y) {
  61373. var add = new THREE.Vector3(x, y , 0 )
  61374. , depth = this.getDepth(uv.x + add.x, uv.y + add.y );
  61375. if (void 0 !== depth) {
  61376. var f = add.applyMatrix3(o);
  61377. return (new THREE.Vector3).addScaledVector(a, f.x).addScaledVector(s, f.y).add(point).sub(origin).normalize().multiplyScalar(depth).add(origin)
  61378. }
  61379. } */
  61380. }
  61381. /* var i = n(4)
  61382. , r = function() {
  61383. function t(t) {
  61384. }
  61385. return t.prototype.getDepth = function(t, e) {
  61386. var n = Math.round(t)
  61387. , i = Math.round(e);
  61388. if (!(n < 0 || i < 0 || n >= this.width || i >= this.height)) {
  61389. var r = this.context.getImageData(n, i, 1, 1).data;
  61390. return r[1] + r[0] / 256
  61391. }
  61392. }
  61393. ,
  61394. Object.defineProperty(t.prototype, "width", {
  61395. get: function() {
  61396. return this.context.canvas.width
  61397. },
  61398. enumerable: !0,
  61399. configurable: !0
  61400. }),
  61401. Object.defineProperty(t.prototype, "height", {
  61402. get: function() {
  61403. return this.context.canvas.height
  61404. },
  61405. enumerable: !0,
  61406. configurable: !0
  61407. }),
  61408. t
  61409. }();
  61410. e.CanvasDepthImage = r;
  61411. var o = function() {
  61412. function t() {}
  61413. return t.sample = function(e, n, r, o, a) {
  61414. var s = n.uv
  61415. , c = s.x * (e.width - 1)
  61416. , l = (1 - s.y) * (e.height - 1)
  61417. , u = e.getDepth(c, l);
  61418. if (!u)
  61419. return !1;
  61420. o.copy(n.point).sub(r).normalize().multiplyScalar(u).add(r);
  61421. var d = new i.Matrix3
  61422. , p = new i.Vector3
  61423. , h = new i.Vector3;
  61424. t.makeUvToPosMap(n, d, p, h);
  61425. var f = this.getNearbyPoint(e, n.point, r, s, d, p, h, -1, 0)
  61426. , g = this.getNearbyPoint(e, n.point, r, s, d, p, h, 1, 0)
  61427. , m = this.getNearbyPoint(e, n.point, r, s, d, p, h, 0, -1)
  61428. , v = this.getNearbyPoint(e, n.point, r, s, d, p, h, 0, 1);
  61429. return this.planeFit(o, r, f, g, m, v, a)
  61430. }
  61431. ,
  61432. t.makeUvToPosMap = function(t, e, n, r) {
  61433. var o = t.object.geometry
  61434. , a = o.attributes.position.array
  61435. , s = new i.Vector3(a[3 * t.face.a],a[3 * t.face.a + 1],a[3 * t.face.a + 2]).applyMatrix4(t.object.matrixWorld)
  61436. , c = new i.Vector3(a[3 * t.face.b],a[3 * t.face.b + 1],a[3 * t.face.b + 2]).applyMatrix4(t.object.matrixWorld)
  61437. , l = new i.Vector3(a[3 * t.face.c],a[3 * t.face.c + 1],a[3 * t.face.c + 2]).applyMatrix4(t.object.matrixWorld);
  61438. n.subVectors(s, c),
  61439. r.subVectors(l, c);
  61440. var u = o.attributes.uv.array
  61441. , d = new i.Vector2(u[2 * t.face.a],u[2 * t.face.a + 1])
  61442. , p = new i.Vector2(u[2 * t.face.b],u[2 * t.face.b + 1])
  61443. , h = new i.Vector2(u[2 * t.face.c],u[2 * t.face.c + 1])
  61444. , f = d.sub(p)
  61445. , g = h.sub(p);
  61446. e.set(f.x, g.x, 0, f.y, g.y, 0, 0, 0, 1),
  61447. e.getInverse(e)
  61448. }
  61449. ,
  61450. t.getNearbyPoint = function(t, e, n, r, o, a, s, c, l) {
  61451. var u = new i.Vector3(c / (t.width - 1),l / (t.height - 1))
  61452. , d = (r.x + u.x) * (t.width - 1)
  61453. , p = (1 - (r.y + u.y)) * (t.height - 1)
  61454. , h = t.getDepth(d, p);
  61455. if (void 0 !== h) {
  61456. var f = u.applyMatrix3(o);
  61457. return (new i.Vector3).addScaledVector(a, f.x).addScaledVector(s, f.y).add(e).sub(n).normalize().multiplyScalar(h).add(n)
  61458. }
  61459. }
  61460. ,
  61461. t.planeFit = function(t, e, n, r, o, a, s) {
  61462. s.set(0, 0, 0);
  61463. var c = t.clone().sub(e)
  61464. , l = new i.Plane;
  61465. function u(e, n) {
  61466. e && n && (l.setFromCoplanarPoints(t, e, n),
  61467. s.addScaledVector(l.normal, c.dot(l.normal) < 0 ? 1 : -1))
  61468. }
  61469. return u(n, o),
  61470. u(n, a),
  61471. u(r, o),
  61472. u(r, a),
  61473. (0 !== s.x || 0 !== s.y || 0 !== s.z) && (s.normalize(),
  61474. !0)
  61475. }
  61476. ,
  61477. t
  61478. }();
  61479. */
  61480. var rot90$1 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  61481. let raycaster = new Raycaster();
  61482. //let currentlyHovered = null;
  61483. let texLoader$3 = new TextureLoader();
  61484. let sm$1 = new MeshBasicMaterial({side: BackSide});
  61485. let tileArr = [];
  61486. let previousView = {
  61487. controls: null,
  61488. position: null,
  61489. target: null,
  61490. };
  61491. const HighMapCubeWidth = 1;
  61492. const directionFactor = 200; //原先10,几乎只往距离近的走了;设置太大楼梯上不去
  61493. class Images360 extends EventDispatcher{
  61494. constructor(viewer ){
  61495. super();
  61496. this.viewer = viewer;
  61497. this.selectingEnabled = true;
  61498. this.panos = [];
  61499. this.neighbourMap = {};
  61500. this.node = new Object3D();
  61501. this.node.name = 'ImagesNode';
  61502. //this.node2 = new THREE.Object3D();
  61503. this.cubePanos = [];
  61504. this.cube = new Mesh(new BoxBufferGeometry(1,1,1,1),new ModelTextureMaterial());
  61505. viewer.updateVisible(this.cube,'showSkybox', false );
  61506. this.cube.layers.set(Potree.config.renderLayers.skybox);
  61507. this.cube.name = 'skyboxCube';
  61508. viewer.scene.scene.add(this.cube);
  61509. this._visible = true;
  61510. this.currentPano = null;
  61511. this.mouseLastMoveTime = Date.now();
  61512. this.scrollZoomSpeed = 0.06;
  61513. this.zoomLevel = 1;
  61514. this.tileDownloader = new TileDownloader;
  61515. this.qualityManager = new QualityManager;
  61516. this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager);
  61517. this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE);
  61518. this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD);
  61519. this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.HIGH);
  61520. this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
  61521. this.tileDownloader.processPriorityQueue = !1;
  61522. this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize);
  61523. this.flying_ = false;
  61524. {//高分辨率cube 放大
  61525. this.addHighMapCube();
  61526. viewer.addEventListener(PanoramaEvents.Enter,(e)=>{
  61527. this.setHighMap(e.newPano);
  61528. });
  61529. viewer.addEventListener('panoSetZoom',(e)=>{
  61530. if(Potree.settings.displayMode == 'showPanos'){
  61531. e.zoomed ? this.showHighMap() : this.hideHighMap(); //add
  61532. }
  61533. });
  61534. }
  61535. this.depthSampler = new DepthImageSampler();
  61536. this.addEventListener('loadedDepthImg',(e)=>{
  61537. e.loaded && this.updateDepthTex(e.pano);
  61538. });
  61539. let scroll = (e)=>{
  61540. if(e.hoverViewport != viewer.mainViewport)return
  61541. /* if(Potree.settings.displayMode == 'showPanos' && Potree.settings.zoom.enabled){
  61542. } */
  61543. };
  61544. viewer.fpControls.addEventListener('dollyStopCauseUnable',(e)=>{
  61545. if(/* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled)return
  61546. if(e.scale != void 0){//触屏
  61547. this.zoomBy(e.scale, e.pointer);
  61548. }else {//滚轮
  61549. let zoom;
  61550. if(e.delta > 0){
  61551. zoom = 1 + this.scrollZoomSpeed;
  61552. }else {
  61553. zoom = 1 - this.scrollZoomSpeed;
  61554. }
  61555. e.delta != 0 && this.zoomBy(zoom);
  61556. }
  61557. });
  61558. let click = (e) => {//不用"mouseup" 是因为 mouseup有drag object时也会触发
  61559. if(e.clickElement ||
  61560. Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算
  61561. || Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView'
  61562. || Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance
  61563. ) return
  61564. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  61565. if( e.hoverViewport == viewer.mapViewer.viewports[0]){
  61566. return viewer.mapViewer.dispatchEvent(e/* {type:'global_click',e } */)
  61567. }else if(e.hoverViewport != viewer.mainViewport){ //如数据集校准其他viewport
  61568. return
  61569. }
  61570. }
  61571. /* if(currentlyHovered && currentlyHovered.pano){
  61572. this.focusPano(currentlyHovered.pano);
  61573. }else{//add */
  61574. if(!Potree.settings.dblToFocusPoint/* && this.currentPano */){//双击不会focus点云 或者 已经focusPano了
  61575. this.flyToPanoClosestToMouse();
  61576. }
  61577. //}
  61578. };
  61579. viewer.addEventListener('global_click' , click);
  61580. viewer.addEventListener("global_mousemove", (e) => {
  61581. if(!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport){//如果不显示marker,就在点击时再更新
  61582. this.updateClosestPano(e.intersect);
  61583. }
  61584. });
  61585. this.addEventListener('markerHover',(e)=>{
  61586. this.updateClosestPano(e.pano, e.hovered);
  61587. });
  61588. if(!Potree.settings.isOfficial){
  61589. this.domRoot = viewer.renderer.domElement.parentElement;
  61590. let elUnfocus = $("<input type='button' value='unfocus'></input>");
  61591. elUnfocus.css({
  61592. position : "absolute",
  61593. right : '25%',
  61594. bottom: '20px',
  61595. zIndex: "10000",
  61596. fontSize:'1em', color:"black",
  61597. display:'none',
  61598. background:'rgba(255,255,255,0.8)',
  61599. });
  61600. elUnfocus.on("click", () => this.unfocus());
  61601. this.elUnfocus = elUnfocus;
  61602. this.domRoot.appendChild(elUnfocus[0]);
  61603. if(Potree.settings.editType != 'merge'){
  61604. let elHide = $("<input type='button' value='隐藏点云'></input>");
  61605. elHide.css({
  61606. position : "absolute",
  61607. right : '40%',
  61608. bottom: '20px',
  61609. zIndex: "10000",
  61610. fontSize:'1em' ,color:"black",
  61611. width : '100px',
  61612. background:'rgba(255,255,255,0.8)',
  61613. });
  61614. this.domRoot.appendChild(elHide[0]);
  61615. elHide.on("click", (e) => {
  61616. let visi = viewer.getObjVisiByReason(viewer.scene.pointclouds[0], 'force');
  61617. viewer.scene.pointclouds.forEach(e=>{
  61618. viewer.updateVisible(e, 'force', !visi);
  61619. });
  61620. elHide.val(!visi ? "隐藏点云" : "显示点云");
  61621. });
  61622. }
  61623. let elDisplayModel = $("<input type='button' value='>>全景'></input>");
  61624. elDisplayModel.css({
  61625. position : "absolute",
  61626. right : '65%',
  61627. bottom: '20px',
  61628. zIndex: "10000",
  61629. fontSize:'1em',color:"black",
  61630. width : '100px',
  61631. background:'rgba(255,255,255,0.8)',
  61632. });
  61633. this.domRoot.appendChild(elDisplayModel[0]);
  61634. elDisplayModel.on("click", (e) => {
  61635. if(Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0)return
  61636. Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud';
  61637. });
  61638. this.elDisplayModel = elDisplayModel;
  61639. }
  61640. {//切换模式
  61641. let displayMode = '';
  61642. let latestRequestMode = '';//因为可能延迟,所以记录下每次的请求模式,延迟后判断这个
  61643. Object.defineProperty(Potree.settings , "displayMode",{
  61644. get: function() {
  61645. return displayMode
  61646. },
  61647. set: (mode)=> {
  61648. latestRequestMode = mode;
  61649. console.warn('Request setMode: ' + mode);
  61650. if(mode != displayMode){
  61651. let config = Potree.config.displayMode[mode];
  61652. let config2;
  61653. let camera = viewer.scene.getActiveCamera();
  61654. if(mode == 'showPanos' && viewer.mainViewport.view.isFlying()){//飞完才能切换全景
  61655. let f = ()=>{
  61656. if(latestRequestMode == mode){//如果ui还是停在这个模式的话
  61657. Potree.settings.displayMode = mode;
  61658. }
  61659. viewer.mainViewport.view.removeEventListener('flyingDone', f);
  61660. };
  61661. viewer.mainViewport.view.addEventListener('flyingDone', f); //once
  61662. return
  61663. }
  61664. if(this.isAtPano() ){//this.currentPano
  61665. if(this.flying)config2 = config.transition;
  61666. else config2 = config.atPano;
  61667. }else {
  61668. config2 = config.atPano;
  61669. if(mode == 'showPanos'){//自动飞入一个pano
  61670. //要改成飞进最近的。。。
  61671. if(this.panos.length == 0)return
  61672. //this.modeChanging = true //主要是因为到全景图不会立刻成功
  61673. let wait = ()=>{
  61674. this.removeEventListener('flyToPanoDone',wait);
  61675. if(latestRequestMode == mode ){
  61676. Potree.settings.displayMode = mode;
  61677. }
  61678. };
  61679. this.flyToPano({
  61680. pano: this.findNearestPano(),
  61681. //dealDoneWhenCancel:true,
  61682. /* callback: ()=>{
  61683. setTimeout(()=>{ //防止循环,所以延迟
  61684. if(latestRequestMode == mode ){
  61685. Potree.settings.displayMode = mode
  61686. }
  61687. },1)
  61688. } */
  61689. });
  61690. this.addEventListener('flyToPanoDone',wait); //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel
  61691. return;
  61692. }else {
  61693. }
  61694. }
  61695. if(config2.showSkybox || config2.showPoint && config2.pointUsePanoTex){
  61696. this.tileDownloader.start();
  61697. }else {
  61698. this.tileDownloader.stop();
  61699. }
  61700. if(config2.showSkybox || config2.pointUsePanoTex){
  61701. let wait = ()=> {
  61702. setTimeout( ()=>{
  61703. if(latestRequestMode == mode ){
  61704. Potree.settings.displayMode = mode;
  61705. }
  61706. },1);
  61707. this.removeEventListener('loadedDepthImg', wait);
  61708. };
  61709. if(!this.currentPano.depthTex && this.currentPano.pointcloud.hasDepthTex){
  61710. this.addEventListener('loadedDepthImg', wait);
  61711. return this.currentPano.loadDepthImg()
  61712. }
  61713. //this.updateDepthTex()
  61714. if(this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, wait)){
  61715. return
  61716. }
  61717. }
  61718. viewer.scene.pointclouds.forEach(e=>{
  61719. viewer.updateVisible(e, 'displayMode', config2.showPoint, 2 );
  61720. });
  61721. if(config2.pointUsePanoTex){
  61722. viewer.scene.pointclouds.forEach(e=>{
  61723. e.material.setProjectedPanos(this.currentPano,this.currentPano, 1);
  61724. });
  61725. }else {
  61726. viewer.scene.pointclouds.forEach(e=>{
  61727. e.material.stopProjectedPanos();
  61728. });
  61729. }
  61730. viewer.updateVisible(this.cube,'showSkybox',config2.showSkybox );// this.cube.visible = config2.showSkybox
  61731. //this.cube.visible = config.atPano.showSkybox
  61732. if(this.cube.visible){
  61733. //this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1)
  61734. this.setProjectedPanos({
  61735. progress:1,
  61736. ifSkybox: true,
  61737. ifPointcloud : false,
  61738. easeInOutRatio : 0,
  61739. pano0:this.currentPano,
  61740. pano1:this.currentPano
  61741. });
  61742. }else {
  61743. this.smoothZoomTo(1);
  61744. this.resetHighMap();
  61745. this.hideHighMap();
  61746. }
  61747. /* viewer.dispatchEvent({
  61748. type: "enableChangePos",
  61749. canLeavePano : config.canLeavePano ,
  61750. viewport:
  61751. }) */
  61752. //viewer.mainViewport.unableChangePos = !config.canLeavePano
  61753. displayMode = mode;
  61754. if(mode == 'showPanos'){
  61755. camera.far = viewer.farWhenShowPano; //修改far
  61756. Potree.settings.pointDensity = 'panorama';
  61757. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  61758. viewer.scene.pointclouds.forEach(e=>{
  61759. e.material.pointSizeType = 'FIXED';
  61760. });
  61761. }
  61762. this.updateCube(this.currentPano);
  61763. }else {
  61764. if(camera.limitFar) camera.far = Potree.settings.cameraFar;//修改far
  61765. Potree.settings.pointDensity = Potree.settings.UserPointDensity;
  61766. //Potree.sdk && Potree.sdk.scene.changePointOpacity()
  61767. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  61768. viewer.scene.pointclouds.forEach(e=>{
  61769. e.material.pointSizeType = Potree.config.material.pointSizeType;
  61770. });
  61771. }
  61772. }
  61773. camera.updateProjectionMatrix();
  61774. if(this.elDisplayModel){
  61775. this.elDisplayModel.val( mode == 'showPointCloud' ? ">>全景" : '>>点云');
  61776. }
  61777. /* this.panos.forEach(e=>{
  61778. viewer.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') //
  61779. }) */
  61780. this.dispatchEvent({type:'endChangeMode',mode});
  61781. console.log('setModeSuccess: ' + mode);
  61782. }else {
  61783. //this.dispatchEvent({type:'endChangeMode',mode})
  61784. }
  61785. }
  61786. });
  61787. Potree.settings.displayMode = 'showPointCloud';
  61788. }// 切换模式 end
  61789. {//
  61790. let currentPano = null;
  61791. Object.defineProperty(this , "currentPano",{
  61792. get: function() {
  61793. return currentPano
  61794. },
  61795. set: function(e) {
  61796. if(e != currentPano){
  61797. currentPano && currentPano.exit();
  61798. e && e.enter();
  61799. currentPano = e;
  61800. }
  61801. }
  61802. });
  61803. }
  61804. {//是否显示marker
  61805. let ifShowMarker = true;
  61806. Object.defineProperty(Potree.settings, "ifShowMarker",{
  61807. get: function() {
  61808. return ifShowMarker
  61809. },
  61810. set: (show)=>{
  61811. show = !!show;
  61812. if(show != ifShowMarker){
  61813. this.panos.forEach(pano=>{
  61814. viewer.updateVisible(pano, 'ifShowMarker', show, 1 );
  61815. });
  61816. //this.emit('markersDisplayChange', show)
  61817. ifShowMarker = show;
  61818. }
  61819. }
  61820. });
  61821. }
  61822. viewer.addEventListener("update", () => {
  61823. this.update(viewer);
  61824. });
  61825. //viewer.inputHandler.addInputListener(this);
  61826. var keys = {
  61827. FORWARD: ['W'.charCodeAt(0), 38],
  61828. BACKWARD: ['S'.charCodeAt(0), 40],
  61829. LEFT: ['A'.charCodeAt(0), 37],
  61830. RIGHT: ['D'.charCodeAt(0), 39],
  61831. };
  61832. viewer.inputHandler.addEventListener('keydown',(e)=>{
  61833. if(Potree.settings.displayMode == 'showPanos'){
  61834. for(let i in keys){
  61835. if(keys[i].some(a => a == e.keyCode)){
  61836. switch(i){
  61837. case 'FORWARD':
  61838. this.flyLocalDirection(Vectors.FORWARD.clone());
  61839. break;
  61840. case 'BACKWARD':
  61841. this.flyLocalDirection(Vectors.BACK.clone());
  61842. break;
  61843. case 'LEFT':
  61844. this.flyLocalDirection(Vectors.LEFT.clone());
  61845. break;
  61846. case 'RIGHT':
  61847. this.flyLocalDirection(Vectors.RIGHT.clone());
  61848. break;
  61849. }
  61850. break;
  61851. }
  61852. }
  61853. }
  61854. });
  61855. };
  61856. updateDepthTex(pano){
  61857. if(this.currentPano != pano || !pano.depthTex)return
  61858. //this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的
  61859. this.cube.material.updateDepthTex(pano); //确保一下
  61860. }
  61861. findNearestPano(pos){
  61862. pos = pos ? new Vector3().copy(pos) : this.position;
  61863. let result = Common.sortByScore(this.panos,[Images360.filters.isEnabled()],[e=>-e.position.distanceTo(pos)]);
  61864. let pano = result && result[0] && result[0].item;
  61865. return pano
  61866. }
  61867. /* set flying(v){//正在飞向pano
  61868. this.flying_ = !!v
  61869. //console.log('this.flying_ ', !!v )
  61870. //this.emit('flying', this.flying_)
  61871. let config = Potree.config.displayMode[Potree.settings.displayMode]
  61872. viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v
  61873. }
  61874. get flying(){
  61875. return this.flying_
  61876. } */
  61877. flyLocalDirection(dir) {
  61878. var direction = this.getDirection(dir),
  61879. option1 = 1 === dir.y ? .4 : .75,
  61880. option2 = 1 === Math.abs(dir.x);
  61881. return this.flyDirection(direction, option1, option2)
  61882. }
  61883. getDirection(e) {
  61884. if(!e){
  61885. return viewer.scene.view.direction
  61886. }else {
  61887. return e = e ? e : (new Vector3).copy(Vectors.FORWARD),
  61888. e.applyQuaternion(viewer.scene.getActiveCamera().quaternion)
  61889. }
  61890. }
  61891. get position(){
  61892. return this.viewer.scene.view.position.clone()
  61893. }
  61894. get visible(){
  61895. return this._visible;
  61896. }
  61897. set visible(visible){
  61898. if(this._visible === visible){
  61899. return;
  61900. }
  61901. /* for(const image of this.panos){
  61902. image.mesh.visible = visible && (this.currentPano == null);
  61903. } */
  61904. //this.sphere.visible = visible && (this.currentPano != null);
  61905. this._visible = visible;
  61906. this.dispatchEvent({
  61907. type: "visibility_changed",
  61908. panos: this,
  61909. });
  61910. }
  61911. isAtPano(){//是否在某个漫游点上
  61912. return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position)
  61913. }
  61914. updateProjectedPanos(){//更新材质贴图
  61915. //console.warn('updateProjectedPanos')
  61916. this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({pano0:this.projectedPano0, pano1:this.projectedPano1});
  61917. }
  61918. setProjectedPanos(o={}){//设置cube和点云的材质贴图
  61919. this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress);
  61920. if(o.ifPointcloud){
  61921. viewer.scene.pointclouds.forEach(e=>{
  61922. e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio);
  61923. });
  61924. }
  61925. //console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id)
  61926. this.projectedPano0 = o.pano0;
  61927. this.projectedPano1 = o.pano1;
  61928. }
  61929. cancelFlyToPano(){//取消当前已有的飞行准备,前提是相机还未移动
  61930. if(viewer.mainViewport.view.isFlying())return
  61931. this.nextPano = null;
  61932. this.latestToPano = null;
  61933. //this.flying = false
  61934. }
  61935. flyToPano(toPano) { //飞向漫游点
  61936. if(!toPano)return
  61937. if(toPano instanceof Panorama){
  61938. toPano = {pano: toPano};
  61939. }
  61940. if(!toPano.pano.enabled)return
  61941. /* if(!this.currentPano){
  61942. return this.focusPano(toPano)
  61943. } */
  61944. let done = (makeIt, disturb)=>{
  61945. //console.log('flyToPano done ', toPano.pano.id, makeIt )
  61946. if(makeIt || disturb) { // disturb已经开始飞行但中途取消
  61947. toPano.callback && toPano.callback(makeIt);
  61948. //this.flying = false
  61949. this.cancelFlyToPano();
  61950. this.updateClosestPano(this.closestPano,false); //飞行结束后取消点击漫游点时得到的closestPano
  61951. }else {
  61952. console.log('makeit fail');
  61953. }
  61954. this.dispatchEvent({type:'flyToPanoDone', makeIt});
  61955. //this.dispatchEvent('cameraMoveDone')
  61956. toPano.deferred && toPano.deferred.resolve(makeIt); //测量线截图时发现,resolve需要写在flying=false 后才行。
  61957. };
  61958. if(this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion ){
  61959. this.dispatchEvent({type:'flyToPano', toPano});
  61960. return done(true);
  61961. }
  61962. if(this.latestToPano && this.latestToPano != toPano){
  61963. return done(false)
  61964. }
  61965. let target = toPano.target;
  61966. let easeName = toPano.easeName || 'easeInOutQuad'; // 'easeInOutSine'//'easeOutSine'
  61967. let config = Potree.config.displayMode[Potree.settings.displayMode];
  61968. var pointcloudVisi = config.atPano.showPoint; //viewer.scene.pointclouds[0].visible
  61969. var pano = toPano.pano;
  61970. let T = Potree.config.transitionsTime;
  61971. let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn;
  61972. var duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * this.position.distanceTo(pano.position), maxTime)) : toPano.duration;
  61973. toPano.duration = duration;
  61974. //console.warn("flyto "+pano.id + ' duration: ' + duration )
  61975. this.nextPano = pano;
  61976. this.latestToPano = toPano;
  61977. //this.flying = true //防止新的请求
  61978. {//不飞的话是否不要执行这段?
  61979. let wait = ()=> {
  61980. if(this.latestToPano != toPano)return //如果取消了
  61981. setTimeout(()=>{
  61982. if(this.latestToPano != toPano)return
  61983. this.flyToPano(toPano);
  61984. },1);
  61985. this.removeEventListener('loadedDepthImg', wait);
  61986. };
  61987. if(!pano.depthTex && pano.pointcloud.hasDepthTex){ //需要用到depthTex计算neighbour
  61988. this.addEventListener('loadedDepthImg', wait);
  61989. return pano.loadDepthImg()
  61990. }
  61991. if(config.atPano.showSkybox || config.atPano.pointUsePanoTex){
  61992. this.updateCube(this.currentPano, toPano.pano);
  61993. if(this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait)){
  61994. return
  61995. }
  61996. }
  61997. }
  61998. viewer.updateVisible(this.cube,'showSkybox', config.atPano.showSkybox ); // this.cube.visible = config.atPano.showSkybox
  61999. /* this.cube.visible && this.cube.material.setProjectedPanos(this.currentPano, pano, 0)
  62000. if(config.transition.showPoint){
  62001. viewer.scene.pointclouds.forEach(e=>{
  62002. viewer.updateVisible(e, 'displayMode', true)
  62003. })
  62004. if(config.transition.pointUsePanoTex){
  62005. let easeInOutRatio = pointcloudVisi ? 0.3 : 0
  62006. viewer.scene.pointclouds.forEach(e=>{
  62007. e.material.setProjectedPanos(this.currentPano, pano, 0, easeInOutRatio)
  62008. })
  62009. }
  62010. } */
  62011. if(config.transition.showPoint){
  62012. viewer.scene.pointclouds.forEach(e=>{
  62013. viewer.updateVisible(e, 'displayMode', true);
  62014. });
  62015. }
  62016. if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  62017. this.setProjectedPanos({
  62018. progress:0,
  62019. ifSkybox: this.cube.visible,
  62020. ifPointcloud : config.transition.pointUsePanoTex,
  62021. easeInOutRatio : pointcloudVisi ? 0.3 : 0,
  62022. pano0:this.currentPano,
  62023. pano1:pano
  62024. });
  62025. }
  62026. const endPosition = pano.position.clone();
  62027. {
  62028. toPano.duration = duration;
  62029. toPano.easeName = easeName;
  62030. this.beforeFlyToPano(toPano);
  62031. }
  62032. let fly = ()=>{
  62033. this.dispatchEvent({type:'flyToPano', toPano});
  62034. viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration,
  62035. callback:()=>{
  62036. if(!config.atPano.pointUsePanoTex){
  62037. viewer.scene.pointclouds.forEach(e=>{
  62038. e.material.stopProjectedPanos();
  62039. });
  62040. }
  62041. //this.currentPano.exit()
  62042. //pano.enter()
  62043. this.currentPano = pano;
  62044. this.nextPano = null;
  62045. if(Potree.settings.displayMode == 'showPanos'){
  62046. viewer.scene.pointclouds.forEach(e=>{
  62047. viewer.updateVisible(e, 'displayMode',pointcloudVisi);
  62048. });
  62049. }
  62050. done(true);
  62051. //this.updateCube(this.currentPano)
  62052. this.updateDepthTex(this.currentPano);
  62053. }, onUpdate:(progress)=>{
  62054. this.cube.material.uniforms.progress.value = progress;
  62055. viewer.scene.pointclouds.forEach(e=>{
  62056. e.material.uniforms.progress.value = progress;
  62057. });
  62058. },
  62059. cancelFun:()=>{ done(false, true); },
  62060. Easing:easeName
  62061. });
  62062. //duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false
  62063. };
  62064. if(Potree.settings.displayMode == 'showPanos'){
  62065. setTimeout(fly, 40); //更新geo后缓冲
  62066. }else {
  62067. fly();
  62068. }
  62069. //console.log('flyToPano:', toPano.pano.id)
  62070. }
  62071. beforeFlyToPano(toPano){
  62072. if(this.currentPano != toPano.pano) {
  62073. if(Potree.settings.displayMode == 'showPanos'){
  62074. this.resetHighMap();
  62075. }
  62076. this.smoothZoomTo(1, toPano.duration / 2);
  62077. }
  62078. }
  62079. /* focusPano(toPano ){
  62080. if(this.currentPano !== null){
  62081. return this.flyToPano(toPano);
  62082. }
  62083. if(toPano instanceof Panorama){
  62084. toPano = {pano: toPano}
  62085. }
  62086. let done = (makeIt)=>{
  62087. toPano.deferred && toPano.deferred.resolve(makeIt)
  62088. makeIt && toPano.callback && toPano.callback()
  62089. }
  62090. var pano = toPano.pano
  62091. let config = Potree.config.displayMode[Potree.settings.displayMode]
  62092. previousView = {
  62093. //controls: this.viewer.controls,
  62094. position: this.position,
  62095. target: viewer.scene.view.getPivot(),
  62096. };
  62097. //this.viewer.setControls(this.viewer.orbitControls);
  62098. this.viewer.orbitControls.doubleClockZoomEnabled = false;
  62099. for(let image of this.panos){
  62100. image.mesh.visible = false;
  62101. }
  62102. this.selectingEnabled = false;
  62103. //console.warn("flyto "+pano.file.split('/').pop() )
  62104. var dur = toPano.duration == void 0 ? 700 : toPano.duration
  62105. if(config.atPano.showSkybox){
  62106. if ( this.checkAndWaitForPanoLoad(pano, this.basePanoSize, ()=> {
  62107. setTimeout( ()=>{
  62108. this.focusPano(toPano)
  62109. },1)
  62110. })
  62111. ) {
  62112. return ;
  62113. }
  62114. }
  62115. this.cube.visible = config.atPano.showSkybox
  62116. //if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  62117. this.setProjectedPanos({
  62118. progress:0,
  62119. ifSkybox: this.cube.visible,
  62120. ifPointcloud : config.atPano.pointUsePanoTex,
  62121. pano0:pano,
  62122. pano1:pano
  62123. })
  62124. //}
  62125. let newCamPos = pano.position.clone()
  62126. let target = newCamPos.clone().add(viewer.scene.view.direction)
  62127. viewer.scene.view.setView( {position:newCamPos, target, duration:dur ,
  62128. callback:()=>{//done
  62129. //pano.enter()
  62130. this.flying = false
  62131. this.currentPano = pano;
  62132. this.updateCube(this.currentPano)
  62133. done(true)
  62134. },onUpdate:(progress)=>{
  62135. },
  62136. cancelFun:()=>{this.flying = false}
  62137. })
  62138. this.flying = true
  62139. this.elUnfocus && (this.elUnfocus[0].style.display = "");
  62140. }
  62141. unfocus(o={}){
  62142. this.selectingEnabled = true;
  62143. Potree.settings.displayMode = 'showPointCloud'
  62144. if(!this.currentPano && !o.position){
  62145. return;
  62146. }
  62147. this.cube.visible = false
  62148. viewer.orbitControls.doubleClockZoomEnabled = true;
  62149. viewer.scene.view.setView($.extend({
  62150. position: previousView.position,
  62151. target:previousView.target,
  62152. duration:500
  62153. },o,{
  62154. callback:()=>{ //done
  62155. for(let pano of this.panos){
  62156. pano.mesh.visible = true;
  62157. //pano.marker.material.depthTest = true
  62158. }
  62159. o.callback && o.callback()
  62160. }
  62161. ,
  62162. cancelFun:()=>{this.flying = false},
  62163. }))
  62164. //this.currentPano.exit()
  62165. this.currentPano = null;
  62166. this.elUnfocus && (this.elUnfocus[0].style.display = "none");
  62167. } */
  62168. updateCube(pano0, pano1){
  62169. if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话
  62170. if(Potree.settings.displayMode != 'showPanos')return
  62171. let f = (bound, size)=>{
  62172. size = size || bound.getSize(new Vector3);
  62173. let center = bound.getCenter(new Vector3);
  62174. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62175. this.cube.scale.copy(size);
  62176. this.cube.position.copy(center);
  62177. };
  62178. let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离
  62179. if(bound1.intersectsBox(bound2))return 0
  62180. let center1 = bound1.getCenter(new Vector3);
  62181. let center2 = bound2.getCenter(new Vector3);
  62182. let dis = center1.distanceTo(center2);
  62183. let dis1 = bound1.distanceToPoint(center2);
  62184. let dis2 = bound2.distanceToPoint(center1);
  62185. return dis1 + dis2 - dis
  62186. };
  62187. if(pano1){//过渡
  62188. if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡
  62189. f(pano0.pointcloud.bound);
  62190. //console.log('updateCube1' )
  62191. }else {//非同一个数据集内的过渡
  62192. let bound = pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound);
  62193. if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){
  62194. f(bound);
  62195. }else {//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用
  62196. let size = bound.getSize(new Vector3);
  62197. let max = Math.max(size.x, size.y, size.z);
  62198. size.set(max,max,max);
  62199. f(bound, size);
  62200. //console.log('updateCube2', size)
  62201. //far可能要修改下
  62202. }
  62203. }
  62204. }else {
  62205. f(pano0.pointcloud.bound); //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小
  62206. //console.log('updateCube3' )
  62207. }
  62208. }
  62209. /* updateCube(pano0, pano1){ //垂直上不分段、 每个pano只有5个方向的版本
  62210. if(Potree.settings.displayMode != 'showPanos')return
  62211. console.log('updateCube',pano0.id, pano1&&pano1.id)
  62212. let f = (bound, size)=>{
  62213. size = size || bound.getSize(new THREE.Vector3)
  62214. let center = bound.getCenter(new THREE.Vector3)
  62215. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  62216. this.cube.scale.copy(size)
  62217. this.cube.position.copy(center)
  62218. }
  62219. this.cube.geometry.dispose();
  62220. if(pano1){//过渡
  62221. let add = (pano, dir, )=>{
  62222. let minZ, maxZ
  62223. minZ = pano.floorPosition.z
  62224. {//天花板高度值
  62225. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62226. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62227. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  62228. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  62229. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62230. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  62231. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  62232. let zs = [dir1,dir2,dir3].map(dir_=>{
  62233. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62234. let z = intersect ? intersect.location.z : pano.position.z
  62235. return z
  62236. })
  62237. zs.sort((a,b)=>{return b-a});//得最大值
  62238. maxZ = zs[0]
  62239. }
  62240. const angle = Math.PI/6 //每次转30度
  62241. let getDir = (angle_)=>{
  62242. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  62243. return dir.clone().applyMatrix4(rotMat)
  62244. }
  62245. let dirs = [getDir(angle*2), getDir(angle),getDir(angle), dir.clone(), getDir(-angle), getDir(-angle*2)]; //总共五个方向,夹角总和180度
  62246. dirs.forEach(dir=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  62247. //上下分别45度 刚好就是
  62248. let dir0 = dir.clone();// 水平方向
  62249. let dir1 = dir.clone().setZ(1).normalize() //上45度方向
  62250. let dir2 = dir.clone().setZ(-1).normalize() // 下45度方向
  62251. let disArr = [dir0,dir1,dir2].map(dir_ =>{
  62252. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62253. let projectLen = intersect.distance ? dir_.dot(dir)*intersect.distance : 0 //得到project在dir的长度
  62254. return projectLen
  62255. })
  62256. disArr.sort((a,b)=>{return b-a});//得最大值
  62257. dir.multiplyScalar( disArr[0] );//得到水平方向上的最远向量
  62258. [minZ,maxZ].forEach(z=>{ //0-9
  62259. posArr.push(pano.position.clone().setZ(z).add(dir))
  62260. })
  62261. });
  62262. [minZ,maxZ].forEach(z=>{ // 10,11
  62263. posArr.push(pano.position.clone().setZ(z))
  62264. })
  62265. }
  62266. let posArr = [];
  62267. let faceArr = [[0,1,2],[1,2,3], [2,3,4],[3,4,5], [4,5,6],[5,6,7], [6,7,8],[7,8,9], //外侧四个面
  62268. [0,2,10],[2,4,10],[4,6,10],[6,8,10],//底部扇形
  62269. [1,3,11],[3,5,11],[5,7,11],[7,9,11],//顶部扇形
  62270. ]
  62271. //两点连线的水平向量
  62272. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  62273. add(pano0, vec)
  62274. add(pano1, vec.negate())
  62275. let faceArr2 = faceArr.map(face=>face.map(i=>i+12))//加上pano2的部分
  62276. faceArr.push(...faceArr2)
  62277. //加上连接的部分,四个面
  62278. faceArr.push([0,1, 8+12],[1, 9+12, 8+12], [8,9,0+12],[9,1+12,0+12],
  62279. [0,8,0+12],[0,0+12,8+12], [1,9,1+12],[1,1+12,9+12],
  62280. )
  62281. let geo = MeshDraw.createGeometry(posArr, faceArr)
  62282. this.cube.geometry = geo
  62283. this.cube.scale.set(1,1,1);
  62284. this.cube.position.set(0,0,0)
  62285. }else{
  62286. if(this.hasUpdateOnePano)return
  62287. this.hasUpdateOnePano = true
  62288. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  62289. f(pano0.pointcloud.bound)
  62290. }
  62291. } */
  62292. /* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个
  62293. if(Potree.settings.displayMode != 'showPanos')return
  62294. console.log('updateCube',pano0.id, pano1&&pano1.id)
  62295. let f = (bound, size)=>{
  62296. size = size || bound.getSize(new THREE.Vector3)
  62297. let center = bound.getCenter(new THREE.Vector3)
  62298. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  62299. this.cube.scale.copy(size)
  62300. this.cube.position.copy(center)
  62301. }
  62302. this.cube.geometry.dispose();
  62303. if(pano1){//过渡
  62304. let count1, count2;
  62305. let panoIndex = 0
  62306. let add = (pano, dir )=>{
  62307. let getPI = function(index, panoIndex_){
  62308. if(panoIndex_ == void 0) panoIndex_ = panoIndex
  62309. return (count1 * count2 + 2 ) * panoIndex_ + index + 2
  62310. }
  62311. let minZ, maxZ
  62312. minZ = pano.floorPosition.z
  62313. {//天花板高度值
  62314. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62315. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62316. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  62317. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  62318. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62319. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  62320. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  62321. let zs = [dir1,dir2,dir3].map(dir_=>{
  62322. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62323. let z = intersect ? intersect.location.z : pano.position.z
  62324. return z
  62325. })
  62326. zs.sort((a,b)=>{return b-a});//得最大值
  62327. maxZ = zs[0]
  62328. let min = pano.position.z + 1
  62329. if(maxZ < pano.position.z + 0.04){//户外
  62330. maxZ = pano.position.z + 50
  62331. }
  62332. maxZ = Math.max(min,maxZ)
  62333. console.log(pano.id, 'maxZ:',maxZ )
  62334. console.log(pano.id, 'minZ:',minZ )
  62335. }
  62336. [maxZ, minZ ].forEach(z=>{
  62337. posArr.push(pano.position.clone().setZ(z))
  62338. })
  62339. const angle = Math.PI/8
  62340. let getDir = (angle_)=>{
  62341. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  62342. return dir.clone().applyMatrix4(rotMat)
  62343. }
  62344. let dirs = [ getDir(angle*4), getDir(angle*3), getDir(angle*2), getDir(angle), dir.clone(), getDir(-angle) , getDir(-angle*2), getDir(-angle*3), getDir(-angle*4) ]; // 夹角总和180度
  62345. count1 = dirs.length
  62346. dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  62347. let dirs_ = [
  62348. dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(),
  62349. dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(),
  62350. dir.clone(), // 水平方向
  62351. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(),
  62352. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62353. ];
  62354. count2 = dirs_.length
  62355. dirs_.forEach((dir_, i) =>{
  62356. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62357. let location
  62358. if(!intersect){ //超级远
  62359. let distance = 100
  62360. location = dir_.clone().multiplyScalar(distance).add(pano.position)
  62361. intersect = {distance,location}
  62362. }
  62363. //intersect.distance
  62364. location = intersect.location.clone()
  62365. let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ);
  62366. let needShrink = false
  62367. if(i == 0){//最上方的点高度直接等于天花板
  62368. shouldZ = maxZ
  62369. if(location.z<maxZ)location.z = maxZ
  62370. else needShrink = true
  62371. }else if(i == count2-1){//最下方的点高度直接等于地板
  62372. shouldZ = minZ
  62373. if(location.z>minZ)location.z = minZ
  62374. else needShrink = true
  62375. }
  62376. if(needShrink ){//需要在保持dir_不变的情况下修改z
  62377. let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance
  62378. location = dir_.clone().multiplyScalar(len).add(pano.position)
  62379. }
  62380. posArr.push(location)
  62381. if(index!=0 && i!=0){//加入一块四方面
  62382. let curIndex = getPI(count2 * index + i);
  62383. faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2],
  62384. [curIndex-1, curIndex, curIndex-count2])
  62385. }
  62386. })
  62387. if(index!=0){
  62388. let top = -2;
  62389. let btm = -1
  62390. faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形
  62391. faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形
  62392. }else{
  62393. //加入和另一个pano连接的其中一个侧边
  62394. let panoIndex2 = (panoIndex + 1) % 2;
  62395. for(let i=1;i<count2;i++){
  62396. faceArr.push([getPI(i-1), getPI(i), getPI((count1-1)*count2 +i, panoIndex2)],
  62397. [getPI(i-1), getPI((count1-1)*count2+i , panoIndex2) , getPI((count1-1)*count2+i-1 ,panoIndex2)])
  62398. }
  62399. faceArr.push([getPI(0), getPI((count1-1)*count2), getPI(0, panoIndex2)])//加入顶部的一半
  62400. faceArr.push([getPI(count2-1), getPI(count1*count2-1), getPI(count2-1, panoIndex2)])//加入底部的一半
  62401. }
  62402. });
  62403. panoIndex ++
  62404. }
  62405. let posArr = [];
  62406. let faceArr = []
  62407. //两点连线的水平向量
  62408. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  62409. add(pano0, vec)
  62410. add(pano1, vec.negate())
  62411. let geo = MeshDraw.createGeometry(posArr, faceArr)
  62412. this.cube.geometry = geo
  62413. this.cube.scale.set(1,1,1);
  62414. this.cube.position.set(0,0,0)
  62415. }else{
  62416. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  62417. f(pano0.pointcloud.bound)
  62418. }
  62419. } */
  62420. updateCube3(pano0, pano1){//增加细分的版本,且垂直方向上取中位数... 侧边只有一条
  62421. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  62422. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  62423. ) return
  62424. this.cubePanos = [pano0, pano1];
  62425. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  62426. let f = (bound, size)=>{
  62427. size = size || bound.getSize(new Vector3);
  62428. let center = bound.getCenter(new Vector3);
  62429. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62430. this.cube.scale.copy(size);
  62431. this.cube.position.copy(center);
  62432. };
  62433. this.cube.geometry.dispose();
  62434. if(pano1){//过渡
  62435. const half = pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex ? ( browser.isMobile() ? 3 : 6 ) : (browser.isMobile() ? 2 : 3); //自行输入 (点云计算的慢,还不准)
  62436. let count1 = 2*half;//偶数个 dir 个数
  62437. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  62438. let panoIndex = 0;
  62439. let getIntersect = (pano, dir, origin)=>{
  62440. if(pano && pano.pointcloud.hasDepthTex ){
  62441. return this.depthSampler.sample( {dir }, pano, true )
  62442. }else {
  62443. origin = origin || pano.position;
  62444. return viewer.inputHandler.getIntersect(viewer.inputHandler.hoverViewport, true, null, null, true, {
  62445. point: origin.clone().add(dir),
  62446. cameraPos: origin
  62447. })
  62448. }
  62449. };
  62450. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  62451. let rotMat = new Matrix4().makeRotationZ(angle_);
  62452. return vec.clone().applyMatrix4(rotMat)
  62453. };
  62454. let getFar = (dir, pano, origin)=>{//获取在这个方向上和墙体intersect的最远距离
  62455. let dirs_ = [
  62456. //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 户外时需要更多向上的方向,所以上方向多一个
  62457. dir.clone().setZ(Math.tan(MathUtils.degToRad(30))).normalize(),
  62458. dir.clone().setZ(Math.tan(MathUtils.degToRad(7))).normalize(),
  62459. dir.clone(), // 水平方向
  62460. dir.clone().setZ(-Math.tan(MathUtils.degToRad(5))).normalize(),
  62461. //dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62462. ];
  62463. let max = 50;
  62464. let count2 = dirs_.length;
  62465. let disArr = dirs_.map((dir_, i) =>{
  62466. let intersect = getIntersect(pano, dir_, origin);
  62467. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  62468. return projectLen
  62469. });
  62470. disArr.sort((a,b)=>{return b-a}); //从大到小
  62471. //console.log(pano ? pano.id : 'side','disArr', disArr)
  62472. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  62473. return dis
  62474. };
  62475. let add = (pano, vec )=>{
  62476. let getPI = function(index, panoIndex_){
  62477. if(panoIndex_ == void 0) panoIndex_ = panoIndex;
  62478. return (count1*2 + 2 ) * panoIndex_ + index + 2
  62479. };
  62480. let minZ, maxZ;
  62481. minZ = pano.floorPosition.z;
  62482. if(pano.ceilZ != void 0){
  62483. maxZ = pano.ceilZ;
  62484. }else {//天花板高度值
  62485. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62486. let rotMat = new Matrix4().makeRotationX(MathUtils.degToRad(40));// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62487. let dir1 = new Vector3(0,0,1).applyMatrix4(rotMat);
  62488. let rotMat1 = new Matrix4().makeRotationZ(Math.PI*2 / 3);
  62489. let rotMat2 = new Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62490. let dir2 = dir1.clone().applyMatrix4(rotMat1);
  62491. let dir3 = dir1.clone().applyMatrix4(rotMat2);
  62492. let zs = [dir1,dir2,dir3].map(dir_=>{
  62493. let intersect = getIntersect(pano, dir_);
  62494. let z = intersect ? intersect.location.z : pano.position.z+50;
  62495. return z
  62496. });
  62497. zs.sort((a,b)=>{return b-a});//得最大值
  62498. maxZ = zs[0];
  62499. let min = pano.position.z + 1;
  62500. maxZ = Math.max(min,maxZ);
  62501. pano.ceilZ = maxZ;
  62502. //console.log(pano.id, 'maxZ:',maxZ )
  62503. //console.log(pano.id, 'minZ:',minZ )
  62504. }
  62505. [maxZ, minZ ].forEach(z=>{
  62506. posArr.push(pano.position.clone().setZ(z));
  62507. });
  62508. const angle = Math.PI/(count1-1);
  62509. //在画面上线条从左往右数
  62510. let dirs = [];
  62511. for(let i=0;i<count1;i++){
  62512. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  62513. }
  62514. let sideDis = [];
  62515. dirs.forEach((dir, index)=>{
  62516. let dis = getFar(dir, pano);
  62517. if(index == 0 || index == count1-1){
  62518. sideDis.push(dis);
  62519. }
  62520. dir.multiplyScalar( dis );
  62521. [maxZ,minZ].forEach(z=>{
  62522. posArr.push(pano.position.clone().setZ(z).add(dir));
  62523. });
  62524. if(index!=0){//加入一块四方面
  62525. let m = index*2;
  62526. faceArr.push([getPI(m), getPI(m-1), getPI(m-2)],
  62527. [getPI(m), getPI(m+1), getPI(m-1)]);
  62528. let top = -2;
  62529. let btm = -1;
  62530. faceArr.push([getPI(m), getPI(m-2), getPI(top) ]);//天花板扇形
  62531. faceArr.push([getPI(btm), getPI(m-1), getPI(m+1) ] );//地板扇形
  62532. }
  62533. });
  62534. let panoIndex2 = (panoIndex + 1) % 2;
  62535. //let m = (count1-1)*2
  62536. /* faceArr.push([getPI(0), getPI(1), getPI(count1*2-1, panoIndex2)],
  62537. [getPI(0), getPI(count1*2-1,panoIndex2) , getPI(count1*2-2,panoIndex2)])
  62538. faceArr.push([getPI(0, panoIndex2), getPI(count1*2-2), getPI(0)])//加入顶部的一半
  62539. faceArr.push([getPI(1), getPI(count1*2-1), getPI(1, panoIndex2)])//加入底部的一半 */
  62540. //加入和另一个pano连接
  62541. let sideMid = count1*4+4; //侧边点start
  62542. //侧边的一半
  62543. faceArr.push([getPI(0), getPI(1), sideMid+panoIndex*2],
  62544. [sideMid+panoIndex*2, getPI(1) , sideMid+panoIndex*2+1 ],
  62545. [getPI(count1*2-2), sideMid+panoIndex2*2+1, getPI(count1*2-1)],
  62546. [getPI(count1*2-2), sideMid+panoIndex2*2, sideMid+panoIndex2*2+1 ]
  62547. );
  62548. faceArr.push([getPI(0), sideMid+panoIndex2*2, getPI(count1*2-2)],
  62549. [getPI(0),sideMid+panoIndex*2, sideMid+panoIndex2*2]
  62550. );//加入顶部的一半
  62551. faceArr.push([getPI(count1*2-1), sideMid+panoIndex2*2+1, getPI(1)],
  62552. [sideMid+panoIndex2*2+1, sideMid+panoIndex*2+1, getPI(1)]
  62553. );//加入底部的一半
  62554. panoIndex ++;
  62555. return sideDis;
  62556. };
  62557. let addSide = ()=>{//两个漫游点间两边各加一条侧线,为了适应四方形房间漫游点在对角方向的那种情况
  62558. //侧边为了取中点,没办法用全景图获取了,用点云
  62559. let sideMaxZ = (pano0.ceilZ + pano1.ceilZ)/2;
  62560. let sideMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  62561. let sideDis_ = [(sideDis0[0] + sideDis1[1])/2, (sideDis0[1] + sideDis1[0])/2];
  62562. let sideDis = [Math.min(sideDis0[0] , sideDis1[1]), Math.min(sideDis0[1] , sideDis1[0])];//
  62563. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  62564. let sideDirs = [getDir(-Math.PI/2, vec), getDir(Math.PI/2, vec)];
  62565. if(pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  62566. let panos = [pano0,pano1];
  62567. let vecs = [vec.negate(), vec];
  62568. let axis = [[-1,1],[1,-1]];
  62569. let dis2d = new Vector2$1().subVectors(pano0.position, pano1.position).length();//水平上的距离
  62570. let angles = [MathUtils.degToRad(45), MathUtils.degToRad(60)];
  62571. sideDirs.forEach((dir, index0)=>{
  62572. let disToSides = [];
  62573. panos.forEach((pano,index)=>{
  62574. let dirs = [getDir(axis[index0][index]*angles[0], vecs[index]), getDir(axis[index0][index]*angles[1], vecs[index])];//一侧的若干角度
  62575. dirs.forEach((dir_,i)=>{
  62576. let dis1 = getFar(dir_, pano);
  62577. //dir_.multiplyScalar( dis1 );
  62578. let disToPano2d = dis1 * Math.cos(angles[i]);
  62579. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入
  62580. let disToSide = dis1 * Math.sin(angles[i]);
  62581. disToSides.push(disToSide);
  62582. }
  62583. });
  62584. });
  62585. let disToSide;
  62586. if(disToSides.length){
  62587. disToSides.sort((a,b)=>{return b-a});//从大到小
  62588. disToSide = disToSides[0];
  62589. console.log('disToSides', index0, disToSides);
  62590. }else {
  62591. disToSide = sideDis[index0];
  62592. }
  62593. dir.multiplyScalar( disToSide );
  62594. [sideMaxZ,sideMinZ].forEach(z=>{
  62595. posArr.push(mid.clone().setZ(z).add(dir)); //是直接使用最长dis的那个intersect点好还是mid
  62596. });
  62597. });
  62598. }else {
  62599. sideDirs.forEach((dir_ ,index)=>{
  62600. let dis = getFar(dir_, null, mid);
  62601. dir_.multiplyScalar( /* sideDis_[index] */ Math.max(dis, sideDis[index]) );
  62602. [sideMaxZ,sideMinZ].forEach(z=>{
  62603. posArr.push(mid.clone().setZ(z).add(dir_));
  62604. });
  62605. });
  62606. }
  62607. };
  62608. let posArr = [];
  62609. let faceArr = [];
  62610. //两点连线的水平向量
  62611. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  62612. let sideDis0 = add(pano0, vec);
  62613. let sideDis1 = add(pano1, vec.negate());
  62614. addSide();
  62615. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  62616. let geo = MeshDraw.createGeometry(posArr, faceArr);
  62617. this.cube.geometry = geo;
  62618. this.cube.scale.set(1,1,1);
  62619. this.cube.position.set(0,0,0);
  62620. //this.cube.scale.set(100,100,100);
  62621. //this.cube.position.copy(pano1.position).multiplyScalar(-100)
  62622. }else {
  62623. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  62624. f(pano0.pointcloud.bound);
  62625. }
  62626. }
  62627. updateCube2(pano0, pano1){//增加细分的版本,且垂直方向上取中位数 侧边多条
  62628. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  62629. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  62630. ) return
  62631. this.cubePanos = [pano0, pano1];
  62632. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  62633. let useBound = (bound, size)=>{
  62634. size = size || bound.getSize(new Vector3);
  62635. let center = bound.getCenter(new Vector3);
  62636. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62637. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  62638. this.cube.scale.copy(size);
  62639. this.cube.position.copy(center);
  62640. };
  62641. this.cube.geometry.dispose();
  62642. if(pano1){//过渡
  62643. if(pano0.pointcloud != pano1.pointcloud){ //距离太远的数据集,过渡会畸变。所以扩大skybox
  62644. let dis = pano0.position.distanceTo(pano1.position);
  62645. if(dis > 100){
  62646. let bound = pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound);
  62647. let size = bound.getSize(new Vector3);
  62648. let max = Math.max(size.x, size.y, size.z);
  62649. size.set(max,max,max);
  62650. return useBound(bound, size)
  62651. }
  62652. }
  62653. const half = pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex ? 6 : (browser.isMobile() ? 2 : 3); //自行输入 (点云计算的慢,还不准)
  62654. let count1 = 2*half;//偶数个 每个pano向 外dir 个数
  62655. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  62656. //let panoIndex = 0
  62657. let getIntersect = (pano, dir, origin)=>{
  62658. if(pano && pano.pointcloud.hasDepthTex ){
  62659. return this.depthSampler.sample( {dir }, pano, true )
  62660. }else {
  62661. origin = origin || pano.position;
  62662. return viewer.inputHandler.getIntersect(viewer.inputHandler.hoverViewport, true, null, null, true, {
  62663. point: origin.clone().add(dir),
  62664. cameraPos: origin
  62665. })
  62666. }
  62667. };
  62668. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  62669. let rotMat = new Matrix4().makeRotationZ(angle_);
  62670. return vec.clone().applyMatrix4(rotMat)
  62671. };
  62672. let getFar = (dir, pano, origin)=>{//获取在这个方向上和墙体intersect的距离
  62673. //在垂直方向上分出多个方向,取一个最可能的接近真实的距离
  62674. let dirs_ = [
  62675. //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 户外时需要更多向上的方向,所以上方向多一个
  62676. dir.clone().setZ(Math.tan(MathUtils.degToRad(30))).normalize(),
  62677. dir.clone().setZ(Math.tan(MathUtils.degToRad(7))).normalize(),
  62678. dir.clone(), // 水平方向
  62679. dir.clone().setZ(-Math.tan(MathUtils.degToRad(5))).normalize(),
  62680. //dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62681. ];
  62682. let max = 50;
  62683. let count2 = dirs_.length;
  62684. let disArr = dirs_.map((dir_, i) =>{
  62685. let intersect = getIntersect(pano, dir_, origin);
  62686. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  62687. return projectLen //得水平距离
  62688. });
  62689. disArr.sort((a,b)=>{return b-a}); //从大到小
  62690. //console.log(pano ? pano.id : 'side','disArr', disArr)
  62691. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  62692. return dis
  62693. };
  62694. let sideCount = [];
  62695. let addPos = (pano, vec )=>{//添加这个pano这一侧向外半圆的顶点
  62696. //添加pano位置对应的最高点最低点:
  62697. let minZ, maxZ;
  62698. minZ = pano.floorPosition.z;
  62699. if(pano.ceilZ != void 0){
  62700. maxZ = pano.ceilZ;
  62701. }else {//天花板高度值
  62702. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62703. let rotMat = new Matrix4().makeRotationX(MathUtils.degToRad(40));// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62704. let dir1 = new Vector3(0,0,1).applyMatrix4(rotMat);
  62705. let rotMat1 = new Matrix4().makeRotationZ(Math.PI*2 / 3);
  62706. let rotMat2 = new Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62707. let dir2 = dir1.clone().applyMatrix4(rotMat1);
  62708. let dir3 = dir1.clone().applyMatrix4(rotMat2);
  62709. let skyHeight = 50;
  62710. let zs = [dir1,dir2,dir3].map(dir_=>{
  62711. let intersect = getIntersect(pano, dir_);
  62712. let z = intersect ? intersect.location.z : pano.position.z+skyHeight; //没有intersect代表可能是天空
  62713. return z
  62714. });
  62715. zs.sort((a,b)=>{return b-a});//得最大值 (不用中位数的原因:在屋檐处,如果仅有一个intersect是天空,因到了室外所以也用天空高度)
  62716. maxZ = zs[0];
  62717. let min = pano.position.z + 1; // 防止意外太低
  62718. maxZ = Math.max(min,maxZ);
  62719. pano.ceilZ = maxZ;
  62720. //console.log(pano.id, 'maxZ:',maxZ )
  62721. //console.log(pano.id, 'minZ:',minZ )
  62722. }
  62723. [maxZ, minZ ].forEach(z=>{
  62724. posArr.push(pano.position.clone().setZ(z));
  62725. });
  62726. //在画面上线条从左往右数
  62727. const angle = Math.PI/(count1-1);
  62728. const dirs = []; //平分这半边180度
  62729. for(let i=0;i<count1;i++){
  62730. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  62731. }
  62732. // let sideDis = []
  62733. dirs.forEach((dir, index)=>{
  62734. let dis = getFar(dir, pano);
  62735. // if(index == 0 || index == count1-1){
  62736. // sideDis.push(dis)
  62737. // }
  62738. dir.multiplyScalar( dis );
  62739. [maxZ,minZ].forEach(z=>{
  62740. posArr.push(pano.position.clone().setZ(z).add(dir)); //获取到外墙点
  62741. });
  62742. });
  62743. //panoIndex ++
  62744. //return sideDis;
  62745. };
  62746. let addSide = ()=>{//两个漫游点间两边各加一些侧线
  62747. //中点处的
  62748. let midMaxZ = (pano0.ceilZ + pano1.ceilZ)/2;
  62749. let midMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  62750. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  62751. /* let sideDis_ = [(sideDis0[0] + sideDis1[1])/2, (sideDis0[1] + sideDis1[0])/2];
  62752. let sideDis = [Math.min(sideDis0[0] , sideDis1[1]), Math.min(sideDis0[1] , sideDis1[0])]//
  62753. */
  62754. if(pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  62755. let panos = [pano0,pano1];
  62756. let vecs = [vec.clone().negate(), vec];
  62757. let axis = [[-1,1],[1,-1]];
  62758. let dis2d = new Vector2$1().subVectors(pano0.position, pano1.position).length();//水平上的距离
  62759. let angles = [MathUtils.degToRad(40), MathUtils.degToRad(70)]; //正的在左边 尽量能够平分中间这段墙体
  62760. axis.forEach((axis_, index0)=>{
  62761. let disToSides = [];
  62762. let accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点
  62763. panos.forEach((pano,index)=>{
  62764. let dirs = [getDir(axis_[index]*angles[0], vecs[index]), getDir(axis_[index]*angles[1], vecs[index])];//一侧的若干角度
  62765. dirs.forEach((dir_,i)=>{
  62766. let dis1 = getFar(dir_, pano);
  62767. let disToPano2d = dis1 * Math.cos(angles[i]);
  62768. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入
  62769. let disToSide = dis1 * Math.sin(angles[i]);
  62770. if(pano != accordingPano){
  62771. disToPano2d = dis2d - disToPano2d; //反一下
  62772. }
  62773. dir_.multiplyScalar( dis1 );
  62774. disToSides.push({disToSide,disToPano2d, pano, dir_});
  62775. }
  62776. });
  62777. });
  62778. sideCount[index0] = disToSides.length; //记录侧边个数
  62779. if(disToSides.length){
  62780. //disToSides.sort((a,b)=>{return b-a});//从大到小
  62781. //由距离accordingPano的近到远:
  62782. disToSides.sort((a,b)=>{return a.disToPano2d-b.disToPano2d});
  62783. //console.log('disToSides', index0, disToSides)
  62784. disToSides.forEach(e=>{//求z
  62785. let ratio = e.disToPano2d / dis2d;
  62786. let r = accordingPano == pano0 ? (1-ratio) : ratio;
  62787. let sideMaxZ_ = pano0.ceilZ * r + pano1.ceilZ * (1-r);
  62788. let sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1-r);
  62789. [sideMaxZ_,sideMinZ_].forEach(z=>{
  62790. posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)); //是直接使用最长dis的那个intersect点好还是mid
  62791. });
  62792. });
  62793. }
  62794. });
  62795. }else {
  62796. //这段针对点云时,仅测试才会执行到
  62797. sideCount = [1,1];
  62798. let sideDirs = [getDir(Math.PI/2, vec), getDir(-Math.PI/2, vec)];
  62799. sideDirs.forEach((dir_ ,index)=>{
  62800. let dis = getFar(dir_, null, mid); //直接从中点求两侧的距离
  62801. dir_.multiplyScalar( /* Math.max( */dis/* , sideDis[index]) */ );
  62802. [midMaxZ,midMinZ].forEach(z=>{
  62803. posArr.push(mid.clone().setZ(z).add(dir_));
  62804. });
  62805. });
  62806. }
  62807. //中心:
  62808. [midMaxZ,midMinZ].forEach(z=>{
  62809. posArr.push(mid.clone().setZ(z));
  62810. });
  62811. };
  62812. //positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点
  62813. let addFaces = ()=>{
  62814. let getPI = function(index, posType, panoIndex){//获取顶点序号
  62815. return 2 + (count1*2 + 2 ) * panoIndex + index*2 + (posType == 'top' ? 0 : 1)
  62816. };
  62817. let getSidePI = function(index, posType, panoIndex){//获取侧边顶点序号
  62818. if(panoIndex == 1) index += sideCount[0];
  62819. return getPI(index, posType, 2)-2
  62820. };
  62821. let getPanoPI = function(posType, panoIndex){//获取pano处对应的点序号
  62822. return getPI(-1, posType, panoIndex)
  62823. };
  62824. let topCenter = posArr.length-2; //最后添加的两个中心点
  62825. let btmCenter = posArr.length-1;
  62826. for(let i=0;i<2;i++){
  62827. for(let index=1; index<count1; index++){
  62828. //pano外侧半圆围墙
  62829. faceArr.push([getPI(index,'top',i), getPI(index-1,'btm',i), getPI(index-1,'top',i)],//加入一块四方面
  62830. [getPI(index,'top',i), getPI(index,'btm',i), getPI(index-1,'btm',i)]);
  62831. faceArr.push([getPI(index,'top',i), getPI(index-1,'top',i), getPanoPI('top',i)]);//天花板扇形
  62832. faceArr.push([getPI(index,'btm',i), getPI(index-1,'btm',i), getPanoPI('btm',i)]);//地板扇形
  62833. }
  62834. let j = (i + 1) % 2; //另一个pano
  62835. //侧边
  62836. for(let u=0; u<=sideCount[i]; u++){
  62837. //侧边每个四方的左上右上左下右下四个点
  62838. let pLT = u == 0 ? getPI(0,'top',i) : getSidePI(u-1, 'top',i);
  62839. let pRT = u == sideCount[i] ? getPI(count1-1,'top',j) : getSidePI(u, 'top',i);
  62840. let pLB = u == 0 ? getPI(0,'btm',i) : getSidePI(u-1, 'btm',i);
  62841. let pRB = u == sideCount[i] ? getPI(count1-1,'btm',j) : getSidePI(u, 'btm',i);
  62842. faceArr.push([pLT,pLB,pRB],[pLT,pRB,pRT]);//外侧四方面
  62843. faceArr.push([pLT,topCenter,pRT] ,[pLB,btmCenter,pRB] );//顶部和底部到整体中心的扇形(由于点的顺序是根据和两个pano的距离,因此到中心的夹角并没按顺序排列,所以可能会重叠)
  62844. if(i==0){//只需要算一次
  62845. //顶部和底部中心与两个pano边构成的三角形
  62846. if(u == 0){
  62847. faceArr.push([pLT,getPI(count1-1,'top',i),topCenter],
  62848. [pLB,getPI(count1-1,'btm',i),btmCenter],
  62849. );
  62850. }
  62851. //不能用else 因为当length==0时u==0也==sideCount[i],此时就是要两个面
  62852. if(u == sideCount[i]){
  62853. faceArr.push([pRT,getPI(0,'top',j),topCenter],
  62854. [pRB,getPI(0,'btm',j),btmCenter],
  62855. );
  62856. }
  62857. }
  62858. }
  62859. }
  62860. };
  62861. let posArr = [];
  62862. let faceArr = [];
  62863. //两点连线的水平向量
  62864. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  62865. /* let sideDis0 = */addPos(pano0, vec);
  62866. /* let sideDis1 = */addPos(pano1, vec.clone().negate());
  62867. addSide();
  62868. addFaces();
  62869. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  62870. let geo = MeshDraw.createGeometry(posArr, faceArr);
  62871. this.cube.geometry = geo;
  62872. this.cube.scale.set(1,1,1);
  62873. this.cube.position.set(0,0,0);
  62874. //this.cube.scale.set(100,100,100);
  62875. //this.cube.position.copy(pano1.position).multiplyScalar(-100)
  62876. }else {
  62877. useBound(pano0.pointcloud.bound);
  62878. }
  62879. }
  62880. /*
  62881. 注: 修改skybox,若不准的话,会遮住其他mesh,比如marker。尤其在没有深度贴图时。
  62882. */
  62883. /* updateCube(params){
  62884. let size = params.boundSize
  62885. this.cube.scale.set(Math.max(size.x, HighMapCubeWidth), Math.max(size.y, HighMapCubeWidth), Math.max(size.z, HighMapCubeWidth) )
  62886. this.cube.position.copy(params.center)
  62887. } */
  62888. bump(direction) {//撞墙弹回效果
  62889. if (!this.bumping && !this.latestToPano) {
  62890. let distance = Potree.settings.displayMode == 'showPanos' ? 0.3 : 0.2;//感觉点云模式比全景模式更明显,所以降低
  62891. let currentPos = this.position.clone();
  62892. let endPosition = new Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance));
  62893. let duration = 150;
  62894. viewer.scene.view.setView({position:endPosition, duration,
  62895. callback:()=>{
  62896. viewer.scene.view.setView({position:currentPos, duration: duration*5,
  62897. callback: ()=>{
  62898. this.bumping = false;
  62899. //this.dispatchEvent('cameraMoveDone')
  62900. },
  62901. Easing:'easeInOutSine',
  62902. cancelFun:()=>{this.bumping = false;}
  62903. });
  62904. this.bumping = true;
  62905. },
  62906. cancelFun:()=>{this.bumping = false;},
  62907. Easing:'easeInOutSine'
  62908. });
  62909. this.bumping = true;
  62910. }
  62911. //备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。
  62912. }
  62913. /* load(pano, ){
  62914. return new Promise(resolve => {
  62915. let texture = texLoader.load(pano.file, resolve);
  62916. texture.wrapS = THREE.RepeatWrapping;
  62917. texture.repeat.x = -1;
  62918. texture.flipY = false//add
  62919. pano.texture = texture;
  62920. //add
  62921. texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
  62922. texture.minFilter = THREE.LinearFilter;
  62923. texture.magFilter = THREE.LinearFilter;
  62924. texture.generateMipmaps = true;
  62925. });
  62926. } */
  62927. flyToPanoClosestToMouse() {
  62928. /* if (Date.now() - this.mouseLastMoveTime > 50) {
  62929. //this.intersect = this.getMouseIntersect();
  62930. this.intersect && this.updateClosestPano(this.intersect);
  62931. } */
  62932. if(!Potree.settings.ifShowMarker){//不显示marker的时候mousemove没更新鼠标最近点所以更新
  62933. this.updateClosestPano(viewer.inputHandler.intersect);
  62934. }
  62935. //console.log('flyToPanoClosestToMouse',this.closestPano)
  62936. if (this.closestPano) {
  62937. let pano = this.closestPano;
  62938. return this.flyToPano({
  62939. pano
  62940. });
  62941. }
  62942. var direction = this.viewer.inputHandler.getMouseDirection().direction;
  62943. this.flyDirection(direction);
  62944. }
  62945. flyDirection(direction, option1, option2) {
  62946. var deferred = $.Deferred();
  62947. //this.history.invalidate();
  62948. var panoSet = this.closestPanoInDirection(direction, option1, option2);
  62949. if (panoSet) {
  62950. this.flyToPano({
  62951. pano: panoSet,
  62952. callback: deferred.resolve.bind(deferred, !0)
  62953. } );
  62954. } else {
  62955. this.bump(direction);
  62956. deferred.resolve(!1);
  62957. }
  62958. return deferred.promise();
  62959. }
  62960. closestPanoInDirection(direction, option1, option2) {
  62961. return this.rankedPanoInDirection(0, direction, option1, option2)
  62962. }
  62963. rankedPanoInDirection(t, direction, option1, option2){
  62964. var panoSet = {
  62965. pano: null,
  62966. candidates: [] //缓存顺序--如果需要打印的话
  62967. };
  62968. t || (t = 0);
  62969. option1 = void 0 !== option1 ? option1 : .75;
  62970. var o = option2 ? "angle" : "direction";
  62971. var floor = viewer.modules.SiteModel.currentFloor;
  62972. var entity = viewer.modules.SiteModel.inEntity;
  62973. var getHeightDis = (pano)=>{
  62974. if(floor && !floor.panos.includes(pano) && pano.position.z < this.position.z){ //若是上方的漫游点,就正常走。因为一般不会点击天花板。
  62975. return this.position.z - pano.position.z
  62976. }else {
  62977. return 0
  62978. }
  62979. };
  62980. var request = [//必要条件
  62981. Images360.filters.inPanoDirection( this.position, direction, option1),
  62982. //Images360.filters.isNeighbourPanoTo(this.currentPano),
  62983. Images360.filters.not(this.currentPano),
  62984. Images360.filters.isEnabled(),
  62985. /* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。
  62986. let dis = getHeightDis(pano)
  62987. //console.log('getHeightDis',pano.id,dis)
  62988. if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行)
  62989. return true
  62990. }else{
  62991. return this.isNeighbour(this.currentPano, pano)
  62992. }
  62993. } */
  62994. ];
  62995. var list = [//决胜项目
  62996. Images360.scoreFunctions.distanceSquared(this.position,1, true),
  62997. Images360.scoreFunctions[o]( this.position, direction,true),
  62998. (pano)=>{
  62999. let neighbour = this.isNeighbour(this.currentPano, pano);
  63000. //console.log('neighbour', pano.id, neighbour ? directionFactor*0.4 : 0)
  63001. return neighbour ? directionFactor*1 : 0;
  63002. }
  63003. /* (pano)=>{//尽量不穿越地板到下一层
  63004. let dis = getHeightDis(pano)
  63005. return -dis * directionFactor * 0.1;
  63006. }, */
  63007. /* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙
  63008. if(entity && !entity.panos.includes(pano) ){
  63009. return - directionFactor * 0.05; //- directionFactor * 0.2;
  63010. }else{ //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外
  63011. return 0
  63012. }
  63013. } */
  63014. ];
  63015. if(viewer.inputHandler.intersectPoint && this.currentPano ){//方便上下楼, 考虑panos之间的角度差
  63016. let pos1 = this.currentPano.floorPosition;
  63017. let vec1 = new Vector3().subVectors(viewer.inputHandler.intersectPoint.location, pos1 ).normalize();//应该只有atPano时才会执行到这吧?
  63018. list.push( function(pano) {
  63019. var pos2 = pano.floorPosition;
  63020. var vec2 = pos2.clone().sub(pos1).normalize();
  63021. //console.log('direction2', pano.id, vec2.dot(vec1) * directionFactor * 1 );
  63022. return vec2.dot(vec1) * directionFactor * 1
  63023. });
  63024. }
  63025. this.findRankedByScore(t,request,list,panoSet);
  63026. return panoSet.pano;
  63027. }
  63028. findRankedByScore(e, t, i, n) {
  63029. n && (n.candidates = null, //candidates 缓存顺序--如果需要打印的话
  63030. n.pano = null),
  63031. e || (e = 0);
  63032. var r = Common.sortByScore(this.panos, t, i);
  63033. //console.log('findRankedByScore', r && r.map(u=>u.item.id + '|' + u.score))
  63034. return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r,
  63035. n.pano = r[e].item),
  63036. r[e].item)
  63037. }
  63038. isNeighbour(pano0, pano1){//是否之间没有遮挡(在加载visibles之前,自己算) 最好pano0是currentPano
  63039. if(!pano0 || !pano1)return
  63040. let map0 = this.neighbourMap[pano0.id];
  63041. if(!map0){
  63042. map0 = {};
  63043. this.neighbourMap[pano0.id] = map0;
  63044. }
  63045. let map1 = this.neighbourMap[pano1.id];
  63046. if(!map1){
  63047. map1 = {};
  63048. this.neighbourMap[pano1.id] = map1;
  63049. }
  63050. let ifNeighbour = map0[pano1.id];//map0.get(pano1)
  63051. if(ifNeighbour == void 0){
  63052. ifNeighbour = true;
  63053. let margin = 0.1;
  63054. let usePointcloud = pano0.depthTex;
  63055. if(pano0.depthTex || pano1.depthTex){
  63056. let mainPano = pano0.depthTex ? pano0 : pano1;
  63057. let subPano = pano0.depthTex ? pano1 : pano0;
  63058. //暂时只判断到pano,不判断到marker的方向
  63059. let dir = new Vector3().subVectors(subPano.position, mainPano.position).normalize();
  63060. let intersectPoint = viewer.images360.depthSampler.sample({dir}, mainPano, true);
  63061. if(intersectPoint && intersectPoint.distance+margin <= pano0.position.distanceTo(pano1.position)){
  63062. ifNeighbour = false;
  63063. }
  63064. }else {
  63065. //使用点云判断(有深度贴图时不会执行到这)
  63066. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect(pano1.position, margin, true, pano0.position);
  63067. console.log('使用点云判断');
  63068. if(ifNeighbour){//点云模式下未加载的点云会判断为true
  63069. let dir = new Vector3().subVectors(pano1.position,pano0.position).normalize();
  63070. let dis = pano1.position.distanceTo(pano0.position);
  63071. let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true );
  63072. let max = Math.cos(MathUtils.degToRad(10));
  63073. let min = Math.cos(MathUtils.degToRad(80));
  63074. if(this.getDirection().dot(dir) < MathUtils.clamp(Math.cos(hfov/2/* THREE.Math.degToRad(40) */) * dis / 10, min, max )){//距离越远要求和视线角度越接近
  63075. ifNeighbour = undefined; //不确定
  63076. }
  63077. }
  63078. }
  63079. map0[pano1.id] = ifNeighbour;//map0.set(pano1, ifNeighbour)
  63080. map1[pano0.id] = ifNeighbour;//map1.set(pano0, ifNeighbour)
  63081. }
  63082. return ifNeighbour
  63083. }
  63084. updateClosestPano(intersect, state) {//hover到的pano 大多数时候是null
  63085. /*
  63086. var pano
  63087. if(this.isAtPano() ){ //为什么之前Panorama要加这个限制?
  63088. if(intersect instanceof Panorama){
  63089. pano = state ? intersect : null
  63090. }else{
  63091. return
  63092. }
  63093. }else{
  63094. if(this.flying)return;
  63095. var filterFuncs = [];
  63096. intersect = intersect && intersect.location
  63097. if(!intersect)return
  63098. let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)]
  63099. pano = Common.find(this.panos, filterFuncs, sortFuncs);
  63100. }
  63101. */
  63102. var pano;
  63103. if(intersect instanceof Panorama){
  63104. pano = state ? intersect : null;
  63105. }else {
  63106. if(this.isAtPano()){
  63107. return
  63108. }else {
  63109. if(this.flying)return;
  63110. var filterFuncs = [];
  63111. intersect = intersect && intersect.location;
  63112. if(!intersect)return
  63113. let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)];
  63114. pano = Common.find(this.panos, filterFuncs, sortFuncs);
  63115. }
  63116. }
  63117. if (pano != this.closestPano) {
  63118. pano && (this.isPanoHover = !0);
  63119. this.closestPanoChanging(this.closestPano, pano); // 高亮marker
  63120. //console.log('closestPano '+ (pano ? pano.id : 'null' ))
  63121. this.closestPano = pano;
  63122. } else {
  63123. this.isPanoHover = !1;
  63124. }
  63125. }
  63126. closestPanoChanging(oldPano, newPano){
  63127. if(!Potree.settings.ifShowMarker)return
  63128. oldPano && oldPano.hoverOff({byImages360:true});
  63129. newPano && newPano.hoverOn({byImages360:true});
  63130. }
  63131. getTileDirection(){//根据不同dataset的来存储
  63132. var vectorForward = viewer.scene.view.direction.clone();
  63133. var vectorForwards = viewer.scene.pointclouds.map(e=>{
  63134. var inv = new Matrix4().copy(e.rotateMatrix).invert();//乘上dataset的旋转的反转
  63135. var direction = vectorForward.clone().applyMatrix4(inv);
  63136. return {
  63137. datasetId: e.dataset_id,
  63138. direction: math.convertVector.ZupToYup(direction)
  63139. }
  63140. });
  63141. //return vectorForwards[0].direction
  63142. return {
  63143. datasetsLocal: vectorForwards,
  63144. vectorForward
  63145. }
  63146. }
  63147. update(){
  63148. let {viewer} = this;
  63149. /* if(currentlyHovered){
  63150. currentlyHovered.material = sm;
  63151. currentlyHovered = null;
  63152. }
  63153. if(this.selectingEnabled){
  63154. this.handleHovering();
  63155. } */
  63156. if(this.tileDownloader.started){
  63157. var vectorForwards = this.getTileDirection();
  63158. //vectorForwards = vectorForwards[0].direction
  63159. this.updateTileDownloader(tileArr, vectorForwards);
  63160. this.updatePanoRenderer(vectorForwards);
  63161. }
  63162. this.updateZoomPano();
  63163. }
  63164. updateTileDownloader(t, vectorForward) {
  63165. var i = this.nextPano || this.currentPano;
  63166. if(i){
  63167. this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone() , vectorForward, t.length > 0 ? t : null),
  63168. this.tileDownloader.processPriorityQueue = !0;
  63169. }
  63170. }
  63171. updatePanoRenderer(vectorForward) {
  63172. var i = this.nextPano || this.currentPano;
  63173. if(i){
  63174. if (this.panoRenderer.hasQueuedTiles() && i) {
  63175. this.panoRenderer.updateDirection(vectorForward);
  63176. }
  63177. }
  63178. }
  63179. //等待部分加载完
  63180. checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) {
  63181. if (!pano) {
  63182. console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano.");
  63183. }
  63184. var vectorForward = this.getTileDirection();
  63185. if (!pano.isLoaded(basePanoSize)) {
  63186. iswait && viewer.waitForLoad(pano, function() {//发送loading
  63187. return pano.isLoaded(basePanoSize)
  63188. });
  63189. /* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。
  63190. hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ),
  63191. vFov: viewer.scene.getActiveCamera().fov
  63192. }//原先是null,不要求方向 */
  63193. var fov = null; //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办
  63194. pano.loadTiledPano(/* 1024 */ basePanoSize , vectorForward, fov, isclear, l, null).done(function(e, t) {
  63195. callback1 && callback1(e, t);
  63196. }
  63197. .bind(this)).fail(function(msg) {
  63198. callback2 && callback2(msg);
  63199. }
  63200. .bind(this)).progress(function(e, t, i) {
  63201. progressCallback && progressCallback(e, t, i);
  63202. }
  63203. .bind(this));
  63204. return !0;
  63205. }
  63206. }
  63207. /* load(){//quickstart里的
  63208. var lowSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE),
  63209. highSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD),
  63210. d = cameraLight.getHFOVForCamera(this.quickStartcamera, $('#player').width(), $('#player').height()),
  63211. p = this.quickStartcamera.fov,
  63212. r = Vectors.FORWARD.clone().applyQuaternion(this.view.quaternion)
  63213. var promise1 = this.view.pano.loadTiledPano(highSize, r, {
  63214. hFov: d,
  63215. vFov: p
  63216. }, !1, !1 , !0 )
  63217. var promise2 = this.view.pano.loadTiledPano(lowSize, r.clone().negate(), null, !1, !1, !0)
  63218. this.loadPromise = this.pano.hasVideo ? promise2 : promise1;
  63219. //this.loadPromise = promise1;
  63220. }
  63221. */
  63222. fitPanoTowardPoint(o){ //寻找最适合的点位
  63223. var point = o.point, //相机最佳位置
  63224. target = o.target, //实际要看的位置
  63225. require = o.require || [],
  63226. rank = o.rank || [],
  63227. force = o.force,
  63228. getAll = o.getAll,
  63229. bestDistance = o.bestDistance || 0;
  63230. let camera = viewer.scene.getActiveCamera();
  63231. if(target){
  63232. var vec = new Vector3().subVectors(target,point).normalize();
  63233. }
  63234. //if(o.floor)require.push(Panorama.filters.atFloor(o.floor))
  63235. if(o.boundSphere){//只接受boundSphere
  63236. let aspect = 1;//size.x / size.y
  63237. let dis;
  63238. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  63239. dis = /* size.y */o.boundSphere.radius/* / 2 *// MathUtils.degToRad(camera.fov / 2);
  63240. }else {
  63241. let hfov = cameraLight.getHFOVForCamera(camera , true );
  63242. dis = /* size.x */ o.boundSphere.radius /* / 2 */ / (hfov / 2);
  63243. }
  63244. bestDistance = dis;//*0.8
  63245. }
  63246. let bestDisSquared = bestDistance * bestDistance;
  63247. rank.push((pano)=>{
  63248. let dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置
  63249. if(!target){
  63250. return -dis1
  63251. }else {
  63252. let dis2 = pano.position.distanceToSquared(target); //距离目标点
  63253. let vec2 = new Vector3().subVectors(target,pano.position).normalize();
  63254. let cos = vec.dot(vec2);
  63255. let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2); // cos+2是为了调整到1-3, 尽量贴近最佳位置的角度;
  63256. //console.log(pano.id, dis1,dis2, cos, result)
  63257. return result
  63258. }
  63259. },(pano)=>{
  63260. if(pano.depthTex && o.checkIntersect){ //没加载好的话,不管了
  63261. let intersect = viewer.inputHandler.ifBlockedByIntersect(target, 0.1 , null, null, null, pano);
  63262. if(intersect){
  63263. //console.log('intersected', pano.id )
  63264. return -10000
  63265. }else return 0
  63266. }else return 0
  63267. });
  63268. /* var temp = {position:point}
  63269. rank.push(Panorama.scoreFunctions.distanceSquared(temp, -2)); */
  63270. var g = Common.sortByScore(this.panos, require, rank);
  63271. if(getAll)return g;
  63272. return g && g.length > 0 && g[0].item
  63273. }
  63274. //---------------scroll zoom ------------------------------------------
  63275. /* zoomIn = function() { //放大
  63276. this.zoomBy(1 + this.zoomSpeed);
  63277. }
  63278. zoomOut = function() {//缩小
  63279. this.zoomBy(1 - this.zoomSpeed);
  63280. } */
  63281. zoomBy(e, pointer) {//以倍数
  63282. this.zoomTo(this.zoomLevel * e, pointer);
  63283. }
  63284. zoomTo(zoomLevel, pointer) {//缩放到某绝对zoomLevel
  63285. let zoom = Potree.settings.zoom;
  63286. if (zoom.enabled) {
  63287. zoomLevel = MathUtils.clamp(zoomLevel, zoom.min, zoom.max);
  63288. //console.log(zoomLevel)
  63289. if(zoomLevel == this.zoomLevel) return;
  63290. /* if (zoomLevel > this.zoomLevel) {
  63291. this.emit(ZoomEvents.ZoomIn);
  63292. zoomLevel === settings.zoom.max && this.emit(ZoomEvents.ZoomMax);
  63293. } else if (zoomLevel < this.zoomLevel) {
  63294. this.emit(ZoomEvents.ZoomOut);
  63295. zoomLevel === settings.zoom.min && this.emit(ZoomEvents.ZoomMin);
  63296. } */
  63297. this.zoomLevel = zoomLevel;
  63298. //定点缩放:使当前鼠标所在的位置缩放后不变
  63299. let view = viewer.scene.view;
  63300. let originDir = viewer.scene.view.direction;
  63301. let oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  63302. viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel));
  63303. let newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  63304. view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch
  63305. let oldPitch = view.pitch, oldYaw = view.yaw;
  63306. view.direction = newPointerDir;
  63307. let newPitch = view.pitch, newYaw = view.yaw;
  63308. view.direction = originDir; //还原
  63309. viewer.scene.view.pitch -= newPitch - oldPitch;
  63310. viewer.scene.view.yaw -= newYaw - oldYaw;
  63311. }
  63312. }
  63313. zoomFovTo( fov ) { //通过fov来算zoomLevel
  63314. let zoomLevel = this.baseFov / fov;
  63315. this.zoomTo( zoomLevel );
  63316. }
  63317. smoothZoomTo(aimLevel, dur=0) {
  63318. var currentLevel = this.zoomLevel;
  63319. if(currentLevel == aimLevel)return;
  63320. var fun = (progress)=>{
  63321. //progress > 1 && (progress = 1)
  63322. let level = currentLevel * (1 - progress) + aimLevel * progress;
  63323. this.zoomTo(level, !0);
  63324. };
  63325. transitions.start(fun, dur, null, null, 0 , easing['easeInOutQuad'] );
  63326. }
  63327. /* zoomDefault{
  63328. this.zoomTo(1, !0)
  63329. }
  63330. smoothZoomToDefault(e, t) {
  63331. var i, n = this.zoomLevel,
  63332. r = function(e) {
  63333. e > 1 && (e = 1),
  63334. i = n * (1 - e) + e,
  63335. this.zoomTo(i, !0)
  63336. }
  63337. .bind(this),
  63338. o = function() {
  63339. this.zoomDefault(),
  63340. t && window.setTimeout(t, 50)
  63341. }
  63342. .bind(this);
  63343. transitions.start(r, e, o, null, 0, easing[settings.transition.blendEasing])
  63344. } */
  63345. updateZoomPano() {
  63346. if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') {
  63347. var currentPano = this.currentPano;
  63348. if (currentPano) {
  63349. var activationThreshold = Potree.settings.navTileClass == '2k' && Potree.settings.tileClass == '4k' ? 1.7 : Potree.settings.zoom.activationThreshold;//1.1
  63350. var t = this.zoomLevel > activationThreshold,
  63351. n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano),
  63352. r = t && n;
  63353. this.tileDownloader.tilePrioritizer.setZoomingActive(r);
  63354. this.panoRenderer.setZoomingActive(r, currentPano, !0);
  63355. var o = (pano, zoomedFlag)=>{
  63356. this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize());
  63357. this.panoRenderer.clearAllQueuedUploadsForPano(pano.id);
  63358. this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1);
  63359. pano.setZoomed(zoomedFlag);
  63360. };
  63361. if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) {
  63362. currentPano.zoomed || o(currentPano, !0);
  63363. if(Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < 2){
  63364. this.panoRenderer.enableHighQuality( function() {//开启2k
  63365. if(Potree.settings.tileClass != '4k') o(currentPano, !0);
  63366. }.bind(this));
  63367. }else {
  63368. this.panoRenderer.enableUltraHighQualityMode(function() {//开启4k getMaxZoomPanoSize
  63369. this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom);
  63370. o(currentPano, !0);
  63371. }.bind(this));
  63372. }
  63373. } else {
  63374. !t && currentPano.zoomed && o(currentPano, !1);
  63375. }
  63376. if(r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k' ){ //目前只有手机端navTileClass == '1k'
  63377. var change = (zoomedFlag)=>{
  63378. this.qualityManager.updateMaximums();//更新maxZoomPanoSize
  63379. this.panoRenderer.setupZoomRenderTarget(); //更新renderTarget
  63380. //currentPano.setZoomed(t);//更新uniforms贴图
  63381. };
  63382. this.qualityManager.zoomLevelResolution = this.zoomLevel >= 2 ? '4k' : this.zoomLevel > 1.1 ? '2k' : '1k';
  63383. if(this.oldZoomLevel < 2 && this.zoomLevel >= 2){//1k/2k-4k
  63384. change();
  63385. o(currentPano, t);
  63386. }else if(this.oldZoomLevel <= Potree.settings.zoom.activationThreshold && this.zoomLevel > Potree.settings.zoom.activationThreshold){//1k-2k
  63387. change();
  63388. }else if(this.oldZoomLevel > 2 && this.zoomLevel <= 2){//4k-2k/1k
  63389. change();
  63390. o(currentPano, t);
  63391. }else if(this.oldZoomLevel > Potree.settings.zoom.activationThreshold && this.zoomLevel <= Potree.settings.zoom.activationThreshold){//2k-1k
  63392. change();
  63393. }
  63394. this.oldZoomLevel = this.zoomLevel;
  63395. }
  63396. }
  63397. }
  63398. }
  63399. //--------------------
  63400. addHighMapCube(){//创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize
  63401. if( Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048){
  63402. var geo = new PlaneGeometry(1, 1, 1, 1);
  63403. var cube = new Object3D;
  63404. for(var cubeIndex=0; cubeIndex<6; cubeIndex++){
  63405. var face = new Object3D;
  63406. for(var i=0;i<8;i++){
  63407. for(var j=0;j<8;j++){
  63408. var tile = new Mesh(geo, new MeshBasicMaterial({
  63409. //side:THREE.DoubleSide
  63410. }));
  63411. tile.position.set(i-3.5, j-3.5, -4);
  63412. tile.material.opacity = 0.4;
  63413. tile.material.transparent = true;
  63414. if(Potree.settings.isTest){
  63415. var colorHue = Math.random();
  63416. tile.material.color = (new Color()).setHSL(colorHue, 0.5, 0.9);
  63417. }
  63418. tile.visible = false;
  63419. face.add(tile);
  63420. }
  63421. }
  63422. switch(cubeIndex){
  63423. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  63424. face.rotation.set(0,Math.PI/2,0);
  63425. break;
  63426. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  63427. face.rotation.set(0,-Math.PI/2,0);
  63428. break;
  63429. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  63430. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  63431. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),Math.PI/2);
  63432. face.quaternion.copy(rot1).multiply(rot2);
  63433. //face.rotation.set(Math.PI/2,0,0);
  63434. break;
  63435. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  63436. //face.rotation.set(-Math.PI/2,0,0);
  63437. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  63438. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),-Math.PI/2);
  63439. face.quaternion.copy(rot1).multiply(rot2);
  63440. break;
  63441. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  63442. face.rotation.set(0,Math.PI,0);
  63443. break;
  63444. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  63445. face.rotation.set(0,0,0);
  63446. }
  63447. face.scale.set(1,-1,1);
  63448. cube.add(face);
  63449. }
  63450. cube.name = 'highMapCube';
  63451. this.highMapCube = cube;
  63452. viewer.scene.scene.add(cube);
  63453. //cube.scale.set(0.01,0.01,0.01)
  63454. this.highMapCube.visible = false;
  63455. viewer.setObjectLayers(this.highMapCube, 'sceneObjects'/* 'skybox' */); //如果是skybox层,点云可见时会被遮住,depthTest为false呢? 但不会遮住场景物体
  63456. //console.warn('addHighMapCube')
  63457. }
  63458. }
  63459. isHighMapLoaded( cubeFace, tileX, tileY){
  63460. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  63461. return !!tile.material.map
  63462. }
  63463. updateHighMap(tex, cubeFace, tileX, tileY){
  63464. //console.warn('updateHighMap')
  63465. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  63466. tile.material.map = tex;
  63467. tile.material.opacity = 1;
  63468. tile.material.transparent = false;
  63469. tile.visible = true;
  63470. tile.material.needsUpdate = true; //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载
  63471. }
  63472. resetHighMap(){
  63473. if(!this.highMapCube) return
  63474. //console.warn('resetHighMap')
  63475. this.highMapCube.children.forEach(e=>e.children.forEach(tile=>{
  63476. if(tile.material.map){
  63477. tile.material.map.dispose();
  63478. tile.material.map.loaded = !1;
  63479. tile.material.map.version = 0;
  63480. var h = viewer.renderer.properties.get(tile.material.map);
  63481. viewer.renderer.getContext().deleteTexture(h.__webglTexture);
  63482. //类似app.sceneRenderer.deallocateCubeTexture(tile.material.map)
  63483. tile.material.map = null;
  63484. /* tile.material.opacity = 0.4;
  63485. tile.material.transparent = true */
  63486. tile.material.needsUpdate = true;
  63487. tile.visible = false;
  63488. }
  63489. }));
  63490. this.highMapCube.visible = false;
  63491. }
  63492. setHighMap(pano){
  63493. if(!this.highMapCube) return
  63494. this.highMapCube.position.copy(pano.position);
  63495. //可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的
  63496. this.highMapCube.quaternion.copy( math.convertQuaternion.YupToZup( pano.quaternion4dkk ) );
  63497. //乘上数据集整体的旋转:
  63498. let modelRotQua = new Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix);
  63499. this.highMapCube.quaternion.premultiply(modelRotQua);
  63500. }
  63501. showHighMap(){
  63502. if(!this.highMapCube) return
  63503. //console.warn('showHighMap')
  63504. this.highMapCube.visible = true;
  63505. }
  63506. hideHighMap(){
  63507. if(!this.highMapCube) return
  63508. //console.warn('hideHighMap')
  63509. this.highMapCube.visible = false;
  63510. }
  63511. //缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示???
  63512. addPanoData(data, datasetId ){
  63513. //data[0].file_id = '00019'
  63514. if(data.data) data = data.data;
  63515. if(data.length == 0)console.error(datasetId + ' 没有漫游点');
  63516. //data = data.sort(function(a,b){return a.id-b.id})
  63517. data.forEach((info)=>{
  63518. //if(Potree.fileServer){
  63519. info.id = this.panos.length; //把info的id的一长串数字改简单点
  63520. //}
  63521. let pano = new Panorama( info, this );
  63522. /* pano.mesh.layers.set(Potree.config.renderLayers.marker)
  63523. pano.marker.layers.set(Potree.config.renderLayers.marker) */
  63524. pano.addEventListener('dispose',(e)=>{
  63525. if(this.closestPano == pano) this.closestPano = null;
  63526. });
  63527. this.panos.push(pano);
  63528. if(Potree.settings.editType == 'pano'){
  63529. Potree.settings.datasetsPanos[datasetId].panos.push(pano);
  63530. }
  63531. });
  63532. }
  63533. loadDone(){
  63534. viewer.setObjectLayers(this.node, 'sceneObjects');
  63535. //this.updateCube(/* viewer.bound */)
  63536. this.panos.forEach(e=>{
  63537. e.label && viewer.setObjectLayers(e.label, 'bothMapAndScene');
  63538. });
  63539. this.tileDownloader.setPanoData(this.panos, [] /* , Potree.settings.number */);
  63540. {
  63541. /* var panosBound = new THREE.Box3
  63542. this.panos.forEach(pano=>{
  63543. panosBound.expandByPoint(pano.position)
  63544. })
  63545. let center = panosBound.getCenter(new THREE.Vector3)
  63546. let minBound = (new THREE.Box3()).setFromCenterAndSize(center, new THREE.Vector3(1,1,1))
  63547. panosBound.union(minBound)
  63548. this.bound = {
  63549. bounding:panosBound,
  63550. size: panosBound.getSize(new THREE.Vector3),
  63551. center,
  63552. } */
  63553. let minSize = new Vector3(1,1,1);
  63554. this.bound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  63555. viewer.scene.pointclouds.forEach(pointcloud=>pointcloud.getPanosBound());
  63556. }
  63557. if(viewer.scene.pointclouds.some(e=>e.panos.length == 0)){
  63558. //console.warn('存在数据集没有pano');
  63559. viewer.hasNoPanoDataset = true;
  63560. }
  63561. }
  63562. getPano(value, typeName='id'){ //默认找的是id,也可以是sid、uuid
  63563. return this.panos.find(p=>p[typeName] == value)
  63564. }
  63565. };
  63566. //判断当前点是否加载了全景图
  63567. Images360.prototype.checkAndWaitForPanoLoad = function() {
  63568. var isLoadedPanos = {},
  63569. LoadedTimePanos = {},
  63570. loadedCallback = {}, //add
  63571. maxTime = 5e3;
  63572. var withinTime = function() {
  63573. for (var panoId in isLoadedPanos)
  63574. if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) {
  63575. var differTime = performance.now() - LoadedTimePanos[panoId];
  63576. if (differTime < maxTime)
  63577. return !0
  63578. }
  63579. return !1
  63580. };
  63581. return function(pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p ) {
  63582. loadedCallback[pano.id] = doneFun1;//add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1
  63583. if (withinTime()){//距离上次请求时间很近
  63584. return !0; //这里感觉应该是!1
  63585. }
  63586. var callback1 = (param1, param2)=>{
  63587. setTimeout(()=>{
  63588. isLoadedPanos[pano.id] = !1;
  63589. loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2);
  63590. },1);
  63591. };
  63592. var callback2 = (param)=>{//没有看到有传doneFun2的
  63593. setTimeout(()=>{
  63594. isLoadedPanos[pano.id] = !1;
  63595. doneFun2 && doneFun2(param);
  63596. },1);
  63597. };
  63598. try {
  63599. null !== iswait && void 0 !== iswait || (iswait = !0);
  63600. isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p );
  63601. //true代表没加载好
  63602. isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now());
  63603. return isLoadedPanos[pano.id];
  63604. } catch (msg) {
  63605. isLoadedPanos[pano.id] = !1;
  63606. LoadedTimePanos[pano.id] = performance.now() - maxTime;
  63607. throw msg;
  63608. }
  63609. }
  63610. }();
  63611. Images360.filters = {
  63612. inPanoDirection : function(pos, dir, i) {
  63613. return function(pano) {
  63614. var r = pano.floorPosition.clone().sub(pos).normalize();
  63615. var o = pano.position.clone().sub(pos).normalize();
  63616. return r.dot(dir) > i || o.dot(dir) > i
  63617. }
  63618. },
  63619. inFloorDirection: function(pos, e, o) {//许钟文 改 for鱼眼
  63620. return function(n) {
  63621. var i = n.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动
  63622. return i.dot(e) > o
  63623. }
  63624. },
  63625. isNotBehindNormal: function(e, t) {
  63626. var i = new Vector3;
  63627. return t = t.clone(),
  63628. function(n) {
  63629. var r = i.copy(n.position).sub(e).normalize();
  63630. return r.dot(t) > 0
  63631. }
  63632. },
  63633. isCloseEnoughTo: function(e, t) {
  63634. return function(i) {//因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近)
  63635. return e.distanceTo(i.floorPosition) < t //许钟文
  63636. }
  63637. },
  63638. not: function(e) {
  63639. return function(t) {
  63640. return t !== e
  63641. }
  63642. } ,
  63643. isEnabled:function() {
  63644. return function(t) {
  63645. return t.enabled
  63646. }
  63647. },
  63648. isVisible:function() {
  63649. return function(t) {
  63650. return t.visible
  63651. }
  63652. }
  63653. };
  63654. Images360.scoreFunctions = {
  63655. direction: function(curPos, dir, ifLog) {
  63656. return function(pano) {
  63657. var pos1 = /* pano.floorPosition */ pano.position; //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到
  63658. var n = pos1.clone().sub(curPos).normalize();
  63659. //ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor )
  63660. return n.dot(dir) * directionFactor
  63661. }
  63662. },
  63663. distanceSquared: function(pos1, r, ifLog) {
  63664. if(pos1.position)pos1 = pos1.position;
  63665. return function(pano) {//许钟文 改
  63666. var pos2 = pano.position.clone();
  63667. //ifLog && console.log('distanceSquared', pano.id, pos1.distanceToSquared(pos2) * -1 )
  63668. return pos1.distanceToSquared(pos2) * -1 * r;
  63669. }
  63670. },
  63671. angle: function(e, t) {
  63672. return function(i) {
  63673. var n = i.position.clone().sub(e).normalize();
  63674. return n.angleTo(t) * Potree.config.navigation.angleFactor
  63675. }
  63676. },
  63677. };
  63678. Images360.sortFunctions = {//排序函数,涉及到两个item相减
  63679. floorDisSquaredToPoint: function(e) {
  63680. return function(t, i) {
  63681. return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e)
  63682. }
  63683. },
  63684. disSquaredToPoint: function(e) {
  63685. return function(t, i) {
  63686. return t.position.distanceToSquared(e) - i.position.distanceToSquared(e)
  63687. }
  63688. },
  63689. };
  63690. /* var centerCross = new THREE.Mesh(new THREE.SphereGeometry(1, 4, 4),new THREE.MeshBasicMaterial({
  63691. transparent:true, color:"#ff0000", opacity:0.5
  63692. })); */
  63693. /* const mapHeight = -1000;//要比点云低。最低
  63694. const cameraHeight = 1000; //最高 */
  63695. const panosHeight = config$1.map.mapHeight + 100; //要比点云低 (marker)
  63696. const cursorHeight = 0;//比地图高就行
  63697. const routeLayerHeight = config$1.map.mapHeight + 105;
  63698. const texLoader$4 = new TextureLoader();
  63699. const planeGeo$2 = new PlaneBufferGeometry(1,1);
  63700. const markerSize = 1;
  63701. var initCameraFeildWidth = 50;
  63702. var panoMarkerMats;
  63703. class MapViewer extends ViewerBase{
  63704. constructor(dom){
  63705. super(dom, {
  63706. clearColor: Potree.config.mapBG,
  63707. name: 'mapViewer'
  63708. });
  63709. this.visible = true;
  63710. this.initScene();
  63711. this.mapLayer = new MapLayer(this, this.viewports[0]);
  63712. this.scene.add(this.mapLayer.sceneGroup);
  63713. this.mapLayer.sceneGroup.position.setZ(Potree.config.map.mapHeight);
  63714. this.mapRatio = 0.5;
  63715. this.splitDir = 'leftRight';
  63716. //this.scene.add(centerCross)
  63717. viewer.addEventListener("camera_changed", (e)=>{
  63718. if(e.viewport == viewer.mainViewport) this.updateCursor();
  63719. else this.updateWhenAtViewer();
  63720. });
  63721. //viewer.addEventListener("global_mousemove", this.updateWhenAtViewer.bind(this)) //鼠标移动时reticule也动,所以直接就needRender
  63722. viewer.reticule.addEventListener('update',(e)=>{
  63723. if(this.attachedToViewer)this.needRender = true;
  63724. });
  63725. viewer.scene.addEventListener("360_images_added", this.addPanos.bind(this));
  63726. viewer.addEventListener("loadPointCloudDone", this.initProjection.bind(this));
  63727. this.addEventListener('global_click',(e)=>{
  63728. if(!e.isTouch && e.button != MOUSE.LEFT)return
  63729. this.updateClosestPano(e.intersect);
  63730. });
  63731. this.addEventListener('add',(e)=>{//添加其他mesh
  63732. this.scene.add(e.object);
  63733. if(e.name == 'route'){
  63734. e.object.position.z = routeLayerHeight;
  63735. }
  63736. viewer.setObjectLayers(e.object, 'mapObjects' );
  63737. });
  63738. if(!Potree.settings.isOfficial){
  63739. let domRoot = viewer.renderer.domElement.parentElement;
  63740. let elAttach = $("<input type='button' value='map绑定'></input>");
  63741. elAttach.css({
  63742. position : "absolute",
  63743. right : '80%',
  63744. bottom: '20px',
  63745. zIndex: "10000",
  63746. fontSize:'1em', color:"black",
  63747. background:'rgba(255,255,255,0.8)',
  63748. });
  63749. let state = false;
  63750. elAttach.on("click", () => {
  63751. state = !state;
  63752. this.attachToMainViewer(state, 'measure');
  63753. elAttach.val(state ? 'map分离':'map绑定');
  63754. });
  63755. domRoot.appendChild(elAttach[0]);
  63756. }
  63757. }
  63758. waitLoadDone(callback){//确保加载完后执行
  63759. if(this.mapLayer.loadingInProgress == 0){
  63760. callback();
  63761. }else {
  63762. var f = ()=>{
  63763. callback();
  63764. this.mapLayer.removeEventListener('loadDone', f);
  63765. };
  63766. this.mapLayer.addEventListener('loadDone', f);
  63767. }
  63768. }
  63769. addListener(images360){
  63770. images360.addEventListener('flyToPano',e=>{
  63771. let toPano = e.toPano;
  63772. if(toPano.dontMoveMap) return
  63773. /* transitions.start(lerp.vector(this.view.position, toPano.pano.position.clone().setZ(cameraHeight),
  63774. (pos, progress)=>{
  63775. }), toPano.duration, null, 0, easing[toPano.easeName] ); */
  63776. let boundSize;// = new THREE.Vector2(10,10)
  63777. this.moveTo(toPano.pano.position.clone().setZ(Potree.config.map.cameraHeight), boundSize, toPano.duration, toPano.easeName);
  63778. });
  63779. }
  63780. initProjection(){
  63781. this.started = true;
  63782. this.mapLayer.initProjection();
  63783. }
  63784. initScene(){
  63785. let w = initCameraFeildWidth;
  63786. let width = this.renderArea.clientWidth;
  63787. let height = this.renderArea.clientHeight;
  63788. //let aspect = width / height
  63789. this.camera = new OrthographicCamera(-width/2,width/2,height/2,-height/2/* -w/2, w/2, w/2/aspect, -w/2/aspect */, 0.01, 10000);
  63790. this.camera.zoom = width / w; //zoom越大视野越小
  63791. //this.camera.position.set(0,0,10);
  63792. this.camera.up.set(0,0,1);
  63793. //this.camera.lookAt(new THREE.Vector3())
  63794. //this.camera.updateMatrixWorld()
  63795. this.view = new View();
  63796. this.view.position.set(0,0,Potree.config.map.cameraHeight);
  63797. this.view.lookAt(0,0,0);
  63798. this.setViewLimit('standard');
  63799. let viewport = new Viewport( this.view, this.camera, {
  63800. left:0, bottom:0, width:1, height: 1, name:'mapViewport'
  63801. });
  63802. viewport.axis = ["x","y"];
  63803. viewport.axisSign = [1,1];
  63804. viewport.noPointcloud = true; //不要渲染点云
  63805. viewport.render = this.render.bind(this);//标志给mainView渲染
  63806. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  63807. this.viewports = [viewport];
  63808. this.controls = new FirstPersonControls(this, this.viewports[0]);
  63809. this.controls.setEnable(true);
  63810. this.scene = new Scene();
  63811. this.inputHandler = new InputHandler(this, this.scene);
  63812. this.inputHandler.name = 'mapInputHandler';
  63813. //this.inputHandler.addInputListener(this.controls);
  63814. this.inputHandler.registerInteractiveScene(this.scene);//interactiveScenes
  63815. this.viewports[0].interactiveScenes = this.inputHandler.interactiveScenes;//供viewer的inputHandler使用
  63816. var cursor = new Mesh(planeGeo$2, new MeshBasicMaterial({
  63817. transparent:true,
  63818. opacity:0.9,
  63819. depthTest : false, //防止透明冲突
  63820. map: texLoader$4.load(Potree.resourcePath+'/textures/pic_location128.png' )
  63821. }));
  63822. cursor.position.set(0,0,cursorHeight);
  63823. this.cursor = cursor;
  63824. this.scene.add(cursor);
  63825. viewer.setObjectLayers(this.scene, 'mapObjects' );
  63826. }
  63827. setViewLimit(state){//设置边界,当编辑空间模型等时要解禁
  63828. let setting = Potree.config.OrthoCameraLimit[state];
  63829. if(setting){
  63830. this.view.limitBound = new Box3().copy(setting.posBound);
  63831. this.camera.zoomLimit = $.extend({},setting.zoom);
  63832. }else {
  63833. this.view.limitBound = null;
  63834. this.camera.zoomLimit = null;
  63835. }
  63836. }
  63837. updateCursor(){
  63838. var scale = math.getScaleForConstantSize( {//规定下最小最大像素
  63839. minSize : 80, maxSize : 200, nearBound : initCameraFeildWidth*0.1 , farBound : initCameraFeildWidth*2,
  63840. camera:this.camera , position: this.cursor.getWorldPosition(new Vector3()),
  63841. resolution: this.viewports[0].resolution//2
  63842. });
  63843. this.cursor.scale.set(scale, scale, scale);//当地图缩放时
  63844. this.cursor.position.copy(viewer.mainViewport.camera.position).setZ(cursorHeight);//当场景镜头旋转移动时
  63845. this.cursor.rotation.z = viewer.mainViewport.view.yaw;
  63846. this.needRender = true;
  63847. }
  63848. addPanos(e){
  63849. var panosGroup = new Object3D;
  63850. panoMarkerMats = {
  63851. default: new MeshBasicMaterial({
  63852. transparent:true,
  63853. opacity: 0.5,
  63854. map: texLoader$4.load(Potree.resourcePath+'/textures/map_marker.png' ),
  63855. }),
  63856. selected: new MeshBasicMaterial({
  63857. transparent:true,
  63858. opacity: 1,
  63859. map: texLoader$4.load(Potree.resourcePath+'/textures/map_marker.png' ),
  63860. })
  63861. };
  63862. e.images.panos.forEach(pano=>{
  63863. pano.mapMarker = new Mesh(planeGeo$2, panoMarkerMats.default);
  63864. pano.mapMarker.position.copy(pano.position).setZ(0);
  63865. pano.mapMarker.scale.set(markerSize,markerSize,markerSize);
  63866. pano.mapMarker.name = 'mapMarker';
  63867. panosGroup.add(pano.mapMarker);
  63868. let mouseover = (e)=>{
  63869. if(!e.byMap){
  63870. pano.mapMarker.material = panoMarkerMats.selected;
  63871. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true});
  63872. this.needRender = true;
  63873. }
  63874. };
  63875. let mouseleave = (e)=>{
  63876. if(!e.byMap){
  63877. pano.mapMarker.material = panoMarkerMats.default;
  63878. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true});
  63879. this.needRender = true;
  63880. }
  63881. };
  63882. pano.mapMarker.addEventListener('mouseover', mouseover);
  63883. pano.mapMarker.addEventListener('mouseleave', mouseleave);
  63884. pano.addEventListener('hoverOn', mouseover);
  63885. pano.addEventListener('hoverOff', mouseleave);
  63886. let onclick = (e)=>{
  63887. viewer.images360.flyToPano(pano);
  63888. };
  63889. pano.mapMarker.addEventListener('click', onclick);
  63890. pano.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  63891. //console.log('panoMarker isVisible', pano.id, e.visible)
  63892. viewer.updateVisible(pano.mapMarker, 'panoVisible', e.visible );
  63893. this.needRender = true;
  63894. });
  63895. pano.addEventListener('rePos',(e)=>{
  63896. pano.mapMarker.position.copy(pano.position).setZ(0);
  63897. });
  63898. });
  63899. this.scene.add(panosGroup);
  63900. panosGroup.position.z = panosHeight;
  63901. this.panosGroup = panosGroup;
  63902. viewer.setObjectLayers(panosGroup, 'mapObjects' );
  63903. /* e.images.on('markersDisplayChange', (show)=>{
  63904. panosGroup.visible = show
  63905. this.needRender = true
  63906. }) */
  63907. //-------
  63908. //this.fitPanosToViewport()
  63909. this.initFitView();
  63910. }
  63911. updateClosestPano(intersect){
  63912. if(viewer.images360.flying)return;
  63913. intersect = intersect && intersect.orthoIntersect;
  63914. if(!intersect)return
  63915. intersect = intersect.clone().setZ(0);
  63916. const minDis = 20; //距离鼠标不能太远
  63917. var filterFuncs = [
  63918. (pano)=>{
  63919. return pano.position.clone().setZ(0).distanceTo(intersect) < minDis
  63920. },
  63921. Images360.filters.isEnabled(),
  63922. Images360.filters.isVisible(),//只走显示的点,否则会走到别的层
  63923. ];
  63924. var pano = Common.find(viewer.images360.panos, filterFuncs, [Images360.sortFunctions.floorDisSquaredToPoint(intersect)]);
  63925. if (pano && pano != viewer.images360.currentPano ) {
  63926. viewer.images360.flyToPano(pano);
  63927. }
  63928. }
  63929. fitPanosToViewport(){//使所有漫游点占满viewport
  63930. //var w = viewer.bound.boundSize.x;
  63931. var boundSize = viewer.images360.bound.size.clone().multiplyScalar(1.1);
  63932. boundSize.max(new Vector3(4,4,4));
  63933. let endPosition = viewer.images360.bound.center.clone();
  63934. this.moveTo(endPosition, boundSize, 0);
  63935. }
  63936. fitToPointcloud(pointcloud, duration=400){
  63937. var boundSize = pointcloud.bound.getSize(new Vector3);/* .multiplyScalar(1.1); */
  63938. boundSize.max(new Vector3(4,4,4));
  63939. let endPosition = pointcloud.bound.getCenter(new Vector3);
  63940. this.moveTo(endPosition, boundSize, duration); //给点duration去变化 否则地图放大后所占的还是很小
  63941. }
  63942. initFitView(){
  63943. let dis = 5 , px = 70; //地图上px像素长度代表的距离为dis //px是手动缩放到5m后发现是这个长度
  63944. let zoom = px / dis;
  63945. this.camera.zoom = zoom;
  63946. this.moveTo(viewer.images360.position/* viewer.images360.bound.center */);
  63947. this.camera.updateProjectionMatrix();
  63948. }
  63949. fitToDatasets(datasets){
  63950. let bound = new Box3;
  63951. datasets.forEach(e=>bound.union(e.bound));
  63952. let center = bound.getCenter(new Vector3);
  63953. let size = bound.getSize(new Vector3);
  63954. this.moveTo(center, size, 200 ); //给duration是为了顺应视口大小改变,缓冲
  63955. }
  63956. moveTo(endPosition, boundSize, duration=0, easeName){//前两个参数有xy即可
  63957. endPosition = new Vector3(endPosition.x,endPosition.y,Potree.config.map.cameraHeight);
  63958. this.view.moveOrthoCamera(this.viewports[0], {endPosition, boundSize }, duration, easeName);
  63959. /* let endZoom, startZoom = this.camera.zoom
  63960. //修改相机为bound中心,这样能看到全部(宽度范围内)
  63961. this.view.setView({ position:endPosition, duration,
  63962. callback:()=>{//done
  63963. },
  63964. onUpdate:(progress)=>{
  63965. if(boundSize){
  63966. let aspect = boundSize.x / boundSize.y
  63967. let w, h;
  63968. if(this.camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  63969. h = boundSize.y
  63970. //w = h * this.camera.aspect
  63971. endZoom = this.viewports[0].resolution.y / h
  63972. }else{
  63973. w = boundSize.x;
  63974. //h = w / this.camera.aspect
  63975. endZoom = this.viewports[0].resolution.x / w
  63976. }
  63977. //onUpdate时更新endzoom是因为画布大小可能更改
  63978. this.camera.zoom = endZoom * progress + startZoom * (1 - progress)
  63979. this.camera.updateProjectionMatrix()
  63980. }
  63981. },
  63982. Easing:easeName
  63983. }) */
  63984. }
  63985. updateWhenAtViewer(e){
  63986. if(this.attachedToViewer){
  63987. if(this.started) this.mapLayer.update();
  63988. this.updateCursor();
  63989. this.needRender = true;
  63990. }
  63991. }
  63992. update(delta, areaSize ){
  63993. if(!this.visible && !this.attachedToViewer )return
  63994. if(this.attachedToViewer){
  63995. if(this.mapLayer.needUpdate){//必须更新。(较少触发)
  63996. this.updateWhenAtViewer();
  63997. }
  63998. return
  63999. }
  64000. this.updateScreenSize();
  64001. this.controls.update(delta);
  64002. this.view.applyToCamera(this.camera);
  64003. let changed = this.cameraChanged();
  64004. if(this.started && (changed || this.mapLayer.needUpdate))this.mapLayer.update();
  64005. if(changed /*|| || this.needRender */){
  64006. this.dispatchEvent({
  64007. type: "camera_changed",
  64008. camera: this.camera,
  64009. viewport : this.viewports[0]
  64010. });
  64011. this.needRender = true;
  64012. this.updateCursor();//更改大小
  64013. }
  64014. this.render();
  64015. }
  64016. attachToMainViewer(state, desc, mapRatio=0.5, options={}){//转移到viewer中。测量时展示or截图需要
  64017. if(!Potree.settings.isOfficial)this.renderArea.style.display = state ? 'none':'block';
  64018. if(state){
  64019. this.enabledOld = this.enabled;
  64020. this.enabled = true;
  64021. if(mapRatio != 'dontSet'){
  64022. this.changeSplitScreenDir(options.dir, mapRatio);
  64023. if(this.attachedToViewer){
  64024. //this.fitPanosToViewport()
  64025. viewer.updateScreenSize({forceUpdateSize:true});
  64026. return
  64027. }
  64028. viewer.viewports = [viewer.mainViewport, viewer.mapViewer.viewports[0] ];//因为mainViewer的相机变化会触发map的变化,所以先渲染mainViewer
  64029. }
  64030. if(desc == 'measure') this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene);//虽然用的是viewer的inputHandler,但借用了this.inputHandler的interactiveScenes
  64031. else if(desc == 'split4Screens') {
  64032. this.inputHandler.registerInteractiveScene(viewer.scene.scene);
  64033. }
  64034. }else {
  64035. if(!this.attachedToViewer)return
  64036. viewer.mainViewport.left = 0;
  64037. viewer.mainViewport.bottom = 0;
  64038. viewer.mainViewport.width = 1;
  64039. viewer.mainViewport.height = 1;
  64040. this.viewports[0].width = 1;
  64041. this.viewports[0].bottom = 0;
  64042. this.viewports[0].height = 1;
  64043. this.viewports[0].left = 0;
  64044. this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene);
  64045. this.inputHandler.unregisterInteractiveScene(viewer.scene.scene);
  64046. viewer.viewports = [viewer.mainViewport];
  64047. this.updateScreenSize({forceUpdateSize:true}); //更新相机projectionMatrix
  64048. }
  64049. //if(desc == 'measure')this.renderMeasure = state
  64050. this.attachedToViewer = state;
  64051. viewer.updateScreenSize({forceUpdateSize:true});
  64052. //mapRatio != 'dontSet' && !options.dontFit && this.moveTo(...)//要写在updateScreenSize后面,因为要根据视图大小来fit
  64053. if(options.moveToCurrentPos){
  64054. let boundSize = new Vector2$1(10,10);
  64055. let duration = 1000;
  64056. this.moveTo(viewer.images360.position.clone(), boundSize, duration);
  64057. }
  64058. this.needRender = true;
  64059. }
  64060. changeSplitScreenDir(dir, mapRatio){//左右 | 上下
  64061. //if(!dir || dir == this.dir)return
  64062. if(dir )this.splitDir = dir;
  64063. this.updateSplitSize(mapRatio);
  64064. /* if(this.attachedToViewer){ //如果已经分屏了,中途修改方向的话……
  64065. this.updateSplitSize()
  64066. } */
  64067. }
  64068. updateSplitSize(mapRatio){
  64069. if(mapRatio != void 0) this.mapRatio = mapRatio;
  64070. //console.log(this.mapRatio)
  64071. if(this.splitDir == 'leftRight'){//地图在左方
  64072. viewer.mainViewport.left = this.mapRatio;
  64073. viewer.mainViewport.width = 1-this.mapRatio;
  64074. this.viewports[0].width = this.mapRatio;
  64075. viewer.mainViewport.bottom = this.viewports[0].bottom = 0;
  64076. viewer.mainViewport.height = this.viewports[0].height = 1;
  64077. }else if(this.splitDir == 'upDown'){ //地图在下方
  64078. viewer.mainViewport.bottom = this.mapRatio;
  64079. viewer.mainViewport.height = 1-this.mapRatio;
  64080. this.viewports[0].height = this.mapRatio;
  64081. viewer.mainViewport.left = this.viewports[0].left = 0;
  64082. viewer.mainViewport.width = this.viewports[0].width = 1;
  64083. }
  64084. if(this.attachedToViewer){
  64085. viewer.updateScreenSize({forceUpdateSize:true});
  64086. }
  64087. }
  64088. render(params={}){
  64089. if(!this.visible && !this.attachedToViewer || !this.needRender && !params.force)return
  64090. let renderer = params.renderer || this.renderer;
  64091. if(params.target){
  64092. renderer.setRenderTarget(params.target);
  64093. }
  64094. /* if(params.resize){
  64095. this.emitResizeMsg(new THREE.Vector2(params.width,params.height, viewport:params.viewport))
  64096. } */
  64097. params.clear ? params.clear() : renderer.clear();
  64098. if(!this.attachedToViewer){
  64099. viewer.dispatchEvent({type: "render.begin", viewer: this, viewport:this.viewports[0], params });
  64100. }
  64101. viewer.setCameraLayers(this.camera, ['map','mapObjects' , 'bothMapAndScene' ]);
  64102. if(this.mapGradientBG){//渲染背景
  64103. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  64104. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  64105. }
  64106. renderer.render(this.scene, this.camera);
  64107. renderer.render(viewer.scene.scene, this.camera);
  64108. //测量线等
  64109. //params.renderOverlay && params.renderOverlay({camera:this.camera, isMap:true, viewport: this.viewports[0] })//其余如reticule 等场景层
  64110. params.renderOverlay && params.renderOverlay( $.extend({}, params, { isMap:true }));
  64111. renderer.setRenderTarget(null);
  64112. this.needRender = false;
  64113. }
  64114. /* render(){
  64115. let camera = viewer.scene.getActiveCamera();
  64116. viewer.scene.view.position.x += 0.01
  64117. viewer.setCameraLayers(camera, ['sceneObjects','marker','reticule','skybox' ])
  64118. this.renderer.render(viewer.scene.scene, camera);
  64119. } */
  64120. }
  64121. //本地调试地图白屏是因为代码自动更新了 但没刷新
  64122. class CSVExporter {
  64123. static toString (points) {
  64124. let string = '';
  64125. let attributes = Object.keys(points.data)
  64126. .filter(a => a !== 'normal')
  64127. .sort((a, b) => {
  64128. if (a === 'position') return -1;
  64129. if (b === 'position') return 1;
  64130. if (a === 'rgba') return -1;
  64131. if (b === 'rgba') return 1;
  64132. });
  64133. let headerValues = [];
  64134. for (let attribute of attributes) {
  64135. let itemSize = points.data[attribute].length / points.numPoints;
  64136. if (attribute === 'position') {
  64137. headerValues = headerValues.concat(['x', 'y', 'z']);
  64138. } else if (attribute === 'rgba') {
  64139. headerValues = headerValues.concat(['r', 'g', 'b', 'a']);
  64140. } else if (itemSize > 1) {
  64141. for (let i = 0; i < itemSize; i++) {
  64142. headerValues.push(`${attribute}_${i}`);
  64143. }
  64144. } else {
  64145. headerValues.push(attribute);
  64146. }
  64147. }
  64148. string = headerValues.join(', ') + '\n';
  64149. for (let i = 0; i < points.numPoints; i++) {
  64150. let values = [];
  64151. for (let attribute of attributes) {
  64152. let itemSize = points.data[attribute].length / points.numPoints;
  64153. let value = points.data[attribute]
  64154. .subarray(itemSize * i, itemSize * i + itemSize)
  64155. .join(', ');
  64156. values.push(value);
  64157. }
  64158. string += values.join(', ') + '\n';
  64159. }
  64160. return string;
  64161. }
  64162. };
  64163. class LASExporter {
  64164. static toLAS (points) {
  64165. // TODO Unused: let string = '';
  64166. let boundingBox = points.boundingBox;
  64167. let offset = boundingBox.min.clone();
  64168. let diagonal = boundingBox.min.distanceTo(boundingBox.max);
  64169. let scale = new Vector3(0.001, 0.001, 0.001);
  64170. if (diagonal > 1000 * 1000) {
  64171. scale = new Vector3(0.01, 0.01, 0.01);
  64172. } else {
  64173. scale = new Vector3(0.001, 0.001, 0.001);
  64174. }
  64175. let setString = function (string, offset, buffer) {
  64176. let view = new Uint8Array(buffer);
  64177. for (let i = 0; i < string.length; i++) {
  64178. let charCode = string.charCodeAt(i);
  64179. view[offset + i] = charCode;
  64180. }
  64181. };
  64182. let buffer = new ArrayBuffer(227 + 28 * points.numPoints);
  64183. let view = new DataView(buffer);
  64184. let u8View = new Uint8Array(buffer);
  64185. // let u16View = new Uint16Array(buffer);
  64186. setString('LASF', 0, buffer);
  64187. u8View[24] = 1;
  64188. u8View[25] = 2;
  64189. // system identifier o:26 l:32
  64190. // generating software o:58 l:32
  64191. setString('Potree 1.7', 58, buffer);
  64192. // file creation day of year o:90 l:2
  64193. // file creation year o:92 l:2
  64194. // header size o:94 l:2
  64195. view.setUint16(94, 227, true);
  64196. // offset to point data o:96 l:4
  64197. view.setUint32(96, 227, true);
  64198. // number of letiable length records o:100 l:4
  64199. // point data record format 104 1
  64200. u8View[104] = 2;
  64201. // point data record length 105 2
  64202. view.setUint16(105, 28, true);
  64203. // number of point records 107 4
  64204. view.setUint32(107, points.numPoints, true);
  64205. // number of points by return 111 20
  64206. // x scale factor 131 8
  64207. view.setFloat64(131, scale.x, true);
  64208. // y scale factor 139 8
  64209. view.setFloat64(139, scale.y, true);
  64210. // z scale factor 147 8
  64211. view.setFloat64(147, scale.z, true);
  64212. // x offset 155 8
  64213. view.setFloat64(155, offset.x, true);
  64214. // y offset 163 8
  64215. view.setFloat64(163, offset.y, true);
  64216. // z offset 171 8
  64217. view.setFloat64(171, offset.z, true);
  64218. // max x 179 8
  64219. view.setFloat64(179, boundingBox.max.x, true);
  64220. // min x 187 8
  64221. view.setFloat64(187, boundingBox.min.x, true);
  64222. // max y 195 8
  64223. view.setFloat64(195, boundingBox.max.y, true);
  64224. // min y 203 8
  64225. view.setFloat64(203, boundingBox.min.y, true);
  64226. // max z 211 8
  64227. view.setFloat64(211, boundingBox.max.z, true);
  64228. // min z 219 8
  64229. view.setFloat64(219, boundingBox.min.z, true);
  64230. let boffset = 227;
  64231. for (let i = 0; i < points.numPoints; i++) {
  64232. let px = points.data.position[3 * i + 0];
  64233. let py = points.data.position[3 * i + 1];
  64234. let pz = points.data.position[3 * i + 2];
  64235. let ux = parseInt((px - offset.x) / scale.x);
  64236. let uy = parseInt((py - offset.y) / scale.y);
  64237. let uz = parseInt((pz - offset.z) / scale.z);
  64238. view.setUint32(boffset + 0, ux, true);
  64239. view.setUint32(boffset + 4, uy, true);
  64240. view.setUint32(boffset + 8, uz, true);
  64241. if (points.data.intensity) {
  64242. view.setUint16(boffset + 12, (points.data.intensity[i]), true);
  64243. }
  64244. let rt = 0;
  64245. if (points.data.returnNumber) {
  64246. rt += points.data.returnNumber[i];
  64247. }
  64248. if (points.data.numberOfReturns) {
  64249. rt += (points.data.numberOfReturns[i] << 3);
  64250. }
  64251. view.setUint8(boffset + 14, rt);
  64252. if (points.data.classification) {
  64253. view.setUint8(boffset + 15, points.data.classification[i]);
  64254. }
  64255. // scan angle rank
  64256. // user data
  64257. // point source id
  64258. if (points.data.pointSourceID) {
  64259. view.setUint16(boffset + 18, points.data.pointSourceID[i]);
  64260. }
  64261. if (points.data.rgba) {
  64262. let rgba = points.data.rgba;
  64263. view.setUint16(boffset + 20, (rgba[4 * i + 0] * 255), true);
  64264. view.setUint16(boffset + 22, (rgba[4 * i + 1] * 255), true);
  64265. view.setUint16(boffset + 24, (rgba[4 * i + 2] * 255), true);
  64266. }
  64267. boffset += 28;
  64268. }
  64269. return buffer;
  64270. }
  64271. }
  64272. function copyMaterial(source, target){
  64273. for(let name of Object.keys(target.uniforms)){
  64274. target.uniforms[name].value = source.uniforms[name].value;
  64275. }
  64276. target.gradientTexture = source.gradientTexture;
  64277. target.visibleNodesTexture = source.visibleNodesTexture;
  64278. target.classificationTexture = source.classificationTexture;
  64279. target.matcapTexture = source.matcapTexture;
  64280. target.activeAttributeName = source.activeAttributeName;
  64281. target.ranges = source.ranges;
  64282. //target.updateShaderSource();
  64283. }
  64284. class Batch{
  64285. constructor(geometry, material){
  64286. this.geometry = geometry;
  64287. this.material = material;
  64288. this.sceneNode = new Points(geometry, material);
  64289. this.geometryNode = {
  64290. estimatedSpacing: 1.0,
  64291. geometry: geometry,
  64292. };
  64293. }
  64294. getLevel(){
  64295. return 0;
  64296. }
  64297. }
  64298. class ProfileFakeOctree extends PointCloudTree{
  64299. constructor(octree){
  64300. super();
  64301. this.trueOctree = octree;
  64302. this.pcoGeometry = octree.pcoGeometry;
  64303. this.points = [];
  64304. this.visibleNodes = [];
  64305. //this.material = this.trueOctree.material;
  64306. this.material = new PointCloudMaterial$1();
  64307. //this.material.copy(this.trueOctree.material);
  64308. copyMaterial(this.trueOctree.material, this.material);
  64309. this.material.pointSizeType = PointSizeType.FIXED;
  64310. this.batchSize = 100 * 1000;
  64311. this.currentBatch = null;
  64312. }
  64313. getAttribute(name){
  64314. return this.trueOctree.getAttribute(name);
  64315. }
  64316. dispose(){
  64317. for(let node of this.visibleNodes){
  64318. node.geometry.dispose();
  64319. }
  64320. this.visibleNodes = [];
  64321. this.currentBatch = null;
  64322. this.points = [];
  64323. }
  64324. addPoints(data){
  64325. // since each call to addPoints can deliver very very few points,
  64326. // we're going to batch them into larger buffers for efficiency.
  64327. if(this.currentBatch === null){
  64328. this.currentBatch = this.createNewBatch(data);
  64329. }
  64330. this.points.push(data);
  64331. let updateRange = {
  64332. start: this.currentBatch.geometry.drawRange.count,
  64333. count: 0
  64334. };
  64335. let projectedBox = new Box3();
  64336. let truePos = new Vector3();
  64337. for(let i = 0; i < data.numPoints; i++){
  64338. if(updateRange.start + updateRange.count >= this.batchSize){
  64339. // current batch full, start new batch
  64340. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  64341. let attribute = this.currentBatch.geometry.attributes[key];
  64342. attribute.updateRange.offset = updateRange.start;
  64343. attribute.updateRange.count = updateRange.count;
  64344. attribute.needsUpdate = true;
  64345. }
  64346. this.currentBatch.geometry.computeBoundingBox();
  64347. this.currentBatch.geometry.computeBoundingSphere();
  64348. this.currentBatch = this.createNewBatch(data);
  64349. updateRange = {
  64350. start: 0,
  64351. count: 0
  64352. };
  64353. }
  64354. truePos.set(
  64355. data.data.position[3 * i + 0] + this.trueOctree.position.x,
  64356. data.data.position[3 * i + 1] + this.trueOctree.position.y,
  64357. data.data.position[3 * i + 2] + this.trueOctree.position.z,
  64358. );
  64359. let x = data.data.mileage[i];
  64360. let y = 0;
  64361. let z = truePos.z;
  64362. projectedBox.expandByPoint(new Vector3(x, y, z));
  64363. let index = updateRange.start + updateRange.count;
  64364. let geometry = this.currentBatch.geometry;
  64365. for(let attributeName of Object.keys(data.data)){
  64366. let source = data.data[attributeName];
  64367. let target = geometry.attributes[attributeName];
  64368. let numElements = target.itemSize;
  64369. for(let item = 0; item < numElements; item++){
  64370. target.array[numElements * index + item] = source[numElements * i + item];
  64371. }
  64372. }
  64373. {
  64374. let position = geometry.attributes.position;
  64375. position.array[3 * index + 0] = x;
  64376. position.array[3 * index + 1] = y;
  64377. position.array[3 * index + 2] = z;
  64378. }
  64379. updateRange.count++;
  64380. this.currentBatch.geometry.drawRange.count++;
  64381. }
  64382. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  64383. let attribute = this.currentBatch.geometry.attributes[key];
  64384. attribute.updateRange.offset = updateRange.start;
  64385. attribute.updateRange.count = updateRange.count;
  64386. attribute.needsUpdate = true;
  64387. }
  64388. data.projectedBox = projectedBox;
  64389. this.projectedBox = this.points.reduce( (a, i) => a.union(i.projectedBox), new Box3());
  64390. }
  64391. createNewBatch(data){
  64392. let geometry = new BufferGeometry();
  64393. // create new batches with batch_size elements of the same type as the attribute
  64394. for(let attributeName of Object.keys(data.data)){
  64395. let buffer = data.data[attributeName];
  64396. let numElements = buffer.length / data.numPoints; // 3 for pos, 4 for col, 1 for scalars
  64397. let constructor = buffer.constructor;
  64398. let normalized = false;
  64399. if(this.trueOctree.root.sceneNode){
  64400. if(this.trueOctree.root.sceneNode.geometry.attributes[attributeName]){
  64401. normalized = this.trueOctree.root.sceneNode.geometry.attributes[attributeName].normalized;
  64402. }
  64403. }
  64404. let batchBuffer = new constructor(numElements * this.batchSize);
  64405. let bufferAttribute = new BufferAttribute(batchBuffer, numElements, normalized);
  64406. bufferAttribute.potree = {
  64407. range: [0, 1],
  64408. };
  64409. geometry.setAttribute(attributeName, bufferAttribute);
  64410. }
  64411. geometry.drawRange.start = 0;
  64412. geometry.drawRange.count = 0;
  64413. let batch = new Batch(geometry, this.material);
  64414. this.visibleNodes.push(batch);
  64415. return batch;
  64416. }
  64417. computeVisibilityTextureData(){
  64418. let data = new Uint8Array(this.visibleNodes.length * 4);
  64419. let offsets = new Map();
  64420. for(let i = 0; i < this.visibleNodes.length; i++){
  64421. let node = this.visibleNodes[i];
  64422. offsets[node] = i;
  64423. }
  64424. return {
  64425. data: data,
  64426. offsets: offsets,
  64427. };
  64428. }
  64429. }
  64430. class ProfileWindow extends EventDispatcher {
  64431. constructor (viewer) {
  64432. super();
  64433. this.viewer = viewer;
  64434. this.elRoot = $('#profile_window');
  64435. this.renderArea = this.elRoot.find('#profileCanvasContainer');
  64436. this.svg = d3.select('svg#profileSVG');
  64437. this.mouseIsDown = false;
  64438. this.projectedBox = new Box3();
  64439. this.pointclouds = new Map();
  64440. this.numPoints = 0;
  64441. this.lastAddPointsTimestamp = undefined;
  64442. this.mouse = new Vector2$1(0, 0);
  64443. this.scale = new Vector3(1, 1, 1);
  64444. this.autoFitEnabled = true; // completely disable/enable
  64445. this.autoFit = false; // internal
  64446. let cwIcon = `${exports.resourcePath}/icons/arrow_cw.svg`;
  64447. $('#potree_profile_rotate_cw').attr('src', cwIcon);
  64448. let ccwIcon = `${exports.resourcePath}/icons/arrow_ccw.svg`;
  64449. $('#potree_profile_rotate_ccw').attr('src', ccwIcon);
  64450. let forwardIcon = `${exports.resourcePath}/icons/arrow_up.svg`;
  64451. $('#potree_profile_move_forward').attr('src', forwardIcon);
  64452. let backwardIcon = `${exports.resourcePath}/icons/arrow_down.svg`;
  64453. $('#potree_profile_move_backward').attr('src', backwardIcon);
  64454. let csvIcon = `${exports.resourcePath}/icons/file_csv_2d.svg`;
  64455. $('#potree_download_csv_icon').attr('src', csvIcon);
  64456. let lasIcon = `${exports.resourcePath}/icons/file_las_3d.svg`;
  64457. $('#potree_download_las_icon').attr('src', lasIcon);
  64458. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  64459. $('#closeProfileContainer').attr("src", closeIcon);
  64460. this.initTHREE();
  64461. this.initSVG();
  64462. this.initListeners();
  64463. this.pRenderer = new Renderer(this.renderer);
  64464. this.elRoot.i18n();
  64465. }
  64466. initListeners () {
  64467. $(window).resize(() => {
  64468. if (this.enabled) {
  64469. this.render();
  64470. }
  64471. });
  64472. this.renderArea.mousedown(e => {
  64473. this.mouseIsDown = true;
  64474. });
  64475. this.renderArea.mouseup(e => {
  64476. this.mouseIsDown = false;
  64477. });
  64478. let viewerPickSphereSizeHandler = () => {
  64479. let camera = this.viewer.scene.getActiveCamera();
  64480. let domElement = this.viewer.renderer.domElement;
  64481. let distance = this.viewerPickSphere.position.distanceTo(camera.position);
  64482. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  64483. let scale = (10 / pr);
  64484. this.viewerPickSphere.scale.set(scale, scale, scale);
  64485. };
  64486. this.renderArea.mousemove(e => {
  64487. if (this.pointclouds.size === 0) {
  64488. return;
  64489. }
  64490. let rect = this.renderArea[0].getBoundingClientRect();
  64491. let x = e.clientX - rect.left;
  64492. let y = e.clientY - rect.top;
  64493. let newMouse = new Vector2$1(x, y);
  64494. if (this.mouseIsDown) {
  64495. // DRAG
  64496. this.autoFit = false;
  64497. this.lastDrag = new Date().getTime();
  64498. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64499. let ncPos = [this.scaleX.invert(newMouse.x), this.scaleY.invert(newMouse.y)];
  64500. this.camera.position.x -= ncPos[0] - cPos[0];
  64501. this.camera.position.z -= ncPos[1] - cPos[1];
  64502. this.render();
  64503. } else if (this.pointclouds.size > 0) {
  64504. // FIND HOVERED POINT
  64505. let radius = Math.abs(this.scaleX.invert(0) - this.scaleX.invert(40));
  64506. let mileage = this.scaleX.invert(newMouse.x);
  64507. let elevation = this.scaleY.invert(newMouse.y);
  64508. let closest = this.selectPoint(mileage, elevation, radius);
  64509. if (closest) {
  64510. let point = closest.point;
  64511. let position = new Float64Array([
  64512. point.position[0] + closest.pointcloud.position.x,
  64513. point.position[1] + closest.pointcloud.position.y,
  64514. point.position[2] + closest.pointcloud.position.z
  64515. ]);
  64516. this.elRoot.find('#profileSelectionProperties').fadeIn(200);
  64517. this.pickSphere.visible = true;
  64518. this.pickSphere.scale.set(0.5 * radius, 0.5 * radius, 0.5 * radius);
  64519. this.pickSphere.position.set(point.mileage, 0, position[2]);
  64520. this.viewerPickSphere.position.set(...position);
  64521. if(!this.viewer.scene.scene.children.includes(this.viewerPickSphere)){
  64522. this.viewer.scene.scene.add(this.viewerPickSphere);
  64523. if(!this.viewer.hasEventListener("update", viewerPickSphereSizeHandler)){
  64524. this.viewer.addEventListener("update", viewerPickSphereSizeHandler);
  64525. }
  64526. }
  64527. let info = this.elRoot.find('#profileSelectionProperties');
  64528. let html = '<table>';
  64529. for (let attributeName of Object.keys(point)) {
  64530. let value = point[attributeName];
  64531. let attribute = closest.pointcloud.getAttribute(attributeName);
  64532. let transform = value => value;
  64533. if(attribute && attribute.type.size > 4){
  64534. let range = attribute.initialRange;
  64535. let scale = 1 / (range[1] - range[0]);
  64536. let offset = range[0];
  64537. transform = value => value / scale + offset;
  64538. }
  64539. if (attributeName === 'position') {
  64540. let values = [...position].map(v => Utils.addCommas(v.toFixed(3)));
  64541. html += `
  64542. <tr>
  64543. <td>x</td>
  64544. <td>${values[0]}</td>
  64545. </tr>
  64546. <tr>
  64547. <td>y</td>
  64548. <td>${values[1]}</td>
  64549. </tr>
  64550. <tr>
  64551. <td>z</td>
  64552. <td>${values[2]}</td>
  64553. </tr>`;
  64554. } else if (attributeName === 'rgba') {
  64555. html += `
  64556. <tr>
  64557. <td>${attributeName}</td>
  64558. <td>${value.join(', ')}</td>
  64559. </tr>`;
  64560. } else if (attributeName === 'normal') {
  64561. continue;
  64562. } else if (attributeName === 'mileage') {
  64563. html += `
  64564. <tr>
  64565. <td>${attributeName}</td>
  64566. <td>${value.toFixed(3)}</td>
  64567. </tr>`;
  64568. } else {
  64569. html += `
  64570. <tr>
  64571. <td>${attributeName}</td>
  64572. <td>${transform(value)}</td>
  64573. </tr>`;
  64574. }
  64575. }
  64576. html += '</table>';
  64577. info.html(html);
  64578. this.selectedPoint = point;
  64579. } else {
  64580. // this.pickSphere.visible = false;
  64581. // this.selectedPoint = null;
  64582. this.viewer.scene.scene.add(this.viewerPickSphere);
  64583. let index = this.viewer.scene.scene.children.indexOf(this.viewerPickSphere);
  64584. if(index >= 0){
  64585. this.viewer.scene.scene.children.splice(index, 1);
  64586. }
  64587. this.viewer.removeEventListener("update", viewerPickSphereSizeHandler);
  64588. }
  64589. this.render();
  64590. }
  64591. this.mouse.copy(newMouse);
  64592. });
  64593. let onWheel = e => {
  64594. this.autoFit = false;
  64595. let delta = 0;
  64596. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  64597. delta = e.wheelDelta;
  64598. } else if (e.detail !== undefined) { // Firefox
  64599. delta = -e.detail;
  64600. }
  64601. let ndelta = Math.sign(delta);
  64602. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64603. if (ndelta > 0) {
  64604. // + 10%
  64605. this.scale.multiplyScalar(1.1);
  64606. } else {
  64607. // - 10%
  64608. this.scale.multiplyScalar(100 / 110);
  64609. }
  64610. this.updateScales();
  64611. let ncPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64612. this.camera.position.x -= ncPos[0] - cPos[0];
  64613. this.camera.position.z -= ncPos[1] - cPos[1];
  64614. this.render();
  64615. this.updateScales();
  64616. };
  64617. $(this.renderArea)[0].addEventListener('mousewheel', onWheel, false);
  64618. $(this.renderArea)[0].addEventListener('DOMMouseScroll', onWheel, false); // Firefox
  64619. $('#closeProfileContainer').click(() => {
  64620. this.hide();
  64621. });
  64622. let getProfilePoints = () => {
  64623. let points = new Points$1();
  64624. for(let [pointcloud, entry] of this.pointclouds){
  64625. for(let pointSet of entry.points){
  64626. let originPos = pointSet.data.position;
  64627. let trueElevationPosition = new Float32Array(originPos);
  64628. for(let i = 0; i < pointSet.numPoints; i++){
  64629. trueElevationPosition[3 * i + 2] += pointcloud.position.z;
  64630. }
  64631. pointSet.data.position = trueElevationPosition;
  64632. points.add(pointSet);
  64633. pointSet.data.position = originPos;
  64634. }
  64635. }
  64636. return points;
  64637. };
  64638. $('#potree_download_csv_icon').click(() => {
  64639. let points = getProfilePoints();
  64640. let string = CSVExporter.toString(points);
  64641. let blob = new Blob([string], {type: "text/string"});
  64642. $('#potree_download_profile_ortho_link').attr('href', URL.createObjectURL(blob));
  64643. });
  64644. $('#potree_download_las_icon').click(() => {
  64645. let points = getProfilePoints();
  64646. let buffer = LASExporter.toLAS(points);
  64647. let blob = new Blob([buffer], {type: "application/octet-binary"});
  64648. $('#potree_download_profile_link').attr('href', URL.createObjectURL(blob));
  64649. });
  64650. }
  64651. selectPoint (mileage, elevation, radius) {
  64652. let closest = {
  64653. distance: Infinity,
  64654. pointcloud: null,
  64655. points: null,
  64656. index: null
  64657. };
  64658. let pointBox = new Box2(
  64659. new Vector2$1(mileage - radius, elevation - radius),
  64660. new Vector2$1(mileage + radius, elevation + radius));
  64661. let numTested = 0;
  64662. let numSkipped = 0;
  64663. let numTestedPoints = 0;
  64664. let numSkippedPoints = 0;
  64665. for (let [pointcloud, entry] of this.pointclouds) {
  64666. for(let points of entry.points){
  64667. let collisionBox = new Box2(
  64668. new Vector2$1(points.projectedBox.min.x, points.projectedBox.min.z),
  64669. new Vector2$1(points.projectedBox.max.x, points.projectedBox.max.z)
  64670. );
  64671. let intersects = collisionBox.intersectsBox(pointBox);
  64672. if(!intersects){
  64673. numSkipped++;
  64674. numSkippedPoints += points.numPoints;
  64675. continue;
  64676. }
  64677. numTested++;
  64678. numTestedPoints += points.numPoints;
  64679. for (let i = 0; i < points.numPoints; i++) {
  64680. let m = points.data.mileage[i] - mileage;
  64681. let e = points.data.position[3 * i + 2] - elevation + pointcloud.position.z;
  64682. let r = Math.sqrt(m * m + e * e);
  64683. const withinDistance = r < radius && r < closest.distance;
  64684. let unfilteredClass = true;
  64685. if(points.data.classification){
  64686. const classification = pointcloud.material.classification;
  64687. const pointClassID = points.data.classification[i];
  64688. const pointClassValue = classification[pointClassID];
  64689. if(pointClassValue && (!pointClassValue.visible || pointClassValue.color.w === 0)){
  64690. unfilteredClass = false;
  64691. }
  64692. }
  64693. if (withinDistance && unfilteredClass) {
  64694. closest = {
  64695. distance: r,
  64696. pointcloud: pointcloud,
  64697. points: points,
  64698. index: i
  64699. };
  64700. }
  64701. }
  64702. }
  64703. }
  64704. //console.log(`nodes: ${numTested}, ${numSkipped} || points: ${numTestedPoints}, ${numSkippedPoints}`);
  64705. if (closest.distance < Infinity) {
  64706. let points = closest.points;
  64707. let point = {};
  64708. let attributes = Object.keys(points.data);
  64709. for (let attribute of attributes) {
  64710. let attributeData = points.data[attribute];
  64711. let itemSize = attributeData.length / points.numPoints;
  64712. let value = attributeData.subarray(itemSize * closest.index, itemSize * closest.index + itemSize);
  64713. if (value.length === 1) {
  64714. point[attribute] = value[0];
  64715. } else {
  64716. point[attribute] = value;
  64717. }
  64718. }
  64719. closest.point = point;
  64720. return closest;
  64721. } else {
  64722. return null;
  64723. }
  64724. }
  64725. initTHREE () {
  64726. this.renderer = new WebGLRenderer({alpha: true, premultipliedAlpha: false});
  64727. this.renderer.setClearColor(0x000000, 0);
  64728. this.renderer.setSize(10, 10);
  64729. this.renderer.autoClear = false;
  64730. this.renderArea.append($(this.renderer.domElement));
  64731. this.renderer.domElement.tabIndex = '2222';
  64732. $(this.renderer.domElement).css('width', '100%');
  64733. $(this.renderer.domElement).css('height', '100%');
  64734. {
  64735. let gl = this.renderer.getContext();
  64736. if(gl.createVertexArray == null){
  64737. let extVAO = gl.getExtension('OES_vertex_array_object');
  64738. if(!extVAO){
  64739. throw new Error("OES_vertex_array_object extension not supported");
  64740. }
  64741. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  64742. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  64743. }
  64744. }
  64745. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  64746. /* */
  64747. if(window.axisYup){
  64748. }else {
  64749. this.camera.up.set(0, 0, 1);
  64750. this.camera.rotation.order = "ZXY";
  64751. this.camera.rotation.x = Math.PI / 2.0;
  64752. }
  64753. this.scene = new Scene();
  64754. this.profileScene = new Scene();
  64755. let sg = new SphereGeometry(1, 16, 16);
  64756. let sm = new MeshNormalMaterial();
  64757. this.pickSphere = new Mesh(sg, sm);
  64758. this.scene.add(this.pickSphere);
  64759. this.viewerPickSphere = new Mesh(sg, sm);
  64760. }
  64761. initSVG () {
  64762. let width = this.renderArea[0].clientWidth;
  64763. let height = this.renderArea[0].clientHeight;
  64764. let marginLeft = this.renderArea[0].offsetLeft;
  64765. this.svg.selectAll('*').remove();
  64766. this.scaleX = d3.scale.linear()
  64767. .domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  64768. .range([0, width]);
  64769. this.scaleY = d3.scale.linear()
  64770. .domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  64771. .range([height, 0]);
  64772. this.xAxis = d3.svg.axis()
  64773. .scale(this.scaleX)
  64774. .orient('bottom')
  64775. .innerTickSize(-height)
  64776. .outerTickSize(1)
  64777. .tickPadding(10)
  64778. .ticks(width / 50);
  64779. this.yAxis = d3.svg.axis()
  64780. .scale(this.scaleY)
  64781. .orient('left')
  64782. .innerTickSize(-width)
  64783. .outerTickSize(1)
  64784. .tickPadding(10)
  64785. .ticks(height / 20);
  64786. this.elXAxis = this.svg.append('g')
  64787. .attr('class', 'x axis')
  64788. .attr('transform', `translate(${marginLeft}, ${height})`)
  64789. .call(this.xAxis);
  64790. this.elYAxis = this.svg.append('g')
  64791. .attr('class', 'y axis')
  64792. .attr('transform', `translate(${marginLeft}, 0)`)
  64793. .call(this.yAxis);
  64794. }
  64795. addPoints (pointcloud, points) {
  64796. if(points.numPoints === 0){
  64797. return;
  64798. }
  64799. let entry = this.pointclouds.get(pointcloud);
  64800. if(!entry){
  64801. entry = new ProfileFakeOctree(pointcloud);
  64802. this.pointclouds.set(pointcloud, entry);
  64803. this.profileScene.add(entry);
  64804. let materialChanged = () => {
  64805. this.render();
  64806. };
  64807. materialChanged();
  64808. pointcloud.material.addEventListener('material_property_changed', materialChanged);
  64809. this.addEventListener("on_reset_once", () => {
  64810. pointcloud.material.removeEventListener('material_property_changed', materialChanged);
  64811. });
  64812. }
  64813. entry.addPoints(points);
  64814. this.projectedBox.union(entry.projectedBox);
  64815. if (this.autoFit && this.autoFitEnabled) {
  64816. let width = this.renderArea[0].clientWidth;
  64817. let height = this.renderArea[0].clientHeight;
  64818. let size = this.projectedBox.getSize(new Vector3());
  64819. let sx = width / size.x;
  64820. let sy = height / size.z;
  64821. let scale = Math.min(sx, sy);
  64822. let center = this.projectedBox.getCenter(new Vector3());
  64823. this.scale.set(scale, scale, 1);
  64824. this.camera.position.copy(center);
  64825. //console.log("camera: ", this.camera.position.toArray().join(", "));
  64826. }
  64827. //console.log(entry);
  64828. this.render();
  64829. let numPoints = 0;
  64830. for (let [key, value] of this.pointclouds.entries()) {
  64831. numPoints += value.points.reduce( (a, i) => a + i.numPoints, 0);
  64832. }
  64833. $(`#profile_num_points`).html(Utils.addCommas(numPoints));
  64834. }
  64835. reset () {
  64836. this.lastReset = new Date().getTime();
  64837. this.dispatchEvent({type: "on_reset_once"});
  64838. this.removeEventListeners("on_reset_once");
  64839. this.autoFit = true;
  64840. this.projectedBox = new Box3();
  64841. for(let [key, entry] of this.pointclouds){
  64842. entry.dispose();
  64843. }
  64844. this.pointclouds.clear();
  64845. this.mouseIsDown = false;
  64846. this.mouse.set(0, 0);
  64847. if(this.autoFitEnabled){
  64848. this.scale.set(1, 1, 1);
  64849. }
  64850. this.pickSphere.visible = false;
  64851. this.elRoot.find('#profileSelectionProperties').hide();
  64852. this.render();
  64853. }
  64854. show () {
  64855. this.elRoot.fadeIn();
  64856. this.enabled = true;
  64857. }
  64858. hide () {
  64859. this.elRoot.fadeOut();
  64860. this.enabled = false;
  64861. }
  64862. updateScales () {
  64863. let width = this.renderArea[0].clientWidth;
  64864. let height = this.renderArea[0].clientHeight;
  64865. let left = (-width / 2) / this.scale.x;
  64866. let right = (+width / 2) / this.scale.x;
  64867. let top = (+height / 2) / this.scale.y;
  64868. let bottom = (-height / 2) / this.scale.y;
  64869. this.camera.left = left;
  64870. this.camera.right = right;
  64871. this.camera.top = top;
  64872. this.camera.bottom = bottom;
  64873. this.camera.updateProjectionMatrix();
  64874. this.scaleX.domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  64875. .range([0, width]);
  64876. this.scaleY.domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  64877. .range([height, 0]);
  64878. let marginLeft = this.renderArea[0].offsetLeft;
  64879. this.xAxis.scale(this.scaleX)
  64880. .orient('bottom')
  64881. .innerTickSize(-height)
  64882. .outerTickSize(1)
  64883. .tickPadding(10)
  64884. .ticks(width / 50);
  64885. this.yAxis.scale(this.scaleY)
  64886. .orient('left')
  64887. .innerTickSize(-width)
  64888. .outerTickSize(1)
  64889. .tickPadding(10)
  64890. .ticks(height / 20);
  64891. this.elXAxis
  64892. .attr('transform', `translate(${marginLeft}, ${height})`)
  64893. .call(this.xAxis);
  64894. this.elYAxis
  64895. .attr('transform', `translate(${marginLeft}, 0)`)
  64896. .call(this.yAxis);
  64897. }
  64898. requestScaleUpdate(){
  64899. let threshold = 100;
  64900. let allowUpdate = ((this.lastReset === undefined) || (this.lastScaleUpdate === undefined))
  64901. || ((new Date().getTime() - this.lastReset) > threshold && (new Date().getTime() - this.lastScaleUpdate) > threshold);
  64902. if(allowUpdate){
  64903. this.updateScales();
  64904. this.lastScaleUpdate = new Date().getTime();
  64905. this.scaleUpdatePending = false;
  64906. }else if(!this.scaleUpdatePending) {
  64907. setTimeout(this.requestScaleUpdate.bind(this), 100);
  64908. this.scaleUpdatePending = true;
  64909. }
  64910. }
  64911. render () {
  64912. let width = this.renderArea[0].clientWidth;
  64913. let height = this.renderArea[0].clientHeight;
  64914. let {renderer, pRenderer, camera, profileScene, scene} = this;
  64915. let {scaleX, pickSphere} = this;
  64916. renderer.setSize(width, height);
  64917. renderer.setClearColor(0x000000, 0);
  64918. renderer.clear(true, true, false);
  64919. for(let pointcloud of this.pointclouds.keys()){
  64920. let source = pointcloud.material;
  64921. let target = this.pointclouds.get(pointcloud).material;
  64922. copyMaterial(source, target);
  64923. target.size = 2;
  64924. }
  64925. pRenderer.render(profileScene, camera, null);
  64926. let radius = Math.abs(scaleX.invert(0) - scaleX.invert(5));
  64927. if (radius === 0) {
  64928. pickSphere.visible = false;
  64929. } else {
  64930. pickSphere.scale.set(radius, radius, radius);
  64931. pickSphere.visible = true;
  64932. }
  64933. renderer.render(scene, camera);
  64934. this.requestScaleUpdate();
  64935. }
  64936. };
  64937. class ProfileWindowController {
  64938. constructor (viewer) {
  64939. this.viewer = viewer;
  64940. this.profileWindow = viewer.profileWindow;
  64941. this.profile = null;
  64942. this.numPoints = 0;
  64943. this.threshold = 60 * 1000;
  64944. this.rotateAmount = 10;
  64945. this.scheduledRecomputeTime = null;
  64946. this.enabled = true;
  64947. this.requests = [];
  64948. this._recompute = () => { this.recompute(); };
  64949. this.viewer.addEventListener("scene_changed", e => {
  64950. e.oldScene.removeEventListener("pointcloud_added", this._recompute);
  64951. e.scene.addEventListener("pointcloud_added", this._recompute);
  64952. });
  64953. this.viewer.scene.addEventListener("pointcloud_added", this._recompute);
  64954. $("#potree_profile_rotate_amount").val(parseInt(this.rotateAmount));
  64955. $("#potree_profile_rotate_amount").on("input", (e) => {
  64956. const str = $("#potree_profile_rotate_amount").val();
  64957. if(!isNaN(str)){
  64958. const value = parseFloat(str);
  64959. this.rotateAmount = value;
  64960. $("#potree_profile_rotate_amount").css("background-color", "");
  64961. }else {
  64962. $("#potree_profile_rotate_amount").css("background-color", "#ff9999");
  64963. }
  64964. });
  64965. const rotate = (radians) => {
  64966. const profile = this.profile;
  64967. const points = profile.points;
  64968. const start = points[0];
  64969. const end = points[points.length - 1];
  64970. const center = start.clone().add(end).multiplyScalar(0.5);
  64971. const mMoveOrigin = new Matrix4().makeTranslation(-center.x, -center.y, -center.z);
  64972. const mRotate = new Matrix4().makeRotationZ(radians);
  64973. const mMoveBack = new Matrix4().makeTranslation(center.x, center.y, center.z);
  64974. //const transform = mMoveOrigin.multiply(mRotate).multiply(mMoveBack);
  64975. const transform = mMoveBack.multiply(mRotate).multiply(mMoveOrigin);
  64976. const rotatedPoints = points.map( point => point.clone().applyMatrix4(transform) );
  64977. this.profileWindow.autoFitEnabled = false;
  64978. for(let i = 0; i < points.length; i++){
  64979. profile.setPosition(i, rotatedPoints[i]);
  64980. }
  64981. };
  64982. $("#potree_profile_rotate_cw").click( () => {
  64983. const radians = MathUtils.degToRad(this.rotateAmount);
  64984. rotate(-radians);
  64985. });
  64986. $("#potree_profile_rotate_ccw").click( () => {
  64987. const radians = MathUtils.degToRad(this.rotateAmount);
  64988. rotate(radians);
  64989. });
  64990. $("#potree_profile_move_forward").click( () => {
  64991. const profile = this.profile;
  64992. const points = profile.points;
  64993. const start = points[0];
  64994. const end = points[points.length - 1];
  64995. const dir = end.clone().sub(start).normalize();
  64996. const up = new Vector3(0, 0, 1);
  64997. const forward = up.cross(dir);
  64998. const move = forward.clone().multiplyScalar(profile.width / 2);
  64999. this.profileWindow.autoFitEnabled = false;
  65000. for(let i = 0; i < points.length; i++){
  65001. profile.setPosition(i, points[i].clone().add(move));
  65002. }
  65003. });
  65004. $("#potree_profile_move_backward").click( () => {
  65005. const profile = this.profile;
  65006. const points = profile.points;
  65007. const start = points[0];
  65008. const end = points[points.length - 1];
  65009. const dir = end.clone().sub(start).normalize();
  65010. const up = new Vector3(0, 0, 1);
  65011. const forward = up.cross(dir);
  65012. const move = forward.clone().multiplyScalar(-profile.width / 2);
  65013. this.profileWindow.autoFitEnabled = false;
  65014. for(let i = 0; i < points.length; i++){
  65015. profile.setPosition(i, points[i].clone().add(move));
  65016. }
  65017. });
  65018. }
  65019. setProfile (profile) {
  65020. if (this.profile !== null && this.profile !== profile) {
  65021. this.profile.removeEventListener('marker_moved', this._recompute);
  65022. this.profile.removeEventListener('marker_added', this._recompute);
  65023. this.profile.removeEventListener('marker_removed', this._recompute);
  65024. this.profile.removeEventListener('width_changed', this._recompute);
  65025. }
  65026. this.profile = profile;
  65027. {
  65028. this.profile.addEventListener('marker_moved', this._recompute);
  65029. this.profile.addEventListener('marker_added', this._recompute);
  65030. this.profile.addEventListener('marker_removed', this._recompute);
  65031. this.profile.addEventListener('width_changed', this._recompute);
  65032. }
  65033. this.recompute();
  65034. }
  65035. reset () {
  65036. this.profileWindow.reset();
  65037. this.numPoints = 0;
  65038. if (this.profile) {
  65039. for (let request of this.requests) {
  65040. request.cancel();
  65041. }
  65042. }
  65043. }
  65044. progressHandler (pointcloud, progress) {
  65045. for (let segment of progress.segments) {
  65046. this.profileWindow.addPoints(pointcloud, segment.points);
  65047. this.numPoints += segment.points.numPoints;
  65048. }
  65049. }
  65050. cancel () {
  65051. for (let request of this.requests) {
  65052. request.cancel();
  65053. // request.finishLevelThenCancel();
  65054. }
  65055. this.requests = [];
  65056. };
  65057. finishLevelThenCancel(){
  65058. for (let request of this.requests) {
  65059. request.finishLevelThenCancel();
  65060. }
  65061. this.requests = [];
  65062. }
  65063. recompute () {
  65064. if (!this.profile) {
  65065. return;
  65066. }
  65067. if (this.scheduledRecomputeTime !== null && this.scheduledRecomputeTime > new Date().getTime()) {
  65068. return;
  65069. } else {
  65070. this.scheduledRecomputeTime = new Date().getTime() + 100;
  65071. }
  65072. this.scheduledRecomputeTime = null;
  65073. this.reset();
  65074. for (let pointcloud of this.viewer.scene.pointclouds.filter(p => p.visible)) {
  65075. let request = pointcloud.getPointsInProfile(this.profile, null, {
  65076. 'onProgress': (event) => {
  65077. if (!this.enabled) {
  65078. return;
  65079. }
  65080. this.progressHandler(pointcloud, event.points);
  65081. if (this.numPoints > this.threshold) {
  65082. this.finishLevelThenCancel();
  65083. }
  65084. },
  65085. 'onFinish': (event) => {
  65086. if (!this.enabled) {
  65087. }
  65088. },
  65089. 'onCancel': () => {
  65090. if (!this.enabled) {
  65091. }
  65092. }
  65093. });
  65094. this.requests.push(request);
  65095. }
  65096. }
  65097. };
  65098. /**
  65099. *
  65100. * @author sigeom sa / http://sigeom.ch
  65101. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  65102. * @author Markus Schütz / http://potree.org
  65103. *
  65104. */
  65105. class GeoJSONExporter{
  65106. static measurementToFeatures (measurement) {
  65107. let coords = measurement.points.map(e => e.position.toArray());
  65108. let features = [];
  65109. if (coords.length === 1) {
  65110. let feature = {
  65111. type: 'Feature',
  65112. geometry: {
  65113. type: 'Point',
  65114. coordinates: coords[0]
  65115. },
  65116. properties: {
  65117. name: measurement.name
  65118. }
  65119. };
  65120. features.push(feature);
  65121. } else if (coords.length > 1 && !measurement.closed) {
  65122. let object = {
  65123. 'type': 'Feature',
  65124. 'geometry': {
  65125. 'type': 'LineString',
  65126. 'coordinates': coords
  65127. },
  65128. 'properties': {
  65129. name: measurement.name
  65130. }
  65131. };
  65132. features.push(object);
  65133. } else if (coords.length > 1 && measurement.closed) {
  65134. let object = {
  65135. 'type': 'Feature',
  65136. 'geometry': {
  65137. 'type': 'Polygon',
  65138. 'coordinates': [[...coords, coords[0]]]
  65139. },
  65140. 'properties': {
  65141. name: measurement.name
  65142. }
  65143. };
  65144. features.push(object);
  65145. }
  65146. if (measurement.showDistances) {
  65147. measurement.edgeLabels.forEach((label) => {
  65148. let labelPoint = {
  65149. type: 'Feature',
  65150. geometry: {
  65151. type: 'Point',
  65152. coordinates: label.position.toArray()
  65153. },
  65154. properties: {
  65155. distance: label.text
  65156. }
  65157. };
  65158. features.push(labelPoint);
  65159. });
  65160. }
  65161. if (measurement.showArea) {
  65162. let point = measurement.areaLabel.position;
  65163. let labelArea = {
  65164. type: 'Feature',
  65165. geometry: {
  65166. type: 'Point',
  65167. coordinates: point.toArray()
  65168. },
  65169. properties: {
  65170. area: measurement.areaLabel.text
  65171. }
  65172. };
  65173. features.push(labelArea);
  65174. }
  65175. return features;
  65176. }
  65177. static toString (measurements) {
  65178. if (!(measurements instanceof Array)) {
  65179. measurements = [measurements];
  65180. }
  65181. measurements = measurements.filter(m => m instanceof Measure);
  65182. let features = [];
  65183. for (let measure of measurements) {
  65184. let f = GeoJSONExporter.measurementToFeatures(measure);
  65185. features = features.concat(f);
  65186. }
  65187. let geojson = {
  65188. 'type': 'FeatureCollection',
  65189. 'features': features
  65190. };
  65191. return JSON.stringify(geojson, null, '\t');
  65192. }
  65193. }
  65194. /**
  65195. *
  65196. * @author sigeom sa / http://sigeom.ch
  65197. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  65198. * @author Markus Schuetz / http://potree.org
  65199. *
  65200. */
  65201. class DXFExporter {
  65202. static measurementPointSection (measurement) {
  65203. let position = measurement.points[0].position;
  65204. if (!position) {
  65205. return '';
  65206. }
  65207. let dxfSection = `0
  65208. CIRCLE
  65209. 8
  65210. layer_point
  65211. 10
  65212. ${position.x}
  65213. 20
  65214. ${position.y}
  65215. 30
  65216. ${position.z}
  65217. 40
  65218. 1.0
  65219. `;
  65220. return dxfSection;
  65221. }
  65222. static measurementPolylineSection (measurement) {
  65223. // bit code for polygons/polylines:
  65224. // https://www.autodesk.com/techpubs/autocad/acad2000/dxf/polyline_dxf_06.htm
  65225. let geomCode = 8;
  65226. if (measurement.closed) {
  65227. geomCode += 1;
  65228. }
  65229. let dxfSection = `0
  65230. POLYLINE
  65231. 8
  65232. layer_polyline
  65233. 62
  65234. 1
  65235. 66
  65236. 1
  65237. 10
  65238. 0.0
  65239. 20
  65240. 0.0
  65241. 30
  65242. 0.0
  65243. 70
  65244. ${geomCode}
  65245. `;
  65246. let xMax = 0.0;
  65247. let yMax = 0.0;
  65248. let zMax = 0.0;
  65249. for (let point of measurement.points) {
  65250. point = point.position;
  65251. xMax = Math.max(xMax, point.x);
  65252. yMax = Math.max(yMax, point.y);
  65253. zMax = Math.max(zMax, point.z);
  65254. dxfSection += `0
  65255. VERTEX
  65256. 8
  65257. 0
  65258. 10
  65259. ${point.x}
  65260. 20
  65261. ${point.y}
  65262. 30
  65263. ${point.z}
  65264. 70
  65265. 32
  65266. `;
  65267. }
  65268. dxfSection += `0
  65269. SEQEND
  65270. `;
  65271. return dxfSection;
  65272. }
  65273. static measurementSection (measurement) {
  65274. // if(measurement.points.length <= 1){
  65275. // return "";
  65276. // }
  65277. if (measurement.points.length === 0) {
  65278. return '';
  65279. } else if (measurement.points.length === 1) {
  65280. return DXFExporter.measurementPointSection(measurement);
  65281. } else if (measurement.points.length >= 2) {
  65282. return DXFExporter.measurementPolylineSection(measurement);
  65283. }
  65284. }
  65285. static toString(measurements){
  65286. if (!(measurements instanceof Array)) {
  65287. measurements = [measurements];
  65288. }
  65289. measurements = measurements.filter(m => m instanceof Measure);
  65290. let points = measurements.filter(m => (m instanceof Measure))
  65291. .map(m => m.points)
  65292. .reduce((a, v) => a.concat(v))
  65293. .map(p => p.position);
  65294. let min = new Vector3(Infinity, Infinity, Infinity);
  65295. let max = new Vector3(-Infinity, -Infinity, -Infinity);
  65296. for (let point of points) {
  65297. min.min(point);
  65298. max.max(point);
  65299. }
  65300. let dxfHeader = `999
  65301. DXF created from potree
  65302. 0
  65303. SECTION
  65304. 2
  65305. HEADER
  65306. 9
  65307. $ACADVER
  65308. 1
  65309. AC1006
  65310. 9
  65311. $INSBASE
  65312. 10
  65313. 0.0
  65314. 20
  65315. 0.0
  65316. 30
  65317. 0.0
  65318. 9
  65319. $EXTMIN
  65320. 10
  65321. ${min.x}
  65322. 20
  65323. ${min.y}
  65324. 30
  65325. ${min.z}
  65326. 9
  65327. $EXTMAX
  65328. 10
  65329. ${max.x}
  65330. 20
  65331. ${max.y}
  65332. 30
  65333. ${max.z}
  65334. 0
  65335. ENDSEC
  65336. `;
  65337. let dxfBody = `0
  65338. SECTION
  65339. 2
  65340. ENTITIES
  65341. `;
  65342. for (let measurement of measurements) {
  65343. dxfBody += DXFExporter.measurementSection(measurement);
  65344. }
  65345. dxfBody += `0
  65346. ENDSEC
  65347. `;
  65348. let dxf = dxfHeader + dxfBody + '0\nEOF';
  65349. return dxf;
  65350. }
  65351. }
  65352. class MeasurePanel{
  65353. constructor(viewer, measurement, propertiesPanel){
  65354. this.viewer = viewer;
  65355. this.measurement = measurement;
  65356. this.propertiesPanel = propertiesPanel;
  65357. this._update = () => { this.update(); };
  65358. }
  65359. createCoordinatesTable(points){
  65360. let table = $(`
  65361. <table class="measurement_value_table">
  65362. <tr>
  65363. <th>x</th>
  65364. <th>y</th>
  65365. <th>z</th>
  65366. <th></th>
  65367. </tr>
  65368. </table>
  65369. `);
  65370. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  65371. for (let point of points) {
  65372. let x = Utils.addCommas(point.x.toFixed(3));
  65373. let y = Utils.addCommas(point.y.toFixed(3));
  65374. let z = Utils.addCommas(point.z.toFixed(3));
  65375. let row = $(`
  65376. <tr>
  65377. <td><span>${x}</span></td>
  65378. <td><span>${y}</span></td>
  65379. <td><span>${z}</span></td>
  65380. <td align="right" style="width: 25%">
  65381. <img name="copy" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65382. </td>
  65383. </tr>
  65384. `);
  65385. this.elCopy = row.find("img[name=copy]");
  65386. this.elCopy.click( () => {
  65387. let msg = point.toArray().map(c => c.toFixed(3)).join(", ");
  65388. Utils.clipboardCopy(msg);
  65389. this.viewer.postMessage(
  65390. `Copied value to clipboard: <br>'${msg}'`,
  65391. {duration: 3000});
  65392. });
  65393. table.append(row);
  65394. }
  65395. return table;
  65396. };
  65397. createAttributesTable(){
  65398. let elTable = $('<table class="measurement_value_table"></table>');
  65399. let point = this.measurement.points[0];
  65400. /* for(let attributeName of Object.keys(point)){
  65401. if(attributeName === "position"){
  65402. }else if(attributeName === "rgba"){
  65403. let color = point.rgba;
  65404. let text = color.join(', ');
  65405. elTable.append($(`
  65406. <tr>
  65407. <td>rgb</td>
  65408. <td>${text}</td>
  65409. </tr>
  65410. `));
  65411. }else{
  65412. let value = point[attributeName];
  65413. let text = value.join(', ');
  65414. elTable.append($(`
  65415. <tr>
  65416. <td>${attributeName}</td>
  65417. <td>${text}</td>
  65418. </tr>
  65419. `));
  65420. }
  65421. } */
  65422. return elTable;
  65423. }
  65424. update(){
  65425. }
  65426. };
  65427. class DistancePanel extends MeasurePanel{
  65428. constructor(viewer, measurement, propertiesPanel){
  65429. super(viewer, measurement, propertiesPanel);
  65430. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65431. this.elContent = $(`
  65432. <div class="measurement_content selectable">
  65433. <span class="coordinates_table_container"></span>
  65434. <br>
  65435. <table id="distances_table" class="measurement_value_table"></table>
  65436. <!-- ACTIONS -->
  65437. <div style="display: flex; margin-top: 12px">
  65438. <span>
  65439. <input type="button" name="make_profile" value="profile from measure" />
  65440. </span>
  65441. <span style="flex-grow: 1"></span>
  65442. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65443. </div>
  65444. </div>
  65445. `);
  65446. this.elRemove = this.elContent.find("img[name=remove]");
  65447. this.elRemove.click( () => {
  65448. this.viewer.scene.removeMeasurement(measurement);
  65449. });
  65450. this.elMakeProfile = this.elContent.find("input[name=make_profile]");
  65451. this.elMakeProfile.click( () => {
  65452. //measurement.points;
  65453. const profile = new Profile();
  65454. profile.name = measurement.name;
  65455. profile.width = measurement.getTotalDistance() / 50;
  65456. for(const point of measurement.points){
  65457. profile.addMarker(point.position.clone());
  65458. }
  65459. this.viewer.scene.addProfile(profile);
  65460. });
  65461. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65462. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65463. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65464. this.update();
  65465. }
  65466. update(){
  65467. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65468. elCoordiantesContainer.empty();
  65469. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65470. let positions = this.measurement.points;
  65471. let distances = [];
  65472. for (let i = 0; i < positions.length - 1; i++) {
  65473. let d = positions[i].distanceTo(positions[i + 1]);
  65474. distances.push(d.toFixed(3));
  65475. }
  65476. let totalDistance = this.measurement.getTotalDistance().toFixed(3);
  65477. let elDistanceTable = this.elContent.find(`#distances_table`);
  65478. elDistanceTable.empty();
  65479. for (let i = 0; i < distances.length; i++) {
  65480. let label = (i === 0) ? 'Distances: ' : '';
  65481. let distance = distances[i];
  65482. let elDistance = $(`
  65483. <tr>
  65484. <th>${label}</th>
  65485. <td style="width: 100%; padding-left: 10px">${distance}</td>
  65486. </tr>`);
  65487. elDistanceTable.append(elDistance);
  65488. }
  65489. let elTotal = $(`
  65490. <tr>
  65491. <th>Total: </td><td style="width: 100%; padding-left: 10px">${totalDistance}</th>
  65492. </tr>`);
  65493. elDistanceTable.append(elTotal);
  65494. }
  65495. };
  65496. class PointPanel extends MeasurePanel{
  65497. constructor(viewer, measurement, propertiesPanel){
  65498. super(viewer, measurement, propertiesPanel);
  65499. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65500. this.elContent = $(`
  65501. <div class="measurement_content selectable">
  65502. <span class="coordinates_table_container"></span>
  65503. <br>
  65504. <span class="attributes_table_container"></span>
  65505. <!-- ACTIONS -->
  65506. <div style="display: flex; margin-top: 12px">
  65507. <span></span>
  65508. <span style="flex-grow: 1"></span>
  65509. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65510. </div>
  65511. </div>
  65512. `);
  65513. this.elRemove = this.elContent.find("img[name=remove]");
  65514. this.elRemove.click( () => {
  65515. this.viewer.scene.removeMeasurement(measurement);
  65516. });
  65517. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65518. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65519. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65520. this.update();
  65521. }
  65522. update(){
  65523. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65524. elCoordiantesContainer.empty();
  65525. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65526. let elAttributesContainer = this.elContent.find('.attributes_table_container');
  65527. elAttributesContainer.empty();
  65528. elAttributesContainer.append(this.createAttributesTable());
  65529. }
  65530. };
  65531. class AreaPanel extends MeasurePanel{
  65532. constructor(viewer, measurement, propertiesPanel){
  65533. super(viewer, measurement, propertiesPanel);
  65534. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65535. this.elContent = $(`
  65536. <div class="measurement_content selectable">
  65537. <span class="coordinates_table_container"></span>
  65538. <br>
  65539. <span style="font-weight: bold">Area: </span>
  65540. <span id="measurement_area"></span>
  65541. <!-- ACTIONS -->
  65542. <div style="display: flex; margin-top: 12px">
  65543. <span></span>
  65544. <span style="flex-grow: 1"></span>
  65545. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65546. </div>
  65547. </div>
  65548. `);
  65549. this.elRemove = this.elContent.find("img[name=remove]");
  65550. this.elRemove.click( () => {
  65551. this.viewer.scene.removeMeasurement(measurement);
  65552. });
  65553. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65554. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65555. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65556. this.update();
  65557. }
  65558. update(){
  65559. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65560. elCoordiantesContainer.empty();
  65561. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65562. let elArea = this.elContent.find(`#measurement_area`);
  65563. elArea.html(this.measurement.area.value.toFixed(3));
  65564. }
  65565. };
  65566. class AnglePanel extends MeasurePanel{
  65567. constructor(viewer, measurement, propertiesPanel){
  65568. super(viewer, measurement, propertiesPanel);
  65569. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65570. this.elContent = $(`
  65571. <div class="measurement_content selectable">
  65572. <span class="coordinates_table_container"></span>
  65573. <br>
  65574. <table class="measurement_value_table">
  65575. <tr>
  65576. <th>\u03b1</th>
  65577. <th>\u03b2</th>
  65578. <th>\u03b3</th>
  65579. </tr>
  65580. <tr>
  65581. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  65582. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  65583. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  65584. </tr>
  65585. </table>
  65586. <!-- ACTIONS -->
  65587. <div style="display: flex; margin-top: 12px">
  65588. <span></span>
  65589. <span style="flex-grow: 1"></span>
  65590. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65591. </div>
  65592. </div>
  65593. `);
  65594. this.elRemove = this.elContent.find("img[name=remove]");
  65595. this.elRemove.click( () => {
  65596. this.viewer.scene.removeMeasurement(measurement);
  65597. });
  65598. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65599. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65600. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65601. this.update();
  65602. }
  65603. update(){
  65604. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65605. elCoordiantesContainer.empty();
  65606. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65607. let angles = [];
  65608. for(let i = 0; i < this.measurement.points.length; i++){
  65609. angles.push(this.measurement.getAngle(i) * (180.0 / Math.PI));
  65610. }
  65611. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  65612. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  65613. let elBetta = this.elContent.find(`#angle_cell_betta`);
  65614. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  65615. elAlpha.html(angles[0]);
  65616. elBetta.html(angles[1]);
  65617. elGamma.html(angles[2]);
  65618. }
  65619. };
  65620. class CirclePanel extends MeasurePanel{
  65621. constructor(viewer, measurement, propertiesPanel){
  65622. super(viewer, measurement, propertiesPanel);
  65623. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65624. this.elContent = $(`
  65625. <div class="measurement_content selectable">
  65626. <span class="coordinates_table_container"></span>
  65627. <br>
  65628. <table id="infos_table" class="measurement_value_table"></table>
  65629. <!-- ACTIONS -->
  65630. <div style="display: flex; margin-top: 12px">
  65631. <span></span>
  65632. <span style="flex-grow: 1"></span>
  65633. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65634. </div>
  65635. </div>
  65636. `);
  65637. this.elRemove = this.elContent.find("img[name=remove]");
  65638. this.elRemove.click( () => {
  65639. this.viewer.scene.removeMeasurement(measurement);
  65640. });
  65641. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65642. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65643. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65644. this.update();
  65645. }
  65646. update(){
  65647. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65648. elCoordiantesContainer.empty();
  65649. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65650. const elInfos = this.elContent.find(`#infos_table`);
  65651. if(this.measurement.points.length !== 3){
  65652. elInfos.empty();
  65653. return;
  65654. }
  65655. const A = this.measurement.points[0].position;
  65656. const B = this.measurement.points[1].position;
  65657. const C = this.measurement.points[2].position;
  65658. const center = Potree.Utils.computeCircleCenter(A, B, C);
  65659. const radius = center.distanceTo(A);
  65660. const circumference = 2 * Math.PI * radius;
  65661. const format = (number) => {
  65662. return Potree.Utils.addCommas(number.toFixed(3));
  65663. };
  65664. const txtCenter = `${format(center.x)} ${format(center.y)} ${format(center.z)}`;
  65665. const txtRadius = format(radius);
  65666. const txtCircumference = format(circumference);
  65667. const thStyle = `style="text-align: left"`;
  65668. const tdStyle = `style="width: 100%; padding: 5px;"`;
  65669. elInfos.html(`
  65670. <tr>
  65671. <th ${thStyle}>Center: </th>
  65672. <td ${tdStyle}></td>
  65673. </tr>
  65674. <tr>
  65675. <td ${tdStyle} colspan="2">
  65676. ${txtCenter}
  65677. </td>
  65678. </tr>
  65679. <tr>
  65680. <th ${thStyle}>Radius: </th>
  65681. <td ${tdStyle}>${txtRadius}</td>
  65682. </tr>
  65683. <tr>
  65684. <th ${thStyle}>Circumference: </th>
  65685. <td ${tdStyle}>${txtCircumference}</td>
  65686. </tr>
  65687. `);
  65688. }
  65689. };
  65690. class HeightPanel extends MeasurePanel{
  65691. constructor(viewer, measurement, propertiesPanel){
  65692. super(viewer, measurement, propertiesPanel);
  65693. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65694. this.elContent = $(`
  65695. <div class="measurement_content selectable">
  65696. <span class="coordinates_table_container"></span>
  65697. <br>
  65698. <span id="height_label">Height: </span><br>
  65699. <!-- ACTIONS -->
  65700. <div style="display: flex; margin-top: 12px">
  65701. <span></span>
  65702. <span style="flex-grow: 1"></span>
  65703. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65704. </div>
  65705. </div>
  65706. `);
  65707. this.elRemove = this.elContent.find("img[name=remove]");
  65708. this.elRemove.click( () => {
  65709. this.viewer.scene.removeMeasurement(measurement);
  65710. });
  65711. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65712. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65713. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65714. this.update();
  65715. }
  65716. update(){
  65717. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65718. elCoordiantesContainer.empty();
  65719. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65720. {
  65721. let points = this.measurement.points;
  65722. let sorted = points.slice().sort((a, b) => a.position.z - b.position.z);
  65723. let lowPoint = sorted[0].position.clone();
  65724. let highPoint = sorted[sorted.length - 1].position.clone();
  65725. let min = lowPoint.z;
  65726. let max = highPoint.z;
  65727. let height = max - min;
  65728. height = height.toFixed(3);
  65729. this.elHeightLabel = this.elContent.find(`#height_label`);
  65730. this.elHeightLabel.html(`<b>Height:</b> ${height}`);
  65731. }
  65732. }
  65733. };
  65734. class VolumePanel extends MeasurePanel{
  65735. constructor(viewer, measurement, propertiesPanel){
  65736. super(viewer, measurement, propertiesPanel);
  65737. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  65738. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65739. let lblLengthText = new Map([
  65740. [BoxVolume, "length"],
  65741. [SphereVolume, "rx"],
  65742. ]).get(measurement.constructor);
  65743. let lblWidthText = new Map([
  65744. [BoxVolume, "width"],
  65745. [SphereVolume, "ry"],
  65746. ]).get(measurement.constructor);
  65747. let lblHeightText = new Map([
  65748. [BoxVolume, "height"],
  65749. [SphereVolume, "rz"],
  65750. ]).get(measurement.constructor);
  65751. this.elContent = $(`
  65752. <div class="measurement_content selectable">
  65753. <span class="coordinates_table_container"></span>
  65754. <table class="measurement_value_table">
  65755. <tr>
  65756. <th>\u03b1</th>
  65757. <th>\u03b2</th>
  65758. <th>\u03b3</th>
  65759. <th></th>
  65760. </tr>
  65761. <tr>
  65762. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  65763. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  65764. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  65765. <td align="right" style="width: 25%">
  65766. <img name="copyRotation" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65767. </td>
  65768. </tr>
  65769. </table>
  65770. <table class="measurement_value_table">
  65771. <tr>
  65772. <th>${lblLengthText}</th>
  65773. <th>${lblWidthText}</th>
  65774. <th>${lblHeightText}</th>
  65775. <th></th>
  65776. </tr>
  65777. <tr>
  65778. <td align="center" id="cell_length" style="width: 33%"></td>
  65779. <td align="center" id="cell_width" style="width: 33%"></td>
  65780. <td align="center" id="cell_height" style="width: 33%"></td>
  65781. <td align="right" style="width: 25%">
  65782. <img name="copyScale" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65783. </td>
  65784. </tr>
  65785. </table>
  65786. <br>
  65787. <span style="font-weight: bold">Volume: </span>
  65788. <span id="measurement_volume"></span>
  65789. <!--
  65790. <li>
  65791. <label style="whitespace: nowrap">
  65792. <input id="volume_show" type="checkbox"/>
  65793. <span>show volume</span>
  65794. </label>
  65795. </li>-->
  65796. <li>
  65797. <label style="whitespace: nowrap">
  65798. <input id="volume_clip" type="checkbox"/>
  65799. <span>make clip volume</span>
  65800. </label>
  65801. </li>
  65802. <li style="margin-top: 10px">
  65803. <input name="download_volume" type="button" value="prepare download" style="width: 100%" />
  65804. <div name="download_message"></div>
  65805. </li>
  65806. <!-- ACTIONS -->
  65807. <li style="display: grid; grid-template-columns: auto auto; grid-column-gap: 5px; margin-top: 10px">
  65808. <input id="volume_reset_orientation" type="button" value="reset orientation"/>
  65809. <input id="volume_make_uniform" type="button" value="make uniform"/>
  65810. </li>
  65811. <div style="display: flex; margin-top: 12px">
  65812. <span></span>
  65813. <span style="flex-grow: 1"></span>
  65814. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65815. </div>
  65816. </div>
  65817. `);
  65818. { // download
  65819. this.elDownloadButton = this.elContent.find("input[name=download_volume]");
  65820. if(this.propertiesPanel.viewer.server){
  65821. this.elDownloadButton.click(() => this.download());
  65822. } else {
  65823. this.elDownloadButton.hide();
  65824. }
  65825. }
  65826. this.elCopyRotation = this.elContent.find("img[name=copyRotation]");
  65827. this.elCopyRotation.click( () => {
  65828. let rotation = this.measurement.rotation.toArray().slice(0, 3);
  65829. let msg = rotation.map(c => c.toFixed(3)).join(", ");
  65830. Utils.clipboardCopy(msg);
  65831. this.viewer.postMessage(
  65832. `Copied value to clipboard: <br>'${msg}'`,
  65833. {duration: 3000});
  65834. });
  65835. this.elCopyScale = this.elContent.find("img[name=copyScale]");
  65836. this.elCopyScale.click( () => {
  65837. let scale = this.measurement.scale.toArray();
  65838. let msg = scale.map(c => c.toFixed(3)).join(", ");
  65839. Utils.clipboardCopy(msg);
  65840. this.viewer.postMessage(
  65841. `Copied value to clipboard: <br>'${msg}'`,
  65842. {duration: 3000});
  65843. });
  65844. this.elRemove = this.elContent.find("img[name=remove]");
  65845. this.elRemove.click( () => {
  65846. this.viewer.scene.removeVolume(measurement);
  65847. });
  65848. this.elContent.find("#volume_reset_orientation").click(() => {
  65849. measurement.rotation.set(0, 0, 0);
  65850. });
  65851. this.elContent.find("#volume_make_uniform").click(() => {
  65852. let mean = (measurement.scale.x + measurement.scale.y + measurement.scale.z) / 3;
  65853. measurement.scale.set(mean, mean, mean);
  65854. });
  65855. this.elCheckClip = this.elContent.find('#volume_clip');
  65856. this.elCheckClip.click(event => {
  65857. this.measurement.clip = event.target.checked;
  65858. });
  65859. this.elCheckShow = this.elContent.find('#volume_show');
  65860. this.elCheckShow.click(event => {
  65861. this.measurement.visible = event.target.checked;
  65862. });
  65863. this.propertiesPanel.addVolatileListener(measurement, "position_changed", this._update);
  65864. this.propertiesPanel.addVolatileListener(measurement, "orientation_changed", this._update);
  65865. this.propertiesPanel.addVolatileListener(measurement, "scale_changed", this._update);
  65866. this.propertiesPanel.addVolatileListener(measurement, "clip_changed", this._update);
  65867. this.update();
  65868. }
  65869. async download(){
  65870. let clipBox = this.measurement;
  65871. let regions = [];
  65872. //for(let clipBox of boxes){
  65873. {
  65874. let toClip = clipBox.matrixWorld;
  65875. let px = new Vector3(+0.5, 0, 0).applyMatrix4(toClip);
  65876. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(toClip);
  65877. let py = new Vector3(0, +0.5, 0).applyMatrix4(toClip);
  65878. let ny = new Vector3(0, -0.5, 0).applyMatrix4(toClip);
  65879. let pz = new Vector3(0, 0, +0.5).applyMatrix4(toClip);
  65880. let nz = new Vector3(0, 0, -0.5).applyMatrix4(toClip);
  65881. let pxN = new Vector3().subVectors(nx, px).normalize();
  65882. let nxN = pxN.clone().multiplyScalar(-1);
  65883. let pyN = new Vector3().subVectors(ny, py).normalize();
  65884. let nyN = pyN.clone().multiplyScalar(-1);
  65885. let pzN = new Vector3().subVectors(nz, pz).normalize();
  65886. let nzN = pzN.clone().multiplyScalar(-1);
  65887. let planes = [
  65888. new Plane().setFromNormalAndCoplanarPoint(pxN, px),
  65889. new Plane().setFromNormalAndCoplanarPoint(nxN, nx),
  65890. new Plane().setFromNormalAndCoplanarPoint(pyN, py),
  65891. new Plane().setFromNormalAndCoplanarPoint(nyN, ny),
  65892. new Plane().setFromNormalAndCoplanarPoint(pzN, pz),
  65893. new Plane().setFromNormalAndCoplanarPoint(nzN, nz),
  65894. ];
  65895. let planeQueryParts = [];
  65896. for(let plane of planes){
  65897. let part = [plane.normal.toArray(), plane.constant].join(",");
  65898. part = `[${part}]`;
  65899. planeQueryParts.push(part);
  65900. }
  65901. let region = "[" + planeQueryParts.join(",") + "]";
  65902. regions.push(region);
  65903. }
  65904. let regionsArg = regions.join(",");
  65905. let pointcloudArgs = [];
  65906. for(let pointcloud of this.viewer.scene.pointclouds){
  65907. if(!pointcloud.visible){
  65908. continue;
  65909. }
  65910. let offset = pointcloud.pcoGeometry.offset.clone();
  65911. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  65912. let matrixWorld = pointcloud.matrixWorld;
  65913. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  65914. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  65915. let arg = {
  65916. path: path,
  65917. transform: transform.elements,
  65918. };
  65919. let argString = JSON.stringify(arg);
  65920. pointcloudArgs.push(argString);
  65921. }
  65922. let pointcloudsArg = pointcloudArgs.join(",");
  65923. let elMessage = this.elContent.find("div[name=download_message]");
  65924. let error = (message) => {
  65925. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  65926. };
  65927. let info = (message) => {
  65928. elMessage.html(`${message}`);
  65929. };
  65930. let handle = null;
  65931. { // START FILTER
  65932. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  65933. //console.log(url);
  65934. info("estimating results ...");
  65935. let response = await fetch(url);
  65936. let jsResponse = await response.json();
  65937. //console.log(jsResponse);
  65938. if(!jsResponse.handle){
  65939. error(jsResponse.message);
  65940. return;
  65941. }else {
  65942. handle = jsResponse.handle;
  65943. }
  65944. }
  65945. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  65946. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  65947. let sleep = (function(duration){
  65948. return new Promise( (res, rej) => {
  65949. setTimeout(() => {
  65950. res();
  65951. }, duration);
  65952. });
  65953. });
  65954. let handleFiltering = (jsResponse) => {
  65955. let {progress, estimate} = jsResponse;
  65956. let progressFract = progress["processed points"] / estimate.points;
  65957. let progressPercents = parseInt(progressFract * 100);
  65958. info(`progress: ${progressPercents}%`);
  65959. };
  65960. let handleFinish = (jsResponse) => {
  65961. let message = "downloads ready: <br>";
  65962. message += "<ul>";
  65963. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  65964. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  65965. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  65966. }
  65967. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  65968. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  65969. message += "</ul>";
  65970. info(message);
  65971. };
  65972. let handleUnexpected = (jsResponse) => {
  65973. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  65974. info(message);
  65975. };
  65976. let handleError = (jsResponse) => {
  65977. let message = `ERROR: ${jsResponse.message}`;
  65978. error(message);
  65979. throw new Error(message);
  65980. };
  65981. let start = Date.now();
  65982. while(true){
  65983. let response = await fetch(url);
  65984. let jsResponse = await response.json();
  65985. if(jsResponse.status === "ERROR"){
  65986. handleError(jsResponse);
  65987. }else if(jsResponse.status === "FILTERING"){
  65988. handleFiltering(jsResponse);
  65989. }else if(jsResponse.status === "FINISHED"){
  65990. handleFinish(jsResponse);
  65991. break;
  65992. }else {
  65993. handleUnexpected(jsResponse);
  65994. }
  65995. let durationS = (Date.now() - start) / 1000;
  65996. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  65997. await sleep(sleepAmountMS);
  65998. }
  65999. }
  66000. }
  66001. update(){
  66002. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  66003. elCoordiantesContainer.empty();
  66004. elCoordiantesContainer.append(this.createCoordinatesTable([this.measurement.position]));
  66005. {
  66006. let angles = this.measurement.rotation.toVector3();
  66007. angles = angles.toArray();
  66008. //angles = [angles.z, angles.x, angles.y];
  66009. angles = angles.map(v => 180 * v / Math.PI);
  66010. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  66011. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  66012. let elBetta = this.elContent.find(`#angle_cell_betta`);
  66013. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  66014. elAlpha.html(angles[0]);
  66015. elBetta.html(angles[1]);
  66016. elGamma.html(angles[2]);
  66017. }
  66018. {
  66019. let dimensions = this.measurement.scale.toArray();
  66020. dimensions = dimensions.map(v => Utils.addCommas(v.toFixed(2)));
  66021. let elLength = this.elContent.find(`#cell_length`);
  66022. let elWidth = this.elContent.find(`#cell_width`);
  66023. let elHeight = this.elContent.find(`#cell_height`);
  66024. elLength.html(dimensions[0]);
  66025. elWidth.html(dimensions[1]);
  66026. elHeight.html(dimensions[2]);
  66027. }
  66028. {
  66029. let elVolume = this.elContent.find(`#measurement_volume`);
  66030. let volume = this.measurement.getVolume();
  66031. elVolume.html(Utils.addCommas(volume.toFixed(2)));
  66032. }
  66033. this.elCheckClip.prop("checked", this.measurement.clip);
  66034. this.elCheckShow.prop("checked", this.measurement.visible);
  66035. }
  66036. };
  66037. class ProfilePanel extends MeasurePanel{
  66038. constructor(viewer, measurement, propertiesPanel){
  66039. super(viewer, measurement, propertiesPanel);
  66040. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  66041. this.elContent = $(`
  66042. <div class="measurement_content selectable">
  66043. <span class="coordinates_table_container"></span>
  66044. <br>
  66045. <span style="display:flex">
  66046. <span style="display:flex; align-items: center; padding-right: 10px">Width: </span>
  66047. <input id="sldProfileWidth" name="sldProfileWidth" value="5.06" style="flex-grow: 1; width:100%">
  66048. </span>
  66049. <br>
  66050. <li style="margin-top: 10px">
  66051. <input name="download_profile" type="button" value="prepare download" style="width: 100%" />
  66052. <div name="download_message"></div>
  66053. </li>
  66054. <br>
  66055. <input type="button" id="show_2d_profile" value="show 2d profile" style="width: 100%"/>
  66056. <!-- ACTIONS -->
  66057. <div style="display: flex; margin-top: 12px">
  66058. <span></span>
  66059. <span style="flex-grow: 1"></span>
  66060. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  66061. </div>
  66062. </div>
  66063. `);
  66064. this.elRemove = this.elContent.find("img[name=remove]");
  66065. this.elRemove.click( () => {
  66066. this.viewer.scene.removeProfile(measurement);
  66067. });
  66068. { // download
  66069. this.elDownloadButton = this.elContent.find(`input[name=download_profile]`);
  66070. if(this.propertiesPanel.viewer.server){
  66071. this.elDownloadButton.click(() => this.download());
  66072. } else {
  66073. this.elDownloadButton.hide();
  66074. }
  66075. }
  66076. { // width spinner
  66077. let elWidthSlider = this.elContent.find(`#sldProfileWidth`);
  66078. elWidthSlider.spinner({
  66079. min: 0, max: 10 * 1000 * 1000, step: 0.01,
  66080. numberFormat: 'n',
  66081. start: () => {},
  66082. spin: (event, ui) => {
  66083. let value = elWidthSlider.spinner('value');
  66084. measurement.setWidth(value);
  66085. },
  66086. change: (event, ui) => {
  66087. let value = elWidthSlider.spinner('value');
  66088. measurement.setWidth(value);
  66089. },
  66090. stop: (event, ui) => {
  66091. let value = elWidthSlider.spinner('value');
  66092. measurement.setWidth(value);
  66093. },
  66094. incremental: (count) => {
  66095. let value = elWidthSlider.spinner('value');
  66096. let step = elWidthSlider.spinner('option', 'step');
  66097. let delta = value * 0.05;
  66098. let increments = Math.max(1, parseInt(delta / step));
  66099. return increments;
  66100. }
  66101. });
  66102. elWidthSlider.spinner('value', measurement.getWidth());
  66103. elWidthSlider.spinner('widget').css('width', '100%');
  66104. let widthListener = (event) => {
  66105. let value = elWidthSlider.spinner('value');
  66106. if (value !== measurement.getWidth()) {
  66107. elWidthSlider.spinner('value', measurement.getWidth());
  66108. }
  66109. };
  66110. this.propertiesPanel.addVolatileListener(measurement, "width_changed", widthListener);
  66111. }
  66112. let elShow2DProfile = this.elContent.find(`#show_2d_profile`);
  66113. elShow2DProfile.click(() => {
  66114. this.propertiesPanel.viewer.profileWindow.show();
  66115. this.propertiesPanel.viewer.profileWindowController.setProfile(measurement);
  66116. });
  66117. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  66118. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  66119. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  66120. this.update();
  66121. }
  66122. update(){
  66123. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  66124. elCoordiantesContainer.empty();
  66125. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  66126. }
  66127. async download(){
  66128. let profile = this.measurement;
  66129. let regions = [];
  66130. {
  66131. let segments = profile.getSegments();
  66132. let width = profile.width;
  66133. for(let segment of segments){
  66134. let start = segment.start.clone().multiply(new Vector3(1, 1, 0));
  66135. let end = segment.end.clone().multiply(new Vector3(1, 1, 0));
  66136. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  66137. let startEndDir = new Vector3().subVectors(end, start).normalize();
  66138. let endStartDir = new Vector3().subVectors(start, end).normalize();
  66139. let upDir = new Vector3(0, 0, 1);
  66140. let rightDir = new Vector3().crossVectors(startEndDir, upDir);
  66141. let leftDir = new Vector3().crossVectors(endStartDir, upDir);
  66142. console.log(leftDir);
  66143. let right = rightDir.clone().multiplyScalar(width * 0.5).add(center);
  66144. let left = leftDir.clone().multiplyScalar(width * 0.5).add(center);
  66145. let planes = [
  66146. new Plane().setFromNormalAndCoplanarPoint(startEndDir, start),
  66147. new Plane().setFromNormalAndCoplanarPoint(endStartDir, end),
  66148. new Plane().setFromNormalAndCoplanarPoint(leftDir, right),
  66149. new Plane().setFromNormalAndCoplanarPoint(rightDir, left),
  66150. ];
  66151. let planeQueryParts = [];
  66152. for(let plane of planes){
  66153. let part = [plane.normal.toArray(), plane.constant].join(",");
  66154. part = `[${part}]`;
  66155. planeQueryParts.push(part);
  66156. }
  66157. let region = "[" + planeQueryParts.join(",") + "]";
  66158. regions.push(region);
  66159. }
  66160. }
  66161. let regionsArg = regions.join(",");
  66162. let pointcloudArgs = [];
  66163. for(let pointcloud of this.viewer.scene.pointclouds){
  66164. if(!pointcloud.visible){
  66165. continue;
  66166. }
  66167. let offset = pointcloud.pcoGeometry.offset.clone();
  66168. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  66169. let matrixWorld = pointcloud.matrixWorld;
  66170. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  66171. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  66172. let arg = {
  66173. path: path,
  66174. transform: transform.elements,
  66175. };
  66176. let argString = JSON.stringify(arg);
  66177. pointcloudArgs.push(argString);
  66178. }
  66179. let pointcloudsArg = pointcloudArgs.join(",");
  66180. let elMessage = this.elContent.find("div[name=download_message]");
  66181. let error = (message) => {
  66182. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  66183. };
  66184. let info = (message) => {
  66185. elMessage.html(`${message}`);
  66186. };
  66187. let handle = null;
  66188. { // START FILTER
  66189. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  66190. //console.log(url);
  66191. info("estimating results ...");
  66192. let response = await fetch(url);
  66193. let jsResponse = await response.json();
  66194. //console.log(jsResponse);
  66195. if(!jsResponse.handle){
  66196. error(jsResponse.message);
  66197. return;
  66198. }else {
  66199. handle = jsResponse.handle;
  66200. }
  66201. }
  66202. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  66203. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  66204. let sleep = (function(duration){
  66205. return new Promise( (res, rej) => {
  66206. setTimeout(() => {
  66207. res();
  66208. }, duration);
  66209. });
  66210. });
  66211. let handleFiltering = (jsResponse) => {
  66212. let {progress, estimate} = jsResponse;
  66213. let progressFract = progress["processed points"] / estimate.points;
  66214. let progressPercents = parseInt(progressFract * 100);
  66215. info(`progress: ${progressPercents}%`);
  66216. };
  66217. let handleFinish = (jsResponse) => {
  66218. let message = "downloads ready: <br>";
  66219. message += "<ul>";
  66220. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  66221. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  66222. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  66223. }
  66224. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  66225. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  66226. message += "</ul>";
  66227. info(message);
  66228. };
  66229. let handleUnexpected = (jsResponse) => {
  66230. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  66231. info(message);
  66232. };
  66233. let handleError = (jsResponse) => {
  66234. let message = `ERROR: ${jsResponse.message}`;
  66235. error(message);
  66236. throw new Error(message);
  66237. };
  66238. let start = Date.now();
  66239. while(true){
  66240. let response = await fetch(url);
  66241. let jsResponse = await response.json();
  66242. if(jsResponse.status === "ERROR"){
  66243. handleError(jsResponse);
  66244. }else if(jsResponse.status === "FILTERING"){
  66245. handleFiltering(jsResponse);
  66246. }else if(jsResponse.status === "FINISHED"){
  66247. handleFinish(jsResponse);
  66248. break;
  66249. }else {
  66250. handleUnexpected(jsResponse);
  66251. }
  66252. let durationS = (Date.now() - start) / 1000;
  66253. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  66254. await sleep(sleepAmountMS);
  66255. }
  66256. }
  66257. }
  66258. };
  66259. class CameraPanel{
  66260. constructor(viewer, propertiesPanel){
  66261. this.viewer = viewer;
  66262. this.propertiesPanel = propertiesPanel;
  66263. this._update = () => { this.update(); };
  66264. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  66265. this.elContent = $(`
  66266. <div class="propertypanel_content">
  66267. <table>
  66268. <tr>
  66269. <th colspan="3">position</th>
  66270. <th></th>
  66271. </tr>
  66272. <tr>
  66273. <td align="center" id="camera_position_x" style="width: 25%"></td>
  66274. <td align="center" id="camera_position_y" style="width: 25%"></td>
  66275. <td align="center" id="camera_position_z" style="width: 25%"></td>
  66276. <td align="right" id="copy_camera_position" style="width: 25%">
  66277. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66278. </td>
  66279. </tr>
  66280. <tr>
  66281. <th colspan="3">target</th>
  66282. <th></th>
  66283. </tr>
  66284. <tr>
  66285. <td align="center" id="camera_target_x" style="width: 25%"></td>
  66286. <td align="center" id="camera_target_y" style="width: 25%"></td>
  66287. <td align="center" id="camera_target_z" style="width: 25%"></td>
  66288. <td align="right" id="copy_camera_target" style="width: 25%">
  66289. <img name="copyTarget" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66290. </td>
  66291. </tr>
  66292. </table>
  66293. </div>
  66294. `);
  66295. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  66296. this.elCopyPosition.click( () => {
  66297. let pos = this.viewer.scene.getActiveCamera().position.toArray();
  66298. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66299. Utils.clipboardCopy(msg);
  66300. this.viewer.postMessage(
  66301. `Copied value to clipboard: <br>'${msg}'`,
  66302. {duration: 3000});
  66303. });
  66304. this.elCopyTarget = this.elContent.find("img[name=copyTarget]");
  66305. this.elCopyTarget.click( () => {
  66306. let pos = this.viewer.scene.view.getPivot().toArray();
  66307. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66308. Utils.clipboardCopy(msg);
  66309. this.viewer.postMessage(
  66310. `Copied value to clipboard: <br>'${msg}'`,
  66311. {duration: 3000});
  66312. });
  66313. this.propertiesPanel.addVolatileListener(viewer, "camera_changed", this._update);
  66314. this.update();
  66315. }
  66316. update(){
  66317. //console.log("updating camera panel");
  66318. let camera = this.viewer.scene.getActiveCamera();
  66319. let view = this.viewer.scene.view;
  66320. let pos = camera.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66321. this.elContent.find("#camera_position_x").html(pos[0]);
  66322. this.elContent.find("#camera_position_y").html(pos[1]);
  66323. this.elContent.find("#camera_position_z").html(pos[2]);
  66324. let target = view.getPivot().toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66325. this.elContent.find("#camera_target_x").html(target[0]);
  66326. this.elContent.find("#camera_target_y").html(target[1]);
  66327. this.elContent.find("#camera_target_z").html(target[2]);
  66328. }
  66329. };
  66330. class AnnotationPanel{
  66331. constructor(viewer, propertiesPanel, annotation){
  66332. this.viewer = viewer;
  66333. this.propertiesPanel = propertiesPanel;
  66334. this.annotation = annotation;
  66335. this._update = () => { this.update(); };
  66336. let copyIconPath = `${Potree.resourcePath}/icons/copy.svg`;
  66337. this.elContent = $(`
  66338. <div class="propertypanel_content">
  66339. <table>
  66340. <tr>
  66341. <th colspan="3">position</th>
  66342. <th></th>
  66343. </tr>
  66344. <tr>
  66345. <td align="center" id="annotation_position_x" style="width: 25%"></td>
  66346. <td align="center" id="annotation_position_y" style="width: 25%"></td>
  66347. <td align="center" id="annotation_position_z" style="width: 25%"></td>
  66348. <td align="right" id="copy_annotation_position" style="width: 25%">
  66349. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66350. </td>
  66351. </tr>
  66352. </table>
  66353. <div>
  66354. <div class="heading">Title</div>
  66355. <div id="annotation_title" contenteditable="true">
  66356. Annotation Title
  66357. </div>
  66358. <div class="heading">Description</div>
  66359. <div id="annotation_description" contenteditable="true">
  66360. A longer description of this annotation.
  66361. Can be multiple lines long. TODO: the user should be able
  66362. to modify title and description.
  66363. </div>
  66364. </div>
  66365. </div>
  66366. `);
  66367. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  66368. this.elCopyPosition.click( () => {
  66369. let pos = this.annotation.position.toArray();
  66370. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66371. Utils.clipboardCopy(msg);
  66372. this.viewer.postMessage(
  66373. `Copied value to clipboard: <br>'${msg}'`,
  66374. {duration: 3000});
  66375. });
  66376. this.elTitle = this.elContent.find("#annotation_title").html(annotation.title);
  66377. this.elDescription = this.elContent.find("#annotation_description").html(annotation.description);
  66378. this.elTitle[0].addEventListener("input", () => {
  66379. const title = this.elTitle.html();
  66380. annotation.title = title;
  66381. }, false);
  66382. this.elDescription[0].addEventListener("input", () => {
  66383. const description = this.elDescription.html();
  66384. annotation.description = description;
  66385. }, false);
  66386. this.update();
  66387. }
  66388. update(){
  66389. const {annotation, elContent, elTitle, elDescription} = this;
  66390. let pos = annotation.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66391. elContent.find("#annotation_position_x").html(pos[0]);
  66392. elContent.find("#annotation_position_y").html(pos[1]);
  66393. elContent.find("#annotation_position_z").html(pos[2]);
  66394. elTitle.html(annotation.title);
  66395. elDescription.html(annotation.description);
  66396. }
  66397. };
  66398. class CameraAnimationPanel{
  66399. constructor(viewer, propertiesPanel, animation){
  66400. this.viewer = viewer;
  66401. this.propertiesPanel = propertiesPanel;
  66402. this.animation = animation;
  66403. this.elContent = $(`
  66404. <div class="propertypanel_content">
  66405. <span id="animation_keyframes"></span>
  66406. <span>
  66407. <span style="display:flex">
  66408. <span style="display:flex; align-items: center; padding-right: 10px">Duration: </span>
  66409. <input name="spnDuration" value="5.0" style="flex-grow: 1; width:100%">
  66410. </span>
  66411. <span>Time: </span><span id="lblTime"></span> <div id="sldTime"></div>
  66412. <input name="play" type="button" value="play"/>
  66413. </span>
  66414. </div>
  66415. `);
  66416. const elPlay = this.elContent.find("input[name=play]");
  66417. elPlay.click( () => {
  66418. animation.play();
  66419. });
  66420. const elSlider = this.elContent.find('#sldTime');
  66421. elSlider.slider({
  66422. value: 0,
  66423. min: 0,
  66424. max: 1,
  66425. step: 0.001,
  66426. slide: (event, ui) => {
  66427. animation.set(ui.value);
  66428. animation.updateFrustum();
  66429. }
  66430. });
  66431. let elDuration = this.elContent.find(`input[name=spnDuration]`);
  66432. elDuration.spinner({
  66433. min: 0, max: 300, step: 0.01,
  66434. numberFormat: 'n',
  66435. start: () => {},
  66436. spin: (event, ui) => {
  66437. let value = elDuration.spinner('value');
  66438. animation.setDuration(value);
  66439. },
  66440. change: (event, ui) => {
  66441. let value = elDuration.spinner('value');
  66442. animation.setDuration(value);
  66443. },
  66444. stop: (event, ui) => {
  66445. let value = elDuration.spinner('value');
  66446. animation.setDuration(value);
  66447. },
  66448. incremental: (count) => {
  66449. let value = elDuration.spinner('value');
  66450. let step = elDuration.spinner('option', 'step');
  66451. let delta = value * 0.05;
  66452. let increments = Math.max(1, parseInt(delta / step));
  66453. return increments;
  66454. }
  66455. });
  66456. elDuration.spinner('value', animation.getDuration());
  66457. elDuration.spinner('widget').css('width', '100%');
  66458. const elKeyframes = this.elContent.find("#animation_keyframes");
  66459. const updateKeyframes = () => {
  66460. elKeyframes.empty();
  66461. //let index = 0;
  66462. // <span style="flex-grow: 0;">
  66463. // <img name="add" src="${Potree.resourcePath}/icons/add.svg" style="width: 1.5em; height: 1.5em"/>
  66464. // </span>
  66465. const addNewKeyframeItem = (index) => {
  66466. let elNewKeyframe = $(`
  66467. <div style="display: flex; margin: 0.2em 0em">
  66468. <span style="flex-grow: 1"></span>
  66469. <input type="button" name="add" value="insert control point" />
  66470. <span style="flex-grow: 1"></span>
  66471. </div>
  66472. `);
  66473. const elAdd = elNewKeyframe.find("input[name=add]");
  66474. elAdd.click( () => {
  66475. animation.createControlPoint(index);
  66476. animation.changeCallback();
  66477. });
  66478. elKeyframes.append(elNewKeyframe);
  66479. };
  66480. const addKeyframeItem = (index) => {
  66481. let elKeyframe = $(`
  66482. <div style="display: flex; margin: 0.2em 0em">
  66483. <span style="flex-grow: 0;">
  66484. <img name="assign" src="${Potree.resourcePath}/icons/assign.svg" style="width: 1.5em; height: 1.5em"/>
  66485. </span>
  66486. <span style="flex-grow: 0;">
  66487. <img name="move" src="${Potree.resourcePath}/icons/circled_dot.svg" style="width: 1.5em; height: 1.5em"/>
  66488. </span>
  66489. <span style="flex-grow: 0; width: 1.5em; height: 1.5em"></span>
  66490. <span style="flex-grow: 0; font-size: 1.5em">keyframe</span>
  66491. <span style="flex-grow: 1"></span>
  66492. <span style="flex-grow: 0;">
  66493. <img name="delete" src="${Potree.resourcePath}/icons/remove.svg" style="width: 1.5em; height: 1.5em"/>
  66494. </span>
  66495. </div>
  66496. `);
  66497. const elAssign = elKeyframe.find("img[name=assign]");
  66498. const elMove = elKeyframe.find("img[name=move]");
  66499. const elDelete = elKeyframe.find("img[name=delete]");
  66500. elAssign.click( () => {
  66501. animation.posCurve.points[index].copy(viewer.scene.view.position);
  66502. animation.targetCurve.points[index].copy(viewer.scene.view.getPivot());
  66503. animation.changeCallback();
  66504. });
  66505. elMove.click( () => {
  66506. viewer.scene.view.position.copy(animation.posCurve.points[index]);
  66507. viewer.scene.view.lookAt(animation.targetCurve.points[index]);
  66508. });
  66509. elDelete.click( () => {
  66510. animation.removeControlPoint(index);
  66511. animation.changeCallback();
  66512. });
  66513. elKeyframes.append(elKeyframe);
  66514. };
  66515. let index = 0;
  66516. addNewKeyframeItem(index);
  66517. animation.posCurve.points.forEach(e=>{
  66518. addKeyframeItem(index);
  66519. index++;
  66520. addNewKeyframeItem(index);
  66521. });
  66522. };
  66523. updateKeyframes();
  66524. animation.addEventListener("controlpoint_added", updateKeyframes);
  66525. animation.addEventListener("controlpoint_removed", updateKeyframes);
  66526. // this._update = () => { this.update(); };
  66527. // this.update();
  66528. }
  66529. update(){
  66530. }
  66531. };
  66532. class PropertiesPanel{
  66533. constructor(container, viewer){
  66534. this.container = container;
  66535. this.viewer = viewer;
  66536. this.object = null;
  66537. this.cleanupTasks = [];
  66538. this.scene = null;
  66539. }
  66540. setScene(scene){
  66541. this.scene = scene;
  66542. }
  66543. set(object){
  66544. if(this.object === object){
  66545. return;
  66546. }
  66547. this.object = object;
  66548. for(let task of this.cleanupTasks){
  66549. task();
  66550. }
  66551. this.cleanupTasks = [];
  66552. this.container.empty();
  66553. if(object instanceof PointCloudTree){
  66554. this.setPointCloud(object);
  66555. }else if(object instanceof Measure || object instanceof Profile || object instanceof Volume){
  66556. this.setMeasurement(object);
  66557. }else if(object instanceof Camera){
  66558. this.setCamera(object);
  66559. }else if(object instanceof Annotation){
  66560. this.setAnnotation(object);
  66561. }else if(object instanceof CameraAnimation){
  66562. this.setCameraAnimation(object);
  66563. }
  66564. }
  66565. //
  66566. // Used for events that should be removed when the property object changes.
  66567. // This is for listening to materials, scene, point clouds, etc.
  66568. // not required for DOM listeners, since they are automatically cleared by removing the DOM subtree.
  66569. //
  66570. addVolatileListener(target, type, callback){
  66571. target.addEventListener(type, callback);
  66572. this.cleanupTasks.push(() => {
  66573. target.removeEventListener(type, callback);
  66574. });
  66575. }
  66576. setPointCloud(pointcloud){
  66577. let material = pointcloud.material;
  66578. let panel = $(`
  66579. <div class="scene_content selectable">
  66580. <ul class="pv-menu-list">
  66581. <li>
  66582. <span data-i18n="appearance.point_size"></span>:&nbsp;<span id="lblPointSize"></span> <div id="sldPointSize"></div>
  66583. </li>
  66584. <li>
  66585. <span data-i18n="appearance.min_point_size"></span>:&nbsp;<span id="lblMinPointSize"></span> <div id="sldMinPointSize"></div>
  66586. </li>
  66587. <!-- SIZE TYPE -->
  66588. <li>
  66589. <label for="optPointSizing" class="pv-select-label" data-i18n="appearance.point_size_type">Point Sizing </label>
  66590. <select id="optPointSizing" name="optPointSizing">
  66591. <option>FIXED</option>
  66592. <option>ATTENUATED</option>
  66593. <option>ADAPTIVE</option>
  66594. </select>
  66595. </li>
  66596. <!-- SHAPE -->
  66597. <li>
  66598. <label for="optShape" class="pv-select-label" data-i18n="appearance.point_shape"></label><br>
  66599. <select id="optShape" name="optShape">
  66600. <option>SQUARE</option>
  66601. <option>CIRCLE</option>
  66602. <option>PARABOLOID</option>
  66603. </select>
  66604. </li>
  66605. <li id="materials_backface_container">
  66606. <label><input id="set_backface_culling" type="checkbox" /><span data-i18n="appearance.backface_culling"></span></label>
  66607. </li>
  66608. <!-- OPACITY -->
  66609. <li><span data-i18n="appearance.point_opacity"></span>:<span id="lblOpacity"></span><div id="sldOpacity"></div></li>
  66610. <div class="divider">
  66611. <span>Attribute</span>
  66612. </div>
  66613. <li>
  66614. <select id="optMaterial" name="optMaterial"></select>
  66615. </li>
  66616. <div id="materials.composite_weight_container">
  66617. <div class="divider">
  66618. <span>Attribute Weights</span>
  66619. </div>
  66620. <li>RGB: <span id="lblWeightRGB"></span> <div id="sldWeightRGB"></div> </li>
  66621. <li>Intensity: <span id="lblWeightIntensity"></span> <div id="sldWeightIntensity"></div> </li>
  66622. <li>Elevation: <span id="lblWeightElevation"></span> <div id="sldWeightElevation"></div> </li>
  66623. <li>Classification: <span id="lblWeightClassification"></span> <div id="sldWeightClassification"></div> </li>
  66624. <li>Return Number: <span id="lblWeightReturnNumber"></span> <div id="sldWeightReturnNumber"></div> </li>
  66625. <li>Source ID: <span id="lblWeightSourceID"></span> <div id="sldWeightSourceID"></div> </li>
  66626. </div>
  66627. <div id="materials.rgb_container">
  66628. <div class="divider">
  66629. <span>RGB</span>
  66630. </div>
  66631. <li>Gamma: <span id="lblRGBGamma"></span> <div id="sldRGBGamma"></div> </li>
  66632. <li>Brightness: <span id="lblRGBBrightness"></span> <div id="sldRGBBrightness"></div> </li>
  66633. <li>Contrast: <span id="lblRGBContrast"></span> <div id="sldRGBContrast"></div> </li>
  66634. </div>
  66635. <div id="materials.extra_container">
  66636. <div class="divider">
  66637. <span>Extra Attribute</span>
  66638. </div>
  66639. <li><span data-i18n="appearance.extra_range"></span>: <span id="lblExtraRange"></span> <div id="sldExtraRange"></div></li>
  66640. <li>Gamma: <span id="lblExtraGamma"></span> <div id="sldExtraGamma"></div></li>
  66641. <li>Brightness: <span id="lblExtraBrightness"></span> <div id="sldExtraBrightness"></div></li>
  66642. <li>Contrast: <span id="lblExtraContrast"></span> <div id="sldExtraContrast"></div></li>
  66643. </div>
  66644. <div id="materials.matcap_container">
  66645. <div class="divider">
  66646. <span>MATCAP</span>
  66647. </div>
  66648. <li>
  66649. <div id="matcap_scheme_selection" style="display: flex; flex-wrap: wrap;"> </div>
  66650. </li>
  66651. </div>
  66652. <div id="materials.color_container">
  66653. <div class="divider">
  66654. <span>Color</span>
  66655. </div>
  66656. <input id="materials.color.picker" />
  66657. </div>
  66658. <div id="materials.elevation_container">
  66659. <div class="divider">
  66660. <span>Elevation</span>
  66661. </div>
  66662. <li><span data-i18n="appearance.elevation_range"></span>: <span id="lblHeightRange"></span> <div id="sldHeightRange"></div> </li>
  66663. <li>
  66664. <selectgroup id="gradient_repeat_option">
  66665. <option id="gradient_repeat_clamp" value="CLAMP">Clamp</option>
  66666. <option id="gradient_repeat_repeat" value="REPEAT">Repeat</option>
  66667. <option id="gradient_repeat_mirrored_repeat" value="MIRRORED_REPEAT">Mirrored Repeat</option>
  66668. </selectgroup>
  66669. </li>
  66670. <li>
  66671. <span>Gradient Scheme:</span>
  66672. <div id="elevation_gradient_scheme_selection" style="display: flex; padding: 1em 0em">
  66673. </div>
  66674. </li>
  66675. </div>
  66676. <div id="materials.transition_container">
  66677. <div class="divider">
  66678. <span>Transition</span>
  66679. </div>
  66680. <li>transition: <span id="lblTransition"></span> <div id="sldTransition"></div> </li>
  66681. </div>
  66682. <div id="materials.intensity_container">
  66683. <div class="divider">
  66684. <span>Intensity</span>
  66685. </div>
  66686. <li>Range: <span id="lblIntensityRange"></span> <div id="sldIntensityRange"></div> </li>
  66687. <li>Gamma: <span id="lblIntensityGamma"></span> <div id="sldIntensityGamma"></div> </li>
  66688. <li>Brightness: <span id="lblIntensityBrightness"></span> <div id="sldIntensityBrightness"></div> </li>
  66689. <li>Contrast: <span id="lblIntensityContrast"></span> <div id="sldIntensityContrast"></div> </li>
  66690. </div>
  66691. <div id="materials.gpstime_container">
  66692. <div class="divider">
  66693. <span>GPS Time</span>
  66694. </div>
  66695. </div>
  66696. <div id="materials.index_container">
  66697. <div class="divider">
  66698. <span>Indices</span>
  66699. </div>
  66700. </div>
  66701. </ul>
  66702. </div>
  66703. `);
  66704. panel.i18n();
  66705. this.container.append(panel);
  66706. { // POINT SIZE
  66707. let sldPointSize = panel.find(`#sldPointSize`);
  66708. let lblPointSize = panel.find(`#lblPointSize`);
  66709. sldPointSize.slider({
  66710. value: material.size,
  66711. min: 0,
  66712. max: 3,
  66713. step: 0.01,
  66714. slide: function (event, ui) { material.size = ui.value; }
  66715. });
  66716. let update = (e) => {
  66717. lblPointSize.html(material.size.toFixed(2));
  66718. sldPointSize.slider({value: material.size});
  66719. };
  66720. this.addVolatileListener(material, "point_size_changed", update);
  66721. update();
  66722. }
  66723. { // MINIMUM POINT SIZE
  66724. let sldMinPointSize = panel.find(`#sldMinPointSize`);
  66725. let lblMinPointSize = panel.find(`#lblMinPointSize`);
  66726. sldMinPointSize.slider({
  66727. value: material.size,
  66728. min: 0,
  66729. max: 3,
  66730. step: 0.01,
  66731. slide: function (event, ui) { material.minSize = ui.value; }
  66732. });
  66733. let update = (e) => {
  66734. lblMinPointSize.html(material.minSize.toFixed(2));
  66735. sldMinPointSize.slider({value: material.minSize});
  66736. };
  66737. this.addVolatileListener(material, "point_size_changed", update);
  66738. update();
  66739. }
  66740. { // POINT SIZING
  66741. let strSizeType = Object.keys(PointSizeType)[material.pointSizeType];
  66742. let opt = panel.find(`#optPointSizing`);
  66743. opt.selectmenu();
  66744. opt.val(strSizeType).selectmenu('refresh');
  66745. opt.selectmenu({
  66746. change: (event, ui) => {
  66747. material.pointSizeType = PointSizeType[ui.item.value];
  66748. }
  66749. });
  66750. }
  66751. { // SHAPE
  66752. let opt = panel.find(`#optShape`);
  66753. opt.selectmenu({
  66754. change: (event, ui) => {
  66755. let value = ui.item.value;
  66756. material.shape = PointShape[value];
  66757. }
  66758. });
  66759. let update = () => {
  66760. let typename = Object.keys(PointShape)[material.shape];
  66761. opt.selectmenu().val(typename).selectmenu('refresh');
  66762. };
  66763. this.addVolatileListener(material, "point_shape_changed", update);
  66764. update();
  66765. }
  66766. { // BACKFACE CULLING
  66767. let opt = panel.find(`#set_backface_culling`);
  66768. opt.click(() => {
  66769. material.backfaceCulling = opt.prop("checked");
  66770. });
  66771. let update = () => {
  66772. let value = material.backfaceCulling;
  66773. opt.prop("checked", value);
  66774. };
  66775. this.addVolatileListener(material, "backface_changed", update);
  66776. update();
  66777. let blockBackface = $('#materials_backface_container');
  66778. blockBackface.css('display', 'none');
  66779. const pointAttributes = pointcloud.pcoGeometry.pointAttributes;
  66780. const hasNormals = pointAttributes.hasNormals ? pointAttributes.hasNormals() : false;
  66781. if(hasNormals) {
  66782. blockBackface.css('display', 'block');
  66783. }
  66784. /*
  66785. opt.checkboxradio({
  66786. clicked: (event, ui) => {
  66787. // let value = ui.item.value;
  66788. let value = ui.item.checked;
  66789. console.log(value);
  66790. material.backfaceCulling = value; // $('#set_freeze').prop("checked");
  66791. }
  66792. });
  66793. */
  66794. }
  66795. { // OPACITY
  66796. let sldOpacity = panel.find(`#sldOpacity`);
  66797. let lblOpacity = panel.find(`#lblOpacity`);
  66798. sldOpacity.slider({
  66799. value: material.opacity,
  66800. min: 0,
  66801. max: 1,
  66802. step: 0.001,
  66803. slide: function (event, ui) {
  66804. material.opacity = ui.value;
  66805. }
  66806. });
  66807. let update = (e) => {
  66808. lblOpacity.html(material.opacity.toFixed(2));
  66809. sldOpacity.slider({value: material.opacity});
  66810. };
  66811. this.addVolatileListener(material, "opacity_changed", update);
  66812. update();
  66813. }
  66814. {
  66815. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  66816. let options = [];
  66817. options.push(...attributes.map(a => a.name));
  66818. const intensityIndex = options.indexOf("intensity");
  66819. if(intensityIndex >= 0){
  66820. options.splice(intensityIndex + 1, 0, "intensity gradient");
  66821. }
  66822. options.push(
  66823. "elevation",
  66824. "color",
  66825. 'matcap',
  66826. 'indices',
  66827. 'level of detail',
  66828. 'composite'
  66829. );
  66830. const blacklist = [
  66831. "POSITION_CARTESIAN",
  66832. "position",
  66833. ];
  66834. options = options.filter(o => !blacklist.includes(o));
  66835. let attributeSelection = panel.find('#optMaterial');
  66836. for(let option of options){
  66837. let elOption = $(`<option>${option}</option>`);
  66838. attributeSelection.append(elOption);
  66839. }
  66840. let updateMaterialPanel = (event, ui) => {
  66841. let selectedValue = attributeSelection.selectmenu().val();
  66842. material.activeAttributeName = selectedValue;
  66843. let attribute = pointcloud.getAttribute(selectedValue);
  66844. if(selectedValue === "intensity gradient"){
  66845. attribute = pointcloud.getAttribute("intensity");
  66846. }
  66847. const isIntensity = attribute ? ["intensity", "intensity gradient"].includes(attribute.name) : false;
  66848. if(isIntensity){
  66849. if(pointcloud.material.intensityRange[0] === Infinity){
  66850. pointcloud.material.intensityRange = attribute.range;
  66851. }
  66852. const [min, max] = attribute.range;
  66853. panel.find('#sldIntensityRange').slider({
  66854. range: true,
  66855. min: min, max: max, step: 0.01,
  66856. values: [min, max],
  66857. slide: (event, ui) => {
  66858. let min = ui.values[0];
  66859. let max = ui.values[1];
  66860. material.intensityRange = [min, max];
  66861. }
  66862. });
  66863. } else if(attribute){
  66864. let [min, max] = attribute.range;
  66865. let selectedRange = material.getRange(attribute.name);
  66866. if(!selectedRange){
  66867. selectedRange = [...attribute.range];
  66868. }
  66869. let minMaxAreNumbers = typeof min === "number" && typeof max === "number";
  66870. /* min = 0 ;max = 50
  66871. selectedRange[0] =min; selectedRange[1] = max; */
  66872. if(minMaxAreNumbers){
  66873. panel.find('#sldExtraRange').slider({
  66874. range: true,
  66875. min: min,
  66876. max: max,
  66877. step: 0.01,
  66878. values: selectedRange,
  66879. slide: (event, ui) => {
  66880. let [a, b] = ui.values;
  66881. material.setRange(attribute.name, [a, b]);
  66882. }
  66883. });
  66884. }
  66885. }
  66886. let blockWeights = $('#materials\\.composite_weight_container');
  66887. let blockElevation = $('#materials\\.elevation_container');
  66888. let blockRGB = $('#materials\\.rgb_container');
  66889. let blockExtra = $('#materials\\.extra_container');
  66890. let blockColor = $('#materials\\.color_container');
  66891. let blockIntensity = $('#materials\\.intensity_container');
  66892. let blockIndex = $('#materials\\.index_container');
  66893. let blockTransition = $('#materials\\.transition_container');
  66894. let blockGps = $('#materials\\.gpstime_container');
  66895. let blockMatcap = $('#materials\\.matcap_container');
  66896. blockIndex.css('display', 'none');
  66897. blockIntensity.css('display', 'none');
  66898. blockElevation.css('display', 'none');
  66899. blockRGB.css('display', 'none');
  66900. blockExtra.css('display', 'none');
  66901. blockColor.css('display', 'none');
  66902. blockWeights.css('display', 'none');
  66903. blockTransition.css('display', 'none');
  66904. blockMatcap.css('display', 'none');
  66905. blockGps.css('display', 'none');
  66906. if (selectedValue === 'composite') {
  66907. blockWeights.css('display', 'block');
  66908. blockElevation.css('display', 'block');
  66909. blockRGB.css('display', 'block');
  66910. blockIntensity.css('display', 'block');
  66911. } else if (selectedValue === 'elevation') {
  66912. blockElevation.css('display', 'block');
  66913. } else if (selectedValue === 'RGB and Elevation') {
  66914. blockRGB.css('display', 'block');
  66915. blockElevation.css('display', 'block');
  66916. } else if (selectedValue === 'rgba') {
  66917. blockRGB.css('display', 'block');
  66918. } else if (selectedValue === 'color') {
  66919. blockColor.css('display', 'block');
  66920. } else if (selectedValue === 'intensity') {
  66921. blockIntensity.css('display', 'block');
  66922. } else if (selectedValue === 'intensity gradient') {
  66923. blockIntensity.css('display', 'block');
  66924. } else if (selectedValue === "indices" ){
  66925. blockIndex.css('display', 'block');
  66926. } else if (selectedValue === "matcap" ){
  66927. blockMatcap.css('display', 'block');
  66928. } else if (selectedValue === "classification" ){
  66929. // add classification color selctor?
  66930. } else if (selectedValue === "gps-time" ){
  66931. blockGps.css('display', 'block');
  66932. } else if(selectedValue === "number of returns"){
  66933. } else if(selectedValue === "return number"){
  66934. } else if(["source id", "point source id"].includes(selectedValue)){
  66935. } else {
  66936. blockExtra.css('display', 'block');
  66937. }
  66938. };
  66939. attributeSelection.selectmenu({change: updateMaterialPanel});
  66940. let update = () => {
  66941. attributeSelection.val(material.activeAttributeName).selectmenu('refresh');
  66942. };
  66943. this.addVolatileListener(material, "point_color_type_changed", update);
  66944. this.addVolatileListener(material, "active_attribute_changed", update);
  66945. update();
  66946. updateMaterialPanel();
  66947. }
  66948. {
  66949. const schemes = Object.keys(Potree.Gradients).map(name => ({name: name, values: Gradients[name]}));
  66950. let elSchemeContainer = panel.find("#elevation_gradient_scheme_selection");
  66951. for(let scheme of schemes){
  66952. let elScheme = $(`
  66953. <span style="flex-grow: 1;">
  66954. </span>
  66955. `);
  66956. const svg = Potree.Utils.createSvgGradient(scheme.values);
  66957. svg.setAttributeNS(null, "class", `button-icon`);
  66958. elScheme.append($(svg));
  66959. elScheme.click( () => {
  66960. material.gradient = Gradients[scheme.name];
  66961. });
  66962. elSchemeContainer.append(elScheme);
  66963. }
  66964. }
  66965. {
  66966. let matcaps = [
  66967. {name: "Normals", icon: `${Potree.resourcePath}/icons/matcap/check_normal+y.jpg`},
  66968. {name: "Basic 1", icon: `${Potree.resourcePath}/icons/matcap/basic_1.jpg`},
  66969. {name: "Basic 2", icon: `${Potree.resourcePath}/icons/matcap/basic_2.jpg`},
  66970. {name: "Basic Dark", icon: `${Potree.resourcePath}/icons/matcap/basic_dark.jpg`},
  66971. {name: "Basic Side", icon: `${Potree.resourcePath}/icons/matcap/basic_side.jpg`},
  66972. {name: "Ceramic Dark", icon: `${Potree.resourcePath}/icons/matcap/ceramic_dark.jpg`},
  66973. {name: "Ceramic Lightbulb", icon: `${Potree.resourcePath}/icons/matcap/ceramic_lightbulb.jpg`},
  66974. {name: "Clay Brown", icon: `${Potree.resourcePath}/icons/matcap/clay_brown.jpg`},
  66975. {name: "Clay Muddy", icon: `${Potree.resourcePath}/icons/matcap/clay_muddy.jpg`},
  66976. {name: "Clay Studio", icon: `${Potree.resourcePath}/icons/matcap/clay_studio.jpg`},
  66977. {name: "Resin", icon: `${Potree.resourcePath}/icons/matcap/resin.jpg`},
  66978. {name: "Skin", icon: `${Potree.resourcePath}/icons/matcap/skin.jpg`},
  66979. {name: "Jade", icon: `${Potree.resourcePath}/icons/matcap/jade.jpg`},
  66980. {name: "Metal_ Anisotropic", icon: `${Potree.resourcePath}/icons/matcap/metal_anisotropic.jpg`},
  66981. {name: "Metal Carpaint", icon: `${Potree.resourcePath}/icons/matcap/metal_carpaint.jpg`},
  66982. {name: "Metal Lead", icon: `${Potree.resourcePath}/icons/matcap/metal_lead.jpg`},
  66983. {name: "Metal Shiny", icon: `${Potree.resourcePath}/icons/matcap/metal_shiny.jpg`},
  66984. {name: "Pearl", icon: `${Potree.resourcePath}/icons/matcap/pearl.jpg`},
  66985. {name: "Toon", icon: `${Potree.resourcePath}/icons/matcap/toon.jpg`},
  66986. {name: "Check Rim Light", icon: `${Potree.resourcePath}/icons/matcap/check_rim_light.jpg`},
  66987. {name: "Check Rim Dark", icon: `${Potree.resourcePath}/icons/matcap/check_rim_dark.jpg`},
  66988. {name: "Contours 1", icon: `${Potree.resourcePath}/icons/matcap/contours_1.jpg`},
  66989. {name: "Contours 2", icon: `${Potree.resourcePath}/icons/matcap/contours_2.jpg`},
  66990. {name: "Contours 3", icon: `${Potree.resourcePath}/icons/matcap/contours_3.jpg`},
  66991. {name: "Reflection Check Horizontal", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_horizontal.jpg`},
  66992. {name: "Reflection Check Vertical", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_vertical.jpg`},
  66993. ];
  66994. let elMatcapContainer = panel.find("#matcap_scheme_selection");
  66995. for(let matcap of matcaps){
  66996. let elMatcap = $(`
  66997. <img src="${matcap.icon}" class="button-icon" style="width: 25%;" />
  66998. `);
  66999. elMatcap.click( () => {
  67000. material.matcap = matcap.icon.substring(matcap.icon.lastIndexOf('/'));
  67001. });
  67002. elMatcapContainer.append(elMatcap);
  67003. }
  67004. }
  67005. {
  67006. panel.find('#sldRGBGamma').slider({
  67007. value: material.rgbGamma,
  67008. min: 0, max: 4, step: 0.01,
  67009. slide: (event, ui) => {material.rgbGamma = ui.value;}
  67010. });
  67011. panel.find('#sldRGBContrast').slider({
  67012. value: material.rgbContrast,
  67013. min: -1, max: 1, step: 0.01,
  67014. slide: (event, ui) => {material.rgbContrast = ui.value;}
  67015. });
  67016. panel.find('#sldRGBBrightness').slider({
  67017. value: material.rgbBrightness,
  67018. min: -1, max: 1, step: 0.01,
  67019. slide: (event, ui) => {material.rgbBrightness = ui.value;}
  67020. });
  67021. panel.find('#sldExtraGamma').slider({
  67022. value: material.extraGamma,
  67023. min: 0, max: 4, step: 0.01,
  67024. slide: (event, ui) => {material.extraGamma = ui.value;}
  67025. });
  67026. panel.find('#sldExtraBrightness').slider({
  67027. value: material.extraBrightness,
  67028. min: -1, max: 1, step: 0.01,
  67029. slide: (event, ui) => {material.extraBrightness = ui.value;}
  67030. });
  67031. panel.find('#sldExtraContrast').slider({
  67032. value: material.extraContrast,
  67033. min: -1, max: 1, step: 0.01,
  67034. slide: (event, ui) => {material.extraContrast = ui.value;}
  67035. });
  67036. panel.find('#sldHeightRange').slider({
  67037. range: true,
  67038. min: 0, max: 1000, step: 0.01,
  67039. values: [0, 1000],
  67040. slide: (event, ui) => {
  67041. material.heightMin = ui.values[0];
  67042. material.heightMax = ui.values[1];
  67043. }
  67044. });
  67045. panel.find('#sldIntensityGamma').slider({
  67046. value: material.intensityGamma,
  67047. min: 0, max: 4, step: 0.01,
  67048. slide: (event, ui) => {material.intensityGamma = ui.value;}
  67049. });
  67050. panel.find('#sldIntensityContrast').slider({
  67051. value: material.intensityContrast,
  67052. min: -1, max: 1, step: 0.01,
  67053. slide: (event, ui) => {material.intensityContrast = ui.value;}
  67054. });
  67055. panel.find('#sldIntensityBrightness').slider({
  67056. value: material.intensityBrightness,
  67057. min: -1, max: 1, step: 0.01,
  67058. slide: (event, ui) => {material.intensityBrightness = ui.value;}
  67059. });
  67060. panel.find('#sldWeightRGB').slider({
  67061. value: material.weightRGB,
  67062. min: 0, max: 1, step: 0.01,
  67063. slide: (event, ui) => {material.weightRGB = ui.value;}
  67064. });
  67065. panel.find('#sldWeightIntensity').slider({
  67066. value: material.weightIntensity,
  67067. min: 0, max: 1, step: 0.01,
  67068. slide: (event, ui) => {material.weightIntensity = ui.value;}
  67069. });
  67070. panel.find('#sldWeightElevation').slider({
  67071. value: material.weightElevation,
  67072. min: 0, max: 1, step: 0.01,
  67073. slide: (event, ui) => {material.weightElevation = ui.value;}
  67074. });
  67075. panel.find('#sldWeightClassification').slider({
  67076. value: material.weightClassification,
  67077. min: 0, max: 1, step: 0.01,
  67078. slide: (event, ui) => {material.weightClassification = ui.value;}
  67079. });
  67080. panel.find('#sldWeightReturnNumber').slider({
  67081. value: material.weightReturnNumber,
  67082. min: 0, max: 1, step: 0.01,
  67083. slide: (event, ui) => {material.weightReturnNumber = ui.value;}
  67084. });
  67085. panel.find('#sldWeightSourceID').slider({
  67086. value: material.weightSourceID,
  67087. min: 0, max: 1, step: 0.01,
  67088. slide: (event, ui) => {material.weightSourceID = ui.value;}
  67089. });
  67090. panel.find(`#materials\\.color\\.picker`).spectrum({
  67091. flat: true,
  67092. showInput: true,
  67093. preferredFormat: 'rgb',
  67094. cancelText: '',
  67095. chooseText: 'Apply',
  67096. color: `#${material.color.getHexString()}`,
  67097. move: color => {
  67098. let cRGB = color.toRgb();
  67099. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  67100. material.color = tc;
  67101. },
  67102. change: color => {
  67103. let cRGB = color.toRgb();
  67104. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  67105. material.color = tc;
  67106. }
  67107. });
  67108. this.addVolatileListener(material, "color_changed", () => {
  67109. panel.find(`#materials\\.color\\.picker`)
  67110. .spectrum('set', `#${material.color.getHexString()}`);
  67111. });
  67112. let updateHeightRange = function () {
  67113. let aPosition = pointcloud.getAttribute("position");
  67114. let bMin, bMax;
  67115. if(aPosition){
  67116. // for new format 2.0 and loader that contain precomputed min/max of attributes
  67117. let min = aPosition.range[0][2];
  67118. let max = aPosition.range[1][2];
  67119. let width = max - min;
  67120. bMin = min - 0.2 * width;
  67121. bMax = max + 0.2 * width;
  67122. }else {
  67123. // for format up until exlusive 2.0
  67124. let box = [pointcloud.pcoGeometry.tightBoundingBox, pointcloud.getBoundingBoxWorld()]
  67125. .find(v => v !== undefined);
  67126. pointcloud.updateMatrixWorld(true);
  67127. box = Utils.computeTransformedBoundingBox(box, pointcloud.matrixWorld);
  67128. let bWidth = box.max.z - box.min.z;
  67129. bMin = box.min.z - 0.2 * bWidth;
  67130. bMax = box.max.z + 0.2 * bWidth;
  67131. }
  67132. let range = material.elevationRange;
  67133. panel.find('#lblHeightRange').html(`${range[0].toFixed(2)} to ${range[1].toFixed(2)}`);
  67134. panel.find('#sldHeightRange').slider({min: bMin, max: bMax, values: range});
  67135. };
  67136. let updateExtraRange = function () {
  67137. let attributeName = material.activeAttributeName;
  67138. let attribute = pointcloud.getAttribute(attributeName);
  67139. if(attribute == null){
  67140. return;
  67141. }
  67142. let range = material.getRange(attributeName);
  67143. if(range == null){
  67144. range = attribute.range;
  67145. }
  67146. // currently only supporting scalar ranges.
  67147. // rgba, normals, positions, etc have vector ranges, however
  67148. let isValidRange = (typeof range[0] === "number") && (typeof range[1] === "number");
  67149. if(!isValidRange){
  67150. return;
  67151. }
  67152. if(range){
  67153. let msg = `${range[0].toFixed(2)} to ${range[1].toFixed(2)}`;
  67154. panel.find('#lblExtraRange').html(msg);
  67155. }else {
  67156. panel.find("could not deduce range");
  67157. }
  67158. };
  67159. let updateIntensityRange = function () {
  67160. let range = material.intensityRange;
  67161. panel.find('#lblIntensityRange').html(`${parseInt(range[0])} to ${parseInt(range[1])}`);
  67162. };
  67163. {
  67164. updateHeightRange();
  67165. panel.find(`#sldHeightRange`).slider('option', 'min');
  67166. panel.find(`#sldHeightRange`).slider('option', 'max');
  67167. }
  67168. {
  67169. let elGradientRepeat = panel.find("#gradient_repeat_option");
  67170. elGradientRepeat.selectgroup({title: "Gradient"});
  67171. elGradientRepeat.find("input").click( (e) => {
  67172. this.viewer.setElevationGradientRepeat(ElevationGradientRepeat[e.target.value]);
  67173. });
  67174. let current = Object.keys(ElevationGradientRepeat)
  67175. .filter(key => ElevationGradientRepeat[key] === this.viewer.elevationGradientRepeat);
  67176. elGradientRepeat.find(`input[value=${current}]`).trigger("click");
  67177. }
  67178. let onIntensityChange = () => {
  67179. let gamma = material.intensityGamma;
  67180. let contrast = material.intensityContrast;
  67181. let brightness = material.intensityBrightness;
  67182. updateIntensityRange();
  67183. panel.find('#lblIntensityGamma').html(gamma.toFixed(2));
  67184. panel.find('#lblIntensityContrast').html(contrast.toFixed(2));
  67185. panel.find('#lblIntensityBrightness').html(brightness.toFixed(2));
  67186. panel.find('#sldIntensityGamma').slider({value: gamma});
  67187. panel.find('#sldIntensityContrast').slider({value: contrast});
  67188. panel.find('#sldIntensityBrightness').slider({value: brightness});
  67189. };
  67190. let onRGBChange = () => {
  67191. let gamma = material.rgbGamma;
  67192. let contrast = material.rgbContrast;
  67193. let brightness = material.rgbBrightness;
  67194. panel.find('#lblRGBGamma').html(gamma.toFixed(2));
  67195. panel.find('#lblRGBContrast').html(contrast.toFixed(2));
  67196. panel.find('#lblRGBBrightness').html(brightness.toFixed(2));
  67197. panel.find('#sldRGBGamma').slider({value: gamma});
  67198. panel.find('#sldRGBContrast').slider({value: contrast});
  67199. panel.find('#sldRGBBrightness').slider({value: brightness});
  67200. };
  67201. this.addVolatileListener(material, "material_property_changed", updateExtraRange);
  67202. this.addVolatileListener(material, "material_property_changed", updateHeightRange);
  67203. this.addVolatileListener(material, "material_property_changed", onIntensityChange);
  67204. this.addVolatileListener(material, "material_property_changed", onRGBChange);
  67205. updateExtraRange();
  67206. updateHeightRange();
  67207. onIntensityChange();
  67208. onRGBChange();
  67209. }
  67210. }
  67211. setMeasurement(object){
  67212. let TYPE = {
  67213. DISTANCE: {panel: DistancePanel},
  67214. AREA: {panel: AreaPanel},
  67215. POINT: {panel: PointPanel},
  67216. ANGLE: {panel: AnglePanel},
  67217. HEIGHT: {panel: HeightPanel},
  67218. PROFILE: {panel: ProfilePanel},
  67219. VOLUME: {panel: VolumePanel},
  67220. CIRCLE: {panel: CirclePanel},
  67221. OTHER: {panel: PointPanel},
  67222. };
  67223. let getType = (measurement) => {
  67224. if (measurement instanceof Measure) {
  67225. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  67226. return TYPE.DISTANCE;
  67227. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  67228. return TYPE.AREA;
  67229. } else if (measurement.maxMarkers === 1) {
  67230. return TYPE.POINT;
  67231. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  67232. return TYPE.ANGLE;
  67233. } else if (measurement.showHeight) {
  67234. return TYPE.HEIGHT;
  67235. } else if (measurement.showCircle) {
  67236. return TYPE.CIRCLE;
  67237. } else {
  67238. return TYPE.OTHER;
  67239. }
  67240. } else if (measurement instanceof Profile) {
  67241. return TYPE.PROFILE;
  67242. } else if (measurement instanceof Volume) {
  67243. return TYPE.VOLUME;
  67244. }
  67245. };
  67246. //this.container.html("measurement");
  67247. let type = getType(object);
  67248. let Panel = type.panel;
  67249. let panel = new Panel(this.viewer, object, this);
  67250. this.container.append(panel.elContent);
  67251. }
  67252. setCamera(camera){
  67253. let panel = new CameraPanel(this.viewer, this);
  67254. this.container.append(panel.elContent);
  67255. }
  67256. setAnnotation(annotation){
  67257. let panel = new AnnotationPanel(this.viewer, this, annotation);
  67258. this.container.append(panel.elContent);
  67259. }
  67260. setCameraAnimation(animation){
  67261. let panel = new CameraAnimationPanel(this.viewer, this, animation);
  67262. this.container.append(panel.elContent);
  67263. }
  67264. }
  67265. function addCommas(nStr){
  67266. nStr += '';
  67267. let x = nStr.split('.');
  67268. let x1 = x[0];
  67269. let x2 = x.length > 1 ? '.' + x[1] : '';
  67270. let rgx = /(\d+)(\d{3})/;
  67271. while (rgx.test(x1)) {
  67272. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  67273. }
  67274. return x1 + x2;
  67275. };
  67276. function format(value){
  67277. return addCommas(value.toFixed(3));
  67278. };
  67279. class HierarchicalSlider{
  67280. constructor(params = {}){
  67281. this.element = document.createElement("div");
  67282. this.labels = [];
  67283. this.sliders = [];
  67284. this.range = params.range != null ? params.range : [0, 1];
  67285. this.slide = params.slide != null ? params.slide : null;
  67286. this.step = params.step != null ? params.step : 0.0001;
  67287. let levels = params.levels != null ? params.levels : 1;
  67288. for(let level = 0; level < levels; level++){
  67289. this.addLevel();
  67290. }
  67291. }
  67292. setRange(range){
  67293. this.range = [...range];
  67294. { // root slider
  67295. let slider = this.sliders[0];
  67296. $(slider).slider({
  67297. min: range[0],
  67298. max: range[1],
  67299. });
  67300. }
  67301. for(let i = 1; i < this.sliders.length; i++){
  67302. let parentSlider = this.sliders[i - 1];
  67303. let slider = this.sliders[i];
  67304. let parentValues = $(parentSlider).slider("option", "values");
  67305. let childRange = [...parentValues];
  67306. $(slider).slider({
  67307. min: childRange[0],
  67308. max: childRange[1],
  67309. });
  67310. }
  67311. this.updateLabels();
  67312. }
  67313. setValues(values){
  67314. for(let slider of this.sliders){
  67315. $(slider).slider({
  67316. values: [...values],
  67317. });
  67318. }
  67319. this.updateLabels();
  67320. }
  67321. addLevel(){
  67322. const elLevel = document.createElement("li");
  67323. const elRange = document.createTextNode("Range: ");
  67324. const label = document.createElement("span");
  67325. const slider = document.createElement("div");
  67326. let level = this.sliders.length;
  67327. let [min, max] = [0, 0];
  67328. if(this.sliders.length === 0){
  67329. [min, max] = this.range;
  67330. }else {
  67331. let parentSlider = this.sliders[this.sliders.length - 1];
  67332. [min, max] = $(parentSlider).slider("option", "values");
  67333. }
  67334. $(slider).slider({
  67335. range: true,
  67336. min: min,
  67337. max: max,
  67338. step: this.step,
  67339. values: [min, max],
  67340. slide: (event, ui) => {
  67341. // set all descendants to same range
  67342. let levels = this.sliders.length;
  67343. for(let i = level + 1; i < levels; i++){
  67344. let descendant = this.sliders[i];
  67345. $(descendant).slider({
  67346. range: true,
  67347. min: ui.values[0],
  67348. max: ui.values[1],
  67349. values: [...ui.values],
  67350. });
  67351. }
  67352. if(this.slide){
  67353. let values = [...ui.values];
  67354. this.slide({
  67355. target: this,
  67356. range: this.range,
  67357. values: values,
  67358. });
  67359. }
  67360. this.updateLabels();
  67361. },
  67362. });
  67363. elLevel.append(elRange, label, slider);
  67364. this.sliders.push(slider);
  67365. this.labels.push(label);
  67366. this.element.append(elLevel);
  67367. this.updateLabels();
  67368. }
  67369. removeLevel(){
  67370. }
  67371. updateSliders(){
  67372. }
  67373. updateLabels(){
  67374. let levels = this.sliders.length;
  67375. for(let i = 0; i < levels; i++){
  67376. let slider = this.sliders[i];
  67377. let label = this.labels[i];
  67378. let [min, max] = $(slider).slider("option", "values");
  67379. let strMin = format(min);
  67380. let strMax = format(max);
  67381. let strLabel = `${strMin} to ${strMax}`;
  67382. label.innerHTML = strLabel;
  67383. }
  67384. }
  67385. }
  67386. class OrientedImageControls extends EventDispatcher{
  67387. constructor(viewer){
  67388. super();
  67389. this.viewer = viewer;
  67390. this.renderer = viewer.renderer;
  67391. this.originalCam = viewer.scene.getActiveCamera();
  67392. this.shearCam = viewer.scene.getActiveCamera().clone();
  67393. this.shearCam.rotation.set(this.originalCam.rotation.toArray());
  67394. this.shearCam.updateProjectionMatrix();
  67395. this.shearCam.updateProjectionMatrix = () => {
  67396. return this.shearCam.projectionMatrix;
  67397. };
  67398. this.image = null;
  67399. this.fadeFactor = 20;
  67400. this.fovDelta = 0;
  67401. this.fovMin = 0.1;
  67402. this.fovMax = 120;
  67403. this.shear = [0, 0];
  67404. // const style = ``;
  67405. this.elUp = $(`<input type="button" value="🡅" style="position: absolute; top: 10px; left: calc(50%); z-index: 1000" />`);
  67406. this.elRight = $(`<input type="button" value="🡆" style="position: absolute; top: calc(50%); right: 10px; z-index: 1000" />`);
  67407. this.elDown = $(`<input type="button" value="🡇" style="position: absolute; bottom: 10px; left: calc(50%); z-index: 1000" />`);
  67408. this.elLeft = $(`<input type="button" value="🡄" style="position: absolute; top: calc(50%); left: 10px; z-index: 1000" />`);
  67409. this.elExit = $(`<input type="button" value="Back to 3D view" style="position: absolute; bottom: 10px; right: 10px; z-index: 1000" />`);
  67410. this.elExit.click( () => {
  67411. this.release();
  67412. });
  67413. this.elUp.click(() => {
  67414. const fovY = viewer.getFOV();
  67415. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67416. this.shear[1] += 0.1 * top;
  67417. });
  67418. this.elRight.click(() => {
  67419. const fovY = viewer.getFOV();
  67420. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67421. this.shear[0] += 0.1 * top;
  67422. });
  67423. this.elDown.click(() => {
  67424. const fovY = viewer.getFOV();
  67425. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67426. this.shear[1] -= 0.1 * top;
  67427. });
  67428. this.elLeft.click(() => {
  67429. const fovY = viewer.getFOV();
  67430. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67431. this.shear[0] -= 0.1 * top;
  67432. });
  67433. this.scene = null;
  67434. this.sceneControls = new Scene();
  67435. let scroll = (e) => {
  67436. this.fovDelta += -e.delta * 1.0;
  67437. };
  67438. this.addEventListener('mousewheel', scroll);
  67439. //this.addEventListener("mousemove", onMove);
  67440. }
  67441. hasSomethingCaptured(){
  67442. return this.image !== null;
  67443. }
  67444. capture(image){
  67445. if(this.hasSomethingCaptured()){
  67446. return;
  67447. }
  67448. this.image = image;
  67449. this.originalFOV = this.viewer.getFOV();
  67450. this.originalControls = this.viewer.getControls();
  67451. this.viewer.setControls(this);
  67452. this.viewer.scene.overrideCamera = this.shearCam;
  67453. const elCanvas = this.viewer.renderer.domElement;
  67454. const elRoot = $(elCanvas.parentElement);
  67455. this.shear = [0, 0];
  67456. elRoot.append(this.elUp);
  67457. elRoot.append(this.elRight);
  67458. elRoot.append(this.elDown);
  67459. elRoot.append(this.elLeft);
  67460. elRoot.append(this.elExit);
  67461. }
  67462. release(){
  67463. this.image = null;
  67464. this.viewer.scene.overrideCamera = null;
  67465. this.elUp.detach();
  67466. this.elRight.detach();
  67467. this.elDown.detach();
  67468. this.elLeft.detach();
  67469. this.elExit.detach();
  67470. this.viewer.setFOV(this.originalFOV);
  67471. this.viewer.setControls(this.originalControls);
  67472. }
  67473. setScene (scene) {
  67474. this.scene = scene;
  67475. }
  67476. update (delta) {
  67477. // const view = this.scene.view;
  67478. // let prevTotal = this.shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  67479. //const progression = Math.min(1, this.fadeFactor * delta);
  67480. //const attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  67481. const progression = 1;
  67482. const attenuation = 0;
  67483. const oldFov = this.viewer.getFOV();
  67484. let fovProgression = progression * this.fovDelta;
  67485. let newFov = oldFov * ((1 + fovProgression / 10));
  67486. newFov = Math.max(this.fovMin, newFov);
  67487. newFov = Math.min(this.fovMax, newFov);
  67488. let diff = newFov / oldFov;
  67489. const mouse = this.viewer.inputHandler.mouse;
  67490. const canvasSize = this.viewer.renderer.getSize(new Vector2$1());
  67491. const uv = [
  67492. (mouse.x / canvasSize.x),
  67493. ((canvasSize.y - mouse.y) / canvasSize.y)
  67494. ];
  67495. const fovY = newFov;
  67496. const aspect = canvasSize.x / canvasSize.y;
  67497. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67498. const height = 2 * top;
  67499. const width = aspect * height;
  67500. const shearRangeX = [
  67501. this.shear[0] - 0.5 * width,
  67502. this.shear[0] + 0.5 * width,
  67503. ];
  67504. const shearRangeY = [
  67505. this.shear[1] - 0.5 * height,
  67506. this.shear[1] + 0.5 * height,
  67507. ];
  67508. const shx = (1 - uv[0]) * shearRangeX[0] + uv[0] * shearRangeX[1];
  67509. const shy = (1 - uv[1]) * shearRangeY[0] + uv[1] * shearRangeY[1];
  67510. const shu = (1 - diff);
  67511. const newShear = [
  67512. (1 - shu) * this.shear[0] + shu * shx,
  67513. (1 - shu) * this.shear[1] + shu * shy,
  67514. ];
  67515. this.shear = newShear;
  67516. this.viewer.setFOV(newFov);
  67517. const {originalCam, shearCam} = this;
  67518. originalCam.fov = newFov;
  67519. originalCam.updateMatrixWorld();
  67520. originalCam.updateProjectionMatrix();
  67521. shearCam.copy(originalCam);
  67522. shearCam.rotation.set(...originalCam.rotation.toArray());
  67523. shearCam.updateMatrixWorld();
  67524. shearCam.projectionMatrix.copy(originalCam.projectionMatrix);
  67525. const [sx, sy] = this.shear;
  67526. const mShear = new Matrix4().set(
  67527. 1, 0, sx, 0,
  67528. 0, 1, sy, 0,
  67529. 0, 0, 1, 0,
  67530. 0, 0, 0, 1,
  67531. );
  67532. const proj = shearCam.projectionMatrix;
  67533. proj.multiply(mShear);
  67534. shearCam.projectionMatrixInverse.copy(proj).invert();
  67535. let total = shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  67536. this.fovDelta *= attenuation;
  67537. }
  67538. };
  67539. // https://support.pix4d.com/hc/en-us/articles/205675256-How-are-yaw-pitch-roll-defined
  67540. // https://support.pix4d.com/hc/en-us/articles/202558969-How-are-omega-phi-kappa-defined
  67541. function createMaterial(){
  67542. let vertexShader = `
  67543. uniform float uNear;
  67544. varying vec2 vUV;
  67545. varying vec4 vDebug;
  67546. void main(){
  67547. vDebug = vec4(0.0, 1.0, 0.0, 1.0);
  67548. vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
  67549. // make sure that this mesh is at least in front of the near plane
  67550. modelViewPosition.xyz += normalize(modelViewPosition.xyz) * uNear;
  67551. gl_Position = projectionMatrix * modelViewPosition;
  67552. vUV = uv;
  67553. }
  67554. `;
  67555. let fragmentShader = `
  67556. uniform sampler2D tColor;
  67557. uniform float uOpacity;
  67558. varying vec2 vUV;
  67559. varying vec4 vDebug;
  67560. void main(){
  67561. vec4 color = texture2D(tColor, vUV);
  67562. gl_FragColor = color;
  67563. gl_FragColor.a = uOpacity;
  67564. }
  67565. `;
  67566. const material = new ShaderMaterial( {
  67567. uniforms: {
  67568. // time: { value: 1.0 },
  67569. // resolution: { value: new THREE.Vector2() }
  67570. tColor: {value: new Texture() },
  67571. uNear: {value: 0.0},
  67572. uOpacity: {value: 1.0},
  67573. },
  67574. vertexShader: vertexShader,
  67575. fragmentShader: fragmentShader,
  67576. side: DoubleSide,
  67577. } );
  67578. material.side = DoubleSide;
  67579. return material;
  67580. }
  67581. const planeGeometry = new PlaneGeometry(1, 1);
  67582. const lineGeometry = new Geometry();
  67583. lineGeometry.vertices.push(
  67584. new Vector3(-0.5, -0.5, 0),
  67585. new Vector3( 0.5, -0.5, 0),
  67586. new Vector3( 0.5, 0.5, 0),
  67587. new Vector3(-0.5, 0.5, 0),
  67588. new Vector3(-0.5, -0.5, 0),
  67589. );
  67590. class OrientedImage{
  67591. constructor(id){
  67592. this.id = id;
  67593. this.fov = 1.0;
  67594. this.position = new Vector3();
  67595. this.rotation = new Vector3();
  67596. this.width = 0;
  67597. this.height = 0;
  67598. this.fov = 1.0;
  67599. const material = createMaterial();
  67600. const lineMaterial = new LineBasicMaterial( { color: 0x00ff00 } );
  67601. this.mesh = new Mesh(planeGeometry, material);
  67602. this.line = new Line(lineGeometry, lineMaterial);
  67603. this.texture = null;
  67604. this.mesh.orientedImage = this;
  67605. }
  67606. set(position, rotation, dimension, fov){
  67607. let radians = rotation.map(MathUtils.degToRad);
  67608. this.position.set(...position);
  67609. this.mesh.position.set(...position);
  67610. this.rotation.set(...radians);
  67611. this.mesh.rotation.set(...radians);
  67612. [this.width, this.height] = dimension;
  67613. this.mesh.scale.set(this.width / this.height, 1, 1);
  67614. this.fov = fov;
  67615. this.updateTransform();
  67616. }
  67617. updateTransform(){
  67618. let {mesh, line, fov} = this;
  67619. mesh.updateMatrixWorld();
  67620. const dir = mesh.getWorldDirection();
  67621. const alpha = MathUtils.degToRad(fov / 2);
  67622. const d = -0.5 / Math.tan(alpha);
  67623. const move = dir.clone().multiplyScalar(d);
  67624. mesh.position.add(move);
  67625. line.position.copy(mesh.position);
  67626. line.scale.copy(mesh.scale);
  67627. line.rotation.copy(mesh.rotation);
  67628. }
  67629. };
  67630. class OrientedImages extends EventDispatcher{
  67631. constructor(){
  67632. super();
  67633. this.node = null;
  67634. this.cameraParams = null;
  67635. this.imageParams = null;
  67636. this.images = null;
  67637. this._visible = true;
  67638. }
  67639. set visible(visible){
  67640. if(this._visible === visible){
  67641. return;
  67642. }
  67643. for(const image of this.images){
  67644. image.mesh.visible = visible;
  67645. image.line.visible = visible;
  67646. }
  67647. this._visible = visible;
  67648. this.dispatchEvent({
  67649. type: "visibility_changed",
  67650. images: this,
  67651. });
  67652. }
  67653. get visible(){
  67654. return this._visible;
  67655. }
  67656. };
  67657. class OrientedImageLoader{
  67658. static async loadCameraParams(path){
  67659. const res = await fetch(path);
  67660. const text = await res.text();
  67661. const parser = new DOMParser();
  67662. const doc = parser.parseFromString(text, "application/xml");
  67663. const width = parseInt(doc.getElementsByTagName("width")[0].textContent);
  67664. const height = parseInt(doc.getElementsByTagName("height")[0].textContent);
  67665. const f = parseFloat(doc.getElementsByTagName("f")[0].textContent);
  67666. let a = (height / 2) / f;
  67667. let fov = 2 * MathUtils.radToDeg(Math.atan(a));
  67668. const params = {
  67669. path: path,
  67670. width: width,
  67671. height: height,
  67672. f: f,
  67673. fov: fov,
  67674. };
  67675. return params;
  67676. }
  67677. static async loadImageParams(path){
  67678. const response = await fetch(path);
  67679. if(!response.ok){
  67680. console.error(`failed to load ${path}`);
  67681. return;
  67682. }
  67683. const content = await response.text();
  67684. const lines = content.split(/\r?\n/);
  67685. const imageParams = [];
  67686. for(let i = 1; i < lines.length; i++){
  67687. const line = lines[i];
  67688. if(line.startsWith("#")){
  67689. continue;
  67690. }
  67691. const tokens = line.split(/\s+/);
  67692. if(tokens.length < 6){
  67693. continue;
  67694. }
  67695. const params = {
  67696. id: tokens[0],
  67697. x: Number.parseFloat(tokens[1]),
  67698. y: Number.parseFloat(tokens[2]),
  67699. z: Number.parseFloat(tokens[3]),
  67700. omega: Number.parseFloat(tokens[4]),
  67701. phi: Number.parseFloat(tokens[5]),
  67702. kappa: Number.parseFloat(tokens[6]),
  67703. };
  67704. // const whitelist = ["47518.jpg"];
  67705. // if(whitelist.includes(params.id)){
  67706. // imageParams.push(params);
  67707. // }
  67708. imageParams.push(params);
  67709. }
  67710. // debug
  67711. //return [imageParams[50]];
  67712. return imageParams;
  67713. }
  67714. static async load(cameraParamsPath, imageParamsPath, viewer){
  67715. const tStart = performance.now();
  67716. const [cameraParams, imageParams] = await Promise.all([
  67717. OrientedImageLoader.loadCameraParams(cameraParamsPath),
  67718. OrientedImageLoader.loadImageParams(imageParamsPath),
  67719. ]);
  67720. const orientedImageControls = new OrientedImageControls(viewer);
  67721. const raycaster = new Raycaster();
  67722. const tEnd = performance.now();
  67723. console.log(tEnd - tStart);
  67724. // const sp = new THREE.PlaneGeometry(1, 1);
  67725. // const lg = new THREE.Geometry();
  67726. // lg.vertices.push(
  67727. // new THREE.Vector3(-0.5, -0.5, 0),
  67728. // new THREE.Vector3( 0.5, -0.5, 0),
  67729. // new THREE.Vector3( 0.5, 0.5, 0),
  67730. // new THREE.Vector3(-0.5, 0.5, 0),
  67731. // new THREE.Vector3(-0.5, -0.5, 0),
  67732. // );
  67733. const {width, height} = cameraParams;
  67734. const orientedImages = [];
  67735. const sceneNode = new Object3D();
  67736. sceneNode.name = "oriented_images";
  67737. for(const params of imageParams){
  67738. // const material = createMaterial();
  67739. // const lm = new THREE.LineBasicMaterial( { color: 0x00ff00 } );
  67740. // const mesh = new THREE.Mesh(sp, material);
  67741. const {x, y, z, omega, phi, kappa} = params;
  67742. // const [rx, ry, rz] = [omega, phi, kappa]
  67743. // .map(THREE.Math.degToRad);
  67744. // mesh.position.set(x, y, z);
  67745. // mesh.scale.set(width / height, 1, 1);
  67746. // mesh.rotation.set(rx, ry, rz);
  67747. // {
  67748. // mesh.updateMatrixWorld();
  67749. // const dir = mesh.getWorldDirection();
  67750. // const alpha = THREE.Math.degToRad(cameraParams.fov / 2);
  67751. // const d = -0.5 / Math.tan(alpha);
  67752. // const move = dir.clone().multiplyScalar(d);
  67753. // mesh.position.add(move);
  67754. // }
  67755. // sceneNode.add(mesh);
  67756. // const line = new THREE.Line(lg, lm);
  67757. // line.position.copy(mesh.position);
  67758. // line.scale.copy(mesh.scale);
  67759. // line.rotation.copy(mesh.rotation);
  67760. // sceneNode.add(line);
  67761. let orientedImage = new OrientedImage(params.id);
  67762. // orientedImage.setPosition(x, y, z);
  67763. // orientedImage.setRotation(omega, phi, kappa);
  67764. // orientedImage.setDimension(width, height);
  67765. let position = [x, y, z];
  67766. let rotation = [omega, phi, kappa];
  67767. let dimension = [width, height];
  67768. orientedImage.set(position, rotation, dimension, cameraParams.fov);
  67769. sceneNode.add(orientedImage.mesh);
  67770. sceneNode.add(orientedImage.line);
  67771. orientedImages.push(orientedImage);
  67772. }
  67773. let hoveredElement = null;
  67774. let clipVolume = null;
  67775. const onMouseMove = (evt) => {
  67776. const tStart = performance.now();
  67777. if(hoveredElement){
  67778. hoveredElement.line.material.color.setRGB(0, 1, 0);
  67779. }
  67780. evt.preventDefault();
  67781. //var array = getMousePosition( container, evt.clientX, evt.clientY );
  67782. const rect = viewer.renderer.domElement.getBoundingClientRect();
  67783. const [x, y] = [evt.clientX, evt.clientY];
  67784. const array = [
  67785. ( x - rect.left ) / rect.width,
  67786. ( y - rect.top ) / rect.height
  67787. ];
  67788. const onClickPosition = new Vector2$1(...array);
  67789. //const intersects = getIntersects(onClickPosition, scene.children);
  67790. const camera = viewer.scene.getActiveCamera();
  67791. const mouse = new Vector3(
  67792. + ( onClickPosition.x * 2 ) - 1,
  67793. - ( onClickPosition.y * 2 ) + 1 );
  67794. const objects = orientedImages.map(i => i.mesh);
  67795. raycaster.setFromCamera( mouse, camera );
  67796. const intersects = raycaster.intersectObjects( objects );
  67797. let selectionChanged = false;
  67798. if ( intersects.length > 0){
  67799. //console.log(intersects);
  67800. const intersection = intersects[0];
  67801. const orientedImage = intersection.object.orientedImage;
  67802. orientedImage.line.material.color.setRGB(1, 0, 0);
  67803. selectionChanged = hoveredElement !== orientedImage;
  67804. hoveredElement = orientedImage;
  67805. }else {
  67806. hoveredElement = null;
  67807. }
  67808. let shouldRemoveClipVolume = clipVolume !== null && hoveredElement === null;
  67809. let shouldAddClipVolume = clipVolume === null && hoveredElement !== null;
  67810. if(clipVolume !== null && (hoveredElement === null || selectionChanged)){
  67811. // remove existing
  67812. viewer.scene.removePolygonClipVolume(clipVolume);
  67813. clipVolume = null;
  67814. }
  67815. if(shouldAddClipVolume || selectionChanged){
  67816. const img = hoveredElement;
  67817. const fov = cameraParams.fov;
  67818. const aspect = cameraParams.width / cameraParams.height;
  67819. const near = 1.0;
  67820. const far = 1000 * 1000;
  67821. const camera = new PerspectiveCamera(fov, aspect, near, far);
  67822. camera.rotation.order = viewer.scene.getActiveCamera().rotation.order;
  67823. camera.rotation.copy(img.mesh.rotation);
  67824. {
  67825. const mesh = img.mesh;
  67826. const dir = mesh.getWorldDirection();
  67827. const pos = mesh.position;
  67828. const alpha = MathUtils.degToRad(fov / 2);
  67829. const d = 0.5 / Math.tan(alpha);
  67830. const newCamPos = pos.clone().add(dir.clone().multiplyScalar(d));
  67831. const newCamDir = pos.clone().sub(newCamPos);
  67832. const newCamTarget = new Vector3().addVectors(
  67833. newCamPos,
  67834. newCamDir.clone().multiplyScalar(viewer.getMoveSpeed()));
  67835. camera.position.copy(newCamPos);
  67836. }
  67837. let volume = new Potree.PolygonClipVolume(camera);
  67838. let m0 = new Mesh();
  67839. let m1 = new Mesh();
  67840. let m2 = new Mesh();
  67841. let m3 = new Mesh();
  67842. m0.position.set(-1, -1, 0);
  67843. m1.position.set( 1, -1, 0);
  67844. m2.position.set( 1, 1, 0);
  67845. m3.position.set(-1, 1, 0);
  67846. volume.markers.push(m0, m1, m2, m3);
  67847. volume.initialized = true;
  67848. viewer.scene.addPolygonClipVolume(volume);
  67849. clipVolume = volume;
  67850. }
  67851. const tEnd = performance.now();
  67852. //console.log(tEnd - tStart);
  67853. };
  67854. const moveToImage = (image) => {
  67855. console.log("move to image " + image.id);
  67856. const mesh = image.mesh;
  67857. const newCamPos = image.position.clone();
  67858. const newCamTarget = mesh.position.clone();
  67859. viewer.scene.view.setView(newCamPos, newCamTarget, 500, () => {
  67860. orientedImageControls.capture(image);
  67861. });
  67862. if(image.texture === null){
  67863. const target = image;
  67864. const tmpImagePath = `${Potree.resourcePath}/images/loading.jpg`;
  67865. new TextureLoader().load(tmpImagePath,
  67866. (texture) => {
  67867. if(target.texture === null){
  67868. target.texture = texture;
  67869. target.mesh.material.uniforms.tColor.value = texture;
  67870. mesh.material.needsUpdate = true;
  67871. }
  67872. }
  67873. );
  67874. const imagePath = `${imageParamsPath}/../${target.id}`;
  67875. new TextureLoader().load(imagePath,
  67876. (texture) => {
  67877. target.texture = texture;
  67878. target.mesh.material.uniforms.tColor.value = texture;
  67879. mesh.material.needsUpdate = true;
  67880. }
  67881. );
  67882. }
  67883. };
  67884. const onMouseClick = (evt) => {
  67885. if(orientedImageControls.hasSomethingCaptured()){
  67886. return;
  67887. }
  67888. if(hoveredElement){
  67889. moveToImage(hoveredElement);
  67890. }
  67891. };
  67892. viewer.renderer.domElement.addEventListener( 'mousemove', onMouseMove, false );
  67893. viewer.renderer.domElement.addEventListener( 'mousedown', onMouseClick, false );
  67894. viewer.addEventListener("update", () => {
  67895. for(const image of orientedImages){
  67896. const world = image.mesh.matrixWorld;
  67897. const {width, height} = image;
  67898. const aspect = width / height;
  67899. const camera = viewer.scene.getActiveCamera();
  67900. const imgPos = image.mesh.getWorldPosition(new Vector3());
  67901. const camPos = camera.position;
  67902. const d = camPos.distanceTo(imgPos);
  67903. const minSize = 1; // in degrees of fov
  67904. const a = MathUtils.degToRad(minSize);
  67905. let r = d * Math.tan(a);
  67906. r = Math.max(r, 1);
  67907. image.mesh.scale.set(r * aspect, r, 1);
  67908. image.line.scale.set(r * aspect, r, 1);
  67909. image.mesh.material.uniforms.uNear.value = camera.near;
  67910. }
  67911. });
  67912. const images = new OrientedImages();
  67913. images.node = sceneNode;
  67914. images.cameraParamsPath = cameraParamsPath;
  67915. images.imageParamsPath = imageParamsPath;
  67916. images.cameraParams = cameraParams;
  67917. images.imageParams = imageParams;
  67918. images.images = orientedImages;
  67919. Potree.debug.moveToImage = moveToImage;
  67920. return images;
  67921. }
  67922. }
  67923. // This is a generated file. Do not edit.
  67924. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
  67925. var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
  67926. var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
  67927. var unicode = {
  67928. Space_Separator: Space_Separator,
  67929. ID_Start: ID_Start,
  67930. ID_Continue: ID_Continue
  67931. };
  67932. var util = {
  67933. isSpaceSeparator (c) {
  67934. return typeof c === 'string' && unicode.Space_Separator.test(c)
  67935. },
  67936. isIdStartChar (c) {
  67937. return typeof c === 'string' && (
  67938. (c >= 'a' && c <= 'z') ||
  67939. (c >= 'A' && c <= 'Z') ||
  67940. (c === '$') || (c === '_') ||
  67941. unicode.ID_Start.test(c)
  67942. )
  67943. },
  67944. isIdContinueChar (c) {
  67945. return typeof c === 'string' && (
  67946. (c >= 'a' && c <= 'z') ||
  67947. (c >= 'A' && c <= 'Z') ||
  67948. (c >= '0' && c <= '9') ||
  67949. (c === '$') || (c === '_') ||
  67950. (c === '\u200C') || (c === '\u200D') ||
  67951. unicode.ID_Continue.test(c)
  67952. )
  67953. },
  67954. isDigit (c) {
  67955. return typeof c === 'string' && /[0-9]/.test(c)
  67956. },
  67957. isHexDigit (c) {
  67958. return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
  67959. },
  67960. };
  67961. let source;
  67962. let parseState;
  67963. let stack;
  67964. let pos;
  67965. let line;
  67966. let column;
  67967. let token;
  67968. let key;
  67969. let root;
  67970. var parse = function parse (text, reviver) {
  67971. source = String(text);
  67972. parseState = 'start';
  67973. stack = [];
  67974. pos = 0;
  67975. line = 1;
  67976. column = 0;
  67977. token = undefined;
  67978. key = undefined;
  67979. root = undefined;
  67980. do {
  67981. token = lex();
  67982. // This code is unreachable.
  67983. // if (!parseStates[parseState]) {
  67984. // throw invalidParseState()
  67985. // }
  67986. parseStates[parseState]();
  67987. } while (token.type !== 'eof')
  67988. if (typeof reviver === 'function') {
  67989. return internalize({'': root}, '', reviver)
  67990. }
  67991. return root
  67992. };
  67993. function internalize (holder, name, reviver) {
  67994. const value = holder[name];
  67995. if (value != null && typeof value === 'object') {
  67996. for (const key in value) {
  67997. const replacement = internalize(value, key, reviver);
  67998. if (replacement === undefined) {
  67999. delete value[key];
  68000. } else {
  68001. value[key] = replacement;
  68002. }
  68003. }
  68004. }
  68005. return reviver.call(holder, name, value)
  68006. }
  68007. let lexState;
  68008. let buffer;
  68009. let doubleQuote;
  68010. let sign$1;
  68011. let c$2;
  68012. function lex () {
  68013. lexState = 'default';
  68014. buffer = '';
  68015. doubleQuote = false;
  68016. sign$1 = 1;
  68017. for (;;) {
  68018. c$2 = peek();
  68019. // This code is unreachable.
  68020. // if (!lexStates[lexState]) {
  68021. // throw invalidLexState(lexState)
  68022. // }
  68023. const token = lexStates[lexState]();
  68024. if (token) {
  68025. return token
  68026. }
  68027. }
  68028. }
  68029. function peek () {
  68030. if (source[pos]) {
  68031. return String.fromCodePoint(source.codePointAt(pos))
  68032. }
  68033. }
  68034. function read () {
  68035. const c = peek();
  68036. if (c === '\n') {
  68037. line++;
  68038. column = 0;
  68039. } else if (c) {
  68040. column += c.length;
  68041. } else {
  68042. column++;
  68043. }
  68044. if (c) {
  68045. pos += c.length;
  68046. }
  68047. return c
  68048. }
  68049. const lexStates = {
  68050. default () {
  68051. switch (c$2) {
  68052. case '\t':
  68053. case '\v':
  68054. case '\f':
  68055. case ' ':
  68056. case '\u00A0':
  68057. case '\uFEFF':
  68058. case '\n':
  68059. case '\r':
  68060. case '\u2028':
  68061. case '\u2029':
  68062. read();
  68063. return
  68064. case '/':
  68065. read();
  68066. lexState = 'comment';
  68067. return
  68068. case undefined:
  68069. read();
  68070. return newToken('eof')
  68071. }
  68072. if (util.isSpaceSeparator(c$2)) {
  68073. read();
  68074. return
  68075. }
  68076. // This code is unreachable.
  68077. // if (!lexStates[parseState]) {
  68078. // throw invalidLexState(parseState)
  68079. // }
  68080. return lexStates[parseState]()
  68081. },
  68082. comment () {
  68083. switch (c$2) {
  68084. case '*':
  68085. read();
  68086. lexState = 'multiLineComment';
  68087. return
  68088. case '/':
  68089. read();
  68090. lexState = 'singleLineComment';
  68091. return
  68092. }
  68093. throw invalidChar(read())
  68094. },
  68095. multiLineComment () {
  68096. switch (c$2) {
  68097. case '*':
  68098. read();
  68099. lexState = 'multiLineCommentAsterisk';
  68100. return
  68101. case undefined:
  68102. throw invalidChar(read())
  68103. }
  68104. read();
  68105. },
  68106. multiLineCommentAsterisk () {
  68107. switch (c$2) {
  68108. case '*':
  68109. read();
  68110. return
  68111. case '/':
  68112. read();
  68113. lexState = 'default';
  68114. return
  68115. case undefined:
  68116. throw invalidChar(read())
  68117. }
  68118. read();
  68119. lexState = 'multiLineComment';
  68120. },
  68121. singleLineComment () {
  68122. switch (c$2) {
  68123. case '\n':
  68124. case '\r':
  68125. case '\u2028':
  68126. case '\u2029':
  68127. read();
  68128. lexState = 'default';
  68129. return
  68130. case undefined:
  68131. read();
  68132. return newToken('eof')
  68133. }
  68134. read();
  68135. },
  68136. value () {
  68137. switch (c$2) {
  68138. case '{':
  68139. case '[':
  68140. return newToken('punctuator', read())
  68141. case 'n':
  68142. read();
  68143. literal('ull');
  68144. return newToken('null', null)
  68145. case 't':
  68146. read();
  68147. literal('rue');
  68148. return newToken('boolean', true)
  68149. case 'f':
  68150. read();
  68151. literal('alse');
  68152. return newToken('boolean', false)
  68153. case '-':
  68154. case '+':
  68155. if (read() === '-') {
  68156. sign$1 = -1;
  68157. }
  68158. lexState = 'sign';
  68159. return
  68160. case '.':
  68161. buffer = read();
  68162. lexState = 'decimalPointLeading';
  68163. return
  68164. case '0':
  68165. buffer = read();
  68166. lexState = 'zero';
  68167. return
  68168. case '1':
  68169. case '2':
  68170. case '3':
  68171. case '4':
  68172. case '5':
  68173. case '6':
  68174. case '7':
  68175. case '8':
  68176. case '9':
  68177. buffer = read();
  68178. lexState = 'decimalInteger';
  68179. return
  68180. case 'I':
  68181. read();
  68182. literal('nfinity');
  68183. return newToken('numeric', Infinity)
  68184. case 'N':
  68185. read();
  68186. literal('aN');
  68187. return newToken('numeric', NaN)
  68188. case '"':
  68189. case "'":
  68190. doubleQuote = (read() === '"');
  68191. buffer = '';
  68192. lexState = 'string';
  68193. return
  68194. }
  68195. throw invalidChar(read())
  68196. },
  68197. identifierNameStartEscape () {
  68198. if (c$2 !== 'u') {
  68199. throw invalidChar(read())
  68200. }
  68201. read();
  68202. const u = unicodeEscape();
  68203. switch (u) {
  68204. case '$':
  68205. case '_':
  68206. break
  68207. default:
  68208. if (!util.isIdStartChar(u)) {
  68209. throw invalidIdentifier()
  68210. }
  68211. break
  68212. }
  68213. buffer += u;
  68214. lexState = 'identifierName';
  68215. },
  68216. identifierName () {
  68217. switch (c$2) {
  68218. case '$':
  68219. case '_':
  68220. case '\u200C':
  68221. case '\u200D':
  68222. buffer += read();
  68223. return
  68224. case '\\':
  68225. read();
  68226. lexState = 'identifierNameEscape';
  68227. return
  68228. }
  68229. if (util.isIdContinueChar(c$2)) {
  68230. buffer += read();
  68231. return
  68232. }
  68233. return newToken('identifier', buffer)
  68234. },
  68235. identifierNameEscape () {
  68236. if (c$2 !== 'u') {
  68237. throw invalidChar(read())
  68238. }
  68239. read();
  68240. const u = unicodeEscape();
  68241. switch (u) {
  68242. case '$':
  68243. case '_':
  68244. case '\u200C':
  68245. case '\u200D':
  68246. break
  68247. default:
  68248. if (!util.isIdContinueChar(u)) {
  68249. throw invalidIdentifier()
  68250. }
  68251. break
  68252. }
  68253. buffer += u;
  68254. lexState = 'identifierName';
  68255. },
  68256. sign () {
  68257. switch (c$2) {
  68258. case '.':
  68259. buffer = read();
  68260. lexState = 'decimalPointLeading';
  68261. return
  68262. case '0':
  68263. buffer = read();
  68264. lexState = 'zero';
  68265. return
  68266. case '1':
  68267. case '2':
  68268. case '3':
  68269. case '4':
  68270. case '5':
  68271. case '6':
  68272. case '7':
  68273. case '8':
  68274. case '9':
  68275. buffer = read();
  68276. lexState = 'decimalInteger';
  68277. return
  68278. case 'I':
  68279. read();
  68280. literal('nfinity');
  68281. return newToken('numeric', sign$1 * Infinity)
  68282. case 'N':
  68283. read();
  68284. literal('aN');
  68285. return newToken('numeric', NaN)
  68286. }
  68287. throw invalidChar(read())
  68288. },
  68289. zero () {
  68290. switch (c$2) {
  68291. case '.':
  68292. buffer += read();
  68293. lexState = 'decimalPoint';
  68294. return
  68295. case 'e':
  68296. case 'E':
  68297. buffer += read();
  68298. lexState = 'decimalExponent';
  68299. return
  68300. case 'x':
  68301. case 'X':
  68302. buffer += read();
  68303. lexState = 'hexadecimal';
  68304. return
  68305. }
  68306. return newToken('numeric', sign$1 * 0)
  68307. },
  68308. decimalInteger () {
  68309. switch (c$2) {
  68310. case '.':
  68311. buffer += read();
  68312. lexState = 'decimalPoint';
  68313. return
  68314. case 'e':
  68315. case 'E':
  68316. buffer += read();
  68317. lexState = 'decimalExponent';
  68318. return
  68319. }
  68320. if (util.isDigit(c$2)) {
  68321. buffer += read();
  68322. return
  68323. }
  68324. return newToken('numeric', sign$1 * Number(buffer))
  68325. },
  68326. decimalPointLeading () {
  68327. if (util.isDigit(c$2)) {
  68328. buffer += read();
  68329. lexState = 'decimalFraction';
  68330. return
  68331. }
  68332. throw invalidChar(read())
  68333. },
  68334. decimalPoint () {
  68335. switch (c$2) {
  68336. case 'e':
  68337. case 'E':
  68338. buffer += read();
  68339. lexState = 'decimalExponent';
  68340. return
  68341. }
  68342. if (util.isDigit(c$2)) {
  68343. buffer += read();
  68344. lexState = 'decimalFraction';
  68345. return
  68346. }
  68347. return newToken('numeric', sign$1 * Number(buffer))
  68348. },
  68349. decimalFraction () {
  68350. switch (c$2) {
  68351. case 'e':
  68352. case 'E':
  68353. buffer += read();
  68354. lexState = 'decimalExponent';
  68355. return
  68356. }
  68357. if (util.isDigit(c$2)) {
  68358. buffer += read();
  68359. return
  68360. }
  68361. return newToken('numeric', sign$1 * Number(buffer))
  68362. },
  68363. decimalExponent () {
  68364. switch (c$2) {
  68365. case '+':
  68366. case '-':
  68367. buffer += read();
  68368. lexState = 'decimalExponentSign';
  68369. return
  68370. }
  68371. if (util.isDigit(c$2)) {
  68372. buffer += read();
  68373. lexState = 'decimalExponentInteger';
  68374. return
  68375. }
  68376. throw invalidChar(read())
  68377. },
  68378. decimalExponentSign () {
  68379. if (util.isDigit(c$2)) {
  68380. buffer += read();
  68381. lexState = 'decimalExponentInteger';
  68382. return
  68383. }
  68384. throw invalidChar(read())
  68385. },
  68386. decimalExponentInteger () {
  68387. if (util.isDigit(c$2)) {
  68388. buffer += read();
  68389. return
  68390. }
  68391. return newToken('numeric', sign$1 * Number(buffer))
  68392. },
  68393. hexadecimal () {
  68394. if (util.isHexDigit(c$2)) {
  68395. buffer += read();
  68396. lexState = 'hexadecimalInteger';
  68397. return
  68398. }
  68399. throw invalidChar(read())
  68400. },
  68401. hexadecimalInteger () {
  68402. if (util.isHexDigit(c$2)) {
  68403. buffer += read();
  68404. return
  68405. }
  68406. return newToken('numeric', sign$1 * Number(buffer))
  68407. },
  68408. string () {
  68409. switch (c$2) {
  68410. case '\\':
  68411. read();
  68412. buffer += escape$1();
  68413. return
  68414. case '"':
  68415. if (doubleQuote) {
  68416. read();
  68417. return newToken('string', buffer)
  68418. }
  68419. buffer += read();
  68420. return
  68421. case "'":
  68422. if (!doubleQuote) {
  68423. read();
  68424. return newToken('string', buffer)
  68425. }
  68426. buffer += read();
  68427. return
  68428. case '\n':
  68429. case '\r':
  68430. throw invalidChar(read())
  68431. case '\u2028':
  68432. case '\u2029':
  68433. separatorChar(c$2);
  68434. break
  68435. case undefined:
  68436. throw invalidChar(read())
  68437. }
  68438. buffer += read();
  68439. },
  68440. start () {
  68441. switch (c$2) {
  68442. case '{':
  68443. case '[':
  68444. return newToken('punctuator', read())
  68445. // This code is unreachable since the default lexState handles eof.
  68446. // case undefined:
  68447. // return newToken('eof')
  68448. }
  68449. lexState = 'value';
  68450. },
  68451. beforePropertyName () {
  68452. switch (c$2) {
  68453. case '$':
  68454. case '_':
  68455. buffer = read();
  68456. lexState = 'identifierName';
  68457. return
  68458. case '\\':
  68459. read();
  68460. lexState = 'identifierNameStartEscape';
  68461. return
  68462. case '}':
  68463. return newToken('punctuator', read())
  68464. case '"':
  68465. case "'":
  68466. doubleQuote = (read() === '"');
  68467. lexState = 'string';
  68468. return
  68469. }
  68470. if (util.isIdStartChar(c$2)) {
  68471. buffer += read();
  68472. lexState = 'identifierName';
  68473. return
  68474. }
  68475. throw invalidChar(read())
  68476. },
  68477. afterPropertyName () {
  68478. if (c$2 === ':') {
  68479. return newToken('punctuator', read())
  68480. }
  68481. throw invalidChar(read())
  68482. },
  68483. beforePropertyValue () {
  68484. lexState = 'value';
  68485. },
  68486. afterPropertyValue () {
  68487. switch (c$2) {
  68488. case ',':
  68489. case '}':
  68490. return newToken('punctuator', read())
  68491. }
  68492. throw invalidChar(read())
  68493. },
  68494. beforeArrayValue () {
  68495. if (c$2 === ']') {
  68496. return newToken('punctuator', read())
  68497. }
  68498. lexState = 'value';
  68499. },
  68500. afterArrayValue () {
  68501. switch (c$2) {
  68502. case ',':
  68503. case ']':
  68504. return newToken('punctuator', read())
  68505. }
  68506. throw invalidChar(read())
  68507. },
  68508. end () {
  68509. // This code is unreachable since it's handled by the default lexState.
  68510. // if (c === undefined) {
  68511. // read()
  68512. // return newToken('eof')
  68513. // }
  68514. throw invalidChar(read())
  68515. },
  68516. };
  68517. function newToken (type, value) {
  68518. return {
  68519. type,
  68520. value,
  68521. line,
  68522. column,
  68523. }
  68524. }
  68525. function literal (s) {
  68526. for (const c of s) {
  68527. const p = peek();
  68528. if (p !== c) {
  68529. throw invalidChar(read())
  68530. }
  68531. read();
  68532. }
  68533. }
  68534. function escape$1 () {
  68535. const c = peek();
  68536. switch (c) {
  68537. case 'b':
  68538. read();
  68539. return '\b'
  68540. case 'f':
  68541. read();
  68542. return '\f'
  68543. case 'n':
  68544. read();
  68545. return '\n'
  68546. case 'r':
  68547. read();
  68548. return '\r'
  68549. case 't':
  68550. read();
  68551. return '\t'
  68552. case 'v':
  68553. read();
  68554. return '\v'
  68555. case '0':
  68556. read();
  68557. if (util.isDigit(peek())) {
  68558. throw invalidChar(read())
  68559. }
  68560. return '\0'
  68561. case 'x':
  68562. read();
  68563. return hexEscape()
  68564. case 'u':
  68565. read();
  68566. return unicodeEscape()
  68567. case '\n':
  68568. case '\u2028':
  68569. case '\u2029':
  68570. read();
  68571. return ''
  68572. case '\r':
  68573. read();
  68574. if (peek() === '\n') {
  68575. read();
  68576. }
  68577. return ''
  68578. case '1':
  68579. case '2':
  68580. case '3':
  68581. case '4':
  68582. case '5':
  68583. case '6':
  68584. case '7':
  68585. case '8':
  68586. case '9':
  68587. throw invalidChar(read())
  68588. case undefined:
  68589. throw invalidChar(read())
  68590. }
  68591. return read()
  68592. }
  68593. function hexEscape () {
  68594. let buffer = '';
  68595. let c = peek();
  68596. if (!util.isHexDigit(c)) {
  68597. throw invalidChar(read())
  68598. }
  68599. buffer += read();
  68600. c = peek();
  68601. if (!util.isHexDigit(c)) {
  68602. throw invalidChar(read())
  68603. }
  68604. buffer += read();
  68605. return String.fromCodePoint(parseInt(buffer, 16))
  68606. }
  68607. function unicodeEscape () {
  68608. let buffer = '';
  68609. let count = 4;
  68610. while (count-- > 0) {
  68611. const c = peek();
  68612. if (!util.isHexDigit(c)) {
  68613. throw invalidChar(read())
  68614. }
  68615. buffer += read();
  68616. }
  68617. return String.fromCodePoint(parseInt(buffer, 16))
  68618. }
  68619. const parseStates = {
  68620. start () {
  68621. if (token.type === 'eof') {
  68622. throw invalidEOF()
  68623. }
  68624. push();
  68625. },
  68626. beforePropertyName () {
  68627. switch (token.type) {
  68628. case 'identifier':
  68629. case 'string':
  68630. key = token.value;
  68631. parseState = 'afterPropertyName';
  68632. return
  68633. case 'punctuator':
  68634. // This code is unreachable since it's handled by the lexState.
  68635. // if (token.value !== '}') {
  68636. // throw invalidToken()
  68637. // }
  68638. pop();
  68639. return
  68640. case 'eof':
  68641. throw invalidEOF()
  68642. }
  68643. // This code is unreachable since it's handled by the lexState.
  68644. // throw invalidToken()
  68645. },
  68646. afterPropertyName () {
  68647. // This code is unreachable since it's handled by the lexState.
  68648. // if (token.type !== 'punctuator' || token.value !== ':') {
  68649. // throw invalidToken()
  68650. // }
  68651. if (token.type === 'eof') {
  68652. throw invalidEOF()
  68653. }
  68654. parseState = 'beforePropertyValue';
  68655. },
  68656. beforePropertyValue () {
  68657. if (token.type === 'eof') {
  68658. throw invalidEOF()
  68659. }
  68660. push();
  68661. },
  68662. beforeArrayValue () {
  68663. if (token.type === 'eof') {
  68664. throw invalidEOF()
  68665. }
  68666. if (token.type === 'punctuator' && token.value === ']') {
  68667. pop();
  68668. return
  68669. }
  68670. push();
  68671. },
  68672. afterPropertyValue () {
  68673. // This code is unreachable since it's handled by the lexState.
  68674. // if (token.type !== 'punctuator') {
  68675. // throw invalidToken()
  68676. // }
  68677. if (token.type === 'eof') {
  68678. throw invalidEOF()
  68679. }
  68680. switch (token.value) {
  68681. case ',':
  68682. parseState = 'beforePropertyName';
  68683. return
  68684. case '}':
  68685. pop();
  68686. }
  68687. // This code is unreachable since it's handled by the lexState.
  68688. // throw invalidToken()
  68689. },
  68690. afterArrayValue () {
  68691. // This code is unreachable since it's handled by the lexState.
  68692. // if (token.type !== 'punctuator') {
  68693. // throw invalidToken()
  68694. // }
  68695. if (token.type === 'eof') {
  68696. throw invalidEOF()
  68697. }
  68698. switch (token.value) {
  68699. case ',':
  68700. parseState = 'beforeArrayValue';
  68701. return
  68702. case ']':
  68703. pop();
  68704. }
  68705. // This code is unreachable since it's handled by the lexState.
  68706. // throw invalidToken()
  68707. },
  68708. end () {
  68709. // This code is unreachable since it's handled by the lexState.
  68710. // if (token.type !== 'eof') {
  68711. // throw invalidToken()
  68712. // }
  68713. },
  68714. };
  68715. function push () {
  68716. let value;
  68717. switch (token.type) {
  68718. case 'punctuator':
  68719. switch (token.value) {
  68720. case '{':
  68721. value = {};
  68722. break
  68723. case '[':
  68724. value = [];
  68725. break
  68726. }
  68727. break
  68728. case 'null':
  68729. case 'boolean':
  68730. case 'numeric':
  68731. case 'string':
  68732. value = token.value;
  68733. break
  68734. // This code is unreachable.
  68735. // default:
  68736. // throw invalidToken()
  68737. }
  68738. if (root === undefined) {
  68739. root = value;
  68740. } else {
  68741. const parent = stack[stack.length - 1];
  68742. if (Array.isArray(parent)) {
  68743. parent.push(value);
  68744. } else {
  68745. parent[key] = value;
  68746. }
  68747. }
  68748. if (value !== null && typeof value === 'object') {
  68749. stack.push(value);
  68750. if (Array.isArray(value)) {
  68751. parseState = 'beforeArrayValue';
  68752. } else {
  68753. parseState = 'beforePropertyName';
  68754. }
  68755. } else {
  68756. const current = stack[stack.length - 1];
  68757. if (current == null) {
  68758. parseState = 'end';
  68759. } else if (Array.isArray(current)) {
  68760. parseState = 'afterArrayValue';
  68761. } else {
  68762. parseState = 'afterPropertyValue';
  68763. }
  68764. }
  68765. }
  68766. function pop () {
  68767. stack.pop();
  68768. const current = stack[stack.length - 1];
  68769. if (current == null) {
  68770. parseState = 'end';
  68771. } else if (Array.isArray(current)) {
  68772. parseState = 'afterArrayValue';
  68773. } else {
  68774. parseState = 'afterPropertyValue';
  68775. }
  68776. }
  68777. // This code is unreachable.
  68778. // function invalidParseState () {
  68779. // return new Error(`JSON5: invalid parse state '${parseState}'`)
  68780. // }
  68781. // This code is unreachable.
  68782. // function invalidLexState (state) {
  68783. // return new Error(`JSON5: invalid lex state '${state}'`)
  68784. // }
  68785. function invalidChar (c) {
  68786. if (c === undefined) {
  68787. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68788. }
  68789. return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  68790. }
  68791. function invalidEOF () {
  68792. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68793. }
  68794. // This code is unreachable.
  68795. // function invalidToken () {
  68796. // if (token.type === 'eof') {
  68797. // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68798. // }
  68799. // const c = String.fromCodePoint(token.value.codePointAt(0))
  68800. // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  68801. // }
  68802. function invalidIdentifier () {
  68803. column -= 5;
  68804. return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
  68805. }
  68806. function separatorChar (c) {
  68807. console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
  68808. }
  68809. function formatChar (c) {
  68810. const replacements = {
  68811. "'": "\\'",
  68812. '"': '\\"',
  68813. '\\': '\\\\',
  68814. '\b': '\\b',
  68815. '\f': '\\f',
  68816. '\n': '\\n',
  68817. '\r': '\\r',
  68818. '\t': '\\t',
  68819. '\v': '\\v',
  68820. '\0': '\\0',
  68821. '\u2028': '\\u2028',
  68822. '\u2029': '\\u2029',
  68823. };
  68824. if (replacements[c]) {
  68825. return replacements[c]
  68826. }
  68827. if (c < ' ') {
  68828. const hexString = c.charCodeAt(0).toString(16);
  68829. return '\\x' + ('00' + hexString).substring(hexString.length)
  68830. }
  68831. return c
  68832. }
  68833. function syntaxError (message) {
  68834. const err = new SyntaxError(message);
  68835. err.lineNumber = line;
  68836. err.columnNumber = column;
  68837. return err
  68838. }
  68839. var stringify = function stringify (value, replacer, space) {
  68840. const stack = [];
  68841. let indent = '';
  68842. let propertyList;
  68843. let replacerFunc;
  68844. let gap = '';
  68845. let quote;
  68846. if (
  68847. replacer != null &&
  68848. typeof replacer === 'object' &&
  68849. !Array.isArray(replacer)
  68850. ) {
  68851. space = replacer.space;
  68852. quote = replacer.quote;
  68853. replacer = replacer.replacer;
  68854. }
  68855. if (typeof replacer === 'function') {
  68856. replacerFunc = replacer;
  68857. } else if (Array.isArray(replacer)) {
  68858. propertyList = [];
  68859. for (const v of replacer) {
  68860. let item;
  68861. if (typeof v === 'string') {
  68862. item = v;
  68863. } else if (
  68864. typeof v === 'number' ||
  68865. v instanceof String ||
  68866. v instanceof Number
  68867. ) {
  68868. item = String(v);
  68869. }
  68870. if (item !== undefined && propertyList.indexOf(item) < 0) {
  68871. propertyList.push(item);
  68872. }
  68873. }
  68874. }
  68875. if (space instanceof Number) {
  68876. space = Number(space);
  68877. } else if (space instanceof String) {
  68878. space = String(space);
  68879. }
  68880. if (typeof space === 'number') {
  68881. if (space > 0) {
  68882. space = Math.min(10, Math.floor(space));
  68883. gap = ' '.substr(0, space);
  68884. }
  68885. } else if (typeof space === 'string') {
  68886. gap = space.substr(0, 10);
  68887. }
  68888. return serializeProperty('', {'': value})
  68889. function serializeProperty (key, holder) {
  68890. let value = holder[key];
  68891. if (value != null) {
  68892. if (typeof value.toJSON5 === 'function') {
  68893. value = value.toJSON5(key);
  68894. } else if (typeof value.toJSON === 'function') {
  68895. value = value.toJSON(key);
  68896. }
  68897. }
  68898. if (replacerFunc) {
  68899. value = replacerFunc.call(holder, key, value);
  68900. }
  68901. if (value instanceof Number) {
  68902. value = Number(value);
  68903. } else if (value instanceof String) {
  68904. value = String(value);
  68905. } else if (value instanceof Boolean) {
  68906. value = value.valueOf();
  68907. }
  68908. switch (value) {
  68909. case null: return 'null'
  68910. case true: return 'true'
  68911. case false: return 'false'
  68912. }
  68913. if (typeof value === 'string') {
  68914. return quoteString(value, false)
  68915. }
  68916. if (typeof value === 'number') {
  68917. return String(value)
  68918. }
  68919. if (typeof value === 'object') {
  68920. return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
  68921. }
  68922. return undefined
  68923. }
  68924. function quoteString (value) {
  68925. const quotes = {
  68926. "'": 0.1,
  68927. '"': 0.2,
  68928. };
  68929. const replacements = {
  68930. "'": "\\'",
  68931. '"': '\\"',
  68932. '\\': '\\\\',
  68933. '\b': '\\b',
  68934. '\f': '\\f',
  68935. '\n': '\\n',
  68936. '\r': '\\r',
  68937. '\t': '\\t',
  68938. '\v': '\\v',
  68939. '\0': '\\0',
  68940. '\u2028': '\\u2028',
  68941. '\u2029': '\\u2029',
  68942. };
  68943. let product = '';
  68944. for (let i = 0; i < value.length; i++) {
  68945. const c = value[i];
  68946. switch (c) {
  68947. case "'":
  68948. case '"':
  68949. quotes[c]++;
  68950. product += c;
  68951. continue
  68952. case '\0':
  68953. if (util.isDigit(value[i + 1])) {
  68954. product += '\\x00';
  68955. continue
  68956. }
  68957. }
  68958. if (replacements[c]) {
  68959. product += replacements[c];
  68960. continue
  68961. }
  68962. if (c < ' ') {
  68963. let hexString = c.charCodeAt(0).toString(16);
  68964. product += '\\x' + ('00' + hexString).substring(hexString.length);
  68965. continue
  68966. }
  68967. product += c;
  68968. }
  68969. const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);
  68970. product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
  68971. return quoteChar + product + quoteChar
  68972. }
  68973. function serializeObject (value) {
  68974. if (stack.indexOf(value) >= 0) {
  68975. throw TypeError('Converting circular structure to JSON5')
  68976. }
  68977. stack.push(value);
  68978. let stepback = indent;
  68979. indent = indent + gap;
  68980. let keys = propertyList || Object.keys(value);
  68981. let partial = [];
  68982. for (const key of keys) {
  68983. const propertyString = serializeProperty(key, value);
  68984. if (propertyString !== undefined) {
  68985. let member = serializeKey(key) + ':';
  68986. if (gap !== '') {
  68987. member += ' ';
  68988. }
  68989. member += propertyString;
  68990. partial.push(member);
  68991. }
  68992. }
  68993. let final;
  68994. if (partial.length === 0) {
  68995. final = '{}';
  68996. } else {
  68997. let properties;
  68998. if (gap === '') {
  68999. properties = partial.join(',');
  69000. final = '{' + properties + '}';
  69001. } else {
  69002. let separator = ',\n' + indent;
  69003. properties = partial.join(separator);
  69004. final = '{\n' + indent + properties + ',\n' + stepback + '}';
  69005. }
  69006. }
  69007. stack.pop();
  69008. indent = stepback;
  69009. return final
  69010. }
  69011. function serializeKey (key) {
  69012. if (key.length === 0) {
  69013. return quoteString(key, true)
  69014. }
  69015. const firstChar = String.fromCodePoint(key.codePointAt(0));
  69016. if (!util.isIdStartChar(firstChar)) {
  69017. return quoteString(key, true)
  69018. }
  69019. for (let i = firstChar.length; i < key.length; i++) {
  69020. if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
  69021. return quoteString(key, true)
  69022. }
  69023. }
  69024. return key
  69025. }
  69026. function serializeArray (value) {
  69027. if (stack.indexOf(value) >= 0) {
  69028. throw TypeError('Converting circular structure to JSON5')
  69029. }
  69030. stack.push(value);
  69031. let stepback = indent;
  69032. indent = indent + gap;
  69033. let partial = [];
  69034. for (let i = 0; i < value.length; i++) {
  69035. const propertyString = serializeProperty(String(i), value);
  69036. partial.push((propertyString !== undefined) ? propertyString : 'null');
  69037. }
  69038. let final;
  69039. if (partial.length === 0) {
  69040. final = '[]';
  69041. } else {
  69042. if (gap === '') {
  69043. let properties = partial.join(',');
  69044. final = '[' + properties + ']';
  69045. } else {
  69046. let separator = ',\n' + indent;
  69047. let properties = partial.join(separator);
  69048. final = '[\n' + indent + properties + ',\n' + stepback + ']';
  69049. }
  69050. }
  69051. stack.pop();
  69052. indent = stepback;
  69053. return final
  69054. }
  69055. };
  69056. const JSON5 = {
  69057. parse,
  69058. stringify,
  69059. };
  69060. var lib = JSON5;
  69061. class Sidebar{
  69062. constructor(viewer){
  69063. this.viewer = viewer;
  69064. this.measuringTool = viewer.measuringTool;
  69065. this.profileTool = viewer.profileTool;
  69066. this.volumeTool = viewer.volumeTool;
  69067. this.dom = $("#sidebar_root");
  69068. }
  69069. createToolIcon(icon, title, callback){
  69070. let element = $(`
  69071. <img src="${icon}"
  69072. style="width: 32px; height: 32px"
  69073. class="button-icon"
  69074. data-i18n="${title}" />
  69075. `);
  69076. element.click(callback);
  69077. return element;
  69078. }
  69079. init(){
  69080. if(Potree.settings.editType == 'merge'){
  69081. this.initMergeBar();
  69082. this.initToolbar();
  69083. this.initScene();
  69084. this.initNavigation();
  69085. }else {
  69086. this.initAccordion();
  69087. this.initAppearance();
  69088. this.initToolbar();
  69089. this.initScene();
  69090. this.initNavigation();
  69091. this.initFilters();
  69092. this.initClippingTool();
  69093. this.initSettings();
  69094. if(Potree.settings.editType != 'pano'){
  69095. this.initAlignment();
  69096. this.initClipModel();
  69097. this.initSiteModel();
  69098. this.initParitcle();
  69099. }else {
  69100. this.initPanosEdit();
  69101. }
  69102. }
  69103. $('#potree_version_number').html(Potree.version.major + "." + Potree.version.minor + Potree.version.suffix);
  69104. }
  69105. initAlignment(){
  69106. let Alignment = viewer.modules.Alignment;
  69107. var pannel = $('#alignment');
  69108. var buttons = pannel.find('[name="transform"] button');
  69109. var applyToPointcloud = (fun, value)=>{
  69110. return function(){
  69111. var selected = $('#alignment li[name="selectPointCloud"] input:checked' );
  69112. Array.from(selected).forEach(e=>{
  69113. var pointcloud = viewer.scene.pointclouds.find(p=>p.name == e.name);
  69114. fun(pointcloud, value);
  69115. });
  69116. }
  69117. };
  69118. //逆时针是正数
  69119. buttons.eq(0).on('click', applyToPointcloud(Alignment.rotate, 10));
  69120. //viewer.scene.pointclouds[0].rotation.z += THREE.Math.degToRad(10)
  69121. buttons.eq(1).on('click' ,applyToPointcloud(Alignment.rotate, 1));
  69122. buttons.eq(2).on('click', applyToPointcloud(Alignment.rotate, 0.1));
  69123. buttons.eq(3).on('click', applyToPointcloud(Alignment.rotate, -10));
  69124. buttons.eq(4).on('click',applyToPointcloud(Alignment.rotate, -1));
  69125. buttons.eq(5).on('click',applyToPointcloud(Alignment.rotate, -0.1));
  69126. buttons.eq(6).on('click', applyToPointcloud(Alignment.translate, new Vector3(-1,0,0)));
  69127. buttons.eq(7).on('click', applyToPointcloud(Alignment.translate, new Vector3(1,0,0)));
  69128. buttons.eq(8).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,-1,0)));
  69129. buttons.eq(9).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,1,0)));
  69130. buttons.eq(10).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,-1)));
  69131. buttons.eq(11).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,1)));
  69132. pannel.find('#startAlignment').on('click', ()=>{
  69133. Alignment.enter();
  69134. });
  69135. pannel.find('#exitAlignment').on('click', ()=>{
  69136. Alignment.save();
  69137. Alignment.leave();
  69138. });
  69139. pannel.find('#rotTool').on('click', ()=>{
  69140. Alignment.switchHandle('rotate');
  69141. });
  69142. pannel.find('#moveTool').on('click', ()=>{
  69143. Alignment.switchHandle('translate');
  69144. });
  69145. }
  69146. initMergeBar(){//多元融合模块
  69147. var pannel = $('#mergeModel');
  69148. var buttons = pannel.find('button');
  69149. let MergeEditor = viewer.modules.MergeEditor;
  69150. let loading = false;
  69151. pannel.find('ul[name="model"] li button').on('click',(e)=>{
  69152. if(loading)return console.log('还在加载', loading)
  69153. let $elem = $(e.target);
  69154. let parent = $elem.parent();
  69155. let name = parent.attr('name');
  69156. if($elem.attr('name') == 'select'){
  69157. return Potree.selectModel(name)
  69158. }
  69159. if($elem.text() == '添加'){
  69160. let startTime = Date.now();
  69161. Potree.addModel(name,()=>{
  69162. loading = false;
  69163. $elem.text('删除');
  69164. let now = Date.now();
  69165. console.log('加载完毕', name, '用时', (now-startTime)/1000, 's');
  69166. });
  69167. loading = name;
  69168. }else {
  69169. Potree.removeModel(name);
  69170. $elem.text('添加');
  69171. }
  69172. });
  69173. pannel.find('li button[name="splitScreen"]').on('click',(e)=>{
  69174. let $elem = $(e.target);
  69175. if($elem.text() == '分屏'){
  69176. $elem.text('恢复');
  69177. MergeEditor.enterSplit();
  69178. }else {
  69179. $elem.text('分屏');
  69180. MergeEditor.leaveSplit();
  69181. }
  69182. });
  69183. let addingTag = false;
  69184. pannel.find('li button[name="tag"]').on('click',(e)=>{
  69185. let $elem = $(e.target);
  69186. viewer.tagTool.startInsertion();
  69187. });
  69188. }
  69189. addAlignmentButton(pointcloud){
  69190. var pannel = $('#alignment li[name="selectPointCloud"]>div');
  69191. var option = $(` <input name="${pointcloud.name}" class="editCheckbox" type="checkbox" >
  69192. <label for="showingLabels">${pointcloud.name}</label>`);
  69193. pannel.append(option);
  69194. /* option.find("input").on('change',function(){
  69195. })
  69196. */
  69197. }
  69198. initClipModel(){
  69199. let Clip = viewer.modules.Clip;
  69200. var pannel = $('#clipModel');
  69201. var buttons = pannel.find('button');
  69202. buttons.eq(0).on('click', Clip.enter.bind(Clip));
  69203. buttons.eq(1).on('click', Clip.download.bind(Clip));
  69204. buttons.eq(2).on('click', Clip.leave.bind(Clip));
  69205. }
  69206. initSiteModel(){
  69207. let SiteModel = viewer.modules.SiteModel;
  69208. var pannel = $('#siteModel');
  69209. pannel.find('button[name="start"] ').on('click', SiteModel.enter.bind(SiteModel));
  69210. pannel.find('button[name="exit"] ').on('click', SiteModel.leave.bind(SiteModel));
  69211. pannel.find('button[name="building"] ').on('click', SiteModel.startInsertion.bind(SiteModel,'building'));
  69212. pannel.find('button[name="floor"] ').on('click', ()=>{
  69213. SiteModel.addFloor(SiteModel.buildings[0], 'top');
  69214. } );
  69215. pannel.find('button[name="room"] ').on('click', ()=>{
  69216. SiteModel.startInsertion('room', SiteModel.buildings[0].buildChildren[0]);
  69217. });
  69218. pannel.find('button[name="digHole"] ').on('click', ()=>{
  69219. SiteModel.selected && SiteModel.startInsertion('hole', SiteModel.selected);
  69220. });
  69221. pannel.find('button[name="selectBuilding"] ').on('click', ()=>{
  69222. SiteModel.selectEntity(SiteModel.buildings[0] );
  69223. } );
  69224. pannel.find('button[name="selectFloor"] ').on('click', ()=>{
  69225. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0]);
  69226. } );
  69227. pannel.find('button[name="selectRoom"] ').on('click', ()=>{
  69228. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  69229. });
  69230. pannel.find('button[name="removeFirstBuilding"] ').on('click', ()=>{
  69231. SiteModel.removeEntity(SiteModel.buildings[0]);
  69232. });
  69233. pannel.find('button[name="removeFirstFloor"] ').on('click', ()=>{
  69234. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0]);
  69235. });
  69236. pannel.find('button[name="removeFirstRoom"] ').on('click', ()=>{
  69237. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  69238. });
  69239. pannel.find('button[name="removeFirstHole"] ').on('click', ()=>{
  69240. SiteModel.selected.removeHole(SiteModel.selected.holes[0]);
  69241. });
  69242. pannel.find('button[name="removeFirstMarker"] ').on('click', ()=>{
  69243. //SiteModel.removeMarker(SiteModel.selected.markers[0])
  69244. SiteModel.selected.removeMarker(0);
  69245. });
  69246. }
  69247. initParitcle(){
  69248. let ParticleEditor = viewer.modules.ParticleEditor;
  69249. var pannel = $('#particle');
  69250. pannel.find('button[name="addFire"] ').on('click', ()=>{
  69251. ParticleEditor.startInsertion('fire+smoke');
  69252. });
  69253. pannel.find('button[name="addExplode"] ').on('click', ()=>{
  69254. ParticleEditor.startInsertion('explode');
  69255. });
  69256. }
  69257. initPanosEdit(){
  69258. let PanoEditor = viewer.modules.PanoEditor;
  69259. let Alignment = viewer.modules.Alignment;
  69260. var pannel = $('#panos');
  69261. pannel.find('button[name="save"] ').on('click', ()=>{
  69262. console.log('saveData',PanoEditor.exportSavingData());
  69263. });
  69264. pannel.find('button[name="translate"] ').on('click', ()=>{
  69265. Alignment.switchHandle('translate');
  69266. });
  69267. pannel.find('button[name="rotate"] ').on('click', ()=>{
  69268. Alignment.switchHandle('rotate');
  69269. });
  69270. pannel.find('button[name="topView"] ').on('click', ()=>{
  69271. PanoEditor.switchView('top');
  69272. });
  69273. pannel.find('button[name="sideView"] ').on('click', ()=>{
  69274. PanoEditor.switchView('right');
  69275. });
  69276. pannel.find('button[name="3DView"] ').on('click', ()=>{
  69277. PanoEditor.switchView('mainView');
  69278. });
  69279. pannel.find('button[name="addLink"] ').on('click', ()=>{
  69280. PanoEditor.setLinkOperateState('addLink', true);
  69281. });
  69282. pannel.find('button[name="removeLink"] ').on('click', ()=>{
  69283. PanoEditor.setLinkOperateState('removeLink', true);
  69284. });
  69285. pannel.find('button[name="getCloser"] ').on('click', ()=>{
  69286. PanoEditor.setZoomInState(true);
  69287. });
  69288. }
  69289. initToolbar(){
  69290. // ANGLE
  69291. let elToolbar = $('#tools');
  69292. elToolbar.append(this.createToolIcon(
  69293. Potree.resourcePath + '/icons/angle.png',
  69294. '[title]tt.angle_measurement',
  69295. () => {
  69296. $('#menu_measurements').next().slideDown();
  69297. let measurement = this.measuringTool.startInsertion({
  69298. showDistances: false,
  69299. showAngles: true,
  69300. showArea: false,
  69301. closed: true,
  69302. maxMarkers: 3,
  69303. minMarkers:3,
  69304. measureType: 'Angle'});
  69305. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69306. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69307. $.jstree.reference(jsonNode.id).deselect_all();
  69308. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69309. }
  69310. ));
  69311. // POINT
  69312. elToolbar.append(this.createToolIcon(
  69313. Potree.resourcePath + '/icons/point.svg',
  69314. '[title]tt.point_measurement',
  69315. () => {
  69316. $('#menu_measurements').next().slideDown();
  69317. let measurement = this.measuringTool.startInsertion({
  69318. showDistances: false,
  69319. showAngles: false,
  69320. showCoordinates: true,
  69321. showEdges:false,
  69322. showArea: false,
  69323. closed: true,
  69324. maxMarkers: 1,
  69325. minMarkers:1,
  69326. measureType: 'Point'});
  69327. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69328. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69329. $.jstree.reference(jsonNode.id).deselect_all();
  69330. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69331. }
  69332. ));
  69333. // DISTANCE
  69334. elToolbar.append(this.createToolIcon(
  69335. Potree.resourcePath + '/icons/distance.svg',
  69336. '[title]tt.distance_measurement',
  69337. () => {
  69338. $('#menu_measurements').next().slideDown();
  69339. let measurement = this.measuringTool.startInsertion({
  69340. showDistances: true,
  69341. showArea: false,
  69342. closed: false,
  69343. minMarkers:2,
  69344. maxMarkers: 2,
  69345. measureType: 'Distance'
  69346. });
  69347. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69348. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69349. $.jstree.reference(jsonNode.id).deselect_all();
  69350. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69351. }
  69352. ));
  69353. // HEIGHT
  69354. elToolbar.append(this.createToolIcon(
  69355. Potree.resourcePath + '/icons/height.svg',
  69356. '[title]tt.height_measurement',
  69357. () => {
  69358. $('#menu_measurements').next().slideDown();
  69359. let measurement = this.measuringTool.startInsertion({
  69360. showDistances: true,//false,
  69361. showHeight: true,
  69362. showArea: false,
  69363. closed: false,
  69364. maxMarkers: 2,
  69365. minMarkers:2,
  69366. //showGuideLine: true: true
  69367. measureType: 'Ver Distance',
  69368. });
  69369. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69370. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69371. $.jstree.reference(jsonNode.id).deselect_all();
  69372. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69373. }
  69374. ));
  69375. // CIRCLE
  69376. elToolbar.append(this.createToolIcon(
  69377. Potree.resourcePath + '/icons/circle.svg',
  69378. '[title]tt.circle_measurement',
  69379. () => {
  69380. $('#menu_measurements').next().slideDown();
  69381. let measurement = this.measuringTool.startInsertion({
  69382. showDistances: false,
  69383. showHeight: false,
  69384. showArea: false,
  69385. showCircle: true,
  69386. showEdges: false,
  69387. closed: false,
  69388. maxMarkers: 3,
  69389. minMarkers:3,
  69390. measureType: 'Circle'
  69391. });
  69392. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69393. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69394. $.jstree.reference(jsonNode.id).deselect_all();
  69395. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69396. }
  69397. ));
  69398. // AZIMUTH
  69399. elToolbar.append(this.createToolIcon(
  69400. Potree.resourcePath + '/icons/azimuth.svg',
  69401. 'Azimuth',
  69402. () => {
  69403. $('#menu_measurements').next().slideDown();
  69404. let measurement = this.measuringTool.startInsertion({
  69405. showDistances: false,
  69406. showHeight: false,
  69407. showArea: false,
  69408. showCircle: false,
  69409. showEdges: false,
  69410. showAzimuth: true,
  69411. closed: false,
  69412. maxMarkers: 2,
  69413. minMarkers:2,
  69414. measureType: 'Azimuth'});
  69415. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69416. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69417. $.jstree.reference(jsonNode.id).deselect_all();
  69418. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69419. }
  69420. ));
  69421. // AREA
  69422. elToolbar.append(this.createToolIcon(
  69423. Potree.resourcePath + '/icons/area.svg',
  69424. '[title]tt.area_measurement',
  69425. () => {
  69426. $('#menu_measurements').next().slideDown();
  69427. let measurement = this.measuringTool.startInsertion({
  69428. showDistances: true,
  69429. showArea: true,
  69430. closed: true,
  69431. minMarkers:3,
  69432. //showGuideLine: true: true,
  69433. measureType: 'Area'});
  69434. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69435. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69436. $.jstree.reference(jsonNode.id).deselect_all();
  69437. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69438. }
  69439. ));
  69440. //Hor AREA
  69441. elToolbar.append(this.createToolIcon(
  69442. Potree.resourcePath + '/icons/area.svg',
  69443. '[title]tt.Hor Area',
  69444. () => {
  69445. $('#menu_measurements').next().slideDown();
  69446. let measurement = this.measuringTool.startInsertion({
  69447. showDistances: true,
  69448. showArea: true,
  69449. closed: true,
  69450. minMarkers:3,
  69451. measureType: 'Hor Area'});
  69452. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69453. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69454. $.jstree.reference(jsonNode.id).deselect_all();
  69455. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69456. }
  69457. ));
  69458. // Ver Area
  69459. elToolbar.append(this.createToolIcon(
  69460. Potree.resourcePath + '/icons/area.svg',
  69461. '[title]tt.Ver Area',
  69462. () => {
  69463. $('#menu_measurements').next().slideDown();
  69464. let measurement = this.measuringTool.startInsertion({
  69465. showDistances: true,
  69466. showArea: true,
  69467. closed: true,
  69468. minMarkers:3,
  69469. measureType: 'Ver Area'});
  69470. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69471. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69472. $.jstree.reference(jsonNode.id).deselect_all();
  69473. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69474. }
  69475. ));
  69476. // rect area freedom direction
  69477. elToolbar.append(this.createToolIcon(
  69478. Potree.resourcePath + '/icons/area.svg',
  69479. '[title]tt.area_freedom_rect',
  69480. () => {
  69481. $('#menu_measurements').next().slideDown();
  69482. let measurement = this.measuringTool.startInsertion({
  69483. showDistances: true,
  69484. showArea: true,
  69485. closed: true,
  69486. minMarkers:4,
  69487. maxMarkers:4,
  69488. //showGuideLine: true: true,
  69489. isRect:true,
  69490. measureType: 'Rect Area'});
  69491. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69492. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69493. $.jstree.reference(jsonNode.id).deselect_all();
  69494. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69495. }
  69496. ));
  69497. // rect area horizontal
  69498. elToolbar.append(this.createToolIcon(
  69499. Potree.resourcePath + '/icons/area.svg',
  69500. '[title]tt.area_horizontal_rect',
  69501. () => {
  69502. $('#menu_measurements').next().slideDown();
  69503. let measurement = this.measuringTool.startInsertion({
  69504. showDistances: true,
  69505. showArea: true,
  69506. closed: true,
  69507. minMarkers:4,
  69508. maxMarkers:4,
  69509. //showGuideLine: true: true,
  69510. isRect:true,
  69511. faceDirection:"horizontal",
  69512. measureType: 'Hor Rect Area'});
  69513. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69514. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69515. $.jstree.reference(jsonNode.id).deselect_all();
  69516. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69517. }
  69518. ));
  69519. // rect area vertical
  69520. elToolbar.append(this.createToolIcon(
  69521. Potree.resourcePath + '/icons/area.svg',
  69522. '[title]tt.area_vertical_rect',
  69523. () => {
  69524. $('#menu_measurements').next().slideDown();
  69525. let measurement = this.measuringTool.startInsertion({
  69526. showDistances: true,
  69527. showArea: true,
  69528. closed: true,
  69529. minMarkers:4,
  69530. maxMarkers:4,
  69531. //showGuideLine: true: true,
  69532. isRect:true,
  69533. faceDirection:"vertical",
  69534. measureType: 'Ver Rect Area'});
  69535. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69536. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69537. $.jstree.reference(jsonNode.id).deselect_all();
  69538. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69539. }
  69540. ));
  69541. // VOLUME
  69542. elToolbar.append(this.createToolIcon(
  69543. Potree.resourcePath + '/icons/volume.svg',
  69544. '[title]tt.volume_measurement',
  69545. () => {
  69546. let volume = this.volumeTool.startInsertion();
  69547. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69548. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  69549. $.jstree.reference(jsonNode.id).deselect_all();
  69550. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69551. }
  69552. ));
  69553. // SPHERE VOLUME
  69554. elToolbar.append(this.createToolIcon(
  69555. Potree.resourcePath + '/icons/sphere_distances.svg',
  69556. '[title]tt.volume_measurement',
  69557. () => {
  69558. let volume = this.volumeTool.startInsertion({type: SphereVolume});
  69559. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69560. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  69561. $.jstree.reference(jsonNode.id).deselect_all();
  69562. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69563. }
  69564. ));
  69565. // PROFILE
  69566. elToolbar.append(this.createToolIcon(
  69567. Potree.resourcePath + '/icons/profile.svg',
  69568. '[title]tt.height_profile',
  69569. () => {
  69570. $('#menu_measurements').next().slideDown(); ;
  69571. let profile = this.profileTool.startInsertion();
  69572. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69573. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === profile.uuid);
  69574. $.jstree.reference(jsonNode.id).deselect_all();
  69575. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69576. }
  69577. ));
  69578. // ANNOTATION
  69579. elToolbar.append(this.createToolIcon(
  69580. Potree.resourcePath + '/icons/annotation.svg',
  69581. '[title]tt.annotation',
  69582. () => {
  69583. $('#menu_measurements').next().slideDown(); ;
  69584. let annotation = this.viewer.annotationTool.startInsertion();
  69585. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  69586. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  69587. $.jstree.reference(jsonNode.id).deselect_all();
  69588. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69589. }
  69590. ));
  69591. // REMOVE ALL
  69592. elToolbar.append(this.createToolIcon(
  69593. Potree.resourcePath + '/icons/reset_tools.svg',
  69594. '[title]tt.remove_all_measurement',
  69595. () => {
  69596. this.viewer.scene.removeAllMeasurements();
  69597. }
  69598. ));
  69599. { // SHOW / HIDE Measurements
  69600. let elShow = $("#measurement_options_show");
  69601. elShow.selectgroup({title: "Show/Hide labels"});
  69602. elShow.find("input").click( (e) => {
  69603. const show = e.target.value === "SHOW";
  69604. this.measuringTool.showLabels = show;
  69605. });
  69606. let currentShow = this.measuringTool.showLabels ? "SHOW" : "HIDE";
  69607. elShow.find(`input[value=${currentShow}]`).trigger("click");
  69608. }
  69609. }
  69610. initScene(){
  69611. let elScene = $("#menu_scene");
  69612. let elObjects = elScene.next().find("#scene_objects");
  69613. let elProperties = elScene.next().find("#scene_object_properties");
  69614. {
  69615. let elExport = elScene.next().find("#scene_export");
  69616. let geoJSONIcon = `${Potree.resourcePath}/icons/file_geojson.svg`;
  69617. let dxfIcon = `${Potree.resourcePath}/icons/file_dxf.svg`;
  69618. let potreeIcon = `${Potree.resourcePath}/icons/file_potree.svg`;
  69619. elExport.append(`
  69620. Export: <br>
  69621. <a href="#" download="measure.json"><img name="geojson_export_button" src="${geoJSONIcon}" class="button-icon" style="height: 24px" /></a>
  69622. <a href="#" download="measure.dxf"><img name="dxf_export_button" src="${dxfIcon}" class="button-icon" style="height: 24px" /></a>
  69623. <a href="#" download="potree.json5"><img name="potree_export_button" src="${potreeIcon}" class="button-icon" style="height: 24px" /></a>
  69624. `);
  69625. let elDownloadJSON = elExport.find("img[name=geojson_export_button]").parent();
  69626. elDownloadJSON.click( (event) => {
  69627. let scene = this.viewer.scene;
  69628. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  69629. if(measurements.length > 0){
  69630. let geoJson = GeoJSONExporter.toString(measurements);
  69631. let url = window.URL.createObjectURL(new Blob([geoJson], {type: 'data:application/octet-stream'}));
  69632. elDownloadJSON.attr('href', url);
  69633. }else {
  69634. this.viewer.postError("nothing to export");
  69635. event.preventDefault();
  69636. }
  69637. });
  69638. let elDownloadDXF = elExport.find("img[name=dxf_export_button]").parent();
  69639. elDownloadDXF.click( (event) => {
  69640. let scene = this.viewer.scene;
  69641. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  69642. if(measurements.length > 0){
  69643. let dxf = DXFExporter.toString(measurements);
  69644. let url = window.URL.createObjectURL(new Blob([dxf], {type: 'data:application/octet-stream'}));
  69645. elDownloadDXF.attr('href', url);
  69646. }else {
  69647. this.viewer.postError("no measurements to export");
  69648. event.preventDefault();
  69649. }
  69650. });
  69651. let elDownloadPotree = elExport.find("img[name=potree_export_button]").parent();
  69652. elDownloadPotree.click( (event) => {
  69653. let data = Potree.saveProject(this.viewer);
  69654. let dataString = lib.stringify(data, null, "\t");
  69655. let url = window.URL.createObjectURL(new Blob([dataString], {type: 'data:application/octet-stream'}));
  69656. elDownloadPotree.attr('href', url);
  69657. });
  69658. }
  69659. let propertiesPanel = new PropertiesPanel(elProperties, this.viewer);
  69660. propertiesPanel.setScene(this.viewer.scene);
  69661. localStorage.removeItem('jstree');
  69662. let tree = $(`<div id="jstree_scene"></div>`);
  69663. elObjects.append(tree);
  69664. tree.jstree({
  69665. 'plugins': ["checkbox", "state"],
  69666. 'core': {
  69667. "dblclick_toggle": false,
  69668. "state": {
  69669. "checked" : true
  69670. },
  69671. 'check_callback': true,
  69672. "expand_selected_onload": true
  69673. },
  69674. "checkbox" : {
  69675. "keep_selected_style": true,
  69676. "three_state": false,
  69677. "whole_node": false,
  69678. "tie_selection": false,
  69679. },
  69680. });
  69681. let createNode = (parent, text, icon, object) => {
  69682. let nodeID = tree.jstree('create_node', parent, {
  69683. "text": text,
  69684. "icon": icon,
  69685. "data": object
  69686. },
  69687. "last", false, false);
  69688. if(object.visible){
  69689. tree.jstree('check_node', nodeID);
  69690. }else {
  69691. tree.jstree('uncheck_node', nodeID);
  69692. }
  69693. return nodeID;
  69694. };
  69695. let pcID = tree.jstree('create_node', "#", { "text": "<b>Point Clouds</b>", "id": "pointclouds"}, "last", false, false);
  69696. let measurementID = tree.jstree('create_node', "#", { "text": "<b>Measurements</b>", "id": "measurements" }, "last", false, false);
  69697. let annotationsID = tree.jstree('create_node', "#", { "text": "<b>Annotations</b>", "id": "annotations" }, "last", false, false);
  69698. let otherID = tree.jstree('create_node', "#", { "text": "<b>Other</b>", "id": "other" }, "last", false, false);
  69699. let vectorsID = tree.jstree('create_node', "#", { "text": "<b>Vectors</b>", "id": "vectors" }, "last", false, false);
  69700. let imagesID = tree.jstree('create_node', "#", { "text": "<b> Images</b>", "id": "images" }, "last", false, false);
  69701. tree.jstree("check_node", pcID);
  69702. tree.jstree("check_node", measurementID);
  69703. tree.jstree("check_node", annotationsID);
  69704. tree.jstree("check_node", otherID);
  69705. tree.jstree("check_node", vectorsID);
  69706. tree.jstree("check_node", imagesID);
  69707. tree.on('create_node.jstree', (e, data) => {
  69708. tree.jstree("open_all");
  69709. });
  69710. tree.on("select_node.jstree", (e, data) => {
  69711. let object = data.node.data;
  69712. propertiesPanel.set(object);
  69713. this.viewer.inputHandler.deselectAll();
  69714. if(object instanceof Volume){
  69715. this.viewer.inputHandler.toggleSelection(object);
  69716. }
  69717. $(this.viewer.renderer.domElement).focus();
  69718. });
  69719. tree.on("deselect_node.jstree", (e, data) => {
  69720. propertiesPanel.set(null);
  69721. });
  69722. tree.on("delete_node.jstree", (e, data) => {
  69723. propertiesPanel.set(null);
  69724. });
  69725. tree.on('dblclick','.jstree-anchor', (e) => {
  69726. let instance = $.jstree.reference(e.target);
  69727. let node = instance.get_node(e.target);
  69728. let object = node.data;
  69729. // ignore double click on checkbox
  69730. if(e.target.classList.contains("jstree-checkbox")){
  69731. return;
  69732. }
  69733. if(object instanceof PointCloudTree){
  69734. let box = this.viewer.getBoundingBox([object]);
  69735. let node = new Object3D();
  69736. node.boundingBox = box;
  69737. this.viewer.zoomTo(node, 1, 500);
  69738. }else if(object instanceof Measure){
  69739. let points = object.points.map(p => p.position);
  69740. let box = new Box3().setFromPoints(points);
  69741. if(box.getSize(new Vector3()).length() == 0){
  69742. box.min = box.max.clone();//禁止相同
  69743. box.expandByVector(new Vector3(1,1,1));
  69744. }
  69745. let node = new Object3D();
  69746. node.boundingBox = box;
  69747. this.viewer.zoomTo(node, 2, 500);
  69748. }else if(object instanceof Profile){
  69749. let points = object.points;
  69750. let box = new Box3().setFromPoints(points);
  69751. if(box.getSize(new Vector3()).length() > 0){
  69752. let node = new Object3D();
  69753. node.boundingBox = box;
  69754. this.viewer.zoomTo(node, 1, 500);
  69755. }
  69756. }else if(object instanceof Volume){
  69757. let box = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  69758. if(box.getSize(new Vector3()).length() > 0){
  69759. let node = new Object3D();
  69760. node.boundingBox = box;
  69761. this.viewer.zoomTo(node, 1, 500);
  69762. }
  69763. }else if(object instanceof Annotation){
  69764. object.moveHere(this.viewer.scene.getActiveCamera());
  69765. }else if(object instanceof PolygonClipVolume){
  69766. let dir = object.camera.getWorldDirection(new Vector3());
  69767. let target;
  69768. if(object.camera instanceof OrthographicCamera){
  69769. dir.multiplyScalar(object.camera.right);
  69770. target = new Vector3().addVectors(object.camera.position, dir);
  69771. this.viewer.setCameraMode(CameraMode.ORTHOGRAPHIC);
  69772. }else if(object.camera instanceof PerspectiveCamera){
  69773. dir.multiplyScalar(this.viewer.scene.view.radius);
  69774. target = new Vector3().addVectors(object.camera.position, dir);
  69775. this.viewer.setCameraMode(CameraMode.PERSPECTIVE);
  69776. }
  69777. this.viewer.scene.view.position.copy(object.camera.position);
  69778. this.viewer.scene.view.lookAt(target);
  69779. }else if(object.type === "SpotLight"){
  69780. let distance = (object.distance > 0) ? object.distance / 4 : 5 * 1000;
  69781. let position = object.position;
  69782. let target = new Vector3().addVectors(
  69783. position,
  69784. object.getWorldDirection(new Vector3()).multiplyScalar(distance));
  69785. this.viewer.scene.view.position.copy(object.position);
  69786. this.viewer.scene.view.lookAt(target);
  69787. }else if(object instanceof Object3D){
  69788. let box = new Box3().setFromObject(object);
  69789. if(box.getSize(new Vector3()).length() > 0){
  69790. let node = new Object3D();
  69791. node.boundingBox = box;
  69792. this.viewer.zoomTo(node, 1, 500);
  69793. }
  69794. }else if(object instanceof OrientedImage){
  69795. // TODO zoom to images
  69796. // let box = new THREE.Box3().setFromObject(object);
  69797. // if(box.getSize(new THREE.Vector3()).length() > 0){
  69798. // let node = new THREE.Object3D();
  69799. // node.boundingBox = box;
  69800. // this.viewer.zoomTo(node, 1, 500);
  69801. // }
  69802. }else if(object instanceof Images360){
  69803. // TODO
  69804. }else if(object instanceof Geopackage){
  69805. // TODO
  69806. }
  69807. });
  69808. tree.on("uncheck_node.jstree", (e, data) => {
  69809. let object = data.node.data;
  69810. if(object){
  69811. object.visible = false;
  69812. }
  69813. });
  69814. tree.on("check_node.jstree", (e, data) => {
  69815. let object = data.node.data;
  69816. if(object){
  69817. object.visible = true;
  69818. }
  69819. });
  69820. let onPointCloudAdded = (e) => {
  69821. let pointcloud = e.pointcloud;
  69822. let cloudIcon = `${Potree.resourcePath}/icons/cloud.svg`;
  69823. let node = createNode(pcID, pointcloud.name, cloudIcon, pointcloud);
  69824. pointcloud.addEventListener("visibility_changed", () => {
  69825. if(pointcloud.visible){
  69826. tree.jstree('check_node', node);
  69827. }else {
  69828. tree.jstree('uncheck_node', node);
  69829. }
  69830. });
  69831. };
  69832. let onMeasurementAdded = (e) => {
  69833. let measurement = e.measurement;
  69834. let icon = Utils.getMeasurementIcon(measurement);
  69835. createNode(measurementID, measurement.name, icon, measurement);
  69836. };
  69837. let onVolumeAdded = (e) => {
  69838. let volume = e.volume;
  69839. let icon = Utils.getMeasurementIcon(volume);
  69840. let node = createNode(measurementID, volume.name, icon, volume);
  69841. volume.addEventListener("visibility_changed", () => {
  69842. if(volume.visible){
  69843. tree.jstree('check_node', node);
  69844. }else {
  69845. tree.jstree('uncheck_node', node);
  69846. }
  69847. });
  69848. };
  69849. let onProfileAdded = (e) => {
  69850. let profile = e.profile;
  69851. let icon = Utils.getMeasurementIcon(profile);
  69852. createNode(measurementID, profile.name, icon, profile);
  69853. };
  69854. let onAnnotationAdded = (e) => {
  69855. let annotation = e.annotation;
  69856. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  69857. let parentID = this.annotationMapping.get(annotation.parent);
  69858. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  69859. this.annotationMapping.set(annotation, annotationID);
  69860. annotation.addEventListener("annotation_changed", (e) => {
  69861. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  69862. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  69863. $.jstree.reference(jsonNode.id).rename_node(jsonNode.id, annotation.title);
  69864. });
  69865. };
  69866. let onCameraAnimationAdded = (e) => {
  69867. const animation = e.animation;
  69868. const animationIcon = `${Potree.resourcePath}/icons/camera_animation.svg`;
  69869. createNode(otherID, "animation", animationIcon, animation);
  69870. };
  69871. let onOrientedImagesAdded = (e) => {
  69872. const images = e.images;
  69873. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  69874. const node = createNode(imagesID, "images", imagesIcon, images);
  69875. images.addEventListener("visibility_changed", () => {
  69876. if(images.visible){
  69877. tree.jstree('check_node', node);
  69878. }else {
  69879. tree.jstree('uncheck_node', node);
  69880. }
  69881. });
  69882. };
  69883. let onImages360Added = (e) => {
  69884. const images = e.images;
  69885. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  69886. const node = createNode(imagesID, "360° images", imagesIcon, images);
  69887. images.addEventListener("visibility_changed", () => {
  69888. if(images.visible){
  69889. tree.jstree('check_node', node);
  69890. }else {
  69891. tree.jstree('uncheck_node', node);
  69892. }
  69893. });
  69894. };
  69895. const onGeopackageAdded = (e) => {
  69896. const geopackage = e.geopackage;
  69897. const geopackageIcon = `${Potree.resourcePath}/icons/triangle.svg`;
  69898. const tree = $(`#jstree_scene`);
  69899. const parentNode = "vectors";
  69900. for(const layer of geopackage.node.children){
  69901. const name = layer.name;
  69902. let shpPointsID = tree.jstree('create_node', parentNode, {
  69903. "text": name,
  69904. "icon": geopackageIcon,
  69905. "object": layer,
  69906. "data": layer,
  69907. },
  69908. "last", false, false);
  69909. tree.jstree(layer.visible ? "check_node" : "uncheck_node", shpPointsID);
  69910. }
  69911. };
  69912. this.viewer.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  69913. this.viewer.scene.addEventListener("measurement_added", onMeasurementAdded);
  69914. this.viewer.scene.addEventListener("profile_added", onProfileAdded);
  69915. this.viewer.scene.addEventListener("volume_added", onVolumeAdded);
  69916. this.viewer.scene.addEventListener("camera_animation_added", onCameraAnimationAdded);
  69917. this.viewer.scene.addEventListener("oriented_images_added", onOrientedImagesAdded);
  69918. this.viewer.scene.addEventListener("360_images_added", onImages360Added);
  69919. this.viewer.scene.addEventListener("geopackage_added", onGeopackageAdded);
  69920. this.viewer.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  69921. this.viewer.scene.annotations.addEventListener("annotation_added", onAnnotationAdded);
  69922. let onMeasurementRemoved = (e) => {
  69923. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69924. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.measurement.uuid);
  69925. tree.jstree("delete_node", jsonNode.id);
  69926. };
  69927. let onVolumeRemoved = (e) => {
  69928. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69929. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  69930. tree.jstree("delete_node", jsonNode.id);
  69931. };
  69932. let onPolygonClipVolumeRemoved = (e) => {
  69933. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69934. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  69935. tree.jstree("delete_node", jsonNode.id);
  69936. };
  69937. let onProfileRemoved = (e) => {
  69938. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69939. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.profile.uuid);
  69940. tree.jstree("delete_node", jsonNode.id);
  69941. };
  69942. this.viewer.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  69943. this.viewer.scene.addEventListener("volume_removed", onVolumeRemoved);
  69944. this.viewer.scene.addEventListener("polygon_clip_volume_removed", onPolygonClipVolumeRemoved);
  69945. this.viewer.scene.addEventListener("profile_removed", onProfileRemoved);
  69946. {
  69947. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  69948. this.annotationMapping = new Map();
  69949. this.annotationMapping.set(this.viewer.scene.annotations, annotationsID);
  69950. this.viewer.scene.annotations.traverseDescendants(annotation => {
  69951. let parentID = this.annotationMapping.get(annotation.parent);
  69952. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  69953. this.annotationMapping.set(annotation, annotationID);
  69954. });
  69955. }
  69956. const scene = this.viewer.scene;
  69957. for(let pointcloud of scene.pointclouds){
  69958. onPointCloudAdded({pointcloud: pointcloud});
  69959. }
  69960. for(let measurement of scene.measurements){
  69961. onMeasurementAdded({measurement: measurement});
  69962. }
  69963. for(let volume of [...scene.volumes, ...scene.polygonClipVolumes]){
  69964. onVolumeAdded({volume: volume});
  69965. }
  69966. for(let animation of scene.cameraAnimations){
  69967. onCameraAnimationAdded({animation: animation});
  69968. }
  69969. for(let images of scene.orientedImages){
  69970. onOrientedImagesAdded({images: images});
  69971. }
  69972. for(let images of scene.images360){
  69973. onImages360Added({images: images});
  69974. }
  69975. for(const geopackage of scene.geopackages){
  69976. onGeopackageAdded({geopackage: geopackage});
  69977. }
  69978. for(let profile of scene.profiles){
  69979. onProfileAdded({profile: profile});
  69980. }
  69981. {
  69982. createNode(otherID, "Camera", null, new Camera());
  69983. }
  69984. this.viewer.addEventListener("scene_changed", (e) => {
  69985. propertiesPanel.setScene(e.scene);
  69986. e.oldScene.removeEventListener("pointcloud_added", onPointCloudAdded);
  69987. e.oldScene.removeEventListener("measurement_added", onMeasurementAdded);
  69988. e.oldScene.removeEventListener("profile_added", onProfileAdded);
  69989. e.oldScene.removeEventListener("volume_added", onVolumeAdded);
  69990. e.oldScene.removeEventListener("polygon_clip_volume_added", onVolumeAdded);
  69991. e.oldScene.removeEventListener("measurement_removed", onMeasurementRemoved);
  69992. e.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  69993. e.scene.addEventListener("measurement_added", onMeasurementAdded);
  69994. e.scene.addEventListener("profile_added", onProfileAdded);
  69995. e.scene.addEventListener("volume_added", onVolumeAdded);
  69996. e.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  69997. e.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  69998. });
  69999. }
  70000. initClippingTool(){
  70001. this.viewer.addEventListener("cliptask_changed", (event) => {
  70002. console.log("TODO");
  70003. });
  70004. this.viewer.addEventListener("clipmethod_changed", (event) => {
  70005. console.log("TODO");
  70006. });
  70007. {
  70008. let elClipTask = $("#cliptask_options");
  70009. elClipTask.selectgroup({title: "Clip Task"});
  70010. elClipTask.find("input").click( (e) => {
  70011. this.viewer.setClipTask(ClipTask[e.target.value]);
  70012. });
  70013. let currentClipTask = Object.keys(ClipTask)
  70014. .filter(key => ClipTask[key] === this.viewer.clipTask);
  70015. elClipTask.find(`input[value=${currentClipTask}]`).trigger("click");
  70016. }
  70017. {
  70018. let elClipMethod = $("#clipmethod_options");
  70019. elClipMethod.selectgroup({title: "Clip Method"});
  70020. elClipMethod.find("input").click( (e) => {
  70021. this.viewer.setClipMethod(ClipMethod[e.target.value]);
  70022. });
  70023. let currentClipMethod = Object.keys(ClipMethod)
  70024. .filter(key => ClipMethod[key] === this.viewer.clipMethod);
  70025. elClipMethod.find(`input[value=${currentClipMethod}]`).trigger("click");
  70026. }
  70027. let clippingToolBar = $("#clipping_tools");
  70028. // CLIP VOLUME
  70029. clippingToolBar.append(this.createToolIcon(
  70030. Potree.resourcePath + '/icons/clip_volume.svg',
  70031. '[title]tt.clip_volume',
  70032. () => {
  70033. let item = this.volumeTool.startInsertion({clip: true});
  70034. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  70035. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  70036. $.jstree.reference(jsonNode.id).deselect_all();
  70037. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  70038. }
  70039. ));
  70040. // CLIP POLYGON
  70041. clippingToolBar.append(this.createToolIcon(
  70042. Potree.resourcePath + "/icons/clip-polygon.svg",
  70043. "[title]tt.clip_polygon",
  70044. () => {
  70045. let item = this.viewer.clippingTool.startInsertion({type: "polygon"});
  70046. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  70047. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  70048. $.jstree.reference(jsonNode.id).deselect_all();
  70049. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  70050. }
  70051. ));
  70052. {// SCREEN BOX SELECT
  70053. let boxSelectTool = new ScreenBoxSelectTool(this.viewer);
  70054. clippingToolBar.append(this.createToolIcon(
  70055. Potree.resourcePath + "/icons/clip-screen.svg",
  70056. "[title]tt.screen_clip_box",
  70057. () => {
  70058. if(!(this.viewer.scene.getActiveCamera() instanceof OrthographicCamera)){
  70059. this.viewer.postMessage(`Switch to Orthographic Camera Mode before using the Screen-Box-Select tool.`,
  70060. {duration: 2000});
  70061. return;
  70062. }
  70063. let item = boxSelectTool.startInsertion();
  70064. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  70065. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  70066. $.jstree.reference(jsonNode.id).deselect_all();
  70067. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  70068. }
  70069. ));
  70070. }
  70071. { // REMOVE CLIPPING TOOLS
  70072. clippingToolBar.append(this.createToolIcon(
  70073. Potree.resourcePath + "/icons/remove.svg",
  70074. "[title]tt.remove_all_clipping_volumes",
  70075. () => {
  70076. this.viewer.scene.removeAllClipVolumes();
  70077. }
  70078. ));
  70079. }
  70080. }
  70081. initFilters(){
  70082. this.initClassificationList();
  70083. this.initReturnFilters();
  70084. this.initGPSTimeFilters();
  70085. this.initPointSourceIDFilters();
  70086. }
  70087. initReturnFilters(){
  70088. let elReturnFilterPanel = $('#return_filter_panel');
  70089. { // RETURN NUMBER
  70090. let sldReturnNumber = elReturnFilterPanel.find('#sldReturnNumber');
  70091. let lblReturnNumber = elReturnFilterPanel.find('#lblReturnNumber');
  70092. sldReturnNumber.slider({
  70093. range: true,
  70094. min: 0, max: 7, step: 1,
  70095. values: [0, 7],
  70096. slide: (event, ui) => {
  70097. this.viewer.setFilterReturnNumberRange(ui.values[0], ui.values[1]);
  70098. }
  70099. });
  70100. let onReturnNumberChanged = (event) => {
  70101. let [from, to] = this.viewer.filterReturnNumberRange;
  70102. lblReturnNumber[0].innerHTML = `${from} to ${to}`;
  70103. sldReturnNumber.slider({values: [from, to]});
  70104. };
  70105. this.viewer.addEventListener('filter_return_number_range_changed', onReturnNumberChanged);
  70106. onReturnNumberChanged();
  70107. }
  70108. { // NUMBER OF RETURNS
  70109. let sldNumberOfReturns = elReturnFilterPanel.find('#sldNumberOfReturns');
  70110. let lblNumberOfReturns = elReturnFilterPanel.find('#lblNumberOfReturns');
  70111. sldNumberOfReturns.slider({
  70112. range: true,
  70113. min: 0, max: 7, step: 1,
  70114. values: [0, 7],
  70115. slide: (event, ui) => {
  70116. this.viewer.setFilterNumberOfReturnsRange(ui.values[0], ui.values[1]);
  70117. }
  70118. });
  70119. let onNumberOfReturnsChanged = (event) => {
  70120. let [from, to] = this.viewer.filterNumberOfReturnsRange;
  70121. lblNumberOfReturns[0].innerHTML = `${from} to ${to}`;
  70122. sldNumberOfReturns.slider({values: [from, to]});
  70123. };
  70124. this.viewer.addEventListener('filter_number_of_returns_range_changed', onNumberOfReturnsChanged);
  70125. onNumberOfReturnsChanged();
  70126. }
  70127. }
  70128. initGPSTimeFilters(){
  70129. let elGPSTimeFilterPanel = $('#gpstime_filter_panel');
  70130. {
  70131. let slider = new HierarchicalSlider({
  70132. levels: 4,
  70133. slide: (event) => {
  70134. this.viewer.setFilterGPSTimeRange(...event.values);
  70135. },
  70136. });
  70137. let initialized = false;
  70138. let initialize = () => {
  70139. let elRangeContainer = $("#gpstime_multilevel_range_container");
  70140. elRangeContainer[0].prepend(slider.element);
  70141. let extent = this.viewer.getGpsTimeExtent();
  70142. slider.setRange(extent);
  70143. slider.setValues(extent);
  70144. initialized = true;
  70145. };
  70146. this.viewer.addEventListener("update", (e) => {
  70147. let extent = this.viewer.getGpsTimeExtent();
  70148. let gpsTimeAvailable = extent[0] !== Infinity;
  70149. if(!initialized && gpsTimeAvailable){
  70150. initialize();
  70151. }
  70152. slider.setRange(extent);
  70153. });
  70154. }
  70155. {
  70156. const txtGpsTime = elGPSTimeFilterPanel.find("#txtGpsTime");
  70157. const btnFindGpsTime = elGPSTimeFilterPanel.find("#btnFindGpsTime");
  70158. let targetTime = null;
  70159. txtGpsTime.on("input", (e) => {
  70160. const str = txtGpsTime.val();
  70161. if(!isNaN(str)){
  70162. const value = parseFloat(str);
  70163. targetTime = value;
  70164. txtGpsTime.css("background-color", "");
  70165. }else {
  70166. targetTime = null;
  70167. txtGpsTime.css("background-color", "#ff9999");
  70168. }
  70169. });
  70170. btnFindGpsTime.click( () => {
  70171. if(targetTime !== null){
  70172. viewer.moveToGpsTimeVicinity(targetTime);
  70173. }
  70174. });
  70175. }
  70176. }
  70177. initPointSourceIDFilters() {
  70178. let elPointSourceIDFilterPanel = $('#pointsourceid_filter_panel');
  70179. {
  70180. let slider = new HierarchicalSlider({
  70181. levels: 4,
  70182. range: [0, 65535],
  70183. precision: 1,
  70184. slide: (event) => {
  70185. let values = event.values;
  70186. this.viewer.setFilterPointSourceIDRange(values[0], values[1]);
  70187. }
  70188. });
  70189. let initialized = false;
  70190. let initialize = () => {
  70191. elPointSourceIDFilterPanel[0].prepend(slider.element);
  70192. initialized = true;
  70193. };
  70194. this.viewer.addEventListener("update", (e) => {
  70195. let extent = this.viewer.filterPointSourceIDRange;
  70196. if(!initialized){
  70197. initialize();
  70198. slider.setValues(extent);
  70199. }
  70200. });
  70201. }
  70202. // let lblPointSourceID = elPointSourceIDFilterPanel.find("#lblPointSourceID");
  70203. // let elPointSourceID = elPointSourceIDFilterPanel.find("#spnPointSourceID");
  70204. // let slider = new ZoomableSlider();
  70205. // elPointSourceID[0].appendChild(slider.element);
  70206. // slider.update();
  70207. // slider.change( () => {
  70208. // let range = slider.chosenRange;
  70209. // this.viewer.setFilterPointSourceIDRange(range[0], range[1]);
  70210. // });
  70211. // let onPointSourceIDExtentChanged = (event) => {
  70212. // let range = this.viewer.filterPointSourceIDExtent;
  70213. // slider.setVisibleRange(range);
  70214. // };
  70215. // let onPointSourceIDChanged = (event) => {
  70216. // let range = this.viewer.filterPointSourceIDRange;
  70217. // let precision = 1;
  70218. // let from = `${Utils.addCommas(range[0].toFixed(precision))}`;
  70219. // let to = `${Utils.addCommas(range[1].toFixed(precision))}`;
  70220. // lblPointSourceID[0].innerHTML = `${from} to ${to}`;
  70221. // slider.setRange(range);
  70222. // };
  70223. // this.viewer.addEventListener('filter_point_source_id_range_changed', onPointSourceIDChanged);
  70224. // this.viewer.addEventListener('filter_point_source_id_extent_changed', onPointSourceIDExtentChanged);
  70225. }
  70226. initClassificationList(){
  70227. let elClassificationList = $('#classificationList');
  70228. let addClassificationItem = (code, name) => {
  70229. const classification = this.viewer.classifications[code];
  70230. const inputID = 'chkClassification_' + code;
  70231. const colorPickerID = 'colorPickerClassification_' + code;
  70232. const checked = classification.visible ? "checked" : "";
  70233. let element = $(`
  70234. <li>
  70235. <label style="whitespace: nowrap; display: flex">
  70236. <input id="${inputID}" type="checkbox" ${checked}/>
  70237. <span style="flex-grow: 1">${name}</span>
  70238. <input id="${colorPickerID}" style="zoom: 0.5" />
  70239. </label>
  70240. </li>
  70241. `);
  70242. const elInput = element.find('input');
  70243. const elColorPicker = element.find(`#${colorPickerID}`);
  70244. elInput.click(event => {
  70245. this.viewer.setClassificationVisibility(code, event.target.checked);
  70246. });
  70247. let defaultColor = classification.color.map(c => c * 255).join(", ");
  70248. defaultColor = `rgb(${defaultColor})`;
  70249. elColorPicker.spectrum({
  70250. // flat: true,
  70251. color: defaultColor,
  70252. showInput: true,
  70253. preferredFormat: 'rgb',
  70254. cancelText: '',
  70255. chooseText: 'Apply',
  70256. move: color => {
  70257. let rgb = color.toRgb();
  70258. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  70259. classification.color = c;
  70260. },
  70261. change: color => {
  70262. let rgb = color.toRgb();
  70263. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  70264. classification.color = c;
  70265. }
  70266. });
  70267. elClassificationList.append(element);
  70268. };
  70269. const addToggleAllButton = () => { // toggle all button
  70270. const element = $(`
  70271. <li>
  70272. <label style="whitespace: nowrap">
  70273. <input id="toggleClassificationFilters" type="checkbox" checked/>
  70274. <span>show/hide all</span>
  70275. </label>
  70276. </li>
  70277. `);
  70278. let elInput = element.find('input');
  70279. elInput.click(event => {
  70280. this.viewer.toggleAllClassificationsVisibility();
  70281. });
  70282. elClassificationList.append(element);
  70283. };
  70284. const addInvertButton = () => {
  70285. const element = $(`
  70286. <li>
  70287. <input type="button" value="invert" />
  70288. </li>
  70289. `);
  70290. let elInput = element.find('input');
  70291. elInput.click( () => {
  70292. const classifications = this.viewer.classifications;
  70293. for(let key of Object.keys(classifications)){
  70294. let value = classifications[key];
  70295. this.viewer.setClassificationVisibility(key, !value.visible);
  70296. }
  70297. });
  70298. elClassificationList.append(element);
  70299. };
  70300. const populate = () => {
  70301. addToggleAllButton();
  70302. for (let classID in this.viewer.classifications) {
  70303. addClassificationItem(classID, this.viewer.classifications[classID].name);
  70304. }
  70305. addInvertButton();
  70306. };
  70307. populate();
  70308. this.viewer.addEventListener("classifications_changed", () => {
  70309. elClassificationList.empty();
  70310. populate();
  70311. });
  70312. this.viewer.addEventListener("classification_visibility_changed", () => {
  70313. { // set checked state of classification buttons
  70314. for(const classID of Object.keys(this.viewer.classifications)){
  70315. const classValue = this.viewer.classifications[classID];
  70316. let elItem = elClassificationList.find(`#chkClassification_${classID}`);
  70317. elItem.prop("checked", classValue.visible);
  70318. }
  70319. }
  70320. { // set checked state of toggle button based on state of all other buttons
  70321. let numVisible = 0;
  70322. let numItems = 0;
  70323. for(const key of Object.keys(this.viewer.classifications)){
  70324. if(this.viewer.classifications[key].visible){
  70325. numVisible++;
  70326. }
  70327. numItems++;
  70328. }
  70329. const allVisible = numVisible === numItems;
  70330. let elToggle = elClassificationList.find("#toggleClassificationFilters");
  70331. elToggle.prop("checked", allVisible);
  70332. }
  70333. });
  70334. }
  70335. initAccordion(){
  70336. $('.accordion > h3').each(function(){
  70337. let header = $(this);
  70338. let content = $(this).next();
  70339. //header.addClass('accordion-header ui-widget');
  70340. //content.addClass('accordion-content ui-widget');
  70341. content.hide();
  70342. header.click(() => {
  70343. content.slideToggle();
  70344. });
  70345. });
  70346. let languages = [
  70347. ["EN", "en"],
  70348. ["FR", "fr"],
  70349. ["DE", "de"],
  70350. ["JP", "jp"],
  70351. ["ES", "es"],
  70352. ["SE", "se"],
  70353. ["ZH", "zh"]
  70354. ];
  70355. let elLanguages = $('#potree_languages');
  70356. for(let i = 0; i < languages.length; i++){
  70357. let [key, value] = languages[i];
  70358. let element = $(`<a>${key}</a>`);
  70359. element.click(() => this.viewer.setLanguage(value));
  70360. if(i === 0){
  70361. element.css("margin-left", "30px");
  70362. }
  70363. elLanguages.append(element);
  70364. if(i < languages.length - 1){
  70365. elLanguages.append($(document.createTextNode(' - ')));
  70366. }
  70367. }
  70368. // to close all, call
  70369. // $(".accordion > div").hide()
  70370. // to open the, for example, tool menu, call:
  70371. // $("#menu_tools").next().show()
  70372. }
  70373. initAppearance(){
  70374. const sldPointBudget = this.dom.find('#sldPointBudget');
  70375. sldPointBudget.slider({
  70376. value: this.viewer.getPointBudget(),
  70377. min: 100 * 1000,
  70378. max: 10 * 1000 * 1000,
  70379. step: 1000,
  70380. slide: (event, ui) => { this.viewer.setPointBudget(ui.value); }
  70381. });
  70382. this.dom.find('#sldFOV').slider({
  70383. value: this.viewer.getFOV(),
  70384. min: 20,
  70385. max: 100,
  70386. step: 1,
  70387. slide: (event, ui) => { this.viewer.setFOV(ui.value); }
  70388. });
  70389. $('#sldEDLRadius').slider({
  70390. value: this.viewer.getEDLRadius(),
  70391. min: 1,
  70392. max: 4,
  70393. step: 0.01,
  70394. slide: (event, ui) => { this.viewer.setEDLRadius(ui.value); }
  70395. });
  70396. $('#sldEDLStrength').slider({
  70397. value: this.viewer.getEDLStrength(),
  70398. min: 0,
  70399. max: 5,
  70400. step: 0.01,
  70401. slide: (event, ui) => { this.viewer.setEDLStrength(ui.value); }
  70402. });
  70403. $('#sldEDLOpacity').slider({
  70404. value: this.viewer.getEDLOpacity(),
  70405. min: 0,
  70406. max: 1,
  70407. step: 0.01,
  70408. slide: (event, ui) => { this.viewer.setEDLOpacity(ui.value); }
  70409. });
  70410. this.viewer.addEventListener('point_budget_changed', (event) => {
  70411. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  70412. sldPointBudget.slider({value: this.viewer.getPointBudget()});
  70413. });
  70414. this.viewer.addEventListener('fov_changed', (event) => {
  70415. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  70416. $('#sldFOV').slider({value: this.viewer.getFOV()});
  70417. });
  70418. this.viewer.addEventListener('use_edl_changed', (event) => {
  70419. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  70420. });
  70421. this.viewer.addEventListener('edl_radius_changed', (event) => {
  70422. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  70423. $('#sldEDLRadius').slider({value: this.viewer.getEDLRadius()});
  70424. });
  70425. this.viewer.addEventListener('edl_strength_changed', (event) => {
  70426. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  70427. $('#sldEDLStrength').slider({value: this.viewer.getEDLStrength()});
  70428. });
  70429. this.viewer.addEventListener('background_changed', (event) => {
  70430. $("input[name=background][value='" + this.viewer.getBackground() + "']").prop('checked', true);
  70431. });
  70432. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  70433. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  70434. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  70435. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  70436. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  70437. {
  70438. let elBackground = $(`#background_options`);
  70439. elBackground.selectgroup();
  70440. elBackground.find("input").click( (e) => {
  70441. this.viewer.setBackground(e.target.value);
  70442. });
  70443. let currentBackground = this.viewer.getBackground();
  70444. try{
  70445. $(`input[name=background_options][value=${currentBackground}]`).trigger("click");
  70446. }catch(e){}
  70447. }
  70448. $('#chkEDLEnabled').click( () => {
  70449. this.viewer.setEDLEnabled($('#chkEDLEnabled').prop("checked"));
  70450. });
  70451. }
  70452. initNavigation(){
  70453. let elNavigation = $('#navigation');
  70454. let sldMoveSpeed = $('#sldMoveSpeed');
  70455. let lblMoveSpeed = $('#lblMoveSpeed');
  70456. elNavigation.append(this.createToolIcon(
  70457. Potree.resourcePath + '/icons/earth_controls_1.png',
  70458. '[title]tt.earth_control',
  70459. () => { this.viewer.setControls(this.viewer.earthControls); }
  70460. ));
  70461. elNavigation.append(this.createToolIcon(
  70462. Potree.resourcePath + '/icons/fps_controls.svg',
  70463. '[title]tt.flight_control',
  70464. () => {
  70465. this.viewer.setControls(this.viewer.fpControls);
  70466. this.viewer.fpControls.lockElevation = false;
  70467. }
  70468. ));
  70469. elNavigation.append(this.createToolIcon(
  70470. Potree.resourcePath + '/icons/helicopter_controls.svg',
  70471. '[title]tt.heli_control',
  70472. () => {
  70473. this.viewer.setControls(this.viewer.fpControls);
  70474. this.viewer.fpControls.lockElevation = true;
  70475. }
  70476. ));
  70477. elNavigation.append(this.createToolIcon(
  70478. Potree.resourcePath + '/icons/orbit_controls.svg',
  70479. '[title]tt.orbit_control',
  70480. () => { this.viewer.setControls(this.viewer.orbitControls); }
  70481. ));
  70482. elNavigation.append(this.createToolIcon(
  70483. Potree.resourcePath + '/icons/focus.svg',
  70484. '[title]tt.focus_control',
  70485. () => { this.viewer.fitToScreen(); }
  70486. ));
  70487. elNavigation.append(this.createToolIcon(
  70488. Potree.resourcePath + "/icons/navigation_cube.svg",
  70489. "[title]tt.navigation_cube_control",
  70490. () => {this.viewer.toggleNavigationCube();}
  70491. ));
  70492. elNavigation.append(this.createToolIcon(
  70493. Potree.resourcePath + "/images/compas.svg",
  70494. "[title]tt.compass",
  70495. () => {
  70496. const visible = !this.viewer.compass.isVisible();
  70497. this.viewer.compass.setVisible(visible);
  70498. }
  70499. ));
  70500. elNavigation.append(this.createToolIcon(
  70501. Potree.resourcePath + "/icons/camera_animation.svg",
  70502. "[title]tt.camera_animation",
  70503. () => {
  70504. const animation = CameraAnimation.defaultFromView(this.viewer);
  70505. viewer.scene.addCameraAnimation(animation);
  70506. }
  70507. ));
  70508. elNavigation.append("<br>");
  70509. elNavigation.append(this.createToolIcon(
  70510. Potree.resourcePath + "/icons/left.svg",
  70511. "[title]tt.left_view_control",
  70512. () => {this.viewer.setLeftView();}
  70513. ));
  70514. elNavigation.append(this.createToolIcon(
  70515. Potree.resourcePath + "/icons/right.svg",
  70516. "[title]tt.right_view_control",
  70517. () => {this.viewer.setRightView();}
  70518. ));
  70519. elNavigation.append(this.createToolIcon(
  70520. Potree.resourcePath + "/icons/front.svg",
  70521. "[title]tt.front_view_control",
  70522. () => {this.viewer.setFrontView();}
  70523. ));
  70524. elNavigation.append(this.createToolIcon(
  70525. Potree.resourcePath + "/icons/back.svg",
  70526. "[title]tt.back_view_control",
  70527. () => {this.viewer.setBackView();}
  70528. ));
  70529. elNavigation.append(this.createToolIcon(
  70530. Potree.resourcePath + "/icons/top.svg",
  70531. "[title]tt.top_view_control",
  70532. () => {this.viewer.setTopView();}
  70533. ));
  70534. elNavigation.append(this.createToolIcon(
  70535. Potree.resourcePath + "/icons/bottom.svg",
  70536. "[title]tt.bottom_view_control",
  70537. () => {this.viewer.setBottomView();}
  70538. ));
  70539. let elCameraProjection = $(`
  70540. <selectgroup id="camera_projection_options">
  70541. <option id="camera_projection_options_perspective" value="PERSPECTIVE">Perspective</option>
  70542. <option id="camera_projection_options_orthigraphic" value="ORTHOGRAPHIC">Orthographic</option>
  70543. </selectgroup>
  70544. `);
  70545. elNavigation.append(elCameraProjection);
  70546. elCameraProjection.selectgroup({title: "Camera Projection"});
  70547. elCameraProjection.find("input").click( (e) => {
  70548. this.viewer.setCameraMode(CameraMode[e.target.value]);
  70549. });
  70550. let cameraMode = Object.keys(CameraMode)
  70551. .filter(key => CameraMode[key] === this.viewer.scene.cameraMode);
  70552. elCameraProjection.find(`input[value=${cameraMode}]`).trigger("click");
  70553. let speedRange = new Vector2$1(1, 10 * 1000);
  70554. let toLinearSpeed = (value) => {
  70555. return Math.pow(value, 4) * speedRange.y + speedRange.x;
  70556. };
  70557. let toExpSpeed = (value) => {
  70558. return Math.pow((value - speedRange.x) / speedRange.y, 1 / 4);
  70559. };
  70560. sldMoveSpeed.slider({
  70561. value: toExpSpeed(this.viewer.getMoveSpeed()),
  70562. min: 0,
  70563. max: 1,
  70564. step: 0.01,
  70565. slide: (event, ui) => { this.viewer.setMoveSpeed(toLinearSpeed(ui.value)); }
  70566. });
  70567. this.viewer.addEventListener('move_speed_changed', (event) => {
  70568. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  70569. sldMoveSpeed.slider({value: toExpSpeed(this.viewer.getMoveSpeed())});
  70570. });
  70571. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  70572. }
  70573. initSettings(){
  70574. {
  70575. $('#sldMinNodeSize').slider({
  70576. value: this.viewer.getMinNodeSize(),
  70577. min: 0,
  70578. max: 1000,
  70579. step: 0.01,
  70580. slide: (event, ui) => { this.viewer.setMinNodeSize(ui.value); }
  70581. });
  70582. this.viewer.addEventListener('minnodesize_changed', (event) => {
  70583. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  70584. $('#sldMinNodeSize').slider({value: this.viewer.getMinNodeSize()});
  70585. });
  70586. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  70587. }
  70588. {
  70589. let elSplatQuality = $("#splat_quality_options");
  70590. elSplatQuality.selectgroup({title: "Splat Quality"});
  70591. elSplatQuality.find("input").click( (e) => {
  70592. if(e.target.value === "standard"){
  70593. this.viewer.useHQ = false;
  70594. }else if(e.target.value === "hq"){
  70595. this.viewer.useHQ = true;
  70596. }
  70597. });
  70598. let currentQuality = this.viewer.useHQ ? "hq" : "standard";
  70599. elSplatQuality.find(`input[value=${currentQuality}]`).trigger("click");
  70600. }
  70601. $('#show_bounding_box').click(() => {
  70602. this.viewer.setShowBoundingBox($('#show_bounding_box').prop("checked"));
  70603. });
  70604. $('#set_freeze').click(() => {
  70605. this.viewer.setFreeze($('#set_freeze').prop("checked"));
  70606. });
  70607. }
  70608. }
  70609. class AnnotationTool extends EventDispatcher{
  70610. constructor (viewer) {
  70611. super();
  70612. this.viewer = viewer;
  70613. this.renderer = viewer.renderer;
  70614. this.sg = new SphereGeometry(0.1);
  70615. this.sm = new MeshNormalMaterial();
  70616. this.s = new Mesh(this.sg, this.sm);
  70617. }
  70618. startInsertion (args = {}) {
  70619. let domElement = this.viewer.renderer.domElement;
  70620. let annotation = new Annotation({
  70621. position: [589748.270, 231444.540, 753.675],
  70622. title: "Annotation Title",
  70623. description: `Annotation Description`,
  70624. radius: 1,//add
  70625. cameraPosition: [589748.270, 231444.540, 753.675],//add
  70626. });
  70627. this.dispatchEvent({type: 'start_inserting_annotation', annotation: annotation});
  70628. const annotations = this.viewer.scene.annotations;
  70629. annotations.add(annotation);
  70630. let callbacks = {
  70631. cancel: null,
  70632. finish: null,
  70633. };
  70634. let insertionCallback = (e) => {
  70635. if (e.button === MOUSE.LEFT) {
  70636. callbacks.finish();
  70637. } else if (e.button === MOUSE.RIGHT) {
  70638. callbacks.cancel();
  70639. }
  70640. };
  70641. callbacks.cancel = e => {
  70642. annotations.remove(annotation);
  70643. domElement.removeEventListener('mouseup', insertionCallback, true);
  70644. };
  70645. callbacks.finish = e => {
  70646. domElement.removeEventListener('mouseup', insertionCallback, true);
  70647. };
  70648. domElement.addEventListener('mouseup', insertionCallback, true);
  70649. let drag = (e) => {
  70650. let camera = e.viewer.scene.getActiveCamera();
  70651. /* let I = Utils.getMousePointCloudIntersection(
  70652. e.drag.end,
  70653. camera,
  70654. e.viewer,
  70655. e.viewer.scene.pointclouds,
  70656. {pickClipped: true}); */
  70657. let I = e.viewer.inputHandler.intersectPoint;
  70658. if (I) {
  70659. this.s.position.copy(I.location);
  70660. annotation.position.copy(I.location);
  70661. annotation.cameraTarget.copy(I.location);//add
  70662. annotation.cameraPosition.copy(camera.position);//add
  70663. }
  70664. };
  70665. let drop = (e) => {
  70666. viewer.scene.scene.remove(this.s);
  70667. this.s.removeEventListener("drag", drag);
  70668. this.s.removeEventListener("drop", drop);
  70669. };
  70670. this.s.addEventListener('drag', drag);
  70671. this.s.addEventListener('drop', drop);
  70672. this.viewer.scene.scene.add(this.s);
  70673. this.viewer.inputHandler.startDragging(this.s);
  70674. return annotation;
  70675. }
  70676. update(){
  70677. // let camera = this.viewer.scene.getActiveCamera();
  70678. // let domElement = this.renderer.domElement;
  70679. // let measurements = this.viewer.scene.measurements;
  70680. // const renderAreaSize = this.renderer.getSize(new THREE.Vector2());
  70681. // let clientWidth = renderAreaSize.width;
  70682. // let clientHeight = renderAreaSize.height;
  70683. }
  70684. render(){
  70685. //this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  70686. }
  70687. };
  70688. const renderOrders = {
  70689. line: 0 ,
  70690. spot: 15, //高过模型
  70691. };
  70692. const planeGeo$3 = new PlaneGeometry(1,1);
  70693. let texLoader$5 = new TextureLoader();
  70694. let lineMat = new LineBasicMaterial({
  70695. color: '#ffffff',
  70696. });
  70697. let spotMat;
  70698. const defaultLineLength = 0.6;
  70699. const defaultSpotScale = 0.4;
  70700. class Tag extends Object3D{
  70701. constructor(o){
  70702. super();
  70703. this.lineLength = o.lineLength != void 0 ? o.lineLength : defaultLineLength;
  70704. this.position.copy(o.position);
  70705. this.normal = o.normal != void 0 ? o.normal : new Vector3(0,0,-1);
  70706. this.root = o.root;
  70707. //this.matrixAutoUpdate = false
  70708. this.build();
  70709. /* this.spot.addEventListener('mouseover',()=>{
  70710. }) */
  70711. }
  70712. build(){
  70713. if(!spotMat){
  70714. spotMat = new MeshBasicMaterial({
  70715. transparent:true,
  70716. map: texLoader$5.load(Potree.resourcePath+'/textures/spot_default.png' ),
  70717. });
  70718. }
  70719. let endPos = this.normal.clone().multiplyScalar(this.lineLength);
  70720. this.line = LineDraw.createLine([
  70721. new Vector3(0,0,0),
  70722. endPos
  70723. ], {mat:lineMat});
  70724. let group = new Object3D();
  70725. this.spot = new Mesh(planeGeo$3, spotMat);
  70726. this.spot.scale.set(defaultSpotScale,defaultSpotScale,defaultSpotScale);
  70727. this.titleLabel = new TextSprite({root: group, text:'1', sizeInfo:{width2d:200},
  70728. textColor:{r:255,g:255,b:255,a:1.0},
  70729. backgroundColor:{r:0,g:0,b:0,a:0.8},
  70730. borderRadius: 6,
  70731. fontsize:13, fontWeight:'',//thick
  70732. renderOrder : renderOrders.spot, pickOrder:renderOrders.spot,
  70733. }); //更新sprite时,实际更新的是root: spot的矩阵
  70734. this.spot.renderOrder = renderOrders.spot;
  70735. /* const mainLabelProp = {
  70736. backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  70737. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  70738. fontsize:16,
  70739. useDepth : true ,
  70740. renderOrder : 5, pickOrder:5,
  70741. } */
  70742. this.titleLabel.position.set(0,0.4,0);
  70743. this.titleLabel.sprite.material.depthTest = this.titleLabel.sprite.material.depthWrite = true;
  70744. group.position.copy(endPos);
  70745. group.add(this.spot);
  70746. group.add(this.titleLabel);
  70747. this.add(group);
  70748. this.add(this.line);
  70749. viewer.scene.tags.add(this);
  70750. }
  70751. changeTitle(title){
  70752. this.titleLabel.changeText(title);
  70753. }
  70754. updateMatrixWorld(force){ //重写,只为了将root当做parent
  70755. this.updateMatrix();
  70756. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  70757. const children = this.children;
  70758. for ( let i = 0, l = children.length; i < l; i ++ ) {
  70759. children[ i ].updateMatrixWorld( force );
  70760. }
  70761. }
  70762. updateWorldMatrix( updateParents, updateChildren ) {//重写,只为了将root当做parent
  70763. if ( updateParents === true && this.root !== null ) {
  70764. this.root.updateWorldMatrix( true, false );
  70765. }
  70766. if ( this.matrixAutoUpdate ) this.updateMatrix();
  70767. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  70768. if ( updateChildren === true ) {
  70769. const children = this.children;
  70770. for ( let i = 0, l = children.length; i < l; i ++ ) {
  70771. children[ i ].updateWorldMatrix( false, true );
  70772. }
  70773. }
  70774. }
  70775. dispose(){
  70776. this.parent.remove(this);
  70777. this.titleLabel.dispatchEvent({type:'dispose'});
  70778. }
  70779. }
  70780. class TagTool extends EventDispatcher{
  70781. constructor (viewer) {
  70782. super();
  70783. this.viewer = viewer;
  70784. this.viewer.addEventListener('start_inserting_tag', e => {
  70785. this.viewer.dispatchEvent({
  70786. type: 'cancel_insertions'
  70787. });
  70788. });
  70789. }
  70790. createTagFromData(data){
  70791. let tag = new Tag({
  70792. title: data.title, position: data.position, normal: data.normal,
  70793. root: data.root //e.intersect.pointcloud || e.intersect.object
  70794. });
  70795. return tag
  70796. }
  70797. startInsertion (args = {}, callback, cancelFun) {
  70798. let deferred = $.Deferred();
  70799. this.viewer.dispatchEvent({
  70800. type: 'start_inserting_tag'
  70801. });
  70802. this.adding = true;
  70803. let cancel = ()=>{
  70804. end();
  70805. };
  70806. let end = ()=>{
  70807. this.adding = false;
  70808. viewer.dispatchEvent({type:"endTagMove"});
  70809. this.viewer.removeEventListener('global_click', click);
  70810. };
  70811. let click = (e)=>{
  70812. var worldPos = e.intersect && (/* e.intersect.orthoIntersect || */e.intersect.location);
  70813. if(!worldPos){
  70814. return
  70815. }
  70816. let localPos = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:e.intersect.pointcloud, object:e.intersect.object, position:worldPos });
  70817. let tag = new Tag({
  70818. title: '1', position: localPos, normal:e.intersect.normal,
  70819. root: e.intersect.pointcloud || e.intersect.object
  70820. });
  70821. //pointcloud里加一个normal 的非float32
  70822. end();
  70823. e.consume && e.consume();
  70824. deferred.resolve(tag);
  70825. return {stopContinue:true}
  70826. };
  70827. this.viewer.addEventListener('global_click', click, 10);
  70828. return deferred.promise()
  70829. }
  70830. }
  70831. class NavigationCube extends Object3D {
  70832. constructor(viewer){
  70833. super();
  70834. this.viewer = viewer;
  70835. let createPlaneMaterial = (img) => {
  70836. let material = new MeshBasicMaterial( {
  70837. depthTest: true,
  70838. depthWrite: true,
  70839. side: DoubleSide
  70840. });
  70841. new TextureLoader().load(
  70842. exports.resourcePath + '/textures/navigation/' + img,
  70843. function(texture) {
  70844. texture.anisotropy = viewer.renderer.capabilities.getMaxAnisotropy();
  70845. material.map = texture;
  70846. material.needsUpdate = true;
  70847. });
  70848. return material;
  70849. };
  70850. let planeGeometry = new PlaneGeometry(1, 1);
  70851. this.front = new Mesh(planeGeometry, createPlaneMaterial('F.png'));
  70852. this.front.position.y = -0.5;
  70853. this.front.rotation.x = Math.PI / 2.0;
  70854. this.front.updateMatrixWorld();
  70855. this.front.name = "F";
  70856. this.add(this.front);
  70857. this.back = new Mesh(planeGeometry, createPlaneMaterial('B.png'));
  70858. this.back.position.y = 0.5;
  70859. this.back.rotation.x = Math.PI / 2.0;
  70860. this.back.updateMatrixWorld();
  70861. this.back.name = "B";
  70862. this.add(this.back);
  70863. this.left = new Mesh(planeGeometry, createPlaneMaterial('L.png'));
  70864. this.left.position.x = -0.5;
  70865. this.left.rotation.y = Math.PI / 2.0;
  70866. this.left.updateMatrixWorld();
  70867. this.left.name = "L";
  70868. this.add(this.left);
  70869. this.right = new Mesh(planeGeometry, createPlaneMaterial('R.png'));
  70870. this.right.position.x = 0.5;
  70871. this.right.rotation.y = Math.PI / 2.0;
  70872. this.right.updateMatrixWorld();
  70873. this.right.name = "R";
  70874. this.add(this.right);
  70875. this.bottom = new Mesh(planeGeometry, createPlaneMaterial('D.png'));
  70876. this.bottom.position.z = -0.5;
  70877. this.bottom.updateMatrixWorld();
  70878. this.bottom.name = "D";
  70879. this.add(this.bottom);
  70880. this.top = new Mesh(planeGeometry, createPlaneMaterial('U.png'));
  70881. this.top.position.z = 0.5;
  70882. this.top.updateMatrixWorld();
  70883. this.top.name = "U";
  70884. this.add(this.top);
  70885. this.width = 150; // in px
  70886. this.camera = new OrthographicCamera(-1, 1, 1, -1, -1, 1);
  70887. this.camera.position.copy(new Vector3(0, 0, 0));
  70888. this.camera.lookAt(new Vector3(0, 1, 0));
  70889. this.camera.updateMatrixWorld();
  70890. this.camera.rotation.order = "ZXY";
  70891. let onMouseDown = (event) => {
  70892. if (!this.visible) {
  70893. return;
  70894. }
  70895. this.pickedFace = null;
  70896. let mouse = new Vector2$1();
  70897. mouse.x = event.clientX - (window.innerWidth - this.width);
  70898. mouse.y = event.clientY;
  70899. if(mouse.x < 0 || mouse.y > this.width) return;
  70900. mouse.x = (mouse.x / this.width) * 2 - 1;
  70901. mouse.y = -(mouse.y / this.width) * 2 + 1;
  70902. let raycaster = new Raycaster();
  70903. raycaster.setFromCamera(mouse, this.camera);
  70904. raycaster.ray.origin.sub(this.camera.getWorldDirection(new Vector3()));
  70905. let intersects = raycaster.intersectObjects(this.children);
  70906. let minDistance = 1000;
  70907. for (let i = 0; i < intersects.length; i++) {
  70908. if(intersects[i].distance < minDistance) {
  70909. this.pickedFace = intersects[i].object.name;
  70910. minDistance = intersects[i].distance;
  70911. }
  70912. }
  70913. if(this.pickedFace) {
  70914. this.viewer.setView(this.pickedFace);
  70915. }
  70916. };
  70917. this.viewer.renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  70918. }
  70919. update(rotation) {
  70920. this.camera.rotation.copy(rotation);
  70921. this.camera.updateMatrixWorld();
  70922. }
  70923. }
  70924. /**
  70925. * @author mschuetz / http://mschuetz.at
  70926. *
  70927. * adapted from THREE.OrbitControls by
  70928. *
  70929. * @author qiao / https://github.com/qiao
  70930. * @author mrdoob / http://mrdoob.com
  70931. * @author alteredq / http://alteredqualia.com/
  70932. * @author WestLangley / http://github.com/WestLangley
  70933. * @author erich666 / http://erichaines.com
  70934. *
  70935. *
  70936. *
  70937. */
  70938. let minRadius = 2;
  70939. class OrbitControls extends EventDispatcher{
  70940. constructor(viewer){
  70941. super();
  70942. this.viewer = viewer;
  70943. this.renderer = viewer.renderer;
  70944. this.scene = null;
  70945. this.sceneControls = new Scene();
  70946. this.rotationSpeed = 3; //旋转速度
  70947. this.fadeFactor = 100;
  70948. this.yawDelta = 0;
  70949. this.pitchDelta = 0;
  70950. this.panDelta = new Vector2$1(0, 0);
  70951. this.radiusDelta = 0;
  70952. this.doubleClockZoomEnabled = true;
  70953. this.tweens = [];
  70954. this.dollyStart = new Vector2$1;
  70955. this.dollyEnd = new Vector2$1;
  70956. this.keys = {
  70957. FORWARD: ['W'.charCodeAt(0), 38],
  70958. BACKWARD: ['S'.charCodeAt(0), 40],
  70959. LEFT: ['A'.charCodeAt(0), 37],
  70960. RIGHT: ['D'.charCodeAt(0), 39],
  70961. UP: ['Q'.charCodeAt(0)],
  70962. DOWN: ['E'.charCodeAt(0)],
  70963. };
  70964. let drag = (e) => {
  70965. if(!this.enabled)return
  70966. let viewport = e.dragViewport;
  70967. if(!viewport || viewport.camera.type == "OrthographicCamera" )return
  70968. //let camera = viewport.camera
  70969. if (e.drag.object !== null) {
  70970. return;
  70971. }
  70972. let mode;
  70973. if(e.isTouch){
  70974. if(e.touches.length == 1){
  70975. mode = 'rotate';
  70976. }else {
  70977. mode = 'scale-pan';
  70978. }
  70979. }else {
  70980. mode = e.buttons === Buttons.LEFT ? 'rotate' : 'pan';
  70981. }
  70982. if (e.drag.startHandled === undefined) {
  70983. e.drag.startHandled = true;
  70984. this.dispatchEvent({type: 'start'});
  70985. }
  70986. let ndrag = e.drag.pointerDelta.clone();//.add(new THREE.Vector2(1,1)).multiplyScalar(0.5)
  70987. ndrag.y *= -1;
  70988. if (mode == 'rotate') {
  70989. this.yawDelta += ndrag.x * this.rotationSpeed;
  70990. this.pitchDelta += ndrag.y * this.rotationSpeed;
  70991. } else if(mode == 'pan'){
  70992. this.panDelta.x += ndrag.x;
  70993. this.panDelta.y += ndrag.y;
  70994. }else if(mode == 'scale-pan'){ //add
  70995. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  70996. var scale = this.dollyEnd.length() / this.dollyStart.length();
  70997. this.dollyStart.copy(this.dollyEnd);
  70998. this.radiusDelta = (1-scale) * this.scene.view.radius;
  70999. //------------------------
  71000. //平移
  71001. let pointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  71002. let delta = new Vector2$1().subVectors(pointer, this.lastScalePointer);
  71003. delta.y *= -1;
  71004. this.panDelta.add(delta);
  71005. this.lastScalePointer = pointer.clone();
  71006. //console.log('scale ',scale, this.radiusDelta)
  71007. }
  71008. this.stopTweens();
  71009. };
  71010. let drop = e => {
  71011. if(!this.enabled)return
  71012. this.dispatchEvent({type: 'end'});
  71013. };
  71014. let scroll = (e) => {
  71015. if(!this.enabled)return
  71016. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  71017. if(resolvedRadius < 0.1 && e.delta>0)return; //防止缩放太小,导致很慢
  71018. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  71019. this.stopTweens();
  71020. };
  71021. let dblclick = (e) => {
  71022. if(!this.enabled)return
  71023. if(this.doubleClockZoomEnabled){
  71024. this.zoomToLocation(e.mouse);
  71025. }
  71026. };
  71027. let previousTouch = null;
  71028. let touchStart = e => {
  71029. previousTouch = e;
  71030. };
  71031. let touchEnd = e => {
  71032. previousTouch = e;
  71033. };
  71034. let touchMove = e => {
  71035. if(!this.enabled)return
  71036. if (e.touches.length === 2 && previousTouch.touches.length === 2){
  71037. let prev = previousTouch;
  71038. let curr = e;
  71039. let prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  71040. let prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  71041. let prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  71042. let currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  71043. let currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  71044. let currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  71045. let delta = currDist / prevDist;
  71046. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  71047. let newRadius = resolvedRadius / delta;
  71048. this.radiusDelta = newRadius - resolvedRadius;
  71049. this.stopTweens();
  71050. }else if(e.touches.length === 3 && previousTouch.touches.length === 3){
  71051. let prev = previousTouch;
  71052. let curr = e;
  71053. let prevMeanX = (prev.touches[0].pageX + prev.touches[1].pageX + prev.touches[2].pageX) / 3;
  71054. let prevMeanY = (prev.touches[0].pageY + prev.touches[1].pageY + prev.touches[2].pageY) / 3;
  71055. let currMeanX = (curr.touches[0].pageX + curr.touches[1].pageX + curr.touches[2].pageX) / 3;
  71056. let currMeanY = (curr.touches[0].pageY + curr.touches[1].pageY + curr.touches[2].pageY) / 3;
  71057. let delta = {
  71058. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  71059. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  71060. };
  71061. this.panDelta.x += delta.x;
  71062. this.panDelta.y += delta.y;
  71063. this.stopTweens();
  71064. }
  71065. previousTouch = e;
  71066. };
  71067. this.addEventListener('touchstart', touchStart);
  71068. this.addEventListener('touchend', touchEnd);
  71069. this.addEventListener('touchmove', touchMove);
  71070. this.viewer.addEventListener('global_drag', drag);
  71071. this.viewer.addEventListener('global_drop', drop);
  71072. this.viewer.addEventListener('global_mousewheel', scroll);
  71073. this.viewer.addEventListener('global_dblclick', dblclick);
  71074. this.viewer.addEventListener('global_touchmove', (e)=>{
  71075. if(e.touches.length>1){//单指的就触发上一句
  71076. //console.log('global_touchmove' )
  71077. drag(e);
  71078. }
  71079. });
  71080. let prepareScale = (e)=>{//触屏的scale
  71081. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  71082. this.lastScalePointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  71083. };
  71084. this.viewer.addEventListener('global_touchstart', (e)=>{
  71085. if(this.enabled && e.touches.length==2){//只监听开头两个指头
  71086. prepareScale(e);
  71087. }
  71088. });
  71089. /* this.viewer.addEventListener('global_touchend', (e)=>{
  71090. if(!this.enabled)return
  71091. if(e.touches.length==1){//停止scale,开始rotate
  71092. prepareRotate(e)
  71093. //this.pointerDragStart = null
  71094. //console.log('只剩一个', e.pointer.toArray())
  71095. }
  71096. }) */
  71097. this.viewer.addEventListener('focusOnObject',(o)=>{
  71098. if(o.position && o.CamTarget){
  71099. let distance = o.position.distanceTo(o.CamTarget);
  71100. if(distance < minRadius) minRadius = distance * 0.5; //融合页面当focus一个很小的物体时,需要将minRadius也调小
  71101. }
  71102. });
  71103. }
  71104. setScene (scene) {
  71105. this.scene = scene;
  71106. }
  71107. setEnable(enabled){
  71108. this.enabled = enabled;
  71109. }
  71110. stop(){
  71111. this.yawDelta = 0;
  71112. this.pitchDelta = 0;
  71113. this.radiusDelta = 0;
  71114. this.panDelta.set(0, 0);
  71115. }
  71116. /* zoomToLocation(mouse){
  71117. if(!this.enabled)return
  71118. let camera = this.scene.getActiveCamera();
  71119. let I = Utils.getMousePointCloudIntersection(
  71120. null, mouse, this.viewer.inputHandler.pointer,
  71121. camera,
  71122. this.viewer,
  71123. this.scene.pointclouds,
  71124. {pickClipped: true});
  71125. if (I === null) {
  71126. return;
  71127. }
  71128. let targetRadius = 0;
  71129. {
  71130. let minimumJumpDistance = 0.2;
  71131. let domElement = this.renderer.domElement;
  71132. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer , camera, domElement.clientWidth, domElement.clientHeight);
  71133. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  71134. let lastNode = nodes[nodes.length - 1];
  71135. let radius = lastNode.getBoundingSphere(new THREE.Sphere()).radius;
  71136. targetRadius = Math.min(this.scene.view.radius, radius);
  71137. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  71138. }
  71139. let d = this.scene.view.direction.multiplyScalar(-1);
  71140. let cameraTargetPosition = new THREE.Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  71141. // TODO Unused: let controlsTargetPosition = I.location;
  71142. let animationDuration = 600;
  71143. let easing = TWEEN.Easing.Quartic.Out;
  71144. { // animate
  71145. let value = {x: 0};
  71146. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  71147. tween.easing(easing);
  71148. this.tweens.push(tween);
  71149. let startPos = this.scene.view.position.clone();
  71150. let targetPos = cameraTargetPosition.clone();
  71151. let startRadius = this.scene.view.radius;
  71152. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  71153. tween.onUpdate(() => {
  71154. let t = value.x;
  71155. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  71156. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  71157. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  71158. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  71159. this.viewer.setMoveSpeed(this.scene.view.radius);
  71160. });
  71161. tween.onComplete(() => {
  71162. this.tweens = this.tweens.filter(e => e !== tween);
  71163. });
  71164. tween.start();
  71165. }
  71166. } */
  71167. zoomToLocation(mouse){
  71168. let I = viewer.inputHandler.intersect;
  71169. if(!I)return
  71170. let object = I.object || I.pointcloud;
  71171. I = I.location;
  71172. if(!I || !object)return;
  71173. let dis = this.scene.view.position.distanceTo(I);
  71174. let bound = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  71175. let size = bound.getSize(new Vector3);
  71176. let len = size.length();
  71177. let distance = MathUtils.clamp(dis, 0.1, Math.max(len * 0.1, 3) );
  71178. minRadius = distance;
  71179. viewer.focusOnObject({ position:I }, 'point', null, {distance});
  71180. }
  71181. stopTweens () {
  71182. this.tweens.forEach(e => e.stop());
  71183. this.tweens = [];
  71184. }
  71185. update (delta) {
  71186. if(!this.enabled)return
  71187. let view = this.scene.view;
  71188. { // accelerate while input is given
  71189. let ih = this.viewer.inputHandler;
  71190. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  71191. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  71192. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  71193. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  71194. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  71195. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  71196. let px = 0 , py = 0, pz = 0;
  71197. if(moveForward){
  71198. py = 1;
  71199. }else if(moveBackward){
  71200. py = -1;
  71201. }
  71202. if(moveLeft){
  71203. px = -1;
  71204. }else if(moveRight){
  71205. px = 1;
  71206. }
  71207. if(moveUp){
  71208. pz = 1;
  71209. }else if(moveDown){
  71210. pz = -1;
  71211. }
  71212. (px!=0 || py!=0 || pz!=0) && view.translate(px, py, pz, true);
  71213. }
  71214. { // apply rotation
  71215. let progression = Math.min(1, this.fadeFactor * delta);
  71216. let yaw = view.yaw;
  71217. let pitch = view.pitch;
  71218. let pivot = view.getPivot();
  71219. yaw -= progression * this.yawDelta;
  71220. pitch -= progression * this.pitchDelta;
  71221. view.yaw = yaw;
  71222. view.pitch = pitch;
  71223. let V = this.scene.view.direction.multiplyScalar(-view.radius);
  71224. let position = new Vector3().addVectors(pivot, V);
  71225. view.position.copy(position);
  71226. }
  71227. { // apply pan
  71228. /* let progression = Math.min(1, this.fadeFactor * delta);
  71229. let panDistance = progression * view.radius * 3; */
  71230. let camera = this.scene.getActiveCamera();
  71231. let panDistance = 2 * view.radius * Math.tan(MathUtils.degToRad(camera.fov / 2));//参照4dkk。 平移target(也就是平移镜头位置),但还是难以保证跟手(navvis也不一定跟手,但是很奇怪在居中时中心点居然是跟手的,可能计算方式不同)
  71232. //计算了下确实是这么算的。 平移pivot。
  71233. let px = -this.panDelta.x * panDistance;
  71234. let py = this.panDelta.y * panDistance;
  71235. view.pan(px, py);
  71236. }
  71237. { // apply zoom
  71238. let progression = 1;//Math.min(1, this.fadeFactor * delta);
  71239. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  71240. let radius = view.radius + progression * this.radiusDelta;
  71241. let V = view.direction.multiplyScalar(-radius);
  71242. let position = new Vector3().addVectors(view.getPivot(), V);
  71243. if(this.constantlyForward) {// 到达中心点后还能继续向前移动,也就是能推进中心点
  71244. if(radius < minRadius){
  71245. radius = minRadius;
  71246. }
  71247. }
  71248. view.radius = radius;
  71249. view.position.copy(position);
  71250. }
  71251. {
  71252. let speed = view.radius;
  71253. this.viewer.setMoveSpeed(speed);
  71254. }
  71255. { // decelerate over time
  71256. /* let progression = Math.min(1, this.fadeFactor * delta);
  71257. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  71258. this.yawDelta *= attenuation;
  71259. this.pitchDelta *= attenuation;
  71260. this.panDelta.multiplyScalar(attenuation);
  71261. // this.radiusDelta *= attenuation;
  71262. this.radiusDelta -= progression * this.radiusDelta; */
  71263. //取消衰减,直接stop
  71264. this.stop();
  71265. }
  71266. }
  71267. };
  71268. class EarthControls extends EventDispatcher {
  71269. constructor (viewer) {
  71270. super(viewer);
  71271. this.viewer = viewer;
  71272. this.renderer = viewer.renderer;
  71273. this.scene = null;
  71274. this.sceneControls = new Scene();
  71275. this.rotationSpeed = 10;
  71276. this.fadeFactor = 20;
  71277. this.wheelDelta = 0;
  71278. this.zoomDelta = new Vector3();
  71279. this.camStart = null;
  71280. this.tweens = [];
  71281. {
  71282. let sg = new SphereGeometry(1, 16, 16);
  71283. let sm = new MeshNormalMaterial();
  71284. this.pivotIndicator = new Mesh(sg, sm);
  71285. this.pivotIndicator.visible = false;
  71286. this.sceneControls.add(this.pivotIndicator);
  71287. }
  71288. let drag = (e) => {
  71289. if (e.drag.object !== null) {
  71290. return;
  71291. }
  71292. if (!this.pivot) {
  71293. return;
  71294. }
  71295. if (e.drag.startHandled === undefined) {
  71296. e.drag.startHandled = true;
  71297. this.dispatchEvent({type: 'start'});
  71298. }
  71299. let camStart = this.camStart;
  71300. let camera = this.scene.getActiveCamera();
  71301. let view = this.viewer.scene.view;
  71302. // let camera = this.viewer.scene.camera;
  71303. let Buttons = e.drag.end;
  71304. let domElement = this.viewer.renderer.domElement;
  71305. if (e.drag.Buttons === Buttons.LEFT) {
  71306. let ray = Utils.ButtonsToRay(this.viewer.inputHandler.pointer/* Buttons */, camera, domElement.clientWidth, domElement.clientHeight);
  71307. let plane = new Plane().setFromNormalAndCoplanarPoint(
  71308. new Vector3(0, 0, 1),
  71309. this.pivot);
  71310. let distanceToPlane = ray.distanceToPlane(plane);
  71311. if (distanceToPlane > 0) {
  71312. let I = new Vector3().addVectors(
  71313. camStart.position,
  71314. ray.direction.clone().multiplyScalar(distanceToPlane));
  71315. let movedBy = new Vector3().subVectors(
  71316. I, this.pivot);
  71317. let newCamPos = camStart.position.clone().sub(movedBy);
  71318. view.position.copy(newCamPos);
  71319. {
  71320. let distance = newCamPos.distanceTo(this.pivot);
  71321. view.radius = distance;
  71322. let speed = view.radius / 2.5;
  71323. this.viewer.setMoveSpeed(speed);
  71324. }
  71325. }
  71326. } else if (e.drag.Buttons === Buttons.RIGHT) {
  71327. let ndrag = {
  71328. x: e.drag.ButtonsDelta.x / this.renderer.domElement.clientWidth,
  71329. y: e.drag.ButtonsDelta.y / this.renderer.domElement.clientHeight
  71330. };
  71331. let yawDelta = -ndrag.x * this.rotationSpeed * 0.5;
  71332. let pitchDelta = -ndrag.y * this.rotationSpeed * 0.2;
  71333. let originalPitch = view.pitch;
  71334. let tmpView = view.clone();
  71335. tmpView.pitch = tmpView.pitch + pitchDelta;
  71336. pitchDelta = tmpView.pitch - originalPitch;
  71337. let pivotToCam = new Vector3().subVectors(view.position, this.pivot);
  71338. let pivotToCamTarget = new Vector3().subVectors(view.getPivot(), this.pivot);
  71339. let side = view.getSide();
  71340. pivotToCam.applyAxisAngle(side, pitchDelta);
  71341. pivotToCamTarget.applyAxisAngle(side, pitchDelta);
  71342. pivotToCam.applyAxisAngle(new Vector3(0, 0, 1), yawDelta);
  71343. pivotToCamTarget.applyAxisAngle(new Vector3(0, 0, 1), yawDelta);
  71344. let newCam = new Vector3().addVectors(this.pivot, pivotToCam);
  71345. // TODO: Unused: let newCamTarget = new THREE.Vector3().addVectors(this.pivot, pivotToCamTarget);
  71346. view.position.copy(newCam);
  71347. view.yaw += yawDelta;
  71348. view.pitch += pitchDelta;
  71349. }
  71350. };
  71351. let onButtonsDown = e => {
  71352. let I = Utils.getButtonsPointCloudIntersection(
  71353. e.Buttons,
  71354. this.scene.getActiveCamera(),
  71355. this.viewer,
  71356. this.scene.pointclouds,
  71357. {pickClipped: false});
  71358. if (I) {
  71359. this.pivot = I.location;
  71360. this.camStart = this.scene.getActiveCamera().clone();
  71361. this.pivotIndicator.visible = true;
  71362. this.pivotIndicator.position.copy(I.location);
  71363. }
  71364. };
  71365. let drop = e => {
  71366. this.dispatchEvent({type: 'end'});
  71367. };
  71368. let onButtonsUp = e => {
  71369. this.camStart = null;
  71370. this.pivot = null;
  71371. this.pivotIndicator.visible = false;
  71372. };
  71373. let scroll = (e) => {
  71374. this.wheelDelta += e.delta;
  71375. };
  71376. let dblclick = (e) => {
  71377. this.zoomToLocation(e.Buttons);
  71378. };
  71379. this.addEventListener('drag', drag);
  71380. this.addEventListener('drop', drop);
  71381. this.addEventListener('Buttonswheel', scroll);
  71382. this.addEventListener('Buttonsdown', onButtonsDown);
  71383. this.addEventListener('Buttonsup', onButtonsUp);
  71384. this.addEventListener('dblclick', dblclick);
  71385. }
  71386. setScene (scene) {
  71387. this.scene = scene;
  71388. }
  71389. stop(){
  71390. this.wheelDelta = 0;
  71391. this.zoomDelta.set(0, 0, 0);
  71392. }
  71393. zoomToLocation(Buttons){
  71394. let camera = this.scene.getActiveCamera();
  71395. let I = Utils.getButtonsPointCloudIntersection(
  71396. Buttons,
  71397. camera,
  71398. this.viewer,
  71399. this.scene.pointclouds);
  71400. if (I === null) {
  71401. return;
  71402. }
  71403. let targetRadius = 0;
  71404. {
  71405. let minimumJumpDistance = 0.2;
  71406. let domElement = this.renderer.domElement;
  71407. let ray = Utils.ButtonsToRay(this.viewer.inputHandler.pointer, camera, domElement.clientWidth, domElement.clientHeight);
  71408. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  71409. let lastNode = nodes[nodes.length - 1];
  71410. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  71411. targetRadius = Math.min(this.scene.view.radius, radius);
  71412. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  71413. }
  71414. let d = this.scene.view.direction.multiplyScalar(-1);
  71415. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  71416. // TODO Unused: let controlsTargetPosition = I.location;
  71417. let animationDuration = 600;
  71418. let easing = TWEEN.Easing.Quartic.Out;
  71419. { // animate
  71420. let value = {x: 0};
  71421. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  71422. tween.easing(easing);
  71423. this.tweens.push(tween);
  71424. let startPos = this.scene.view.position.clone();
  71425. let targetPos = cameraTargetPosition.clone();
  71426. let startRadius = this.scene.view.radius;
  71427. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  71428. tween.onUpdate(() => {
  71429. let t = value.x;
  71430. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  71431. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  71432. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  71433. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  71434. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  71435. });
  71436. tween.onComplete(() => {
  71437. this.tweens = this.tweens.filter(e => e !== tween);
  71438. });
  71439. tween.start();
  71440. }
  71441. }
  71442. update (delta) {
  71443. let view = this.scene.view;
  71444. let fade = Math.pow(0.5, this.fadeFactor * delta);
  71445. let progression = 1 - fade;
  71446. let camera = this.scene.getActiveCamera();
  71447. // compute zoom
  71448. if (this.wheelDelta !== 0) {
  71449. let I = Utils.getButtonsPointCloudIntersection(
  71450. this.viewer.inputHandler.Buttons,
  71451. this.scene.getActiveCamera(),
  71452. this.viewer,
  71453. this.scene.pointclouds);
  71454. if (I) {
  71455. let resolvedPos = new Vector3().addVectors(view.position, this.zoomDelta);
  71456. let distance = I.location.distanceTo(resolvedPos);
  71457. let jumpDistance = distance * 0.2 * this.wheelDelta;
  71458. let targetDir = new Vector3().subVectors(I.location, view.position);
  71459. targetDir.normalize();
  71460. resolvedPos.add(targetDir.multiplyScalar(jumpDistance));
  71461. this.zoomDelta.subVectors(resolvedPos, view.position);
  71462. {
  71463. let distance = resolvedPos.distanceTo(I.location);
  71464. view.radius = distance;
  71465. let speed = view.radius / 2.5;
  71466. this.viewer.setMoveSpeed(speed);
  71467. }
  71468. }
  71469. }
  71470. // apply zoom
  71471. if (this.zoomDelta.length() !== 0) {
  71472. let p = this.zoomDelta.clone().multiplyScalar(progression);
  71473. let newPos = new Vector3().addVectors(view.position, p);
  71474. view.position.copy(newPos);
  71475. }
  71476. if (this.pivotIndicator.visible) {
  71477. let distance = this.pivotIndicator.position.distanceTo(view.position);
  71478. let pixelwidth = this.renderer.domElement.clientwidth;
  71479. let pixelHeight = this.renderer.domElement.clientHeight;
  71480. let pr = Utils.projectedRadius(1, camera, distance, pixelwidth, pixelHeight);
  71481. let scale = (10 / pr);
  71482. this.pivotIndicator.scale.set(scale, scale, scale);
  71483. }
  71484. // decelerate over time
  71485. {
  71486. this.zoomDelta.multiplyScalar(fade);
  71487. this.wheelDelta = 0;
  71488. }
  71489. }
  71490. };
  71491. /**
  71492. * @author chrisl / Geodan
  71493. *
  71494. * adapted from Potree.FirstPersonControls by
  71495. *
  71496. * @author mschuetz / http://mschuetz.at
  71497. *
  71498. * and THREE.DeviceOrientationControls by
  71499. *
  71500. * @author richt / http://richt.me
  71501. * @author WestLangley / http://github.com/WestLangley
  71502. *
  71503. *
  71504. *
  71505. */
  71506. class DeviceOrientationControls extends EventDispatcher{
  71507. constructor(viewer){
  71508. super();
  71509. this.viewer = viewer;
  71510. this.renderer = viewer.renderer;
  71511. this.scene = null;
  71512. this.sceneControls = new Scene();
  71513. this.screenOrientation = window.orientation || 0;
  71514. let deviceOrientationChange = e => {
  71515. this.deviceOrientation = e;
  71516. };
  71517. let screenOrientationChange = e => {
  71518. this.screenOrientation = window.orientation || 0;
  71519. };
  71520. if ('ondeviceorientationabsolute' in window) {
  71521. window.addEventListener('deviceorientationabsolute', deviceOrientationChange);
  71522. } else if ('ondeviceorientation' in window) {
  71523. window.addEventListener('deviceorientation', deviceOrientationChange);
  71524. } else {
  71525. console.warn("No device orientation found.");
  71526. }
  71527. // window.addEventListener('deviceorientation', deviceOrientationChange);
  71528. window.addEventListener('orientationchange', screenOrientationChange);
  71529. }
  71530. setScene (scene) {
  71531. this.scene = scene;
  71532. }
  71533. update (delta) {
  71534. let computeQuaternion = function (alpha, beta, gamma, orient) {
  71535. let quaternion = new Quaternion();
  71536. let zee = new Vector3(0, 0, 1);
  71537. let euler = new Euler();
  71538. let q0 = new Quaternion();
  71539. euler.set(beta, gamma, alpha, 'ZXY');
  71540. quaternion.setFromEuler(euler);
  71541. quaternion.multiply(q0.setFromAxisAngle(zee, -orient));
  71542. return quaternion;
  71543. };
  71544. if (typeof this.deviceOrientation !== 'undefined') {
  71545. let alpha = this.deviceOrientation.alpha ? MathUtils.degToRad(this.deviceOrientation.alpha) : 0;
  71546. let beta = this.deviceOrientation.beta ? MathUtils.degToRad(this.deviceOrientation.beta) : 0;
  71547. let gamma = this.deviceOrientation.gamma ? MathUtils.degToRad(this.deviceOrientation.gamma) : 0;
  71548. let orient = this.screenOrientation ? MathUtils.degToRad(this.screenOrientation) : 0;
  71549. let quaternion = computeQuaternion(alpha, beta, gamma, orient);
  71550. viewer.scene.cameraP.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  71551. }
  71552. }
  71553. };
  71554. const _taskCache = new WeakMap();
  71555. class DRACOLoader extends Loader {
  71556. constructor( manager ) {
  71557. super( manager );
  71558. this.decoderPath = '';
  71559. this.decoderConfig = {};
  71560. this.decoderBinary = null;
  71561. this.decoderPending = null;
  71562. this.workerLimit = 4;
  71563. this.workerPool = [];
  71564. this.workerNextTaskID = 1;
  71565. this.workerSourceURL = '';
  71566. this.defaultAttributeIDs = {
  71567. position: 'POSITION',
  71568. normal: 'NORMAL',
  71569. color: 'COLOR',
  71570. uv: 'TEX_COORD'
  71571. };
  71572. this.defaultAttributeTypes = {
  71573. position: 'Float32Array',
  71574. normal: 'Float32Array',
  71575. color: 'Float32Array',
  71576. uv: 'Float32Array'
  71577. };
  71578. }
  71579. setDecoderPath( path ) {
  71580. this.decoderPath = path;
  71581. return this;
  71582. }
  71583. setDecoderConfig( config ) {
  71584. this.decoderConfig = config;
  71585. return this;
  71586. }
  71587. setWorkerLimit( workerLimit ) {
  71588. this.workerLimit = workerLimit;
  71589. return this;
  71590. }
  71591. load( url, onLoad, onProgress, onError ) {
  71592. const loader = new FileLoader( this.manager );
  71593. loader.setPath( this.path );
  71594. loader.setResponseType( 'arraybuffer' );
  71595. loader.setRequestHeader( this.requestHeader );
  71596. loader.setWithCredentials( this.withCredentials );
  71597. loader.load( url, ( buffer ) => {
  71598. const taskConfig = {
  71599. attributeIDs: this.defaultAttributeIDs,
  71600. attributeTypes: this.defaultAttributeTypes,
  71601. useUniqueIDs: false
  71602. };
  71603. this.decodeGeometry( buffer, taskConfig )
  71604. .then( onLoad )
  71605. .catch( onError );
  71606. }, onProgress, onError );
  71607. }
  71608. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  71609. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes ) {
  71610. const taskConfig = {
  71611. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  71612. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  71613. useUniqueIDs: !! attributeIDs
  71614. };
  71615. this.decodeGeometry( buffer, taskConfig ).then( callback );
  71616. }
  71617. decodeGeometry( buffer, taskConfig ) {
  71618. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  71619. // references (rather than names) to typed array constructors. These must be
  71620. // serialized before sending them to the worker.
  71621. for ( const attribute in taskConfig.attributeTypes ) {
  71622. const type = taskConfig.attributeTypes[ attribute ];
  71623. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  71624. taskConfig.attributeTypes[ attribute ] = type.name;
  71625. }
  71626. }
  71627. //
  71628. const taskKey = JSON.stringify( taskConfig );
  71629. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  71630. // again from this thread.
  71631. if ( _taskCache.has( buffer ) ) {
  71632. const cachedTask = _taskCache.get( buffer );
  71633. if ( cachedTask.key === taskKey ) {
  71634. return cachedTask.promise;
  71635. } else if ( buffer.byteLength === 0 ) {
  71636. // Technically, it would be possible to wait for the previous task to complete,
  71637. // transfer the buffer back, and decode again with the second configuration. That
  71638. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  71639. // different ways, so this is left unimplemented.
  71640. throw new Error(
  71641. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  71642. 'settings. Buffer has already been transferred.'
  71643. );
  71644. }
  71645. }
  71646. //
  71647. let worker;
  71648. const taskID = this.workerNextTaskID ++;
  71649. const taskCost = buffer.byteLength;
  71650. // Obtain a worker and assign a task, and construct a geometry instance
  71651. // when the task completes.
  71652. const geometryPending = this._getWorker( taskID, taskCost )
  71653. .then( ( _worker ) => {
  71654. worker = _worker;
  71655. return new Promise( ( resolve, reject ) => {
  71656. worker._callbacks[ taskID ] = { resolve, reject };
  71657. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  71658. // this.debug();
  71659. } );
  71660. } )
  71661. .then( ( message ) => this._createGeometry( message.geometry ) );
  71662. // Remove task from the task list.
  71663. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  71664. geometryPending
  71665. .catch( () => true )
  71666. .then( () => {
  71667. if ( worker && taskID ) {
  71668. this._releaseTask( worker, taskID );
  71669. // this.debug();
  71670. }
  71671. } );
  71672. // Cache the task result.
  71673. _taskCache.set( buffer, {
  71674. key: taskKey,
  71675. promise: geometryPending
  71676. } );
  71677. return geometryPending;
  71678. }
  71679. _createGeometry( geometryData ) {
  71680. const geometry = new BufferGeometry();
  71681. if ( geometryData.index ) {
  71682. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  71683. }
  71684. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  71685. const attribute = geometryData.attributes[ i ];
  71686. const name = attribute.name;
  71687. const array = attribute.array;
  71688. const itemSize = attribute.itemSize;
  71689. geometry.setAttribute( name, new BufferAttribute( array, itemSize ) );
  71690. }
  71691. return geometry;
  71692. }
  71693. _loadLibrary( url, responseType ) {
  71694. const loader = new FileLoader( this.manager );
  71695. loader.setPath( this.decoderPath );
  71696. loader.setResponseType( responseType );
  71697. loader.setWithCredentials( this.withCredentials );
  71698. return new Promise( ( resolve, reject ) => {
  71699. loader.load( url, resolve, undefined, reject );
  71700. } );
  71701. }
  71702. preload() {
  71703. this._initDecoder();
  71704. return this;
  71705. }
  71706. _initDecoder() {
  71707. if ( this.decoderPending ) return this.decoderPending;
  71708. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  71709. const librariesPending = [];
  71710. if ( useJS ) {
  71711. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  71712. } else {
  71713. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  71714. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  71715. }
  71716. this.decoderPending = Promise.all( librariesPending )
  71717. .then( ( libraries ) => {
  71718. const jsContent = libraries[ 0 ];
  71719. if ( ! useJS ) {
  71720. this.decoderConfig.wasmBinary = libraries[ 1 ];
  71721. }
  71722. const fn = DRACOWorker.toString();
  71723. const body = [
  71724. '/* draco decoder */',
  71725. jsContent,
  71726. '',
  71727. '/* worker */',
  71728. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  71729. ].join( '\n' );
  71730. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  71731. } );
  71732. return this.decoderPending;
  71733. }
  71734. _getWorker( taskID, taskCost ) {
  71735. return this._initDecoder().then( () => {
  71736. if ( this.workerPool.length < this.workerLimit ) {
  71737. const worker = new Worker( this.workerSourceURL );
  71738. worker._callbacks = {};
  71739. worker._taskCosts = {};
  71740. worker._taskLoad = 0;
  71741. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  71742. worker.onmessage = function ( e ) {
  71743. const message = e.data;
  71744. switch ( message.type ) {
  71745. case 'decode':
  71746. worker._callbacks[ message.id ].resolve( message );
  71747. break;
  71748. case 'error':
  71749. worker._callbacks[ message.id ].reject( message );
  71750. break;
  71751. default:
  71752. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  71753. }
  71754. };
  71755. this.workerPool.push( worker );
  71756. } else {
  71757. this.workerPool.sort( function ( a, b ) {
  71758. return a._taskLoad > b._taskLoad ? - 1 : 1;
  71759. } );
  71760. }
  71761. const worker = this.workerPool[ this.workerPool.length - 1 ];
  71762. worker._taskCosts[ taskID ] = taskCost;
  71763. worker._taskLoad += taskCost;
  71764. return worker;
  71765. } );
  71766. }
  71767. _releaseTask( worker, taskID ) {
  71768. worker._taskLoad -= worker._taskCosts[ taskID ];
  71769. delete worker._callbacks[ taskID ];
  71770. delete worker._taskCosts[ taskID ];
  71771. }
  71772. debug() {
  71773. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  71774. }
  71775. dispose() {
  71776. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  71777. this.workerPool[ i ].terminate();
  71778. }
  71779. this.workerPool.length = 0;
  71780. return this;
  71781. }
  71782. }
  71783. /* WEB WORKER */
  71784. function DRACOWorker() {
  71785. let decoderConfig;
  71786. let decoderPending;
  71787. onmessage = function ( e ) {
  71788. const message = e.data;
  71789. switch ( message.type ) {
  71790. case 'init':
  71791. decoderConfig = message.decoderConfig;
  71792. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  71793. decoderConfig.onModuleLoaded = function ( draco ) {
  71794. // Module is Promise-like. Wrap before resolving to avoid loop.
  71795. resolve( { draco: draco } );
  71796. };
  71797. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  71798. } );
  71799. break;
  71800. case 'decode':
  71801. const buffer = message.buffer;
  71802. const taskConfig = message.taskConfig;
  71803. decoderPending.then( ( module ) => {
  71804. const draco = module.draco;
  71805. const decoder = new draco.Decoder();
  71806. const decoderBuffer = new draco.DecoderBuffer();
  71807. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  71808. try {
  71809. const geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  71810. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  71811. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  71812. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  71813. } catch ( error ) {
  71814. console.error( error );
  71815. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  71816. } finally {
  71817. draco.destroy( decoderBuffer );
  71818. draco.destroy( decoder );
  71819. }
  71820. } );
  71821. break;
  71822. }
  71823. };
  71824. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  71825. const attributeIDs = taskConfig.attributeIDs;
  71826. const attributeTypes = taskConfig.attributeTypes;
  71827. let dracoGeometry;
  71828. let decodingStatus;
  71829. const geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  71830. if ( geometryType === draco.TRIANGULAR_MESH ) {
  71831. dracoGeometry = new draco.Mesh();
  71832. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  71833. } else if ( geometryType === draco.POINT_CLOUD ) {
  71834. dracoGeometry = new draco.PointCloud();
  71835. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  71836. } else {
  71837. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  71838. }
  71839. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  71840. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  71841. }
  71842. const geometry = { index: null, attributes: [] };
  71843. // Gather all vertex attributes.
  71844. for ( const attributeName in attributeIDs ) {
  71845. const attributeType = self[ attributeTypes[ attributeName ] ];
  71846. let attribute;
  71847. let attributeID;
  71848. // A Draco file may be created with default vertex attributes, whose attribute IDs
  71849. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  71850. // a Draco file may contain a custom set of attributes, identified by known unique
  71851. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  71852. if ( taskConfig.useUniqueIDs ) {
  71853. attributeID = attributeIDs[ attributeName ];
  71854. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  71855. } else {
  71856. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  71857. if ( attributeID === - 1 ) continue;
  71858. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  71859. }
  71860. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  71861. }
  71862. // Add index.
  71863. if ( geometryType === draco.TRIANGULAR_MESH ) {
  71864. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  71865. }
  71866. draco.destroy( dracoGeometry );
  71867. return geometry;
  71868. }
  71869. function decodeIndex( draco, decoder, dracoGeometry ) {
  71870. const numFaces = dracoGeometry.num_faces();
  71871. const numIndices = numFaces * 3;
  71872. const byteLength = numIndices * 4;
  71873. const ptr = draco._malloc( byteLength );
  71874. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  71875. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  71876. draco._free( ptr );
  71877. return { array: index, itemSize: 1 };
  71878. }
  71879. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  71880. const numComponents = attribute.num_components();
  71881. const numPoints = dracoGeometry.num_points();
  71882. const numValues = numPoints * numComponents;
  71883. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  71884. const dataType = getDracoDataType( draco, attributeType );
  71885. const ptr = draco._malloc( byteLength );
  71886. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  71887. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  71888. draco._free( ptr );
  71889. return {
  71890. name: attributeName,
  71891. array: array,
  71892. itemSize: numComponents
  71893. };
  71894. }
  71895. function getDracoDataType( draco, attributeType ) {
  71896. switch ( attributeType ) {
  71897. case Float32Array: return draco.DT_FLOAT32;
  71898. case Int8Array: return draco.DT_INT8;
  71899. case Int16Array: return draco.DT_INT16;
  71900. case Int32Array: return draco.DT_INT32;
  71901. case Uint8Array: return draco.DT_UINT8;
  71902. case Uint16Array: return draco.DT_UINT16;
  71903. case Uint32Array: return draco.DT_UINT32;
  71904. }
  71905. }
  71906. }
  71907. /**
  71908. * @author Deepkolos / https://github.com/deepkolos
  71909. */
  71910. class WorkerPool$1 {
  71911. constructor( pool = 4 ) {
  71912. this.pool = pool;
  71913. this.queue = [];
  71914. this.workers = [];
  71915. this.workersResolve = [];
  71916. this.workerStatus = 0;
  71917. }
  71918. _initWorker( workerId ) {
  71919. if ( ! this.workers[ workerId ] ) {
  71920. const worker = this.workerCreator();
  71921. worker.addEventListener( 'message', this._onMessage.bind( this, workerId ) );
  71922. this.workers[ workerId ] = worker;
  71923. }
  71924. }
  71925. _getIdleWorker() {
  71926. for ( let i = 0; i < this.pool; i ++ )
  71927. if ( ! ( this.workerStatus & ( 1 << i ) ) ) return i;
  71928. return - 1;
  71929. }
  71930. _onMessage( workerId, msg ) {
  71931. const resolve = this.workersResolve[ workerId ];
  71932. resolve && resolve( msg );
  71933. if ( this.queue.length ) {
  71934. const { resolve, msg, transfer } = this.queue.shift();
  71935. this.workersResolve[ workerId ] = resolve;
  71936. this.workers[ workerId ].postMessage( msg, transfer );
  71937. } else {
  71938. this.workerStatus ^= 1 << workerId;
  71939. }
  71940. }
  71941. setWorkerCreator( workerCreator ) {
  71942. this.workerCreator = workerCreator;
  71943. }
  71944. setWorkerLimit( pool ) {
  71945. this.pool = pool;
  71946. }
  71947. postMessage( msg, transfer ) {
  71948. return new Promise( ( resolve ) => {
  71949. const workerId = this._getIdleWorker();
  71950. if ( workerId !== - 1 ) {
  71951. this._initWorker( workerId );
  71952. this.workerStatus |= 1 << workerId;
  71953. this.workersResolve[ workerId ] = resolve;
  71954. this.workers[ workerId ].postMessage( msg, transfer );
  71955. } else {
  71956. this.queue.push( { resolve, msg, transfer } );
  71957. }
  71958. } );
  71959. }
  71960. dispose() {
  71961. this.workers.forEach( ( worker ) => worker.terminate() );
  71962. this.workersResolve.length = 0;
  71963. this.workers.length = 0;
  71964. this.queue.length = 0;
  71965. this.workerStatus = 0;
  71966. }
  71967. }
  71968. const t=0,e$1=1,n$1=2,i$2=3,s=0,a$1=0,r=2,o$1=0,l$1=1,f=160,U$1=161,c$3=162,h$2=163,_$1=0,p=1,g=0,y=1,x$2=2,u$2=3,b$1=4,d=5,m=6,w$1=7,D=8,B=9,L=10,A=11,k=12,v=13,S$1=14,I=15,O=16,T$1=17,V=18,E=0,F=1,P=2,C=3,z=4,M$1=5,W=6,N=7,H=8,K=9,X=10,j=11,R=0,Y=1,q=2,G=13,J=14,Q=15,Z=128,$$1=64,tt=32,et=16,nt=0,it=1,st=2,at=3,rt=4,ot=5,lt=6,ft=7,Ut=8,ct=9,ht=10,_t=13,pt=14,gt=15,yt=16,xt=17,ut=20,bt=21,dt=22,mt=23,wt=24,Dt=27,Bt=28,Lt=29,At=30,kt=31,vt=34,St=35,It=36,Ot=37,Tt=38,Vt=41,Et=42,Ft=43,Pt=44,Ct=45,zt=48,Mt=49,Wt=50,Nt=58,Ht=59,Kt=62,Xt=63,jt=64,Rt=65,Yt=68,qt=69,Gt=70,Jt=71,Qt=74,Zt=75,$t=76,te=77,ee=78,ne=81,ie=82,se=83,ae=84,re=85,oe=88,le=89,fe=90,Ue=91,ce=92,he=95,_e=96,pe=97,ge=98,ye=99,xe=100,ue=101,be=102,de=103,me=104,we=105,De=106,Be=107,Le=108,Ae=109,ke=110,ve=111,Se=112,Ie=113,Oe=114,Te=115,Ve=116,Ee=117,Fe=118,Pe=119,Ce=120,ze=121,Me=122,We=123,Ne=124,He=125,Ke=126,Xe=127,je=128,Re=129,Ye=130,qe=131,Ge=132,Je=133,Qe=134,Ze=135,$e=136,tn=137,en=138,nn=139,sn=140,an=141,rn=142,on=143,ln=144,fn=145,Un=146,cn=147,hn=148,_n=149,pn=150,gn=151,yn=152,xn=153,un=154,bn=155,dn=156,mn=157,wn=158,Dn=159,Bn=160,Ln=161,An=162,kn=163,vn=164,Sn=165,In=166,On=167,Tn=168,Vn=169,En=170,Fn=171,Pn=172,Cn=173,zn=174,Mn=175,Wn=176,Nn=177,Hn=178,Kn=179,Xn=180,jn=181,Rn=182,Yn=183,qn=184,Gn=1000156007,Jn=1000156008,Qn=1000156009,Zn=1000156010,$n=1000156011,ti=1000156017,ei=1000156018,ni=1000156019,ii=1000156020,si=1000156021,ai=1000054e3,ri=1000054001,oi=1000054002,li=1000054003,fi=1000054004,Ui=1000054005,ci=1000054006,hi=1000054007,_i=1000066e3,pi=1000066001,gi=1000066002,yi=1000066003,xi=1000066004,ui=1000066005,bi=1000066006,di=1000066007,mi=1000066008,wi=1000066009,Di=1000066010,Bi=1000066011,Li=1000066012,Ai=1000066013,ki=100034e4,vi=1000340001;class Si{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null;}}class Ii{constructor(t,e,n,i){this._dataView=new DataView(t.buffer,t.byteOffset+e,n),this._littleEndian=i,this._offset=0;}_nextUint8(){const t=this._dataView.getUint8(this._offset);return this._offset+=1,t}_nextUint16(){const t=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,t}_nextUint32(){const t=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint64(){const t=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,t}_nextInt32(){const t=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,t}_skip(t){return this._offset+=t,this}_scan(t,e=0){const n=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==e&&i<t;)i++,this._offset++;return i<t&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}const Oi=new Uint8Array([0]),Ti=[171,75,84,88,32,50,48,187,13,10,26,10];function Vi(t){return "undefined"!=typeof TextEncoder?(new TextEncoder).encode(t):Buffer.from(t)}function Ei(t){return "undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}function Fi(t){let e=0;for(const n of t)e+=n.byteLength;const n=new Uint8Array(e);let i=0;for(const e of t)n.set(new Uint8Array(e),i),i+=e.byteLength;return n}function Pi(t){const e=new Uint8Array(t.buffer,t.byteOffset,Ti.length);if(e[0]!==Ti[0]||e[1]!==Ti[1]||e[2]!==Ti[2]||e[3]!==Ti[3]||e[4]!==Ti[4]||e[5]!==Ti[5]||e[6]!==Ti[6]||e[7]!==Ti[7]||e[8]!==Ti[8]||e[9]!==Ti[9]||e[10]!==Ti[10]||e[11]!==Ti[11])throw new Error("Missing KTX 2.0 identifier.");const n=new Si,i=17*Uint32Array.BYTES_PER_ELEMENT,s=new Ii(t,Ti.length,i,!0);n.vkFormat=s._nextUint32(),n.typeSize=s._nextUint32(),n.pixelWidth=s._nextUint32(),n.pixelHeight=s._nextUint32(),n.pixelDepth=s._nextUint32(),n.layerCount=s._nextUint32(),n.faceCount=s._nextUint32();const a=s._nextUint32();n.supercompressionScheme=s._nextUint32();const r=s._nextUint32(),o=s._nextUint32(),l=s._nextUint32(),f=s._nextUint32(),U=s._nextUint64(),c=s._nextUint64(),h=new Ii(t,Ti.length+i,3*a*8,!0);for(let e=0;e<a;e++)n.levels.push({levelData:new Uint8Array(t.buffer,t.byteOffset+h._nextUint64(),h._nextUint64()),uncompressedByteLength:h._nextUint64()});const _=new Ii(t,r,o,!0),p={vendorId:_._skip(4)._nextUint16(),descriptorType:_._nextUint16(),versionNumber:_._nextUint16(),descriptorBlockSize:_._nextUint16(),colorModel:_._nextUint8(),colorPrimaries:_._nextUint8(),transferFunction:_._nextUint8(),flags:_._nextUint8(),texelBlockDimension:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],bytesPlane:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],samples:[]},g=(p.descriptorBlockSize/4-6)/4;for(let t=0;t<g;t++){const e={bitOffset:_._nextUint16(),bitLength:_._nextUint8(),channelType:_._nextUint8(),samplePosition:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],sampleLower:-Infinity,sampleUpper:Infinity};64&e.channelType?(e.sampleLower=_._nextInt32(),e.sampleUpper=_._nextInt32()):(e.sampleLower=_._nextUint32(),e.sampleUpper=_._nextUint32()),p.samples[t]=e;}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(p);const y=new Ii(t,l,f,!0);for(;y._offset<f;){const t=y._nextUint32(),e=y._scan(t),i=Ei(e),s=y._scan(t-e.byteLength);n.keyValue[i]=i.match(/^ktx/i)?Ei(s):s,y._offset%4&&y._skip(4-y._offset%4);}if(c<=0)return n;const x=new Ii(t,U,c,!0),u=x._nextUint16(),b=x._nextUint16(),d=x._nextUint32(),m=x._nextUint32(),w=x._nextUint32(),D=x._nextUint32(),B=[];for(let t=0;t<a;t++)B.push({imageFlags:x._nextUint32(),rgbSliceByteOffset:x._nextUint32(),rgbSliceByteLength:x._nextUint32(),alphaSliceByteOffset:x._nextUint32(),alphaSliceByteLength:x._nextUint32()});const L=U+x._offset,A=L+d,k=A+m,v=k+w,S=new Uint8Array(t.buffer,t.byteOffset+L,d),I=new Uint8Array(t.buffer,t.byteOffset+A,m),O=new Uint8Array(t.buffer,t.byteOffset+k,w),T=new Uint8Array(t.buffer,t.byteOffset+v,D);return n.globalData={endpointCount:u,selectorCount:b,imageDescs:B,endpointsData:S,selectorsData:I,tablesData:O,extendedData:T},n}function Ci(){return (Ci=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i]);}return t}).apply(this,arguments)}const zi={keepWriter:!1};function Mi(t,e={}){e=Ci({},zi,e);let n=new ArrayBuffer(0);if(t.globalData){const e=new ArrayBuffer(20+5*t.globalData.imageDescs.length*4),i=new DataView(e);i.setUint16(0,t.globalData.endpointCount,!0),i.setUint16(2,t.globalData.selectorCount,!0),i.setUint32(4,t.globalData.endpointsData.byteLength,!0),i.setUint32(8,t.globalData.selectorsData.byteLength,!0),i.setUint32(12,t.globalData.tablesData.byteLength,!0),i.setUint32(16,t.globalData.extendedData.byteLength,!0);for(let e=0;e<t.globalData.imageDescs.length;e++){const n=t.globalData.imageDescs[e];i.setUint32(20+5*e*4+0,n.imageFlags,!0),i.setUint32(20+5*e*4+4,n.rgbSliceByteOffset,!0),i.setUint32(20+5*e*4+8,n.rgbSliceByteLength,!0),i.setUint32(20+5*e*4+12,n.alphaSliceByteOffset,!0),i.setUint32(20+5*e*4+16,n.alphaSliceByteLength,!0);}n=Fi([e,t.globalData.endpointsData,t.globalData.selectorsData,t.globalData.tablesData,t.globalData.extendedData]);}const i=[];let s=t.keyValue;e.keepWriter||(s=Ci({},t.keyValue,{KTXwriter:"KTX-Parse v0.3.1"}));for(const t in s){const e=s[t],n=Vi(t),a="string"==typeof e?Vi(e):e,r=n.byteLength+1+a.byteLength+1,o=r%4?4-r%4:0;i.push(Fi([new Uint32Array([r]),n,Oi,a,Oi,new Uint8Array(o).fill(0)]));}const a=Fi(i);if(1!==t.dataFormatDescriptor.length||0!==t.dataFormatDescriptor[0].descriptorType)throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");const r=t.dataFormatDescriptor[0],o=new ArrayBuffer(28+16*r.samples.length),l=new DataView(o),f=24+16*r.samples.length;if(l.setUint32(0,o.byteLength,!0),l.setUint16(4,r.vendorId,!0),l.setUint16(6,r.descriptorType,!0),l.setUint16(8,r.versionNumber,!0),l.setUint16(10,f,!0),l.setUint8(12,r.colorModel),l.setUint8(13,r.colorPrimaries),l.setUint8(14,r.transferFunction),l.setUint8(15,r.flags),!Array.isArray(r.texelBlockDimension))throw new Error("texelBlockDimension is now an array. For dimensionality `d`, set `d - 1`.");l.setUint8(16,r.texelBlockDimension[0]),l.setUint8(17,r.texelBlockDimension[1]),l.setUint8(18,r.texelBlockDimension[2]),l.setUint8(19,r.texelBlockDimension[3]);for(let t=0;t<8;t++)l.setUint8(20+t,r.bytesPlane[t]);for(let t=0;t<r.samples.length;t++){const e=r.samples[t],n=28+16*t;if(e.channelID)throw new Error("channelID has been renamed to channelType.");l.setUint16(n+0,e.bitOffset,!0),l.setUint8(n+2,e.bitLength),l.setUint8(n+3,e.channelType),l.setUint8(n+4,e.samplePosition[0]),l.setUint8(n+5,e.samplePosition[1]),l.setUint8(n+6,e.samplePosition[2]),l.setUint8(n+7,e.samplePosition[3]),64&e.channelType?(l.setInt32(n+8,e.sampleLower,!0),l.setInt32(n+12,e.sampleUpper,!0)):(l.setUint32(n+8,e.sampleLower,!0),l.setUint32(n+12,e.sampleUpper,!0));}const U=Ti.length+68+3*t.levels.length*8,c=U+o.byteLength;let h=n.byteLength>0?c+a.byteLength:0;h%8&&(h+=8-h%8);const _=[],p=new DataView(new ArrayBuffer(3*t.levels.length*8));let g=(h||c+a.byteLength)+n.byteLength;for(let e=0;e<t.levels.length;e++){const n=t.levels[e];_.push(n.levelData),p.setBigUint64(24*e+0,BigInt(g),!0),p.setBigUint64(24*e+8,BigInt(n.levelData.byteLength),!0),p.setBigUint64(24*e+16,BigInt(n.uncompressedByteLength),!0),g+=n.levelData.byteLength;}const y=new ArrayBuffer(68),x=new DataView(y);return x.setUint32(0,t.vkFormat,!0),x.setUint32(4,t.typeSize,!0),x.setUint32(8,t.pixelWidth,!0),x.setUint32(12,t.pixelHeight,!0),x.setUint32(16,t.pixelDepth,!0),x.setUint32(20,t.layerCount,!0),x.setUint32(24,t.faceCount,!0),x.setUint32(28,t.levels.length,!0),x.setUint32(32,t.supercompressionScheme,!0),x.setUint32(36,U,!0),x.setUint32(40,o.byteLength,!0),x.setUint32(44,c,!0),x.setUint32(48,a.byteLength,!0),x.setBigUint64(52,BigInt(n.byteLength>0?h:0),!0),x.setBigUint64(60,BigInt(n.byteLength),!0),new Uint8Array(Fi([new Uint8Array(Ti).buffer,y,p.buffer,o,a,h>0?new ArrayBuffer(h-(c+a.byteLength)):new ArrayBuffer(0),n,..._]))}
  71969. var KTX = /*#__PURE__*/Object.freeze({
  71970. __proto__: null,
  71971. KHR_DF_CHANNEL_RGBSDA_ALPHA: Q,
  71972. KHR_DF_CHANNEL_RGBSDA_BLUE: q,
  71973. KHR_DF_CHANNEL_RGBSDA_DEPTH: J,
  71974. KHR_DF_CHANNEL_RGBSDA_GREEN: Y,
  71975. KHR_DF_CHANNEL_RGBSDA_RED: R,
  71976. KHR_DF_CHANNEL_RGBSDA_STENCIL: G,
  71977. KHR_DF_FLAG_ALPHA_PREMULTIPLIED: p,
  71978. KHR_DF_FLAG_ALPHA_STRAIGHT: _$1,
  71979. KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT: s,
  71980. KHR_DF_MODEL_ASTC: c$3,
  71981. KHR_DF_MODEL_ETC1: f,
  71982. KHR_DF_MODEL_ETC1S: h$2,
  71983. KHR_DF_MODEL_ETC2: U$1,
  71984. KHR_DF_MODEL_RGBSDA: l$1,
  71985. KHR_DF_MODEL_UNSPECIFIED: o$1,
  71986. KHR_DF_PRIMARIES_ACES: W,
  71987. KHR_DF_PRIMARIES_ACESCC: N,
  71988. KHR_DF_PRIMARIES_ADOBERGB: j,
  71989. KHR_DF_PRIMARIES_BT2020: z,
  71990. KHR_DF_PRIMARIES_BT601_EBU: P,
  71991. KHR_DF_PRIMARIES_BT601_SMPTE: C,
  71992. KHR_DF_PRIMARIES_BT709: F,
  71993. KHR_DF_PRIMARIES_CIEXYZ: M$1,
  71994. KHR_DF_PRIMARIES_DISPLAYP3: X,
  71995. KHR_DF_PRIMARIES_NTSC1953: H,
  71996. KHR_DF_PRIMARIES_PAL525: K,
  71997. KHR_DF_PRIMARIES_UNSPECIFIED: E,
  71998. KHR_DF_SAMPLE_DATATYPE_EXPONENT: tt,
  71999. KHR_DF_SAMPLE_DATATYPE_FLOAT: Z,
  72000. KHR_DF_SAMPLE_DATATYPE_LINEAR: et,
  72001. KHR_DF_SAMPLE_DATATYPE_SIGNED: $$1,
  72002. KHR_DF_TRANSFER_ACESCC: O,
  72003. KHR_DF_TRANSFER_ACESCCT: T$1,
  72004. KHR_DF_TRANSFER_ADOBERGB: V,
  72005. KHR_DF_TRANSFER_BT1886: w$1,
  72006. KHR_DF_TRANSFER_DCIP3: k,
  72007. KHR_DF_TRANSFER_HLG_EOTF: B,
  72008. KHR_DF_TRANSFER_HLG_OETF: D,
  72009. KHR_DF_TRANSFER_ITU: u$2,
  72010. KHR_DF_TRANSFER_LINEAR: y,
  72011. KHR_DF_TRANSFER_NTSC: b$1,
  72012. KHR_DF_TRANSFER_PAL625_EOTF: S$1,
  72013. KHR_DF_TRANSFER_PAL_OETF: v,
  72014. KHR_DF_TRANSFER_PQ_EOTF: L,
  72015. KHR_DF_TRANSFER_PQ_OETF: A,
  72016. KHR_DF_TRANSFER_SLOG: d,
  72017. KHR_DF_TRANSFER_SLOG2: m,
  72018. KHR_DF_TRANSFER_SRGB: x$2,
  72019. KHR_DF_TRANSFER_ST240: I,
  72020. KHR_DF_TRANSFER_UNSPECIFIED: g,
  72021. KHR_DF_VENDORID_KHRONOS: a$1,
  72022. KHR_DF_VERSION: r,
  72023. KHR_SUPERCOMPRESSION_BASISLZ: e$1,
  72024. KHR_SUPERCOMPRESSION_NONE: t,
  72025. KHR_SUPERCOMPRESSION_ZLIB: i$2,
  72026. KHR_SUPERCOMPRESSION_ZSTD: n$1,
  72027. KTX2Container: Si,
  72028. VK_FORMAT_A1R5G5B5_UNORM_PACK16: Ut,
  72029. VK_FORMAT_A2B10G10R10_SINT_PACK32: qt,
  72030. VK_FORMAT_A2B10G10R10_SNORM_PACK32: Rt,
  72031. VK_FORMAT_A2B10G10R10_UINT_PACK32: Yt,
  72032. VK_FORMAT_A2B10G10R10_UNORM_PACK32: jt,
  72033. VK_FORMAT_A2R10G10B10_SINT_PACK32: Xt,
  72034. VK_FORMAT_A2R10G10B10_SNORM_PACK32: Ht,
  72035. VK_FORMAT_A2R10G10B10_UINT_PACK32: Kt,
  72036. VK_FORMAT_A2R10G10B10_UNORM_PACK32: Nt,
  72037. VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT: vi,
  72038. VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT: ki,
  72039. VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT: Bi,
  72040. VK_FORMAT_ASTC_10x10_SRGB_BLOCK: Xn,
  72041. VK_FORMAT_ASTC_10x10_UNORM_BLOCK: Kn,
  72042. VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT: mi,
  72043. VK_FORMAT_ASTC_10x5_SRGB_BLOCK: zn,
  72044. VK_FORMAT_ASTC_10x5_UNORM_BLOCK: Cn,
  72045. VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT: wi,
  72046. VK_FORMAT_ASTC_10x6_SRGB_BLOCK: Wn,
  72047. VK_FORMAT_ASTC_10x6_UNORM_BLOCK: Mn,
  72048. VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT: Di,
  72049. VK_FORMAT_ASTC_10x8_SRGB_BLOCK: Hn,
  72050. VK_FORMAT_ASTC_10x8_UNORM_BLOCK: Nn,
  72051. VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT: Li,
  72052. VK_FORMAT_ASTC_12x10_SRGB_BLOCK: Rn,
  72053. VK_FORMAT_ASTC_12x10_UNORM_BLOCK: jn,
  72054. VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT: Ai,
  72055. VK_FORMAT_ASTC_12x12_SRGB_BLOCK: qn,
  72056. VK_FORMAT_ASTC_12x12_UNORM_BLOCK: Yn,
  72057. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT: _i,
  72058. VK_FORMAT_ASTC_4x4_SRGB_BLOCK: wn,
  72059. VK_FORMAT_ASTC_4x4_UNORM_BLOCK: mn,
  72060. VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT: pi,
  72061. VK_FORMAT_ASTC_5x4_SRGB_BLOCK: Bn,
  72062. VK_FORMAT_ASTC_5x4_UNORM_BLOCK: Dn,
  72063. VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT: gi,
  72064. VK_FORMAT_ASTC_5x5_SRGB_BLOCK: An,
  72065. VK_FORMAT_ASTC_5x5_UNORM_BLOCK: Ln,
  72066. VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT: yi,
  72067. VK_FORMAT_ASTC_6x5_SRGB_BLOCK: vn,
  72068. VK_FORMAT_ASTC_6x5_UNORM_BLOCK: kn,
  72069. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT: xi,
  72070. VK_FORMAT_ASTC_6x6_SRGB_BLOCK: In,
  72071. VK_FORMAT_ASTC_6x6_UNORM_BLOCK: Sn,
  72072. VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT: ui,
  72073. VK_FORMAT_ASTC_8x5_SRGB_BLOCK: Tn,
  72074. VK_FORMAT_ASTC_8x5_UNORM_BLOCK: On,
  72075. VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT: bi,
  72076. VK_FORMAT_ASTC_8x6_SRGB_BLOCK: En,
  72077. VK_FORMAT_ASTC_8x6_UNORM_BLOCK: Vn,
  72078. VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT: di,
  72079. VK_FORMAT_ASTC_8x8_SRGB_BLOCK: Pn,
  72080. VK_FORMAT_ASTC_8x8_UNORM_BLOCK: Fn,
  72081. VK_FORMAT_B10G11R11_UFLOAT_PACK32: Me,
  72082. VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: $n,
  72083. VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: si,
  72084. VK_FORMAT_B4G4R4A4_UNORM_PACK16: at,
  72085. VK_FORMAT_B5G5R5A1_UNORM_PACK16: ft,
  72086. VK_FORMAT_B5G6R5_UNORM_PACK16: ot,
  72087. VK_FORMAT_B8G8R8A8_SINT: Mt,
  72088. VK_FORMAT_B8G8R8A8_SNORM: Ct,
  72089. VK_FORMAT_B8G8R8A8_SRGB: Wt,
  72090. VK_FORMAT_B8G8R8A8_UINT: zt,
  72091. VK_FORMAT_B8G8R8A8_UNORM: Pt,
  72092. VK_FORMAT_B8G8R8_SINT: St,
  72093. VK_FORMAT_B8G8R8_SNORM: kt,
  72094. VK_FORMAT_B8G8R8_SRGB: It,
  72095. VK_FORMAT_B8G8R8_UINT: vt,
  72096. VK_FORMAT_B8G8R8_UNORM: At,
  72097. VK_FORMAT_BC1_RGBA_SRGB_BLOCK: Qe,
  72098. VK_FORMAT_BC1_RGBA_UNORM_BLOCK: Je,
  72099. VK_FORMAT_BC1_RGB_SRGB_BLOCK: Ge,
  72100. VK_FORMAT_BC1_RGB_UNORM_BLOCK: qe,
  72101. VK_FORMAT_BC2_SRGB_BLOCK: $e,
  72102. VK_FORMAT_BC2_UNORM_BLOCK: Ze,
  72103. VK_FORMAT_BC3_SRGB_BLOCK: en,
  72104. VK_FORMAT_BC3_UNORM_BLOCK: tn,
  72105. VK_FORMAT_BC4_SNORM_BLOCK: sn,
  72106. VK_FORMAT_BC4_UNORM_BLOCK: nn,
  72107. VK_FORMAT_BC5_SNORM_BLOCK: rn,
  72108. VK_FORMAT_BC5_UNORM_BLOCK: an,
  72109. VK_FORMAT_BC6H_SFLOAT_BLOCK: ln,
  72110. VK_FORMAT_BC6H_UFLOAT_BLOCK: on,
  72111. VK_FORMAT_BC7_SRGB_BLOCK: Un,
  72112. VK_FORMAT_BC7_UNORM_BLOCK: fn,
  72113. VK_FORMAT_D16_UNORM: Ne,
  72114. VK_FORMAT_D16_UNORM_S8_UINT: je,
  72115. VK_FORMAT_D24_UNORM_S8_UINT: Re,
  72116. VK_FORMAT_D32_SFLOAT: Ke,
  72117. VK_FORMAT_D32_SFLOAT_S8_UINT: Ye,
  72118. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: We,
  72119. VK_FORMAT_EAC_R11G11_SNORM_BLOCK: dn,
  72120. VK_FORMAT_EAC_R11G11_UNORM_BLOCK: bn,
  72121. VK_FORMAT_EAC_R11_SNORM_BLOCK: un,
  72122. VK_FORMAT_EAC_R11_UNORM_BLOCK: xn,
  72123. VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: pn,
  72124. VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: _n,
  72125. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: yn,
  72126. VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: gn,
  72127. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: hn,
  72128. VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: cn,
  72129. VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: Zn,
  72130. VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: ii,
  72131. VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG: fi,
  72132. VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG: ai,
  72133. VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG: Ui,
  72134. VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG: ri,
  72135. VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG: ci,
  72136. VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG: oi,
  72137. VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: hi,
  72138. VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG: li,
  72139. VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: Qn,
  72140. VK_FORMAT_R10X6G10X6_UNORM_2PACK16: Jn,
  72141. VK_FORMAT_R10X6_UNORM_PACK16: Gn,
  72142. VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: ni,
  72143. VK_FORMAT_R12X4G12X4_UNORM_2PACK16: ei,
  72144. VK_FORMAT_R12X4_UNORM_PACK16: ti,
  72145. VK_FORMAT_R16G16B16A16_SFLOAT: pe,
  72146. VK_FORMAT_R16G16B16A16_SINT: _e,
  72147. VK_FORMAT_R16G16B16A16_SNORM: ce,
  72148. VK_FORMAT_R16G16B16A16_UINT: he,
  72149. VK_FORMAT_R16G16B16A16_UNORM: Ue,
  72150. VK_FORMAT_R16G16B16_SFLOAT: fe,
  72151. VK_FORMAT_R16G16B16_SINT: le,
  72152. VK_FORMAT_R16G16B16_SNORM: re,
  72153. VK_FORMAT_R16G16B16_UINT: oe,
  72154. VK_FORMAT_R16G16B16_UNORM: ae,
  72155. VK_FORMAT_R16G16_SFLOAT: se,
  72156. VK_FORMAT_R16G16_SINT: ie,
  72157. VK_FORMAT_R16G16_SNORM: ee,
  72158. VK_FORMAT_R16G16_UINT: ne,
  72159. VK_FORMAT_R16G16_UNORM: te,
  72160. VK_FORMAT_R16_SFLOAT: $t,
  72161. VK_FORMAT_R16_SINT: Zt,
  72162. VK_FORMAT_R16_SNORM: Jt,
  72163. VK_FORMAT_R16_UINT: Qt,
  72164. VK_FORMAT_R16_UNORM: Gt,
  72165. VK_FORMAT_R32G32B32A32_SFLOAT: Ae,
  72166. VK_FORMAT_R32G32B32A32_SINT: Le,
  72167. VK_FORMAT_R32G32B32A32_UINT: Be,
  72168. VK_FORMAT_R32G32B32_SFLOAT: De,
  72169. VK_FORMAT_R32G32B32_SINT: we,
  72170. VK_FORMAT_R32G32B32_UINT: me,
  72171. VK_FORMAT_R32G32_SFLOAT: de,
  72172. VK_FORMAT_R32G32_SINT: be,
  72173. VK_FORMAT_R32G32_UINT: ue,
  72174. VK_FORMAT_R32_SFLOAT: xe,
  72175. VK_FORMAT_R32_SINT: ye,
  72176. VK_FORMAT_R32_UINT: ge,
  72177. VK_FORMAT_R4G4B4A4_UNORM_PACK16: st,
  72178. VK_FORMAT_R4G4_UNORM_PACK8: it,
  72179. VK_FORMAT_R5G5B5A1_UNORM_PACK16: lt,
  72180. VK_FORMAT_R5G6B5_UNORM_PACK16: rt,
  72181. VK_FORMAT_R64G64B64A64_SFLOAT: ze,
  72182. VK_FORMAT_R64G64B64A64_SINT: Ce,
  72183. VK_FORMAT_R64G64B64A64_UINT: Pe,
  72184. VK_FORMAT_R64G64B64_SFLOAT: Fe,
  72185. VK_FORMAT_R64G64B64_SINT: Ee,
  72186. VK_FORMAT_R64G64B64_UINT: Ve,
  72187. VK_FORMAT_R64G64_SFLOAT: Te,
  72188. VK_FORMAT_R64G64_SINT: Oe,
  72189. VK_FORMAT_R64G64_UINT: Ie,
  72190. VK_FORMAT_R64_SFLOAT: Se,
  72191. VK_FORMAT_R64_SINT: ve,
  72192. VK_FORMAT_R64_UINT: ke,
  72193. VK_FORMAT_R8G8B8A8_SINT: Et,
  72194. VK_FORMAT_R8G8B8A8_SNORM: Tt,
  72195. VK_FORMAT_R8G8B8A8_SRGB: Ft,
  72196. VK_FORMAT_R8G8B8A8_UINT: Vt,
  72197. VK_FORMAT_R8G8B8A8_UNORM: Ot,
  72198. VK_FORMAT_R8G8B8_SINT: Bt,
  72199. VK_FORMAT_R8G8B8_SNORM: wt,
  72200. VK_FORMAT_R8G8B8_SRGB: Lt,
  72201. VK_FORMAT_R8G8B8_UINT: Dt,
  72202. VK_FORMAT_R8G8B8_UNORM: mt,
  72203. VK_FORMAT_R8G8_SINT: bt,
  72204. VK_FORMAT_R8G8_SNORM: xt,
  72205. VK_FORMAT_R8G8_SRGB: dt,
  72206. VK_FORMAT_R8G8_UINT: ut,
  72207. VK_FORMAT_R8G8_UNORM: yt,
  72208. VK_FORMAT_R8_SINT: pt,
  72209. VK_FORMAT_R8_SNORM: ht,
  72210. VK_FORMAT_R8_SRGB: gt,
  72211. VK_FORMAT_R8_UINT: _t,
  72212. VK_FORMAT_R8_UNORM: ct,
  72213. VK_FORMAT_S8_UINT: Xe,
  72214. VK_FORMAT_UNDEFINED: nt,
  72215. VK_FORMAT_X8_D24_UNORM_PACK32: He,
  72216. read: Pi,
  72217. write: Mi
  72218. });
  72219. /**
  72220. * Loader for KTX 2.0 GPU Texture containers.
  72221. *
  72222. * KTX 2.0 is a container format for various GPU texture formats. The loader
  72223. * supports Basis Universal GPU textures, which can be quickly transcoded to
  72224. * a wide variety of GPU texture compression formats, as well as some
  72225. * uncompressed DataTexture and Data3DTexture formats.
  72226. *
  72227. * References:
  72228. * - KTX: http://github.khronos.org/KTX-Specification/
  72229. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  72230. */
  72231. const {
  72232. read: read$1,
  72233. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  72234. KHR_DF_TRANSFER_SRGB,
  72235. VK_FORMAT_UNDEFINED,
  72236. VK_FORMAT_R16_SFLOAT,
  72237. VK_FORMAT_R16G16_SFLOAT,
  72238. VK_FORMAT_R16G16B16A16_SFLOAT,
  72239. VK_FORMAT_R32_SFLOAT,
  72240. VK_FORMAT_R32G32_SFLOAT,
  72241. VK_FORMAT_R32G32B32A32_SFLOAT,
  72242. VK_FORMAT_R8_SRGB,
  72243. VK_FORMAT_R8_UNORM,
  72244. VK_FORMAT_R8G8_SRGB,
  72245. VK_FORMAT_R8G8_UNORM,
  72246. VK_FORMAT_R8G8B8A8_SRGB,
  72247. VK_FORMAT_R8G8B8A8_UNORM,
  72248. } = KTX; // eslint-disable-line no-undef
  72249. const _taskCache$1 = new WeakMap();
  72250. let _activeLoaders = 0;
  72251. class KTX2Loader extends Loader {
  72252. constructor( manager ) {
  72253. super( manager );
  72254. this.transcoderPath = '';
  72255. this.transcoderBinary = null;
  72256. this.transcoderPending = null;
  72257. this.workerPool = new WorkerPool$1();
  72258. this.workerSourceURL = '';
  72259. this.workerConfig = null;
  72260. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  72261. console.warn(
  72262. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  72263. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  72264. );
  72265. }
  72266. }
  72267. setTranscoderPath( path ) {
  72268. this.transcoderPath = path;
  72269. return this;
  72270. }
  72271. setWorkerLimit( num ) {
  72272. this.workerPool.setWorkerLimit( num );
  72273. return this;
  72274. }
  72275. detectSupport( renderer ) {
  72276. this.workerConfig = {
  72277. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  72278. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  72279. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  72280. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  72281. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  72282. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  72283. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  72284. };
  72285. if ( renderer.capabilities.isWebGL2 ) {
  72286. // https://github.com/mrdoob/three.js/pull/22928
  72287. this.workerConfig.etc1Supported = false;
  72288. }
  72289. return this;
  72290. }
  72291. init() {
  72292. if ( ! this.transcoderPending ) {
  72293. // Load transcoder wrapper.
  72294. const jsLoader = new FileLoader( this.manager );
  72295. jsLoader.setPath( this.transcoderPath );
  72296. jsLoader.setWithCredentials( this.withCredentials );
  72297. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  72298. // Load transcoder WASM binary.
  72299. const binaryLoader = new FileLoader( this.manager );
  72300. binaryLoader.setPath( this.transcoderPath );
  72301. binaryLoader.setResponseType( 'arraybuffer' );
  72302. binaryLoader.setWithCredentials( this.withCredentials );
  72303. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  72304. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  72305. .then( ( [ jsContent, binaryContent ] ) => {
  72306. const fn = KTX2Loader.BasisWorker.toString();
  72307. const body = [
  72308. '/* constants */',
  72309. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  72310. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  72311. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  72312. '/* basis_transcoder.js */',
  72313. jsContent,
  72314. '/* worker */',
  72315. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  72316. ].join( '\n' );
  72317. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  72318. this.transcoderBinary = binaryContent;
  72319. this.workerPool.setWorkerCreator( () => {
  72320. const worker = new Worker( this.workerSourceURL );
  72321. const transcoderBinary = this.transcoderBinary.slice( 0 );
  72322. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  72323. return worker;
  72324. } );
  72325. } );
  72326. if ( _activeLoaders > 0 ) {
  72327. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  72328. console.warn(
  72329. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  72330. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  72331. );
  72332. }
  72333. _activeLoaders ++;
  72334. }
  72335. return this.transcoderPending;
  72336. }
  72337. load( url, onLoad, onProgress, onError ) {
  72338. if ( this.workerConfig === null ) {
  72339. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  72340. }
  72341. const loader = new FileLoader( this.manager );
  72342. loader.setResponseType( 'arraybuffer' );
  72343. loader.setWithCredentials( this.withCredentials );
  72344. loader.load( url, ( buffer ) => {
  72345. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  72346. // again from this thread.
  72347. if ( _taskCache$1.has( buffer ) ) {
  72348. const cachedTask = _taskCache$1.get( buffer );
  72349. return cachedTask.promise.then( onLoad ).catch( onError );
  72350. }
  72351. this._createTexture( buffer )
  72352. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  72353. .catch( onError );
  72354. }, onProgress, onError );
  72355. }
  72356. _createTextureFrom( transcodeResult ) {
  72357. const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult;
  72358. if ( type === 'error' ) return Promise.reject( error );
  72359. const texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  72360. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  72361. texture.magFilter = LinearFilter;
  72362. texture.generateMipmaps = false;
  72363. texture.needsUpdate = true;
  72364. texture.encoding = dfdTransferFn === KHR_DF_TRANSFER_SRGB ? sRGBEncoding : LinearEncoding;
  72365. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  72366. return texture;
  72367. }
  72368. /**
  72369. * @param {ArrayBuffer} buffer
  72370. * @param {object?} config
  72371. * @return {Promise<CompressedTexture|DataTexture|Data3DTexture>}
  72372. */
  72373. _createTexture( buffer, config = {} ) {
  72374. const container = read$1( new Uint8Array( buffer ) );
  72375. if ( container.vkFormat !== VK_FORMAT_UNDEFINED ) {
  72376. return createDataTexture( container );
  72377. }
  72378. //
  72379. const taskConfig = config;
  72380. const texturePending = this.init().then( () => {
  72381. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  72382. } ).then( ( e ) => this._createTextureFrom( e.data ) );
  72383. // Cache the task result.
  72384. _taskCache$1.set( buffer, { promise: texturePending } );
  72385. return texturePending;
  72386. }
  72387. dispose() {
  72388. this.workerPool.dispose();
  72389. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  72390. _activeLoaders --;
  72391. return this;
  72392. }
  72393. }
  72394. /* CONSTANTS */
  72395. KTX2Loader.BasisFormat = {
  72396. ETC1S: 0,
  72397. UASTC_4x4: 1,
  72398. };
  72399. KTX2Loader.TranscoderFormat = {
  72400. ETC1: 0,
  72401. ETC2: 1,
  72402. BC1: 2,
  72403. BC3: 3,
  72404. BC4: 4,
  72405. BC5: 5,
  72406. BC7_M6_OPAQUE_ONLY: 6,
  72407. BC7_M5: 7,
  72408. PVRTC1_4_RGB: 8,
  72409. PVRTC1_4_RGBA: 9,
  72410. ASTC_4x4: 10,
  72411. ATC_RGB: 11,
  72412. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  72413. RGBA32: 13,
  72414. RGB565: 14,
  72415. BGR565: 15,
  72416. RGBA4444: 16,
  72417. };
  72418. KTX2Loader.EngineFormat = {
  72419. RGBAFormat: RGBAFormat,
  72420. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  72421. RGBA_BPTC_Format: RGBA_BPTC_Format,
  72422. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  72423. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  72424. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  72425. RGB_ETC1_Format: RGB_ETC1_Format,
  72426. RGB_ETC2_Format: RGB_ETC2_Format,
  72427. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  72428. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  72429. };
  72430. /* WEB WORKER */
  72431. KTX2Loader.BasisWorker = function () {
  72432. let config;
  72433. let transcoderPending;
  72434. let BasisModule;
  72435. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  72436. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  72437. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  72438. self.addEventListener( 'message', function ( e ) {
  72439. const message = e.data;
  72440. switch ( message.type ) {
  72441. case 'init':
  72442. config = message.config;
  72443. init( message.transcoderBinary );
  72444. break;
  72445. case 'transcode':
  72446. transcoderPending.then( () => {
  72447. try {
  72448. const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode( message.buffer );
  72449. const buffers = [];
  72450. for ( let i = 0; i < mipmaps.length; ++ i ) {
  72451. buffers.push( mipmaps[ i ].data.buffer );
  72452. }
  72453. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers );
  72454. } catch ( error ) {
  72455. console.error( error );
  72456. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  72457. }
  72458. } );
  72459. break;
  72460. }
  72461. } );
  72462. function init( wasmBinary ) {
  72463. transcoderPending = new Promise( ( resolve ) => {
  72464. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  72465. BASIS( BasisModule ); // eslint-disable-line no-undef
  72466. } ).then( () => {
  72467. BasisModule.initializeBasis();
  72468. if ( BasisModule.KTX2File === undefined ) {
  72469. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  72470. }
  72471. } );
  72472. }
  72473. function transcode( buffer ) {
  72474. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  72475. function cleanup() {
  72476. ktx2File.close();
  72477. ktx2File.delete();
  72478. }
  72479. if ( ! ktx2File.isValid() ) {
  72480. cleanup();
  72481. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  72482. }
  72483. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  72484. const width = ktx2File.getWidth();
  72485. const height = ktx2File.getHeight();
  72486. const levels = ktx2File.getLevels();
  72487. const hasAlpha = ktx2File.getHasAlpha();
  72488. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  72489. const dfdFlags = ktx2File.getDFDFlags();
  72490. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  72491. if ( ! width || ! height || ! levels ) {
  72492. cleanup();
  72493. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  72494. }
  72495. if ( ! ktx2File.startTranscoding() ) {
  72496. cleanup();
  72497. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  72498. }
  72499. const mipmaps = [];
  72500. for ( let mip = 0; mip < levels; mip ++ ) {
  72501. const levelInfo = ktx2File.getImageLevelInfo( mip, 0, 0 );
  72502. const mipWidth = levelInfo.origWidth;
  72503. const mipHeight = levelInfo.origHeight;
  72504. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, 0, 0, transcoderFormat ) );
  72505. const status = ktx2File.transcodeImage(
  72506. dst,
  72507. mip,
  72508. 0,
  72509. 0,
  72510. transcoderFormat,
  72511. 0,
  72512. - 1,
  72513. - 1,
  72514. );
  72515. if ( ! status ) {
  72516. cleanup();
  72517. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  72518. }
  72519. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  72520. }
  72521. cleanup();
  72522. return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags };
  72523. }
  72524. //
  72525. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  72526. // device capabilities, and texture dimensions. The list below ranks the formats separately
  72527. // for ETC1S and UASTC.
  72528. //
  72529. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  72530. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  72531. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  72532. const FORMAT_OPTIONS = [
  72533. {
  72534. if: 'astcSupported',
  72535. basisFormat: [ BasisFormat.UASTC_4x4 ],
  72536. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  72537. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  72538. priorityETC1S: Infinity,
  72539. priorityUASTC: 1,
  72540. needsPowerOfTwo: false,
  72541. },
  72542. {
  72543. if: 'bptcSupported',
  72544. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72545. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  72546. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  72547. priorityETC1S: 3,
  72548. priorityUASTC: 2,
  72549. needsPowerOfTwo: false,
  72550. },
  72551. {
  72552. if: 'dxtSupported',
  72553. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72554. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  72555. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  72556. priorityETC1S: 4,
  72557. priorityUASTC: 5,
  72558. needsPowerOfTwo: false,
  72559. },
  72560. {
  72561. if: 'etc2Supported',
  72562. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72563. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  72564. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  72565. priorityETC1S: 1,
  72566. priorityUASTC: 3,
  72567. needsPowerOfTwo: false,
  72568. },
  72569. {
  72570. if: 'etc1Supported',
  72571. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72572. transcoderFormat: [ TranscoderFormat.ETC1 ],
  72573. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  72574. priorityETC1S: 2,
  72575. priorityUASTC: 4,
  72576. needsPowerOfTwo: false,
  72577. },
  72578. {
  72579. if: 'pvrtcSupported',
  72580. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72581. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  72582. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  72583. priorityETC1S: 5,
  72584. priorityUASTC: 6,
  72585. needsPowerOfTwo: true,
  72586. },
  72587. ];
  72588. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  72589. return a.priorityETC1S - b.priorityETC1S;
  72590. } );
  72591. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  72592. return a.priorityUASTC - b.priorityUASTC;
  72593. } );
  72594. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  72595. let transcoderFormat;
  72596. let engineFormat;
  72597. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  72598. for ( let i = 0; i < options.length; i ++ ) {
  72599. const opt = options[ i ];
  72600. if ( ! config[ opt.if ] ) continue;
  72601. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  72602. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  72603. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  72604. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  72605. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  72606. return { transcoderFormat, engineFormat };
  72607. }
  72608. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  72609. transcoderFormat = TranscoderFormat.RGBA32;
  72610. engineFormat = EngineFormat.RGBAFormat;
  72611. return { transcoderFormat, engineFormat };
  72612. }
  72613. function isPowerOfTwo( value ) {
  72614. if ( value <= 2 ) return true;
  72615. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  72616. }
  72617. };
  72618. //
  72619. // DataTexture and Data3DTexture parsing.
  72620. const FORMAT_MAP = {
  72621. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  72622. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  72623. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  72624. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  72625. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  72626. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  72627. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  72628. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  72629. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  72630. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  72631. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  72632. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  72633. };
  72634. const TYPE_MAP = {
  72635. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  72636. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  72637. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  72638. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  72639. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  72640. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  72641. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  72642. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  72643. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  72644. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  72645. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  72646. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  72647. };
  72648. const ENCODING_MAP = {
  72649. [ VK_FORMAT_R8G8B8A8_SRGB ]: sRGBEncoding,
  72650. [ VK_FORMAT_R8G8_SRGB ]: sRGBEncoding,
  72651. [ VK_FORMAT_R8_SRGB ]: sRGBEncoding,
  72652. };
  72653. function createDataTexture( container ) {
  72654. const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container;
  72655. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  72656. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  72657. }
  72658. //
  72659. let view;
  72660. const levelData = container.levels[ 0 ].levelData;
  72661. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  72662. view = new Float32Array(
  72663. levelData.buffer,
  72664. levelData.byteOffset,
  72665. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  72666. );
  72667. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  72668. view = new Uint16Array(
  72669. levelData.buffer,
  72670. levelData.byteOffset,
  72671. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  72672. );
  72673. } else {
  72674. view = levelData;
  72675. }
  72676. //
  72677. const texture = pixelDepth === 0
  72678. ? new DataTexture( view, pixelWidth, pixelHeight )
  72679. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  72680. texture.type = TYPE_MAP[ vkFormat ];
  72681. texture.format = FORMAT_MAP[ vkFormat ];
  72682. texture.encoding = ENCODING_MAP[ vkFormat ] || LinearEncoding;
  72683. texture.needsUpdate = true;
  72684. //
  72685. return Promise.resolve( texture );
  72686. }
  72687. // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  72688. // Copyright (C) 2016-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  72689. var MeshoptDecoder = (function() {
  72690. "use strict";
  72691. // Built with clang version 11.0.0 (https://github.com/llvm/llvm-project.git 0160ad802e899c2922bc9b29564080c22eb0908c)
  72692. // Built from meshoptimizer 0.14
  72693. var wasm_base = "B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB";
  72694. var wasm_simd = "B9h9z9tFBBBFiI9gBB9gLaaaaaFa9gEaaaB9gFaFaEMcBBFBFFGGGEILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBOn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBNI9z9iqlBVc+N9IcIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMk8lLbaE97F9+FaL978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAeDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAeDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBReCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBH8ZCFD9tA8ZAPD9OD9hD9RH8ZDQBTFtGmEYIPLdKeOnHpAIAQJDBIBHyCFD9tAyAPD9OD9hD9RHyAIASJDBIBH8cCFD9tA8cAPD9OD9hD9RH8cDQBTFtGmEYIPLdKeOnH8dDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAeD9uHeDyBjGBAEAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeApA8dDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNiV8ZcpMyS8cQ8df8eb8fHdAyA8cDQNiV8ZcpMyS8cQ8df8eb8fH8ZDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/dLEK97FaF97GXGXAGCI9HQBAF9FQFCBRGEXABABDBBBHECiD+rFCiD+sFD/6FHIAECND+rFCiD+sFD/6FAID/gFAECTD+rFCiD+sFD/6FHLD/gFD/kFD/lFHKCBDtD+2FHOAICUUUU94DtHND9OD9RD/kFHI9DBB/+hDYAIAID/mFAKAKD/mFALAOALAND9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHLD/mF9DBBX9LDYHOD/kFCgFDtD9OAECUUU94DtD9OD9QAIALD/mFAOD/kFCND+rFCU/+EDtD9OD9QAKALD/mFAOD/kFCTD+rFCUU/8ODtD9OD9QDMBBABCTJRBAGCIJHGAF9JQBSGMMAF9FQBCBRGEXABCTJHVAVDBBBHECBDtHOCUU98D8cFCUU98D8cEHND9OABDBBBHKAEDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAKAEDQBFGENVcMTtmYi8ZpyHECTD+sFD/6FHID/gFAECTD+rFCTD+sFD/6FHLD/gFD/kFD/lFHE9DB/+g6DYALAEAOD+2FHOALCUUUU94DtHcD9OD9RD/kFHLALD/mFAEAED/mFAIAOAIAcD9OD9RD/kFHEAED/mFD/kFD/kFD/jFD/nFHID/mF9DBBX9LDYHOD/kFCTD+rFALAID/mFAOD/kFCggEDtD9OD9QHLAEAID/mFAOD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHEDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAKAND9OALAEDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM/hEIGaF97FaL978jUUUUBCTlREGXAF9FQBCBRIEXAEABDBBBHLABCTJHKDBBBHODQILKOSQfbPden8c8d8e8fHNCTD+sFHVCID+rFDMIBAB9DBBU8/DY9D/zI818/DYAVCEDtD9QD/6FD/nFHVALAODQBFGENVcMTtmYi8ZpyHLCTD+rFCTD+sFD/6FD/mFHOAOD/mFAVALCTD+sFD/6FD/mFHcAcD/mFAVANCTD+rFCTD+sFD/6FD/mFHNAND/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHVD/mF9DBBX9LDYHLD/kFCggEDtHMD9OAcAVD/mFALD/kFCTD+rFD9QHcANAVD/mFALD/kFCTD+rFAOAVD/mFALD/kFAMD9OD9QHVDQBFTtGEmYILPdKOenHLD8dBAEDBIBDyB+t+J83EBABCNJALD8dFAEDBIBDyF+t+J83EBAKAcAVDQNVi8ZcMpySQ8c8dfb8e8fHVD8dBAEDBIBDyG+t+J83EBABCiJAVD8dFAEDBIBDyE+t+J83EBABCAJRBAICIJHIAF9JQBMMM9jFF97GXAGCGrAF9sHG9FQBCBRFEXABABDBBBHECND+rFCND+sFD/6FAECiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBABCTJRBAFCIJHFAG9JQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB";
  72695. // Uses bulk-memory and simd extensions
  72696. var detector = new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);
  72697. // Used to unpack wasm
  72698. var wasmpack = new Uint8Array([32,0,65,253,3,1,2,34,4,106,6,5,11,8,7,20,13,33,12,16,128,9,116,64,19,113,127,15,10,21,22,14,255,66,24,54,136,107,18,23,192,26,114,118,132,17,77,101,130,144,27,87,131,44,45,74,156,154,70,167]);
  72699. if (typeof WebAssembly !== 'object') {
  72700. // This module requires WebAssembly to function
  72701. return {
  72702. supported: false,
  72703. };
  72704. }
  72705. var wasm = wasm_base;
  72706. if (WebAssembly.validate(detector)) {
  72707. wasm = wasm_simd;
  72708. console.log("Warning: meshopt_decoder is using experimental SIMD support");
  72709. }
  72710. var instance;
  72711. var promise =
  72712. WebAssembly.instantiate(unpack(wasm), {})
  72713. .then(function(result) {
  72714. instance = result.instance;
  72715. instance.exports.__wasm_call_ctors();
  72716. });
  72717. function unpack(data) {
  72718. var result = new Uint8Array(data.length);
  72719. for (var i = 0; i < data.length; ++i) {
  72720. var ch = data.charCodeAt(i);
  72721. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  72722. }
  72723. var write = 0;
  72724. for (var i = 0; i < data.length; ++i) {
  72725. result[write++] = (result[i] < 60) ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  72726. }
  72727. return result.buffer.slice(0, write);
  72728. }
  72729. function decode(fun, target, count, size, source, filter) {
  72730. var sbrk = instance.exports.sbrk;
  72731. var count4 = (count + 3) & ~3; // pad for SIMD filter
  72732. var tp = sbrk(count4 * size);
  72733. var sp = sbrk(source.length);
  72734. var heap = new Uint8Array(instance.exports.memory.buffer);
  72735. heap.set(source, sp);
  72736. var res = fun(tp, count, size, sp, source.length);
  72737. if (res == 0 && filter) {
  72738. filter(tp, count4, size);
  72739. }
  72740. target.set(heap.subarray(tp, tp + count * size));
  72741. sbrk(tp - sbrk(0));
  72742. if (res != 0) {
  72743. throw new Error("Malformed buffer data: " + res);
  72744. }
  72745. };
  72746. var filters = {
  72747. // legacy index-based enums for glTF
  72748. 0: "",
  72749. 1: "meshopt_decodeFilterOct",
  72750. 2: "meshopt_decodeFilterQuat",
  72751. 3: "meshopt_decodeFilterExp",
  72752. // string-based enums for glTF
  72753. NONE: "",
  72754. OCTAHEDRAL: "meshopt_decodeFilterOct",
  72755. QUATERNION: "meshopt_decodeFilterQuat",
  72756. EXPONENTIAL: "meshopt_decodeFilterExp",
  72757. };
  72758. var decoders = {
  72759. // legacy index-based enums for glTF
  72760. 0: "meshopt_decodeVertexBuffer",
  72761. 1: "meshopt_decodeIndexBuffer",
  72762. 2: "meshopt_decodeIndexSequence",
  72763. // string-based enums for glTF
  72764. ATTRIBUTES: "meshopt_decodeVertexBuffer",
  72765. TRIANGLES: "meshopt_decodeIndexBuffer",
  72766. INDICES: "meshopt_decodeIndexSequence",
  72767. };
  72768. return {
  72769. ready: promise,
  72770. supported: true,
  72771. decodeVertexBuffer: function(target, count, size, source, filter) {
  72772. decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
  72773. },
  72774. decodeIndexBuffer: function(target, count, size, source) {
  72775. decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
  72776. },
  72777. decodeIndexSequence: function(target, count, size, source) {
  72778. decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
  72779. },
  72780. decodeGltfBuffer: function(target, count, size, source, mode, filter) {
  72781. decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
  72782. }
  72783. };
  72784. })();
  72785. var DDSLoader = function ( manager ) {
  72786. CompressedTextureLoader.call( this, manager );
  72787. };
  72788. DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prototype ), {
  72789. constructor: DDSLoader,
  72790. parse: function ( buffer, loadMipmaps ) {
  72791. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  72792. // Adapted from @toji's DDS utils
  72793. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  72794. // All values and structures referenced from:
  72795. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72796. var DDS_MAGIC = 0x20534444;
  72797. // var DDSD_CAPS = 0x1;
  72798. // var DDSD_HEIGHT = 0x2;
  72799. // var DDSD_WIDTH = 0x4;
  72800. // var DDSD_PITCH = 0x8;
  72801. // var DDSD_PIXELFORMAT = 0x1000;
  72802. var DDSD_MIPMAPCOUNT = 0x20000;
  72803. // var DDSD_LINEARSIZE = 0x80000;
  72804. // var DDSD_DEPTH = 0x800000;
  72805. // var DDSCAPS_COMPLEX = 0x8;
  72806. // var DDSCAPS_MIPMAP = 0x400000;
  72807. // var DDSCAPS_TEXTURE = 0x1000;
  72808. var DDSCAPS2_CUBEMAP = 0x200;
  72809. var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400;
  72810. var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800;
  72811. var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000;
  72812. var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000;
  72813. var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000;
  72814. var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000;
  72815. // var DDSCAPS2_VOLUME = 0x200000;
  72816. // var DDPF_ALPHAPIXELS = 0x1;
  72817. // var DDPF_ALPHA = 0x2;
  72818. var DDPF_FOURCC = 0x4;
  72819. // var DDPF_RGB = 0x40;
  72820. // var DDPF_YUV = 0x200;
  72821. // var DDPF_LUMINANCE = 0x20000;
  72822. function fourCCToInt32( value ) {
  72823. return value.charCodeAt( 0 ) +
  72824. ( value.charCodeAt( 1 ) << 8 ) +
  72825. ( value.charCodeAt( 2 ) << 16 ) +
  72826. ( value.charCodeAt( 3 ) << 24 );
  72827. }
  72828. function int32ToFourCC( value ) {
  72829. return String.fromCharCode(
  72830. value & 0xff,
  72831. ( value >> 8 ) & 0xff,
  72832. ( value >> 16 ) & 0xff,
  72833. ( value >> 24 ) & 0xff
  72834. );
  72835. }
  72836. function loadARGBMip( buffer, dataOffset, width, height ) {
  72837. var dataLength = width * height * 4;
  72838. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  72839. var byteArray = new Uint8Array( dataLength );
  72840. var dst = 0;
  72841. var src = 0;
  72842. for ( var y = 0; y < height; y ++ ) {
  72843. for ( var x = 0; x < width; x ++ ) {
  72844. var b = srcBuffer[ src ]; src ++;
  72845. var g = srcBuffer[ src ]; src ++;
  72846. var r = srcBuffer[ src ]; src ++;
  72847. var a = srcBuffer[ src ]; src ++;
  72848. byteArray[ dst ] = r; dst ++; //r
  72849. byteArray[ dst ] = g; dst ++; //g
  72850. byteArray[ dst ] = b; dst ++; //b
  72851. byteArray[ dst ] = a; dst ++; //a
  72852. }
  72853. }
  72854. return byteArray;
  72855. }
  72856. var FOURCC_DXT1 = fourCCToInt32( 'DXT1' );
  72857. var FOURCC_DXT3 = fourCCToInt32( 'DXT3' );
  72858. var FOURCC_DXT5 = fourCCToInt32( 'DXT5' );
  72859. var FOURCC_ETC1 = fourCCToInt32( 'ETC1' );
  72860. var headerLengthInt = 31; // The header length in 32 bit ints
  72861. // Offsets into the header array
  72862. var off_magic = 0;
  72863. var off_size = 1;
  72864. var off_flags = 2;
  72865. var off_height = 3;
  72866. var off_width = 4;
  72867. var off_mipmapCount = 7;
  72868. var off_pfFlags = 20;
  72869. var off_pfFourCC = 21;
  72870. var off_RGBBitCount = 22;
  72871. var off_RBitMask = 23;
  72872. var off_GBitMask = 24;
  72873. var off_BBitMask = 25;
  72874. var off_ABitMask = 26;
  72875. // var off_caps = 27;
  72876. var off_caps2 = 28;
  72877. // var off_caps3 = 29;
  72878. // var off_caps4 = 30;
  72879. // Parse header
  72880. var header = new Int32Array( buffer, 0, headerLengthInt );
  72881. if ( header[ off_magic ] !== DDS_MAGIC ) {
  72882. console.error( 'THREE.DDSLoader.parse: Invalid magic number in DDS header.' );
  72883. return dds;
  72884. }
  72885. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  72886. console.error( 'THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code.' );
  72887. return dds;
  72888. }
  72889. var blockBytes;
  72890. var fourCC = header[ off_pfFourCC ];
  72891. var isRGBAUncompressed = false;
  72892. switch ( fourCC ) {
  72893. case FOURCC_DXT1:
  72894. blockBytes = 8;
  72895. dds.format = RGB_S3TC_DXT1_Format;
  72896. break;
  72897. case FOURCC_DXT3:
  72898. blockBytes = 16;
  72899. dds.format = RGBA_S3TC_DXT3_Format;
  72900. break;
  72901. case FOURCC_DXT5:
  72902. blockBytes = 16;
  72903. dds.format = RGBA_S3TC_DXT5_Format$1;
  72904. break;
  72905. case FOURCC_ETC1:
  72906. blockBytes = 8;
  72907. dds.format = RGB_ETC1_Format;
  72908. break;
  72909. default:
  72910. if ( header[ off_RGBBitCount ] === 32
  72911. && header[ off_RBitMask ] & 0xff0000
  72912. && header[ off_GBitMask ] & 0xff00
  72913. && header[ off_BBitMask ] & 0xff
  72914. && header[ off_ABitMask ] & 0xff000000 ) {
  72915. isRGBAUncompressed = true;
  72916. blockBytes = 64;
  72917. dds.format = RGBAFormat;
  72918. } else {
  72919. console.error( 'THREE.DDSLoader.parse: Unsupported FourCC code ', int32ToFourCC( fourCC ) );
  72920. return dds;
  72921. }
  72922. }
  72923. dds.mipmapCount = 1;
  72924. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  72925. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  72926. }
  72927. var caps2 = header[ off_caps2 ];
  72928. dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false;
  72929. if ( dds.isCubemap && (
  72930. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEX ) ||
  72931. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX ) ||
  72932. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEY ) ||
  72933. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY ) ||
  72934. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ ) ||
  72935. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ )
  72936. ) ) {
  72937. console.error( 'THREE.DDSLoader.parse: Incomplete cubemap faces' );
  72938. return dds;
  72939. }
  72940. dds.width = header[ off_width ];
  72941. dds.height = header[ off_height ];
  72942. var dataOffset = header[ off_size ] + 4;
  72943. // Extract mipmaps buffers
  72944. var faces = dds.isCubemap ? 6 : 1;
  72945. for ( var face = 0; face < faces; face ++ ) {
  72946. var width = dds.width;
  72947. var height = dds.height;
  72948. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  72949. if ( isRGBAUncompressed ) {
  72950. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  72951. var dataLength = byteArray.length;
  72952. } else {
  72953. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  72954. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  72955. }
  72956. var mipmap = { 'data': byteArray, 'width': width, 'height': height };
  72957. dds.mipmaps.push( mipmap );
  72958. dataOffset += dataLength;
  72959. width = Math.max( width >> 1, 1 );
  72960. height = Math.max( height >> 1, 1 );
  72961. }
  72962. }
  72963. return dds;
  72964. }
  72965. } );
  72966. var GLTFLoader = ( function () {
  72967. function GLTFLoader( manager, renderer, urlPrefix) {
  72968. Loader.call( this, manager );
  72969. /* this.dracoLoader = null;
  72970. this.ddsLoader = null;
  72971. this.ktx2Loader = null;
  72972. this.meshoptDecoder = null; */
  72973. //xzw add:
  72974. this.dracoLoader = new DRACOLoader;
  72975. this.ktx2Loader = new KTX2Loader;
  72976. this.meshoptDecoder = MeshoptDecoder;
  72977. this.ddsLoader = new DDSLoader; //这个没测过
  72978. //路径相对于index.html
  72979. this.dracoLoader.setDecoderPath( urlPrefix + 'three.js/loaders/draco/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/draco/gltf/' 版本可升级 */); //这两个路径可以自己改。在laser的环境也要放一份这个路径
  72980. this.ktx2Loader.setTranscoderPath(urlPrefix + 'three.js/loaders/ktx/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/basis/' 版本可升级 */).detectSupport( renderer );
  72981. //------------
  72982. this.pluginCallbacks = [];
  72983. this.register( function ( parser ) {
  72984. return new GLTFMaterialsClearcoatExtension( parser );
  72985. } );
  72986. this.register( function ( parser ) {
  72987. return new GLTFTextureBasisUExtension( parser );
  72988. } );
  72989. this.register( function ( parser ) {
  72990. return new GLTFTextureWebPExtension( parser );
  72991. } );
  72992. this.register( function ( parser ) {
  72993. return new GLTFMaterialsTransmissionExtension( parser );
  72994. } );
  72995. this.register( function ( parser ) {
  72996. return new GLTFLightsExtension( parser );
  72997. } );
  72998. this.register( function ( parser ) {
  72999. return new GLTFMeshoptCompression( parser );
  73000. } );
  73001. }
  73002. GLTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  73003. constructor: GLTFLoader,
  73004. load: function ( url, onLoad, onProgress, onError ) {
  73005. var scope = this;
  73006. var resourcePath;
  73007. if ( this.resourcePath !== '' ) {
  73008. resourcePath = this.resourcePath;
  73009. } else if ( this.path !== '' ) {
  73010. resourcePath = this.path;
  73011. } else {
  73012. resourcePath = LoaderUtils.extractUrlBase( url );
  73013. }
  73014. // Tells the LoadingManager to track an extra item, which resolves after
  73015. // the model is fully loaded. This means the count of items loaded will
  73016. // be incorrect, but ensures manager.onLoad() does not fire early.
  73017. this.manager.itemStart( url );
  73018. var _onError = function ( e ) {
  73019. if ( onError ) {
  73020. onError( e );
  73021. } else {
  73022. console.error( e );
  73023. }
  73024. scope.manager.itemError( url );
  73025. scope.manager.itemEnd( url );
  73026. };
  73027. var loader = new FileLoader( this.manager );
  73028. loader.setPath( this.path );
  73029. loader.setResponseType( 'arraybuffer' );
  73030. loader.setRequestHeader( this.requestHeader );
  73031. loader.setWithCredentials( this.withCredentials );
  73032. loader.load( url, function ( data, total ) {// xzw add total
  73033. console.log('数据加载成功', url.split('/').pop(), ' ,total: '+total);
  73034. let f = ()=>{
  73035. try {
  73036. scope.parse( data, resourcePath, function ( gltf ) {
  73037. onLoad( gltf, total );
  73038. scope.manager.itemEnd( url );
  73039. }, _onError );
  73040. } catch ( e ) {
  73041. _onError( e );
  73042. }
  73043. };
  73044. f();
  73045. //setTimeout(f,5000)/////////////////test
  73046. }, onProgress, _onError );
  73047. },
  73048. setDRACOLoader: function ( dracoLoader ) {
  73049. this.dracoLoader = dracoLoader;
  73050. return this;
  73051. },
  73052. setDDSLoader: function ( ddsLoader ) {
  73053. this.ddsLoader = ddsLoader;
  73054. return this;
  73055. },
  73056. setKTX2Loader: function ( ktx2Loader ) {
  73057. this.ktx2Loader = ktx2Loader;
  73058. return this;
  73059. },
  73060. setMeshoptDecoder: function ( meshoptDecoder ) {
  73061. this.meshoptDecoder = meshoptDecoder;
  73062. return this;
  73063. },
  73064. register: function ( callback ) {
  73065. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  73066. this.pluginCallbacks.push( callback );
  73067. }
  73068. return this;
  73069. },
  73070. unregister: function ( callback ) {
  73071. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  73072. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  73073. }
  73074. return this;
  73075. },
  73076. parse: function ( data, path, onLoad, onError ) {
  73077. var content;
  73078. var extensions = {};
  73079. var plugins = {};
  73080. if ( typeof data === 'string' ) {
  73081. content = data;
  73082. } else {
  73083. var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  73084. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  73085. try {
  73086. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  73087. } catch ( error ) {
  73088. if ( onError ) onError( error );
  73089. return;
  73090. }
  73091. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  73092. } else {
  73093. content = LoaderUtils.decodeText( new Uint8Array( data ) );
  73094. }
  73095. }
  73096. var json = JSON.parse( content );
  73097. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  73098. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  73099. return;
  73100. }
  73101. var parser = new GLTFParser( json, {
  73102. path: path || this.resourcePath || '',
  73103. crossOrigin: this.crossOrigin,
  73104. manager: this.manager,
  73105. ktx2Loader: this.ktx2Loader,
  73106. meshoptDecoder: this.meshoptDecoder,
  73107. } );
  73108. parser.unlitMat = this.unlitMat;//add
  73109. parser.fileLoader.setRequestHeader( this.requestHeader );
  73110. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  73111. var plugin = this.pluginCallbacks[ i ]( parser );
  73112. plugins[ plugin.name ] = plugin;
  73113. // Workaround to avoid determining as unknown extension
  73114. // in addUnknownExtensionsToUserData().
  73115. // Remove this workaround if we move all the existing
  73116. // extension handlers to plugin system
  73117. extensions[ plugin.name ] = true;
  73118. }
  73119. if ( json.extensionsUsed ) {
  73120. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  73121. var extensionName = json.extensionsUsed[ i ];
  73122. var extensionsRequired = json.extensionsRequired || [];
  73123. switch ( extensionName ) {
  73124. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  73125. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  73126. break;
  73127. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  73128. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  73129. break;
  73130. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  73131. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  73132. break;
  73133. case EXTENSIONS.MSFT_TEXTURE_DDS:
  73134. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  73135. break;
  73136. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  73137. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  73138. break;
  73139. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  73140. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  73141. break;
  73142. default:
  73143. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  73144. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  73145. }
  73146. }
  73147. }
  73148. }
  73149. parser.setExtensions( extensions );
  73150. parser.setPlugins( plugins );
  73151. parser.parse( onLoad, onError );
  73152. }
  73153. } );
  73154. /* GLTFREGISTRY */
  73155. function GLTFRegistry() {
  73156. var objects = {};
  73157. return {
  73158. get: function ( key ) {
  73159. return objects[ key ];
  73160. },
  73161. add: function ( key, object ) {
  73162. objects[ key ] = object;
  73163. },
  73164. remove: function ( key ) {
  73165. delete objects[ key ];
  73166. },
  73167. removeAll: function () {
  73168. objects = {};
  73169. }
  73170. };
  73171. }
  73172. /*********************************/
  73173. /********** EXTENSIONS ***********/
  73174. /*********************************/
  73175. var EXTENSIONS = {
  73176. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  73177. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  73178. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  73179. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  73180. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  73181. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  73182. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  73183. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  73184. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  73185. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  73186. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  73187. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  73188. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  73189. };
  73190. /**
  73191. * DDS Texture Extension
  73192. *
  73193. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  73194. *
  73195. */
  73196. function GLTFTextureDDSExtension( ddsLoader ) {
  73197. if ( ! ddsLoader ) {
  73198. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader' );
  73199. }
  73200. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  73201. this.ddsLoader = ddsLoader;
  73202. }
  73203. /**
  73204. * Punctual Lights Extension
  73205. *
  73206. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  73207. */
  73208. function GLTFLightsExtension( parser ) {
  73209. this.parser = parser;
  73210. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  73211. // Object3D instance caches
  73212. this.cache = { refs: {}, uses: {} };
  73213. }
  73214. GLTFLightsExtension.prototype._markDefs = function () {
  73215. var parser = this.parser;
  73216. var nodeDefs = this.parser.json.nodes || [];
  73217. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  73218. var nodeDef = nodeDefs[ nodeIndex ];
  73219. if ( nodeDef.extensions
  73220. && nodeDef.extensions[ this.name ]
  73221. && nodeDef.extensions[ this.name ].light !== undefined ) {
  73222. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  73223. }
  73224. }
  73225. };
  73226. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  73227. var parser = this.parser;
  73228. var cacheKey = 'light:' + lightIndex;
  73229. var dependency = parser.cache.get( cacheKey );
  73230. if ( dependency ) return dependency;
  73231. var json = parser.json;
  73232. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  73233. var lightDefs = extensions.lights || [];
  73234. var lightDef = lightDefs[ lightIndex ];
  73235. var lightNode;
  73236. var color = new Color( 0xffffff );
  73237. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  73238. var range = lightDef.range !== undefined ? lightDef.range : 0;
  73239. switch ( lightDef.type ) {
  73240. case 'directional':
  73241. lightNode = new DirectionalLight( color );
  73242. lightNode.target.position.set( 0, 0, - 1 );
  73243. lightNode.add( lightNode.target );
  73244. break;
  73245. case 'point':
  73246. lightNode = new PointLight( color );
  73247. lightNode.distance = range;
  73248. break;
  73249. case 'spot':
  73250. lightNode = new SpotLight( color );
  73251. lightNode.distance = range;
  73252. // Handle spotlight properties.
  73253. lightDef.spot = lightDef.spot || {};
  73254. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  73255. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  73256. lightNode.angle = lightDef.spot.outerConeAngle;
  73257. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  73258. lightNode.target.position.set( 0, 0, - 1 );
  73259. lightNode.add( lightNode.target );
  73260. break;
  73261. default:
  73262. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  73263. }
  73264. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  73265. // here, because node-level parsing will only override position if explicitly specified.
  73266. lightNode.position.set( 0, 0, 0 );
  73267. lightNode.decay = 2;
  73268. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  73269. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  73270. dependency = Promise.resolve( lightNode );
  73271. parser.cache.add( cacheKey, dependency );
  73272. return dependency;
  73273. };
  73274. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  73275. var self = this;
  73276. var parser = this.parser;
  73277. var json = parser.json;
  73278. var nodeDef = json.nodes[ nodeIndex ];
  73279. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  73280. var lightIndex = lightDef.light;
  73281. if ( lightIndex === undefined ) return null;
  73282. return this._loadLight( lightIndex ).then( function ( light ) {
  73283. return parser._getNodeRef( self.cache, lightIndex, light );
  73284. } );
  73285. };
  73286. /**
  73287. * Unlit Materials Extension
  73288. *
  73289. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  73290. */
  73291. function GLTFMaterialsUnlitExtension() {
  73292. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  73293. }
  73294. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  73295. return MeshBasicMaterial;
  73296. };
  73297. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  73298. var pending = [];
  73299. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  73300. materialParams.opacity = 1.0;
  73301. var metallicRoughness = materialDef.pbrMetallicRoughness;
  73302. if ( metallicRoughness ) {
  73303. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  73304. var array = metallicRoughness.baseColorFactor;
  73305. materialParams.color.fromArray( array );
  73306. materialParams.opacity = array[ 3 ];
  73307. }
  73308. if ( metallicRoughness.baseColorTexture !== undefined ) {
  73309. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  73310. }
  73311. }
  73312. return Promise.all( pending );
  73313. };
  73314. /**
  73315. * Clearcoat Materials Extension
  73316. *
  73317. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  73318. */
  73319. function GLTFMaterialsClearcoatExtension( parser ) {
  73320. this.parser = parser;
  73321. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  73322. }
  73323. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  73324. var parser = this.parser;
  73325. var materialDef = parser.json.materials[ materialIndex ];
  73326. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  73327. return MeshPhysicalMaterial;
  73328. };
  73329. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  73330. var parser = this.parser;
  73331. var materialDef = parser.json.materials[ materialIndex ];
  73332. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  73333. return Promise.resolve();
  73334. }
  73335. var pending = [];
  73336. var extension = materialDef.extensions[ this.name ];
  73337. if ( extension.clearcoatFactor !== undefined ) {
  73338. materialParams.clearcoat = extension.clearcoatFactor;
  73339. }
  73340. if ( extension.clearcoatTexture !== undefined ) {
  73341. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  73342. }
  73343. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  73344. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  73345. }
  73346. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  73347. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  73348. }
  73349. if ( extension.clearcoatNormalTexture !== undefined ) {
  73350. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  73351. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  73352. var scale = extension.clearcoatNormalTexture.scale;
  73353. materialParams.clearcoatNormalScale = new Vector2$1( scale, scale );
  73354. }
  73355. }
  73356. return Promise.all( pending );
  73357. };
  73358. /**
  73359. * Transmission Materials Extension
  73360. *
  73361. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  73362. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  73363. */
  73364. function GLTFMaterialsTransmissionExtension( parser ) {
  73365. this.parser = parser;
  73366. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  73367. }
  73368. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  73369. var parser = this.parser;
  73370. var materialDef = parser.json.materials[ materialIndex ];
  73371. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  73372. return MeshPhysicalMaterial;
  73373. };
  73374. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  73375. var parser = this.parser;
  73376. var materialDef = parser.json.materials[ materialIndex ];
  73377. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  73378. return Promise.resolve();
  73379. }
  73380. var pending = [];
  73381. var extension = materialDef.extensions[ this.name ];
  73382. if ( extension.transmissionFactor !== undefined ) {
  73383. materialParams.transmission = extension.transmissionFactor;
  73384. }
  73385. if ( extension.transmissionTexture !== undefined ) {
  73386. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  73387. }
  73388. return Promise.all( pending );
  73389. };
  73390. /**
  73391. * BasisU Texture Extension
  73392. *
  73393. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  73394. */
  73395. function GLTFTextureBasisUExtension( parser ) {
  73396. this.parser = parser;
  73397. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  73398. }
  73399. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  73400. var parser = this.parser;
  73401. var json = parser.json;
  73402. var textureDef = json.textures[ textureIndex ];
  73403. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  73404. return null;
  73405. }
  73406. var extension = textureDef.extensions[ this.name ];
  73407. var source = json.images[ extension.source ];
  73408. var loader = parser.options.ktx2Loader;
  73409. if ( ! loader ) {
  73410. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  73411. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  73412. } else {
  73413. // Assumes that the extension is optional and that a fallback texture is present
  73414. return null;
  73415. }
  73416. }
  73417. return parser.loadTextureImage( textureIndex, source, loader );
  73418. };
  73419. /**
  73420. * WebP Texture Extension
  73421. *
  73422. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  73423. */
  73424. function GLTFTextureWebPExtension( parser ) {
  73425. this.parser = parser;
  73426. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  73427. this.isSupported = null;
  73428. }
  73429. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  73430. var name = this.name;
  73431. var parser = this.parser;
  73432. var json = parser.json;
  73433. var textureDef = json.textures[ textureIndex ];
  73434. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  73435. return null;
  73436. }
  73437. var extension = textureDef.extensions[ name ];
  73438. var source = json.images[ extension.source ];
  73439. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  73440. return this.detectSupport().then( function ( isSupported ) {
  73441. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  73442. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  73443. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  73444. }
  73445. // Fall back to PNG or JPEG.
  73446. return parser.loadTexture( textureIndex );
  73447. } );
  73448. };
  73449. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  73450. if ( ! this.isSupported ) {
  73451. this.isSupported = new Promise( function ( resolve ) {
  73452. var image = new Image();
  73453. // Lossy test image. Support for lossy images doesn't guarantee support for all
  73454. // WebP images, unfortunately.
  73455. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  73456. image.onload = image.onerror = function () {
  73457. resolve( image.height === 1 );
  73458. };
  73459. } );
  73460. }
  73461. return this.isSupported;
  73462. };
  73463. /**
  73464. * meshopt BufferView Compression Extension
  73465. *
  73466. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  73467. */
  73468. function GLTFMeshoptCompression( parser ) {
  73469. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  73470. this.parser = parser;
  73471. }
  73472. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  73473. var json = this.parser.json;
  73474. var bufferView = json.bufferViews[ index ];
  73475. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  73476. var extensionDef = bufferView.extensions[ this.name ];
  73477. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  73478. var decoder = this.parser.options.meshoptDecoder;
  73479. if ( ! decoder || ! decoder.supported ) {
  73480. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  73481. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  73482. } else {
  73483. // Assumes that the extension is optional and that fallback buffer data is present
  73484. return null;
  73485. }
  73486. }
  73487. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  73488. var byteOffset = extensionDef.byteOffset || 0;
  73489. var byteLength = extensionDef.byteLength || 0;
  73490. var count = extensionDef.count;
  73491. var stride = extensionDef.byteStride;
  73492. var result = new ArrayBuffer( count * stride );
  73493. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  73494. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  73495. return result;
  73496. } );
  73497. } else {
  73498. return null;
  73499. }
  73500. };
  73501. /* BINARY EXTENSION */
  73502. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  73503. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  73504. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  73505. function GLTFBinaryExtension( data ) {
  73506. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  73507. this.content = null;
  73508. this.body = null;
  73509. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  73510. this.header = {
  73511. magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  73512. version: headerView.getUint32( 4, true ),
  73513. length: headerView.getUint32( 8, true )
  73514. };
  73515. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  73516. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  73517. } else if ( this.header.version < 2.0 ) {
  73518. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  73519. }
  73520. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  73521. var chunkIndex = 0;
  73522. while ( chunkIndex < chunkView.byteLength ) {
  73523. var chunkLength = chunkView.getUint32( chunkIndex, true );
  73524. chunkIndex += 4;
  73525. var chunkType = chunkView.getUint32( chunkIndex, true );
  73526. chunkIndex += 4;
  73527. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  73528. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  73529. this.content = LoaderUtils.decodeText( contentArray );
  73530. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  73531. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  73532. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  73533. }
  73534. // Clients must ignore chunks with unknown types.
  73535. chunkIndex += chunkLength;
  73536. }
  73537. if ( this.content === null ) {
  73538. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  73539. }
  73540. }
  73541. /**
  73542. * DRACO Mesh Compression Extension
  73543. *
  73544. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  73545. */
  73546. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  73547. if ( ! dracoLoader ) {
  73548. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  73549. }
  73550. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  73551. this.json = json;
  73552. this.dracoLoader = dracoLoader;
  73553. this.dracoLoader.preload();
  73554. }
  73555. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  73556. var json = this.json;
  73557. var dracoLoader = this.dracoLoader;
  73558. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  73559. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  73560. var threeAttributeMap = {};
  73561. var attributeNormalizedMap = {};
  73562. var attributeTypeMap = {};
  73563. for ( var attributeName in gltfAttributeMap ) {
  73564. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  73565. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  73566. }
  73567. for ( attributeName in primitive.attributes ) {
  73568. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  73569. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  73570. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  73571. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  73572. attributeTypeMap[ threeAttributeName ] = componentType;
  73573. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  73574. }
  73575. }
  73576. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  73577. return new Promise( function ( resolve ) {
  73578. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  73579. for ( var attributeName in geometry.attributes ) {
  73580. var attribute = geometry.attributes[ attributeName ];
  73581. var normalized = attributeNormalizedMap[ attributeName ];
  73582. if ( normalized !== undefined ) attribute.normalized = normalized;
  73583. }
  73584. resolve( geometry );
  73585. }, threeAttributeMap, attributeTypeMap );
  73586. } );
  73587. } );
  73588. };
  73589. /**
  73590. * Texture Transform Extension
  73591. *
  73592. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  73593. */
  73594. function GLTFTextureTransformExtension() {
  73595. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  73596. }
  73597. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  73598. texture = texture.clone();
  73599. if ( transform.offset !== undefined ) {
  73600. texture.offset.fromArray( transform.offset );
  73601. }
  73602. if ( transform.rotation !== undefined ) {
  73603. texture.rotation = transform.rotation;
  73604. }
  73605. if ( transform.scale !== undefined ) {
  73606. texture.repeat.fromArray( transform.scale );
  73607. }
  73608. if ( transform.texCoord !== undefined ) {
  73609. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  73610. }
  73611. texture.needsUpdate = true;
  73612. return texture;
  73613. };
  73614. /**
  73615. * Specular-Glossiness Extension
  73616. *
  73617. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  73618. */
  73619. /**
  73620. * A sub class of StandardMaterial with some of the functionality
  73621. * changed via the `onBeforeCompile` callback
  73622. * @pailhead
  73623. */
  73624. function GLTFMeshStandardSGMaterial( params ) {
  73625. MeshStandardMaterial.call( this );
  73626. this.isGLTFSpecularGlossinessMaterial = true;
  73627. //various chunks that need replacing
  73628. var specularMapParsFragmentChunk = [
  73629. '#ifdef USE_SPECULARMAP',
  73630. ' uniform sampler2D specularMap;',
  73631. '#endif'
  73632. ].join( '\n' );
  73633. var glossinessMapParsFragmentChunk = [
  73634. '#ifdef USE_GLOSSINESSMAP',
  73635. ' uniform sampler2D glossinessMap;',
  73636. '#endif'
  73637. ].join( '\n' );
  73638. var specularMapFragmentChunk = [
  73639. 'vec3 specularFactor = specular;',
  73640. '#ifdef USE_SPECULARMAP',
  73641. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  73642. ' texelSpecular = sRGBToLinear( texelSpecular );',
  73643. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  73644. ' specularFactor *= texelSpecular.rgb;',
  73645. '#endif'
  73646. ].join( '\n' );
  73647. var glossinessMapFragmentChunk = [
  73648. 'float glossinessFactor = glossiness;',
  73649. '#ifdef USE_GLOSSINESSMAP',
  73650. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  73651. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  73652. ' glossinessFactor *= texelGlossiness.a;',
  73653. '#endif'
  73654. ].join( '\n' );
  73655. var lightPhysicalFragmentChunk = [
  73656. 'PhysicalMaterial material;',
  73657. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  73658. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  73659. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  73660. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  73661. 'material.specularRoughness += geometryRoughness;',
  73662. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  73663. 'material.specularColor = specularFactor;',
  73664. ].join( '\n' );
  73665. var uniforms = {
  73666. specular: { value: new Color().setHex( 0xffffff ) },
  73667. glossiness: { value: 1 },
  73668. specularMap: { value: null },
  73669. glossinessMap: { value: null }
  73670. };
  73671. this._extraUniforms = uniforms;
  73672. this.onBeforeCompile = function ( shader ) {
  73673. for ( var uniformName in uniforms ) {
  73674. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  73675. }
  73676. shader.fragmentShader = shader.fragmentShader
  73677. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  73678. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  73679. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  73680. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  73681. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  73682. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  73683. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  73684. };
  73685. Object.defineProperties( this, {
  73686. specular: {
  73687. get: function () {
  73688. return uniforms.specular.value;
  73689. },
  73690. set: function ( v ) {
  73691. uniforms.specular.value = v;
  73692. }
  73693. },
  73694. specularMap: {
  73695. get: function () {
  73696. return uniforms.specularMap.value;
  73697. },
  73698. set: function ( v ) {
  73699. uniforms.specularMap.value = v;
  73700. if ( v ) {
  73701. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  73702. } else {
  73703. delete this.defines.USE_SPECULARMAP;
  73704. }
  73705. }
  73706. },
  73707. glossiness: {
  73708. get: function () {
  73709. return uniforms.glossiness.value;
  73710. },
  73711. set: function ( v ) {
  73712. uniforms.glossiness.value = v;
  73713. }
  73714. },
  73715. glossinessMap: {
  73716. get: function () {
  73717. return uniforms.glossinessMap.value;
  73718. },
  73719. set: function ( v ) {
  73720. uniforms.glossinessMap.value = v;
  73721. if ( v ) {
  73722. this.defines.USE_GLOSSINESSMAP = '';
  73723. this.defines.USE_UV = '';
  73724. } else {
  73725. delete this.defines.USE_GLOSSINESSMAP;
  73726. delete this.defines.USE_UV;
  73727. }
  73728. }
  73729. }
  73730. } );
  73731. delete this.metalness;
  73732. delete this.roughness;
  73733. delete this.metalnessMap;
  73734. delete this.roughnessMap;
  73735. this.setValues( params );
  73736. }
  73737. GLTFMeshStandardSGMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  73738. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  73739. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  73740. MeshStandardMaterial.prototype.copy.call( this, source );
  73741. this.specularMap = source.specularMap;
  73742. this.specular.copy( source.specular );
  73743. this.glossinessMap = source.glossinessMap;
  73744. this.glossiness = source.glossiness;
  73745. delete this.metalness;
  73746. delete this.roughness;
  73747. delete this.metalnessMap;
  73748. delete this.roughnessMap;
  73749. return this;
  73750. };
  73751. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  73752. return {
  73753. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  73754. specularGlossinessParams: [
  73755. 'color',
  73756. 'map',
  73757. 'lightMap',
  73758. 'lightMapIntensity',
  73759. 'aoMap',
  73760. 'aoMapIntensity',
  73761. 'emissive',
  73762. 'emissiveIntensity',
  73763. 'emissiveMap',
  73764. 'bumpMap',
  73765. 'bumpScale',
  73766. 'normalMap',
  73767. 'normalMapType',
  73768. 'displacementMap',
  73769. 'displacementScale',
  73770. 'displacementBias',
  73771. 'specularMap',
  73772. 'specular',
  73773. 'glossinessMap',
  73774. 'glossiness',
  73775. 'alphaMap',
  73776. 'envMap',
  73777. 'envMapIntensity',
  73778. 'refractionRatio',
  73779. ],
  73780. getMaterialType: function () {
  73781. return GLTFMeshStandardSGMaterial;
  73782. },
  73783. extendParams: function ( materialParams, materialDef, parser ) {
  73784. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  73785. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  73786. materialParams.opacity = 1.0;
  73787. var pending = [];
  73788. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  73789. var array = pbrSpecularGlossiness.diffuseFactor;
  73790. materialParams.color.fromArray( array );
  73791. materialParams.opacity = array[ 3 ];
  73792. }
  73793. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  73794. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  73795. }
  73796. materialParams.emissive = new Color( 0.0, 0.0, 0.0 );
  73797. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  73798. materialParams.specular = new Color( 1.0, 1.0, 1.0 );
  73799. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  73800. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  73801. }
  73802. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  73803. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  73804. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  73805. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  73806. }
  73807. return Promise.all( pending );
  73808. },
  73809. createMaterial: function ( materialParams ) {
  73810. var material = new GLTFMeshStandardSGMaterial( materialParams );
  73811. material.fog = true;
  73812. material.color = materialParams.color;
  73813. material.map = materialParams.map === undefined ? null : materialParams.map;
  73814. material.lightMap = null;
  73815. material.lightMapIntensity = 1.0;
  73816. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  73817. material.aoMapIntensity = 1.0;
  73818. material.emissive = materialParams.emissive;
  73819. material.emissiveIntensity = 1.0;
  73820. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  73821. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  73822. material.bumpScale = 1;
  73823. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  73824. material.normalMapType = TangentSpaceNormalMap;
  73825. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  73826. material.displacementMap = null;
  73827. material.displacementScale = 1;
  73828. material.displacementBias = 0;
  73829. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  73830. material.specular = materialParams.specular;
  73831. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  73832. material.glossiness = materialParams.glossiness;
  73833. material.alphaMap = null;
  73834. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  73835. material.envMapIntensity = 1.0;
  73836. material.refractionRatio = 0.98;
  73837. return material;
  73838. },
  73839. };
  73840. }
  73841. /**
  73842. * Mesh Quantization Extension
  73843. *
  73844. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  73845. */
  73846. function GLTFMeshQuantizationExtension() {
  73847. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  73848. }
  73849. /*********************************/
  73850. /********** INTERPOLATION ********/
  73851. /*********************************/
  73852. // Spline Interpolation
  73853. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  73854. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  73855. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  73856. }
  73857. GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype );
  73858. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  73859. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  73860. // Copies a sample value to the result buffer. See description of glTF
  73861. // CUBICSPLINE values layout in interpolate_() function below.
  73862. var result = this.resultBuffer,
  73863. values = this.sampleValues,
  73864. valueSize = this.valueSize,
  73865. offset = index * valueSize * 3 + valueSize;
  73866. for ( var i = 0; i !== valueSize; i ++ ) {
  73867. result[ i ] = values[ offset + i ];
  73868. }
  73869. return result;
  73870. };
  73871. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  73872. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  73873. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  73874. var result = this.resultBuffer;
  73875. var values = this.sampleValues;
  73876. var stride = this.valueSize;
  73877. var stride2 = stride * 2;
  73878. var stride3 = stride * 3;
  73879. var td = t1 - t0;
  73880. var p = ( t - t0 ) / td;
  73881. var pp = p * p;
  73882. var ppp = pp * p;
  73883. var offset1 = i1 * stride3;
  73884. var offset0 = offset1 - stride3;
  73885. var s2 = - 2 * ppp + 3 * pp;
  73886. var s3 = ppp - pp;
  73887. var s0 = 1 - s2;
  73888. var s1 = s3 - pp + p;
  73889. // Layout of keyframe output values for CUBICSPLINE animations:
  73890. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  73891. for ( var i = 0; i !== stride; i ++ ) {
  73892. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  73893. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  73894. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  73895. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  73896. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  73897. }
  73898. return result;
  73899. };
  73900. /*********************************/
  73901. /********** INTERNALS ************/
  73902. /*********************************/
  73903. /* CONSTANTS */
  73904. var WEBGL_CONSTANTS = {
  73905. FLOAT: 5126,
  73906. //FLOAT_MAT2: 35674,
  73907. FLOAT_MAT3: 35675,
  73908. FLOAT_MAT4: 35676,
  73909. FLOAT_VEC2: 35664,
  73910. FLOAT_VEC3: 35665,
  73911. FLOAT_VEC4: 35666,
  73912. LINEAR: 9729,
  73913. REPEAT: 10497,
  73914. SAMPLER_2D: 35678,
  73915. POINTS: 0,
  73916. LINES: 1,
  73917. LINE_LOOP: 2,
  73918. LINE_STRIP: 3,
  73919. TRIANGLES: 4,
  73920. TRIANGLE_STRIP: 5,
  73921. TRIANGLE_FAN: 6,
  73922. UNSIGNED_BYTE: 5121,
  73923. UNSIGNED_SHORT: 5123
  73924. };
  73925. var WEBGL_COMPONENT_TYPES = {
  73926. 5120: Int8Array,
  73927. 5121: Uint8Array,
  73928. 5122: Int16Array,
  73929. 5123: Uint16Array,
  73930. 5125: Uint32Array,
  73931. 5126: Float32Array
  73932. };
  73933. var WEBGL_FILTERS = {
  73934. 9728: NearestFilter,
  73935. 9729: LinearFilter,
  73936. 9984: NearestMipmapNearestFilter,
  73937. 9985: LinearMipmapNearestFilter,
  73938. 9986: NearestMipmapLinearFilter,
  73939. 9987: LinearMipmapLinearFilter
  73940. };
  73941. var WEBGL_WRAPPINGS = {
  73942. 33071: ClampToEdgeWrapping,
  73943. 33648: MirroredRepeatWrapping,
  73944. 10497: RepeatWrapping
  73945. };
  73946. var WEBGL_TYPE_SIZES = {
  73947. 'SCALAR': 1,
  73948. 'VEC2': 2,
  73949. 'VEC3': 3,
  73950. 'VEC4': 4,
  73951. 'MAT2': 4,
  73952. 'MAT3': 9,
  73953. 'MAT4': 16
  73954. };
  73955. var ATTRIBUTES = {
  73956. POSITION: 'position',
  73957. NORMAL: 'normal',
  73958. TANGENT: 'tangent',
  73959. TEXCOORD_0: 'uv',
  73960. TEXCOORD_1: 'uv2',
  73961. COLOR_0: 'color',
  73962. WEIGHTS_0: 'skinWeight',
  73963. JOINTS_0: 'skinIndex',
  73964. };
  73965. var PATH_PROPERTIES = {
  73966. scale: 'scale',
  73967. translation: 'position',
  73968. rotation: 'quaternion',
  73969. weights: 'morphTargetInfluences'
  73970. };
  73971. var INTERPOLATION = {
  73972. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  73973. // keyframe track will be initialized with a default interpolation type, then modified.
  73974. LINEAR: InterpolateLinear,
  73975. STEP: InterpolateDiscrete
  73976. };
  73977. var ALPHA_MODES = {
  73978. OPAQUE: 'OPAQUE',
  73979. MASK: 'MASK',
  73980. BLEND: 'BLEND'
  73981. };
  73982. /* UTILITY FUNCTIONS */
  73983. function resolveURL( url, path ) {
  73984. // Invalid URL
  73985. if ( typeof url !== 'string' || url === '' ) return '';
  73986. // Host Relative URL
  73987. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  73988. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  73989. }
  73990. // Absolute URL http://,https://,//
  73991. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  73992. // Data URI
  73993. if ( /^data:.*,.*$/i.test( url ) ) return url;
  73994. // Blob URL
  73995. if ( /^blob:.*$/i.test( url ) ) return url;
  73996. // Relative URL
  73997. return path + url;
  73998. }
  73999. /**
  74000. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  74001. */
  74002. function createDefaultMaterial( cache ) {
  74003. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  74004. cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {
  74005. color: 0xFFFFFF,
  74006. emissive: 0x000000,
  74007. metalness: 1,
  74008. roughness: 1,
  74009. transparent: false,
  74010. depthTest: true,
  74011. side: FrontSide
  74012. } );
  74013. }
  74014. return cache[ 'DefaultMaterial' ];
  74015. }
  74016. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  74017. // Add unknown glTF extensions to an object's userData.
  74018. for ( var name in objectDef.extensions ) {
  74019. if ( knownExtensions[ name ] === undefined ) {
  74020. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  74021. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  74022. }
  74023. }
  74024. }
  74025. /**
  74026. * @param {Object3D|Material|BufferGeometry} object
  74027. * @param {GLTF.definition} gltfDef
  74028. */
  74029. function assignExtrasToUserData( object, gltfDef ) {
  74030. if ( gltfDef.extras !== undefined ) {
  74031. if ( typeof gltfDef.extras === 'object' ) {
  74032. Object.assign( object.userData, gltfDef.extras );
  74033. } else {
  74034. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  74035. }
  74036. }
  74037. }
  74038. /**
  74039. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  74040. *
  74041. * @param {BufferGeometry} geometry
  74042. * @param {Array<GLTF.Target>} targets
  74043. * @param {GLTFParser} parser
  74044. * @return {Promise<BufferGeometry>}
  74045. */
  74046. function addMorphTargets( geometry, targets, parser ) {
  74047. var hasMorphPosition = false;
  74048. var hasMorphNormal = false;
  74049. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74050. var target = targets[ i ];
  74051. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  74052. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  74053. if ( hasMorphPosition && hasMorphNormal ) break;
  74054. }
  74055. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  74056. var pendingPositionAccessors = [];
  74057. var pendingNormalAccessors = [];
  74058. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74059. var target = targets[ i ];
  74060. if ( hasMorphPosition ) {
  74061. var pendingAccessor = target.POSITION !== undefined
  74062. ? parser.getDependency( 'accessor', target.POSITION )
  74063. : geometry.attributes.position;
  74064. pendingPositionAccessors.push( pendingAccessor );
  74065. }
  74066. if ( hasMorphNormal ) {
  74067. var pendingAccessor = target.NORMAL !== undefined
  74068. ? parser.getDependency( 'accessor', target.NORMAL )
  74069. : geometry.attributes.normal;
  74070. pendingNormalAccessors.push( pendingAccessor );
  74071. }
  74072. }
  74073. return Promise.all( [
  74074. Promise.all( pendingPositionAccessors ),
  74075. Promise.all( pendingNormalAccessors )
  74076. ] ).then( function ( accessors ) {
  74077. var morphPositions = accessors[ 0 ];
  74078. var morphNormals = accessors[ 1 ];
  74079. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  74080. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  74081. geometry.morphTargetsRelative = true;
  74082. return geometry;
  74083. } );
  74084. }
  74085. /**
  74086. * @param {Mesh} mesh
  74087. * @param {GLTF.Mesh} meshDef
  74088. */
  74089. function updateMorphTargets( mesh, meshDef ) {
  74090. mesh.updateMorphTargets();
  74091. if ( meshDef.weights !== undefined ) {
  74092. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  74093. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  74094. }
  74095. }
  74096. // .extras has user-defined data, so check that .extras.targetNames is an array.
  74097. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  74098. var targetNames = meshDef.extras.targetNames;
  74099. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  74100. mesh.morphTargetDictionary = {};
  74101. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  74102. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  74103. }
  74104. } else {
  74105. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  74106. }
  74107. }
  74108. }
  74109. function createPrimitiveKey( primitiveDef ) {
  74110. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  74111. var geometryKey;
  74112. if ( dracoExtension ) {
  74113. geometryKey = 'draco:' + dracoExtension.bufferView
  74114. + ':' + dracoExtension.indices
  74115. + ':' + createAttributesKey( dracoExtension.attributes );
  74116. } else {
  74117. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  74118. }
  74119. return geometryKey;
  74120. }
  74121. function createAttributesKey( attributes ) {
  74122. var attributesKey = '';
  74123. var keys = Object.keys( attributes ).sort();
  74124. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  74125. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  74126. }
  74127. return attributesKey;
  74128. }
  74129. /* GLTF PARSER */
  74130. function GLTFParser( json, options ) {
  74131. this.json = json || {};
  74132. this.extensions = {};
  74133. this.plugins = {};
  74134. this.options = options || {};
  74135. // loader object cache
  74136. this.cache = new GLTFRegistry();
  74137. // associations between Three.js objects and glTF elements
  74138. this.associations = new Map();
  74139. // BufferGeometry caching
  74140. this.primitiveCache = {};
  74141. // Object3D instance caches
  74142. this.meshCache = { refs: {}, uses: {} };
  74143. this.cameraCache = { refs: {}, uses: {} };
  74144. this.lightCache = { refs: {}, uses: {} };
  74145. // Track node names, to ensure no duplicates
  74146. this.nodeNamesUsed = {};
  74147. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  74148. // expensive work of uploading a texture to the GPU off the main thread.
  74149. /* if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  74150. this.textureLoader = new ImageBitmapLoader( this.options.manager );
  74151. } else { */
  74152. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,改用TextureLoader by xzw
  74153. this.textureLoader = new TextureLoader( this.options.manager );
  74154. //}
  74155. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  74156. this.fileLoader = new FileLoader( this.options.manager );
  74157. this.fileLoader.setResponseType( 'arraybuffer' );
  74158. if ( this.options.crossOrigin === 'use-credentials' ) {
  74159. this.fileLoader.setWithCredentials( true );
  74160. }
  74161. }
  74162. GLTFParser.prototype.setExtensions = function ( extensions ) {
  74163. this.extensions = extensions;
  74164. };
  74165. GLTFParser.prototype.setPlugins = function ( plugins ) {
  74166. this.plugins = plugins;
  74167. };
  74168. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  74169. var parser = this;
  74170. var json = this.json;
  74171. var extensions = this.extensions;
  74172. // Clear the loader cache
  74173. this.cache.removeAll();
  74174. // Mark the special nodes/meshes in json for efficient parse
  74175. this._invokeAll( function ( ext ) {
  74176. return ext._markDefs && ext._markDefs();
  74177. } );
  74178. Promise.all( [
  74179. this.getDependencies( 'scene' ),
  74180. this.getDependencies( 'animation' ),
  74181. this.getDependencies( 'camera' ),
  74182. ] ).then( function ( dependencies ) {
  74183. var result = {
  74184. scene: dependencies[ 0 ][ json.scene || 0 ],
  74185. scenes: dependencies[ 0 ],
  74186. animations: dependencies[ 1 ],
  74187. cameras: dependencies[ 2 ],
  74188. asset: json.asset,
  74189. parser: parser,
  74190. userData: {}
  74191. };
  74192. addUnknownExtensionsToUserData( extensions, result, json );
  74193. assignExtrasToUserData( result, json );
  74194. onLoad( result );
  74195. } ).catch( onError );
  74196. };
  74197. /**
  74198. * Marks the special nodes/meshes in json for efficient parse.
  74199. */
  74200. GLTFParser.prototype._markDefs = function () {
  74201. var nodeDefs = this.json.nodes || [];
  74202. var skinDefs = this.json.skins || [];
  74203. var meshDefs = this.json.meshes || [];
  74204. // Nothing in the node definition indicates whether it is a Bone or an
  74205. // Object3D. Use the skins' joint references to mark bones.
  74206. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  74207. var joints = skinDefs[ skinIndex ].joints;
  74208. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  74209. nodeDefs[ joints[ i ] ].isBone = true;
  74210. }
  74211. }
  74212. // Iterate over all nodes, marking references to shared resources,
  74213. // as well as skeleton joints.
  74214. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  74215. var nodeDef = nodeDefs[ nodeIndex ];
  74216. if ( nodeDef.mesh !== undefined ) {
  74217. this._addNodeRef( this.meshCache, nodeDef.mesh );
  74218. // Nothing in the mesh definition indicates whether it is
  74219. // a SkinnedMesh or Mesh. Use the node's mesh reference
  74220. // to mark SkinnedMesh if node has skin.
  74221. if ( nodeDef.skin !== undefined ) {
  74222. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  74223. }
  74224. }
  74225. if ( nodeDef.camera !== undefined ) {
  74226. this._addNodeRef( this.cameraCache, nodeDef.camera );
  74227. }
  74228. }
  74229. };
  74230. /**
  74231. * Counts references to shared node / Object3D resources. These resources
  74232. * can be reused, or "instantiated", at multiple nodes in the scene
  74233. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  74234. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  74235. * Textures) can be reused directly and are not marked here.
  74236. *
  74237. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  74238. */
  74239. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  74240. if ( index === undefined ) return;
  74241. if ( cache.refs[ index ] === undefined ) {
  74242. cache.refs[ index ] = cache.uses[ index ] = 0;
  74243. }
  74244. cache.refs[ index ] ++;
  74245. };
  74246. /** Returns a reference to a shared resource, cloning it if necessary. */
  74247. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  74248. if ( cache.refs[ index ] <= 1 ) return object;
  74249. var ref = object.clone();
  74250. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  74251. return ref;
  74252. };
  74253. GLTFParser.prototype._invokeOne = function ( func ) {
  74254. var extensions = Object.values( this.plugins );
  74255. extensions.push( this );
  74256. for ( var i = 0; i < extensions.length; i ++ ) {
  74257. var result = func( extensions[ i ] );
  74258. if ( result ) return result;
  74259. }
  74260. };
  74261. GLTFParser.prototype._invokeAll = function ( func ) {
  74262. var extensions = Object.values( this.plugins );
  74263. extensions.unshift( this );
  74264. var pending = [];
  74265. for ( var i = 0; i < extensions.length; i ++ ) {
  74266. var result = func( extensions[ i ] );
  74267. if ( result ) pending.push( result );
  74268. }
  74269. return pending;
  74270. };
  74271. /**
  74272. * Requests the specified dependency asynchronously, with caching.
  74273. * @param {string} type
  74274. * @param {number} index
  74275. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  74276. */
  74277. GLTFParser.prototype.getDependency = function ( type, index ) {
  74278. var cacheKey = type + ':' + index;
  74279. var dependency = this.cache.get( cacheKey );
  74280. if ( ! dependency ) {
  74281. switch ( type ) {
  74282. case 'scene':
  74283. dependency = this.loadScene( index );
  74284. break;
  74285. case 'node':
  74286. dependency = this.loadNode( index );
  74287. break;
  74288. case 'mesh':
  74289. dependency = this._invokeOne( function ( ext ) {
  74290. return ext.loadMesh && ext.loadMesh( index );
  74291. } );
  74292. break;
  74293. case 'accessor':
  74294. dependency = this.loadAccessor( index );
  74295. break;
  74296. case 'bufferView':
  74297. dependency = this._invokeOne( function ( ext ) {
  74298. return ext.loadBufferView && ext.loadBufferView( index );
  74299. } );
  74300. break;
  74301. case 'buffer':
  74302. dependency = this.loadBuffer( index );
  74303. break;
  74304. case 'material':
  74305. dependency = this._invokeOne( function ( ext ) {
  74306. return ext.loadMaterial && ext.loadMaterial( index );
  74307. } );
  74308. break;
  74309. case 'texture':
  74310. dependency = this._invokeOne( function ( ext ) {
  74311. return ext.loadTexture && ext.loadTexture( index );
  74312. } );
  74313. break;
  74314. case 'skin':
  74315. dependency = this.loadSkin( index );
  74316. break;
  74317. case 'animation':
  74318. dependency = this.loadAnimation( index );
  74319. break;
  74320. case 'camera':
  74321. dependency = this.loadCamera( index );
  74322. break;
  74323. default:
  74324. throw new Error( 'Unknown type: ' + type );
  74325. }
  74326. this.cache.add( cacheKey, dependency );
  74327. }
  74328. return dependency;
  74329. };
  74330. /**
  74331. * Requests all dependencies of the specified type asynchronously, with caching.
  74332. * @param {string} type
  74333. * @return {Promise<Array<Object>>}
  74334. */
  74335. GLTFParser.prototype.getDependencies = function ( type ) {
  74336. var dependencies = this.cache.get( type );
  74337. if ( ! dependencies ) {
  74338. var parser = this;
  74339. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  74340. dependencies = Promise.all( defs.map( function ( def, index ) {
  74341. return parser.getDependency( type, index );
  74342. } ) );
  74343. this.cache.add( type, dependencies );
  74344. }
  74345. return dependencies;
  74346. };
  74347. /**
  74348. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  74349. * @param {number} bufferIndex
  74350. * @return {Promise<ArrayBuffer>}
  74351. */
  74352. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  74353. var bufferDef = this.json.buffers[ bufferIndex ];
  74354. var loader = this.fileLoader;
  74355. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  74356. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  74357. }
  74358. // If present, GLB container is required to be the first buffer.
  74359. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  74360. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  74361. }
  74362. var options = this.options;
  74363. return new Promise( function ( resolve, reject ) {
  74364. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  74365. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  74366. } );
  74367. } );
  74368. };
  74369. /**
  74370. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  74371. * @param {number} bufferViewIndex
  74372. * @return {Promise<ArrayBuffer>}
  74373. */
  74374. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  74375. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  74376. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  74377. var byteLength = bufferViewDef.byteLength || 0;
  74378. var byteOffset = bufferViewDef.byteOffset || 0;
  74379. return buffer.slice( byteOffset, byteOffset + byteLength );
  74380. } );
  74381. };
  74382. /**
  74383. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  74384. * @param {number} accessorIndex
  74385. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  74386. */
  74387. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  74388. var parser = this;
  74389. var json = this.json;
  74390. var accessorDef = this.json.accessors[ accessorIndex ];
  74391. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  74392. // Ignore empty accessors, which may be used to declare runtime
  74393. // information about attributes coming from another source (e.g. Draco
  74394. // compression extension).
  74395. return Promise.resolve( null );
  74396. }
  74397. var pendingBufferViews = [];
  74398. if ( accessorDef.bufferView !== undefined ) {
  74399. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  74400. } else {
  74401. pendingBufferViews.push( null );
  74402. }
  74403. if ( accessorDef.sparse !== undefined ) {
  74404. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  74405. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  74406. }
  74407. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  74408. var bufferView = bufferViews[ 0 ];
  74409. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  74410. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  74411. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  74412. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  74413. var itemBytes = elementBytes * itemSize;
  74414. var byteOffset = accessorDef.byteOffset || 0;
  74415. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  74416. var normalized = accessorDef.normalized === true;
  74417. var array, bufferAttribute;
  74418. // The buffer is not interleaved if the stride is the item size in bytes.
  74419. if ( byteStride && byteStride !== itemBytes ) {
  74420. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  74421. // This makes sure that IBA.count reflects accessor.count properly
  74422. var ibSlice = Math.floor( byteOffset / byteStride );
  74423. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  74424. var ib = parser.cache.get( ibCacheKey );
  74425. if ( ! ib ) {
  74426. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  74427. // Integer parameters to IB/IBA are in array elements, not bytes.
  74428. ib = new InterleavedBuffer( array, byteStride / elementBytes );
  74429. parser.cache.add( ibCacheKey, ib );
  74430. }
  74431. bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  74432. } else {
  74433. if ( bufferView === null ) {
  74434. array = new TypedArray( accessorDef.count * itemSize );
  74435. } else {
  74436. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  74437. }
  74438. bufferAttribute = new BufferAttribute( array, itemSize, normalized );
  74439. }
  74440. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  74441. if ( accessorDef.sparse !== undefined ) {
  74442. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  74443. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  74444. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  74445. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  74446. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  74447. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  74448. if ( bufferView !== null ) {
  74449. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  74450. bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  74451. }
  74452. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  74453. var index = sparseIndices[ i ];
  74454. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  74455. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  74456. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  74457. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  74458. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  74459. }
  74460. }
  74461. return bufferAttribute;
  74462. } );
  74463. };
  74464. /**
  74465. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  74466. * @param {number} textureIndex
  74467. * @return {Promise<THREE.Texture>}
  74468. */
  74469. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  74470. var parser = this;
  74471. var json = this.json;
  74472. var options = this.options;
  74473. var textureDef = json.textures[ textureIndex ];
  74474. var textureExtensions = textureDef.extensions || {};
  74475. var source;
  74476. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  74477. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  74478. } else {
  74479. source = json.images[ textureDef.source ];
  74480. }
  74481. var loader;
  74482. if ( source.uri ) {
  74483. loader = options.manager.getHandler( source.uri );
  74484. }
  74485. if ( ! loader ) {
  74486. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  74487. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  74488. : this.textureLoader;
  74489. }
  74490. return this.loadTextureImage( textureIndex, source, loader );
  74491. };
  74492. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  74493. var parser = this;
  74494. var json = this.json;
  74495. var options = this.options;
  74496. var textureDef = json.textures[ textureIndex ];
  74497. var URL = self.URL || self.webkitURL;
  74498. var sourceURI = source.uri;
  74499. var isObjectURL = false;
  74500. var hasAlpha = true;
  74501. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  74502. if ( source.bufferView !== undefined ) {
  74503. // Load binary image data from bufferView, if provided.
  74504. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  74505. if ( source.mimeType === 'image/png' ) {
  74506. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  74507. // alpha channel. This check is conservative — the image could have an alpha
  74508. // channel with all values == 1, and the indexed type (colorType == 3) only
  74509. // sometimes contains alpha.
  74510. //
  74511. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  74512. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  74513. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  74514. }
  74515. isObjectURL = true;
  74516. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  74517. sourceURI = URL.createObjectURL( blob );
  74518. return sourceURI;
  74519. } );
  74520. }
  74521. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  74522. return new Promise( function ( resolve, reject ) {
  74523. /* var onLoad = resolve;
  74524. if ( loader.isImageBitmapLoader === true ) {
  74525. onLoad = function ( imageBitmap ) {
  74526. //console.log('resolveURL onLoad',textureIndex )
  74527. resolve( new CanvasTexture( imageBitmap ) );
  74528. };
  74529. }
  74530. */
  74531. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,重新写贴图加载方式:
  74532. parser.textureLoader.load(sourceURI, (tex)=>{
  74533. tex.minFilter = THREE.LinearMipmapLinearFilter; //原本:NearestMipMapNearestFilter 闪烁
  74534. //tex.needsUpdate
  74535. resolve(tex);
  74536. });
  74537. return;
  74538. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, (e,url)=>{
  74539. console.log('reject',textureIndex, arguments);
  74540. if ( loader.isImageBitmapLoader === true ) {
  74541. let img = new Image;
  74542. img.setAttribute('crossOrigin', 'Anonymous');
  74543. img.src = url;
  74544. resolve(new THREE.Texture(img));
  74545. /* img.onload = ()=>{
  74546. let canvas = document.createElement('canvas')
  74547. let context = canvas.getContext('2d')
  74548. context.canvas.width = img.width
  74549. context.canvas.height = img.height
  74550. context.drawImage(img, 0, 0, img.width, img.height)
  74551. resolve( new CanvasTexture( canvas ) );
  74552. console.log('自己绘制 onload', textureIndex)
  74553. } */
  74554. }else {
  74555. reject.apply(this,arguments);
  74556. }
  74557. } /* , reject */ );
  74558. } );
  74559. } ).then( function ( texture ) {
  74560. // Clean up resources and configure Texture.
  74561. //console.log('texture', textureIndex, texture.image)
  74562. if ( isObjectURL === true ) {
  74563. URL.revokeObjectURL( sourceURI );
  74564. }
  74565. texture.flipY = false;
  74566. if ( textureDef.name ) texture.name = textureDef.name;
  74567. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  74568. if ( ! hasAlpha ) texture.format = RGBFormat;
  74569. var samplers = json.samplers || {};
  74570. var sampler = samplers[ textureDef.sampler ] || {};
  74571. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  74572. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
  74573. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  74574. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  74575. parser.associations.set( texture, {
  74576. type: 'textures',
  74577. index: textureIndex
  74578. } );
  74579. return texture;
  74580. } );
  74581. };
  74582. /**
  74583. * Asynchronously assigns a texture to the given material parameters.
  74584. * @param {Object} materialParams
  74585. * @param {string} mapName
  74586. * @param {Object} mapDef
  74587. * @return {Promise}
  74588. */
  74589. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  74590. var parser = this;
  74591. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  74592. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  74593. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  74594. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  74595. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  74596. }
  74597. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  74598. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  74599. if ( transform ) {
  74600. var gltfReference = parser.associations.get( texture );
  74601. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  74602. parser.associations.set( texture, gltfReference );
  74603. }
  74604. }
  74605. materialParams[ mapName ] = texture;
  74606. } );
  74607. };
  74608. /**
  74609. * Assigns final material to a Mesh, Line, or Points instance. The instance
  74610. * already has a material (generated from the glTF material options alone)
  74611. * but reuse of the same glTF material may require multiple threejs materials
  74612. * to accomodate different primitive types, defines, etc. New materials will
  74613. * be created if necessary, and reused from a cache.
  74614. * @param {Object3D} mesh Mesh, Line, or Points instance.
  74615. */
  74616. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  74617. var geometry = mesh.geometry;
  74618. var material = mesh.material;
  74619. var useVertexTangents = geometry.attributes.tangent !== undefined;
  74620. var useVertexColors = geometry.attributes.color !== undefined;
  74621. var useFlatShading = geometry.attributes.normal === undefined;
  74622. var useSkinning = mesh.isSkinnedMesh === true;
  74623. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  74624. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  74625. if ( mesh.isPoints ) {
  74626. var cacheKey = 'PointsMaterial:' + material.uuid;
  74627. var pointsMaterial = this.cache.get( cacheKey );
  74628. if ( ! pointsMaterial ) {
  74629. pointsMaterial = new PointsMaterial();
  74630. Material.prototype.copy.call( pointsMaterial, material );
  74631. pointsMaterial.color.copy( material.color );
  74632. pointsMaterial.map = material.map;
  74633. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  74634. this.cache.add( cacheKey, pointsMaterial );
  74635. }
  74636. material = pointsMaterial;
  74637. } else if ( mesh.isLine ) {
  74638. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  74639. var lineMaterial = this.cache.get( cacheKey );
  74640. if ( ! lineMaterial ) {
  74641. lineMaterial = new LineBasicMaterial();
  74642. Material.prototype.copy.call( lineMaterial, material );
  74643. lineMaterial.color.copy( material.color );
  74644. this.cache.add( cacheKey, lineMaterial );
  74645. }
  74646. material = lineMaterial;
  74647. }
  74648. // Clone the material if it will be modified
  74649. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  74650. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  74651. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  74652. if ( useSkinning ) cacheKey += 'skinning:';
  74653. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  74654. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  74655. if ( useFlatShading ) cacheKey += 'flat-shading:';
  74656. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  74657. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  74658. var cachedMaterial = this.cache.get( cacheKey );
  74659. if ( ! cachedMaterial ) {
  74660. cachedMaterial = material.clone();
  74661. if ( useSkinning ) cachedMaterial.skinning = true;
  74662. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  74663. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  74664. if ( useFlatShading ) cachedMaterial.flatShading = true;
  74665. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  74666. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  74667. this.cache.add( cacheKey, cachedMaterial );
  74668. this.associations.set( cachedMaterial, this.associations.get( material ) );
  74669. }
  74670. material = cachedMaterial;
  74671. }
  74672. // workarounds for mesh and geometry
  74673. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  74674. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  74675. }
  74676. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  74677. if ( material.normalScale && ! useVertexTangents ) {
  74678. material.normalScale.y = - material.normalScale.y;
  74679. }
  74680. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  74681. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  74682. }
  74683. mesh.material = material;
  74684. };
  74685. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  74686. return this.unlitMat ? MeshBasicMaterial : MeshStandardMaterial; //xzw add unlitMat
  74687. };
  74688. /**
  74689. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  74690. * @param {number} materialIndex
  74691. * @return {Promise<Material>}
  74692. */
  74693. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  74694. var parser = this;
  74695. var json = this.json;
  74696. var extensions = this.extensions;
  74697. var materialDef = json.materials[ materialIndex ];
  74698. var materialType;
  74699. var materialParams = {};
  74700. var materialExtensions = materialDef.extensions || {};
  74701. var pending = [];
  74702. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  74703. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  74704. materialType = sgExtension.getMaterialType();
  74705. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  74706. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  74707. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  74708. materialType = kmuExtension.getMaterialType();
  74709. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  74710. } else {
  74711. // Specification:
  74712. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  74713. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  74714. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  74715. materialParams.opacity = 1.0;
  74716. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  74717. var array = metallicRoughness.baseColorFactor;
  74718. materialParams.color.fromArray( array );
  74719. materialParams.opacity = array[ 3 ];
  74720. }
  74721. if ( metallicRoughness.baseColorTexture !== undefined ) {
  74722. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  74723. }
  74724. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  74725. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  74726. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  74727. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  74728. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  74729. }
  74730. materialType = this._invokeOne( function ( ext ) {
  74731. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  74732. } );
  74733. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  74734. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  74735. } ) ) );
  74736. }
  74737. if ( materialDef.doubleSided === true ) {
  74738. materialParams.side = DoubleSide;
  74739. }
  74740. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  74741. if ( alphaMode === ALPHA_MODES.BLEND ) {
  74742. materialParams.transparent = true;
  74743. // See: https://github.com/mrdoob/three.js/issues/17706
  74744. materialParams.depthWrite = false;
  74745. } else {
  74746. materialParams.transparent = false;
  74747. if ( alphaMode === ALPHA_MODES.MASK ) {
  74748. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  74749. }
  74750. }
  74751. if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74752. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  74753. materialParams.normalScale = new Vector2$1( 1, 1 );
  74754. if ( materialDef.normalTexture.scale !== undefined ) {
  74755. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  74756. }
  74757. }
  74758. if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74759. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  74760. if ( materialDef.occlusionTexture.strength !== undefined ) {
  74761. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  74762. }
  74763. }
  74764. if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
  74765. materialParams.emissive = new Color().fromArray( materialDef.emissiveFactor );
  74766. }
  74767. if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74768. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  74769. }
  74770. return Promise.all( pending ).then( function () {
  74771. var material;
  74772. if ( materialType === GLTFMeshStandardSGMaterial ) {
  74773. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  74774. } else {
  74775. material = new materialType( materialParams );
  74776. }
  74777. if ( materialDef.name ) material.name = materialDef.name;
  74778. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  74779. if ( material.map ) material.map.encoding = sRGBEncoding;
  74780. if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding;
  74781. assignExtrasToUserData( material, materialDef );
  74782. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  74783. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  74784. return material;
  74785. } );
  74786. };
  74787. /** When Object3D instances are targeted by animation, they need unique names. */
  74788. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  74789. var sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );
  74790. var name = sanitizedName;
  74791. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  74792. name = sanitizedName + '_' + i;
  74793. }
  74794. this.nodeNamesUsed[ name ] = true;
  74795. return name;
  74796. };
  74797. /**
  74798. * @param {BufferGeometry} geometry
  74799. * @param {GLTF.Primitive} primitiveDef
  74800. * @param {GLTFParser} parser
  74801. */
  74802. function computeBounds( geometry, primitiveDef, parser ) {
  74803. var attributes = primitiveDef.attributes;
  74804. var box = new Box3();
  74805. if ( attributes.POSITION !== undefined ) {
  74806. var accessor = parser.json.accessors[ attributes.POSITION ];
  74807. var min = accessor.min;
  74808. var max = accessor.max;
  74809. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  74810. if ( min !== undefined && max !== undefined ) {
  74811. box.set(
  74812. new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  74813. new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  74814. } else {
  74815. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  74816. return;
  74817. }
  74818. } else {
  74819. return;
  74820. }
  74821. var targets = primitiveDef.targets;
  74822. if ( targets !== undefined ) {
  74823. var maxDisplacement = new Vector3();
  74824. var vector = new Vector3();
  74825. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74826. var target = targets[ i ];
  74827. if ( target.POSITION !== undefined ) {
  74828. var accessor = parser.json.accessors[ target.POSITION ];
  74829. var min = accessor.min;
  74830. var max = accessor.max;
  74831. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  74832. if ( min !== undefined && max !== undefined ) {
  74833. // we need to get max of absolute components because target weight is [-1,1]
  74834. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  74835. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  74836. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  74837. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  74838. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  74839. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  74840. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  74841. maxDisplacement.max( vector );
  74842. } else {
  74843. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  74844. }
  74845. }
  74846. }
  74847. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  74848. box.expandByVector( maxDisplacement );
  74849. }
  74850. geometry.boundingBox = box;
  74851. var sphere = new Sphere();
  74852. box.getCenter( sphere.center );
  74853. sphere.radius = box.min.distanceTo( box.max ) / 2;
  74854. geometry.boundingSphere = sphere;
  74855. }
  74856. /**
  74857. * @param {BufferGeometry} geometry
  74858. * @param {GLTF.Primitive} primitiveDef
  74859. * @param {GLTFParser} parser
  74860. * @return {Promise<BufferGeometry>}
  74861. */
  74862. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  74863. var attributes = primitiveDef.attributes;
  74864. var pending = [];
  74865. function assignAttributeAccessor( accessorIndex, attributeName ) {
  74866. return parser.getDependency( 'accessor', accessorIndex )
  74867. .then( function ( accessor ) {
  74868. geometry.setAttribute( attributeName, accessor );
  74869. } );
  74870. }
  74871. for ( var gltfAttributeName in attributes ) {
  74872. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  74873. // Skip attributes already provided by e.g. Draco extension.
  74874. if ( threeAttributeName in geometry.attributes ) continue;
  74875. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  74876. }
  74877. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  74878. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  74879. geometry.setIndex( accessor );
  74880. } );
  74881. pending.push( accessor );
  74882. }
  74883. assignExtrasToUserData( geometry, primitiveDef );
  74884. computeBounds( geometry, primitiveDef, parser );
  74885. return Promise.all( pending ).then( function () {
  74886. return primitiveDef.targets !== undefined
  74887. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  74888. : geometry;
  74889. } );
  74890. }
  74891. /**
  74892. * @param {BufferGeometry} geometry
  74893. * @param {Number} drawMode
  74894. * @return {BufferGeometry}
  74895. */
  74896. function toTrianglesDrawMode( geometry, drawMode ) {
  74897. var index = geometry.getIndex();
  74898. // generate index if not present
  74899. if ( index === null ) {
  74900. var indices = [];
  74901. var position = geometry.getAttribute( 'position' );
  74902. if ( position !== undefined ) {
  74903. for ( var i = 0; i < position.count; i ++ ) {
  74904. indices.push( i );
  74905. }
  74906. geometry.setIndex( indices );
  74907. index = geometry.getIndex();
  74908. } else {
  74909. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  74910. return geometry;
  74911. }
  74912. }
  74913. //
  74914. var numberOfTriangles = index.count - 2;
  74915. var newIndices = [];
  74916. if ( drawMode === TriangleFanDrawMode ) {
  74917. // gl.TRIANGLE_FAN
  74918. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  74919. newIndices.push( index.getX( 0 ) );
  74920. newIndices.push( index.getX( i ) );
  74921. newIndices.push( index.getX( i + 1 ) );
  74922. }
  74923. } else {
  74924. // gl.TRIANGLE_STRIP
  74925. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  74926. if ( i % 2 === 0 ) {
  74927. newIndices.push( index.getX( i ) );
  74928. newIndices.push( index.getX( i + 1 ) );
  74929. newIndices.push( index.getX( i + 2 ) );
  74930. } else {
  74931. newIndices.push( index.getX( i + 2 ) );
  74932. newIndices.push( index.getX( i + 1 ) );
  74933. newIndices.push( index.getX( i ) );
  74934. }
  74935. }
  74936. }
  74937. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  74938. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  74939. }
  74940. // build final geometry
  74941. var newGeometry = geometry.clone();
  74942. newGeometry.setIndex( newIndices );
  74943. return newGeometry;
  74944. }
  74945. /**
  74946. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  74947. *
  74948. * Creates BufferGeometries from primitives.
  74949. *
  74950. * @param {Array<GLTF.Primitive>} primitives
  74951. * @return {Promise<Array<BufferGeometry>>}
  74952. */
  74953. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  74954. var parser = this;
  74955. var extensions = this.extensions;
  74956. var cache = this.primitiveCache;
  74957. function createDracoPrimitive( primitive ) {
  74958. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  74959. .decodePrimitive( primitive, parser )
  74960. .then( function ( geometry ) {
  74961. return addPrimitiveAttributes( geometry, primitive, parser );
  74962. } );
  74963. }
  74964. var pending = [];
  74965. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  74966. var primitive = primitives[ i ];
  74967. var cacheKey = createPrimitiveKey( primitive );
  74968. // See if we've already created this geometry
  74969. var cached = cache[ cacheKey ];
  74970. if ( cached ) {
  74971. // Use the cached geometry if it exists
  74972. pending.push( cached.promise );
  74973. } else {
  74974. var geometryPromise;
  74975. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  74976. // Use DRACO geometry if available
  74977. geometryPromise = createDracoPrimitive( primitive );
  74978. } else {
  74979. // Otherwise create a new geometry
  74980. geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
  74981. }
  74982. // Cache this geometry
  74983. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  74984. pending.push( geometryPromise );
  74985. }
  74986. }
  74987. return Promise.all( pending );
  74988. };
  74989. /**
  74990. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  74991. * @param {number} meshIndex
  74992. * @return {Promise<Group|Mesh|SkinnedMesh>}
  74993. */
  74994. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  74995. var parser = this;
  74996. var json = this.json;
  74997. var extensions = this.extensions;
  74998. var meshDef = json.meshes[ meshIndex ];
  74999. var primitives = meshDef.primitives;
  75000. var pending = [];
  75001. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  75002. var material = primitives[ i ].material === undefined
  75003. ? createDefaultMaterial( this.cache )
  75004. : this.getDependency( 'material', primitives[ i ].material );
  75005. pending.push( material );
  75006. }
  75007. pending.push( parser.loadGeometries( primitives ) );
  75008. return Promise.all( pending ).then( function ( results ) {
  75009. var materials = results.slice( 0, results.length - 1 );
  75010. var geometries = results[ results.length - 1 ];
  75011. var meshes = [];
  75012. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  75013. var geometry = geometries[ i ];
  75014. var primitive = primitives[ i ];
  75015. // 1. create Mesh
  75016. var mesh;
  75017. var material = materials[ i ];
  75018. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  75019. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  75020. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  75021. primitive.mode === undefined ) {
  75022. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  75023. mesh = meshDef.isSkinnedMesh === true
  75024. ? new SkinnedMesh( geometry, material )
  75025. : new Mesh( geometry, material );
  75026. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  75027. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  75028. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  75029. mesh.normalizeSkinWeights();
  75030. }
  75031. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  75032. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode );
  75033. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  75034. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode );
  75035. }
  75036. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  75037. mesh = new LineSegments( geometry, material );
  75038. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  75039. mesh = new Line( geometry, material );
  75040. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  75041. mesh = new LineLoop( geometry, material );
  75042. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  75043. mesh = new Points( geometry, material );
  75044. } else {
  75045. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  75046. }
  75047. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  75048. updateMorphTargets( mesh, meshDef );
  75049. }
  75050. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  75051. assignExtrasToUserData( mesh, meshDef );
  75052. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  75053. parser.assignFinalMaterial( mesh );
  75054. meshes.push( mesh );
  75055. }
  75056. if ( meshes.length === 1 ) {
  75057. return meshes[ 0 ];
  75058. }
  75059. var group = new Group();
  75060. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  75061. group.add( meshes[ i ] );
  75062. }
  75063. return group;
  75064. } );
  75065. };
  75066. /**
  75067. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  75068. * @param {number} cameraIndex
  75069. * @return {Promise<THREE.Camera>}
  75070. */
  75071. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  75072. var camera;
  75073. var cameraDef = this.json.cameras[ cameraIndex ];
  75074. var params = cameraDef[ cameraDef.type ];
  75075. if ( ! params ) {
  75076. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  75077. return;
  75078. }
  75079. if ( cameraDef.type === 'perspective' ) {
  75080. camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  75081. } else if ( cameraDef.type === 'orthographic' ) {
  75082. camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  75083. }
  75084. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  75085. assignExtrasToUserData( camera, cameraDef );
  75086. return Promise.resolve( camera );
  75087. };
  75088. /**
  75089. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  75090. * @param {number} skinIndex
  75091. * @return {Promise<Object>}
  75092. */
  75093. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  75094. var skinDef = this.json.skins[ skinIndex ];
  75095. var skinEntry = { joints: skinDef.joints };
  75096. if ( skinDef.inverseBindMatrices === undefined ) {
  75097. return Promise.resolve( skinEntry );
  75098. }
  75099. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  75100. skinEntry.inverseBindMatrices = accessor;
  75101. return skinEntry;
  75102. } );
  75103. };
  75104. /**
  75105. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  75106. * @param {number} animationIndex
  75107. * @return {Promise<AnimationClip>}
  75108. */
  75109. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  75110. var json = this.json;
  75111. var animationDef = json.animations[ animationIndex ];
  75112. var pendingNodes = [];
  75113. var pendingInputAccessors = [];
  75114. var pendingOutputAccessors = [];
  75115. var pendingSamplers = [];
  75116. var pendingTargets = [];
  75117. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  75118. var channel = animationDef.channels[ i ];
  75119. var sampler = animationDef.samplers[ channel.sampler ];
  75120. var target = channel.target;
  75121. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  75122. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  75123. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  75124. pendingNodes.push( this.getDependency( 'node', name ) );
  75125. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  75126. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  75127. pendingSamplers.push( sampler );
  75128. pendingTargets.push( target );
  75129. }
  75130. return Promise.all( [
  75131. Promise.all( pendingNodes ),
  75132. Promise.all( pendingInputAccessors ),
  75133. Promise.all( pendingOutputAccessors ),
  75134. Promise.all( pendingSamplers ),
  75135. Promise.all( pendingTargets )
  75136. ] ).then( function ( dependencies ) {
  75137. var nodes = dependencies[ 0 ];
  75138. var inputAccessors = dependencies[ 1 ];
  75139. var outputAccessors = dependencies[ 2 ];
  75140. var samplers = dependencies[ 3 ];
  75141. var targets = dependencies[ 4 ];
  75142. var tracks = [];
  75143. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  75144. var node = nodes[ i ];
  75145. var inputAccessor = inputAccessors[ i ];
  75146. var outputAccessor = outputAccessors[ i ];
  75147. var sampler = samplers[ i ];
  75148. var target = targets[ i ];
  75149. if ( node === undefined ) continue;
  75150. node.updateMatrix();
  75151. node.matrixAutoUpdate = true;
  75152. var TypedKeyframeTrack;
  75153. switch ( PATH_PROPERTIES[ target.path ] ) {
  75154. case PATH_PROPERTIES.weights:
  75155. TypedKeyframeTrack = NumberKeyframeTrack;
  75156. break;
  75157. case PATH_PROPERTIES.rotation:
  75158. TypedKeyframeTrack = QuaternionKeyframeTrack;
  75159. break;
  75160. case PATH_PROPERTIES.position:
  75161. case PATH_PROPERTIES.scale:
  75162. default:
  75163. TypedKeyframeTrack = VectorKeyframeTrack;
  75164. break;
  75165. }
  75166. var targetName = node.name ? node.name : node.uuid;
  75167. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  75168. var targetNames = [];
  75169. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  75170. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  75171. node.traverse( function ( object ) {
  75172. if ( object.isMesh === true && object.morphTargetInfluences ) {
  75173. targetNames.push( object.name ? object.name : object.uuid );
  75174. }
  75175. } );
  75176. } else {
  75177. targetNames.push( targetName );
  75178. }
  75179. var outputArray = outputAccessor.array;
  75180. if ( outputAccessor.normalized ) {
  75181. var scale;
  75182. if ( outputArray.constructor === Int8Array ) {
  75183. scale = 1 / 127;
  75184. } else if ( outputArray.constructor === Uint8Array ) {
  75185. scale = 1 / 255;
  75186. } else if ( outputArray.constructor == Int16Array ) {
  75187. scale = 1 / 32767;
  75188. } else if ( outputArray.constructor === Uint16Array ) {
  75189. scale = 1 / 65535;
  75190. } else {
  75191. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  75192. }
  75193. var scaled = new Float32Array( outputArray.length );
  75194. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  75195. scaled[ j ] = outputArray[ j ] * scale;
  75196. }
  75197. outputArray = scaled;
  75198. }
  75199. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  75200. var track = new TypedKeyframeTrack(
  75201. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  75202. inputAccessor.array,
  75203. outputArray,
  75204. interpolation
  75205. );
  75206. // Override interpolation with custom factory method.
  75207. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  75208. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  75209. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  75210. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  75211. // must be divided by three to get the interpolant's sampleSize argument.
  75212. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  75213. };
  75214. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  75215. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  75216. }
  75217. tracks.push( track );
  75218. }
  75219. }
  75220. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  75221. return new AnimationClip( name, undefined, tracks );
  75222. } );
  75223. };
  75224. /**
  75225. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  75226. * @param {number} nodeIndex
  75227. * @return {Promise<Object3D>}
  75228. */
  75229. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  75230. var json = this.json;
  75231. var extensions = this.extensions;
  75232. var parser = this;
  75233. var nodeDef = json.nodes[ nodeIndex ];
  75234. // reserve node's name before its dependencies, so the root has the intended name.
  75235. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  75236. return ( function () {
  75237. var pending = [];
  75238. if ( nodeDef.mesh !== undefined ) {
  75239. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  75240. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  75241. // if weights are provided on the node, override weights on the mesh.
  75242. if ( nodeDef.weights !== undefined ) {
  75243. node.traverse( function ( o ) {
  75244. if ( ! o.isMesh ) return;
  75245. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  75246. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  75247. }
  75248. } );
  75249. }
  75250. return node;
  75251. } ) );
  75252. }
  75253. if ( nodeDef.camera !== undefined ) {
  75254. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  75255. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  75256. } ) );
  75257. }
  75258. parser._invokeAll( function ( ext ) {
  75259. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  75260. } ).forEach( function ( promise ) {
  75261. pending.push( promise );
  75262. } );
  75263. return Promise.all( pending );
  75264. }() ).then( function ( objects ) {
  75265. var node;
  75266. // .isBone isn't in glTF spec. See ._markDefs
  75267. if ( nodeDef.isBone === true ) {
  75268. node = new Bone();
  75269. } else if ( objects.length > 1 ) {
  75270. node = new Group();
  75271. } else if ( objects.length === 1 ) {
  75272. node = objects[ 0 ];
  75273. } else {
  75274. node = new Object3D();
  75275. }
  75276. if ( node !== objects[ 0 ] ) {
  75277. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  75278. node.add( objects[ i ] );
  75279. }
  75280. }
  75281. if ( nodeDef.name ) {
  75282. node.userData.name = nodeDef.name;
  75283. node.name = nodeName;
  75284. }
  75285. assignExtrasToUserData( node, nodeDef );
  75286. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  75287. if ( nodeDef.matrix !== undefined ) {
  75288. var matrix = new Matrix4();
  75289. matrix.fromArray( nodeDef.matrix );
  75290. node.applyMatrix4( matrix );
  75291. } else {
  75292. if ( nodeDef.translation !== undefined ) {
  75293. node.position.fromArray( nodeDef.translation );
  75294. }
  75295. if ( nodeDef.rotation !== undefined ) {
  75296. node.quaternion.fromArray( nodeDef.rotation );
  75297. }
  75298. if ( nodeDef.scale !== undefined ) {
  75299. node.scale.fromArray( nodeDef.scale );
  75300. }
  75301. }
  75302. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  75303. return node;
  75304. } );
  75305. };
  75306. /**
  75307. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  75308. * @param {number} sceneIndex
  75309. * @return {Promise<Group>}
  75310. */
  75311. GLTFParser.prototype.loadScene = function () {
  75312. // scene node hierachy builder
  75313. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  75314. var nodeDef = json.nodes[ nodeId ];
  75315. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  75316. if ( nodeDef.skin === undefined ) return node;
  75317. // build skeleton here as well
  75318. var skinEntry;
  75319. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  75320. skinEntry = skin;
  75321. var pendingJoints = [];
  75322. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  75323. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  75324. }
  75325. return Promise.all( pendingJoints );
  75326. } ).then( function ( jointNodes ) {
  75327. node.traverse( function ( mesh ) {
  75328. if ( ! mesh.isMesh ) return;
  75329. var bones = [];
  75330. var boneInverses = [];
  75331. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  75332. var jointNode = jointNodes[ j ];
  75333. if ( jointNode ) {
  75334. bones.push( jointNode );
  75335. var mat = new Matrix4();
  75336. if ( skinEntry.inverseBindMatrices !== undefined ) {
  75337. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  75338. }
  75339. boneInverses.push( mat );
  75340. } else {
  75341. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  75342. }
  75343. }
  75344. mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld );
  75345. } );
  75346. return node;
  75347. } );
  75348. } ).then( function ( node ) {
  75349. // build node hierachy
  75350. parentObject.add( node );
  75351. var pending = [];
  75352. if ( nodeDef.children ) {
  75353. var children = nodeDef.children;
  75354. for ( var i = 0, il = children.length; i < il; i ++ ) {
  75355. var child = children[ i ];
  75356. pending.push( buildNodeHierachy( child, node, json, parser ) );
  75357. }
  75358. }
  75359. return Promise.all( pending );
  75360. } );
  75361. }
  75362. return function loadScene( sceneIndex ) {
  75363. var json = this.json;
  75364. var extensions = this.extensions;
  75365. var sceneDef = this.json.scenes[ sceneIndex ];
  75366. var parser = this;
  75367. // Loader returns Group, not Scene.
  75368. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  75369. var scene = new Group();
  75370. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  75371. assignExtrasToUserData( scene, sceneDef );
  75372. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  75373. var nodeIds = sceneDef.nodes || [];
  75374. var pending = [];
  75375. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  75376. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  75377. }
  75378. return Promise.all( pending ).then( function () {
  75379. return scene;
  75380. } );
  75381. };
  75382. }();
  75383. return GLTFLoader;
  75384. } )();
  75385. /**
  75386. * @webxr-input-profiles/motion-controllers 1.0.0 https://github.com/immersive-web/webxr-input-profiles
  75387. */
  75388. const Constants = {
  75389. Handedness: Object.freeze({
  75390. NONE: 'none',
  75391. LEFT: 'left',
  75392. RIGHT: 'right'
  75393. }),
  75394. ComponentState: Object.freeze({
  75395. DEFAULT: 'default',
  75396. TOUCHED: 'touched',
  75397. PRESSED: 'pressed'
  75398. }),
  75399. ComponentProperty: Object.freeze({
  75400. BUTTON: 'button',
  75401. X_AXIS: 'xAxis',
  75402. Y_AXIS: 'yAxis',
  75403. STATE: 'state'
  75404. }),
  75405. ComponentType: Object.freeze({
  75406. TRIGGER: 'trigger',
  75407. SQUEEZE: 'squeeze',
  75408. TOUCHPAD: 'touchpad',
  75409. THUMBSTICK: 'thumbstick',
  75410. BUTTON: 'button'
  75411. }),
  75412. ButtonTouchThreshold: 0.05,
  75413. AxisTouchThreshold: 0.1,
  75414. VisualResponseProperty: Object.freeze({
  75415. TRANSFORM: 'transform',
  75416. VISIBILITY: 'visibility'
  75417. })
  75418. };
  75419. /**
  75420. * @description Static helper function to fetch a JSON file and turn it into a JS object
  75421. * @param {string} path - Path to JSON file to be fetched
  75422. */
  75423. async function fetchJsonFile(path) {
  75424. const response = await fetch(path);
  75425. if (!response.ok) {
  75426. throw new Error(response.statusText);
  75427. } else {
  75428. return response.json();
  75429. }
  75430. }
  75431. async function fetchProfilesList(basePath) {
  75432. if (!basePath) {
  75433. throw new Error('No basePath supplied');
  75434. }
  75435. const profileListFileName = 'profilesList.json';
  75436. const profilesList = await fetchJsonFile(`${basePath}/${profileListFileName}`);
  75437. return profilesList;
  75438. }
  75439. async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) {
  75440. if (!xrInputSource) {
  75441. throw new Error('No xrInputSource supplied');
  75442. }
  75443. if (!basePath) {
  75444. throw new Error('No basePath supplied');
  75445. }
  75446. // Get the list of profiles
  75447. const supportedProfilesList = await fetchProfilesList(basePath);
  75448. // Find the relative path to the first requested profile that is recognized
  75449. let match;
  75450. xrInputSource.profiles.some((profileId) => {
  75451. const supportedProfile = supportedProfilesList[profileId];
  75452. if (supportedProfile) {
  75453. match = {
  75454. profileId,
  75455. profilePath: `${basePath}/${supportedProfile.path}`,
  75456. deprecated: !!supportedProfile.deprecated
  75457. };
  75458. }
  75459. return !!match;
  75460. });
  75461. if (!match) {
  75462. if (!defaultProfile) {
  75463. throw new Error('No matching profile name found');
  75464. }
  75465. const supportedProfile = supportedProfilesList[defaultProfile];
  75466. if (!supportedProfile) {
  75467. throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`);
  75468. }
  75469. match = {
  75470. profileId: defaultProfile,
  75471. profilePath: `${basePath}/${supportedProfile.path}`,
  75472. deprecated: !!supportedProfile.deprecated
  75473. };
  75474. }
  75475. const profile = await fetchJsonFile(match.profilePath);
  75476. let assetPath;
  75477. if (getAssetPath) {
  75478. let layout;
  75479. if (xrInputSource.handedness === 'any') {
  75480. layout = profile.layouts[Object.keys(profile.layouts)[0]];
  75481. } else {
  75482. layout = profile.layouts[xrInputSource.handedness];
  75483. }
  75484. if (!layout) {
  75485. throw new Error(
  75486. `No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}`
  75487. );
  75488. }
  75489. if (layout.assetPath) {
  75490. assetPath = match.profilePath.replace('profile.json', layout.assetPath);
  75491. }
  75492. }
  75493. return { profile, assetPath };
  75494. }
  75495. /** @constant {Object} */
  75496. const defaultComponentValues = {
  75497. xAxis: 0,
  75498. yAxis: 0,
  75499. button: 0,
  75500. state: Constants.ComponentState.DEFAULT
  75501. };
  75502. /**
  75503. * @description Converts an X, Y coordinate from the range -1 to 1 (as reported by the Gamepad
  75504. * API) to the range 0 to 1 (for interpolation). Also caps the X, Y values to be bounded within
  75505. * a circle. This ensures that thumbsticks are not animated outside the bounds of their physical
  75506. * range of motion and touchpads do not report touch locations off their physical bounds.
  75507. * @param {number} x The original x coordinate in the range -1 to 1
  75508. * @param {number} y The original y coordinate in the range -1 to 1
  75509. */
  75510. function normalizeAxes(x = 0, y = 0) {
  75511. let xAxis = x;
  75512. let yAxis = y;
  75513. // Determine if the point is outside the bounds of the circle
  75514. // and, if so, place it on the edge of the circle
  75515. const hypotenuse = Math.sqrt((x * x) + (y * y));
  75516. if (hypotenuse > 1) {
  75517. const theta = Math.atan2(y, x);
  75518. xAxis = Math.cos(theta);
  75519. yAxis = Math.sin(theta);
  75520. }
  75521. // Scale and move the circle so values are in the interpolation range. The circle's origin moves
  75522. // from (0, 0) to (0.5, 0.5). The circle's radius scales from 1 to be 0.5.
  75523. const result = {
  75524. normalizedXAxis: (xAxis * 0.5) + 0.5,
  75525. normalizedYAxis: (yAxis * 0.5) + 0.5
  75526. };
  75527. return result;
  75528. }
  75529. /**
  75530. * Contains the description of how the 3D model should visually respond to a specific user input.
  75531. * This is accomplished by initializing the object with the name of a node in the 3D model and
  75532. * property that need to be modified in response to user input, the name of the nodes representing
  75533. * the allowable range of motion, and the name of the input which triggers the change. In response
  75534. * to the named input changing, this object computes the appropriate weighting to use for
  75535. * interpolating between the range of motion nodes.
  75536. */
  75537. class VisualResponse {
  75538. constructor(visualResponseDescription) {
  75539. this.componentProperty = visualResponseDescription.componentProperty;
  75540. this.states = visualResponseDescription.states;
  75541. this.valueNodeName = visualResponseDescription.valueNodeName;
  75542. this.valueNodeProperty = visualResponseDescription.valueNodeProperty;
  75543. if (this.valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
  75544. this.minNodeName = visualResponseDescription.minNodeName;
  75545. this.maxNodeName = visualResponseDescription.maxNodeName;
  75546. }
  75547. // Initializes the response's current value based on default data
  75548. this.value = 0;
  75549. this.updateFromComponent(defaultComponentValues);
  75550. }
  75551. /**
  75552. * Computes the visual response's interpolation weight based on component state
  75553. * @param {Object} componentValues - The component from which to update
  75554. * @param {number} xAxis - The reported X axis value of the component
  75555. * @param {number} yAxis - The reported Y axis value of the component
  75556. * @param {number} button - The reported value of the component's button
  75557. * @param {string} state - The component's active state
  75558. */
  75559. updateFromComponent({
  75560. xAxis, yAxis, button, state
  75561. }) {
  75562. const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis, yAxis);
  75563. switch (this.componentProperty) {
  75564. case Constants.ComponentProperty.X_AXIS:
  75565. this.value = (this.states.includes(state)) ? normalizedXAxis : 0.5;
  75566. break;
  75567. case Constants.ComponentProperty.Y_AXIS:
  75568. this.value = (this.states.includes(state)) ? normalizedYAxis : 0.5;
  75569. break;
  75570. case Constants.ComponentProperty.BUTTON:
  75571. this.value = (this.states.includes(state)) ? button : 0;
  75572. break;
  75573. case Constants.ComponentProperty.STATE:
  75574. if (this.valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) {
  75575. this.value = (this.states.includes(state));
  75576. } else {
  75577. this.value = this.states.includes(state) ? 1.0 : 0.0;
  75578. }
  75579. break;
  75580. default:
  75581. throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`);
  75582. }
  75583. }
  75584. }
  75585. class Component {
  75586. /**
  75587. * @param {Object} componentId - Id of the component
  75588. * @param {Object} componentDescription - Description of the component to be created
  75589. */
  75590. constructor(componentId, componentDescription) {
  75591. if (!componentId
  75592. || !componentDescription
  75593. || !componentDescription.visualResponses
  75594. || !componentDescription.gamepadIndices
  75595. || Object.keys(componentDescription.gamepadIndices).length === 0) {
  75596. throw new Error('Invalid arguments supplied');
  75597. }
  75598. this.id = componentId;
  75599. this.type = componentDescription.type;
  75600. this.rootNodeName = componentDescription.rootNodeName;
  75601. this.touchPointNodeName = componentDescription.touchPointNodeName;
  75602. // Build all the visual responses for this component
  75603. this.visualResponses = {};
  75604. Object.keys(componentDescription.visualResponses).forEach((responseName) => {
  75605. const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]);
  75606. this.visualResponses[responseName] = visualResponse;
  75607. });
  75608. // Set default values
  75609. this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices);
  75610. this.values = {
  75611. state: Constants.ComponentState.DEFAULT,
  75612. button: (this.gamepadIndices.button !== undefined) ? 0 : undefined,
  75613. xAxis: (this.gamepadIndices.xAxis !== undefined) ? 0 : undefined,
  75614. yAxis: (this.gamepadIndices.yAxis !== undefined) ? 0 : undefined
  75615. };
  75616. }
  75617. get data() {
  75618. const data = { id: this.id, ...this.values };
  75619. return data;
  75620. }
  75621. /**
  75622. * @description Poll for updated data based on current gamepad state
  75623. * @param {Object} gamepad - The gamepad object from which the component data should be polled
  75624. */
  75625. updateFromGamepad(gamepad) {
  75626. // Set the state to default before processing other data sources
  75627. this.values.state = Constants.ComponentState.DEFAULT;
  75628. // Get and normalize button
  75629. if (this.gamepadIndices.button !== undefined
  75630. && gamepad.buttons.length > this.gamepadIndices.button) {
  75631. const gamepadButton = gamepad.buttons[this.gamepadIndices.button];
  75632. this.values.button = gamepadButton.value;
  75633. this.values.button = (this.values.button < 0) ? 0 : this.values.button;
  75634. this.values.button = (this.values.button > 1) ? 1 : this.values.button;
  75635. // Set the state based on the button
  75636. if (gamepadButton.pressed || this.values.button === 1) {
  75637. this.values.state = Constants.ComponentState.PRESSED;
  75638. } else if (gamepadButton.touched || this.values.button > Constants.ButtonTouchThreshold) {
  75639. this.values.state = Constants.ComponentState.TOUCHED;
  75640. }
  75641. }
  75642. // Get and normalize x axis value
  75643. if (this.gamepadIndices.xAxis !== undefined
  75644. && gamepad.axes.length > this.gamepadIndices.xAxis) {
  75645. this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis];
  75646. this.values.xAxis = (this.values.xAxis < -1) ? -1 : this.values.xAxis;
  75647. this.values.xAxis = (this.values.xAxis > 1) ? 1 : this.values.xAxis;
  75648. // If the state is still default, check if the xAxis makes it touched
  75649. if (this.values.state === Constants.ComponentState.DEFAULT
  75650. && Math.abs(this.values.xAxis) > Constants.AxisTouchThreshold) {
  75651. this.values.state = Constants.ComponentState.TOUCHED;
  75652. }
  75653. }
  75654. // Get and normalize Y axis value
  75655. if (this.gamepadIndices.yAxis !== undefined
  75656. && gamepad.axes.length > this.gamepadIndices.yAxis) {
  75657. this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis];
  75658. this.values.yAxis = (this.values.yAxis < -1) ? -1 : this.values.yAxis;
  75659. this.values.yAxis = (this.values.yAxis > 1) ? 1 : this.values.yAxis;
  75660. // If the state is still default, check if the yAxis makes it touched
  75661. if (this.values.state === Constants.ComponentState.DEFAULT
  75662. && Math.abs(this.values.yAxis) > Constants.AxisTouchThreshold) {
  75663. this.values.state = Constants.ComponentState.TOUCHED;
  75664. }
  75665. }
  75666. // Update the visual response weights based on the current component data
  75667. Object.values(this.visualResponses).forEach((visualResponse) => {
  75668. visualResponse.updateFromComponent(this.values);
  75669. });
  75670. }
  75671. }
  75672. /**
  75673. * @description Builds a motion controller with components and visual responses based on the
  75674. * supplied profile description. Data is polled from the xrInputSource's gamepad.
  75675. * @author Nell Waliczek / https://github.com/NellWaliczek
  75676. */
  75677. class MotionController {
  75678. /**
  75679. * @param {Object} xrInputSource - The XRInputSource to build the MotionController around
  75680. * @param {Object} profile - The best matched profile description for the supplied xrInputSource
  75681. * @param {Object} assetUrl
  75682. */
  75683. constructor(xrInputSource, profile, assetUrl) {
  75684. if (!xrInputSource) {
  75685. throw new Error('No xrInputSource supplied');
  75686. }
  75687. if (!profile) {
  75688. throw new Error('No profile supplied');
  75689. }
  75690. this.xrInputSource = xrInputSource;
  75691. this.assetUrl = assetUrl;
  75692. this.id = profile.profileId;
  75693. // Build child components as described in the profile description
  75694. this.layoutDescription = profile.layouts[xrInputSource.handedness];
  75695. this.components = {};
  75696. Object.keys(this.layoutDescription.components).forEach((componentId) => {
  75697. const componentDescription = this.layoutDescription.components[componentId];
  75698. this.components[componentId] = new Component(componentId, componentDescription);
  75699. });
  75700. // Initialize components based on current gamepad state
  75701. this.updateFromGamepad();
  75702. }
  75703. get gripSpace() {
  75704. return this.xrInputSource.gripSpace;
  75705. }
  75706. get targetRaySpace() {
  75707. return this.xrInputSource.targetRaySpace;
  75708. }
  75709. /**
  75710. * @description Returns a subset of component data for simplified debugging
  75711. */
  75712. get data() {
  75713. const data = [];
  75714. Object.values(this.components).forEach((component) => {
  75715. data.push(component.data);
  75716. });
  75717. return data;
  75718. }
  75719. /**
  75720. * @description Poll for updated data based on current gamepad state
  75721. */
  75722. updateFromGamepad() {
  75723. Object.values(this.components).forEach((component) => {
  75724. component.updateFromGamepad(this.xrInputSource.gamepad);
  75725. });
  75726. }
  75727. }
  75728. const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles';
  75729. const DEFAULT_PROFILE = 'generic-trigger';
  75730. function XRControllerModel( ) {
  75731. Object3D.call( this );
  75732. this.motionController = null;
  75733. this.envMap = null;
  75734. }
  75735. XRControllerModel.prototype = Object.assign( Object.create( Object3D.prototype ), {
  75736. constructor: XRControllerModel,
  75737. setEnvironmentMap: function ( envMap ) {
  75738. if ( this.envMap == envMap ) {
  75739. return this;
  75740. }
  75741. this.envMap = envMap;
  75742. this.traverse( ( child ) => {
  75743. if ( child.isMesh ) {
  75744. child.material.envMap = this.envMap;
  75745. child.material.needsUpdate = true;
  75746. }
  75747. } );
  75748. return this;
  75749. },
  75750. /**
  75751. * Polls data from the XRInputSource and updates the model's components to match
  75752. * the real world data
  75753. */
  75754. updateMatrixWorld: function ( force ) {
  75755. Object3D.prototype.updateMatrixWorld.call( this, force );
  75756. if ( ! this.motionController ) return;
  75757. // Cause the MotionController to poll the Gamepad for data
  75758. this.motionController.updateFromGamepad();
  75759. // Update the 3D model to reflect the button, thumbstick, and touchpad state
  75760. Object.values( this.motionController.components ).forEach( ( component ) => {
  75761. // Update node data based on the visual responses' current states
  75762. Object.values( component.visualResponses ).forEach( ( visualResponse ) => {
  75763. const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse;
  75764. // Skip if the visual response node is not found. No error is needed,
  75765. // because it will have been reported at load time.
  75766. if ( ! valueNode ) return;
  75767. // Calculate the new properties based on the weight supplied
  75768. if ( valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY ) {
  75769. valueNode.visible = value;
  75770. } else if ( valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM ) {
  75771. Quaternion.slerp(
  75772. minNode.quaternion,
  75773. maxNode.quaternion,
  75774. valueNode.quaternion,
  75775. value
  75776. );
  75777. valueNode.position.lerpVectors(
  75778. minNode.position,
  75779. maxNode.position,
  75780. value
  75781. );
  75782. }
  75783. } );
  75784. } );
  75785. }
  75786. } );
  75787. /**
  75788. * Walks the model's tree to find the nodes needed to animate the components and
  75789. * saves them to the motionContoller components for use in the frame loop. When
  75790. * touchpads are found, attaches a touch dot to them.
  75791. */
  75792. function findNodes( motionController, scene ) {
  75793. // Loop through the components and find the nodes needed for each components' visual responses
  75794. Object.values( motionController.components ).forEach( ( component ) => {
  75795. const { type, touchPointNodeName, visualResponses } = component;
  75796. if ( type === Constants.ComponentType.TOUCHPAD ) {
  75797. component.touchPointNode = scene.getObjectByName( touchPointNodeName );
  75798. if ( component.touchPointNode ) {
  75799. // Attach a touch dot to the touchpad.
  75800. const sphereGeometry = new SphereBufferGeometry( 0.001 );
  75801. const material = new MeshBasicMaterial( { color: 0x0000FF } );
  75802. const sphere = new Mesh( sphereGeometry, material );
  75803. component.touchPointNode.add( sphere );
  75804. } else {
  75805. console.warn( `Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${component.id}` );
  75806. }
  75807. }
  75808. // Loop through all the visual responses to be applied to this component
  75809. Object.values( visualResponses ).forEach( ( visualResponse ) => {
  75810. const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;
  75811. // If animating a transform, find the two nodes to be interpolated between.
  75812. if ( valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM ) {
  75813. visualResponse.minNode = scene.getObjectByName( minNodeName );
  75814. visualResponse.maxNode = scene.getObjectByName( maxNodeName );
  75815. // If the extents cannot be found, skip this animation
  75816. if ( ! visualResponse.minNode ) {
  75817. console.warn( `Could not find ${minNodeName} in the model` );
  75818. return;
  75819. }
  75820. if ( ! visualResponse.maxNode ) {
  75821. console.warn( `Could not find ${maxNodeName} in the model` );
  75822. return;
  75823. }
  75824. }
  75825. // If the target node cannot be found, skip this animation
  75826. visualResponse.valueNode = scene.getObjectByName( valueNodeName );
  75827. if ( ! visualResponse.valueNode ) {
  75828. console.warn( `Could not find ${valueNodeName} in the model` );
  75829. }
  75830. } );
  75831. } );
  75832. }
  75833. function addAssetSceneToControllerModel( controllerModel, scene ) {
  75834. // Find the nodes needed for animation and cache them on the motionController.
  75835. findNodes( controllerModel.motionController, scene );
  75836. // Apply any environment map that the mesh already has set.
  75837. if ( controllerModel.envMap ) {
  75838. scene.traverse( ( child ) => {
  75839. if ( child.isMesh ) {
  75840. child.material.envMap = controllerModel.envMap;
  75841. child.material.needsUpdate = true;
  75842. }
  75843. } );
  75844. }
  75845. // Add the glTF scene to the controllerModel.
  75846. controllerModel.add( scene );
  75847. }
  75848. var XRControllerModelFactory = ( function () {
  75849. function XRControllerModelFactory( gltfLoader = null ) {
  75850. this.gltfLoader = gltfLoader;
  75851. this.path = DEFAULT_PROFILES_PATH;
  75852. this._assetCache = {};
  75853. // If a GLTFLoader wasn't supplied to the constructor create a new one.
  75854. if ( ! this.gltfLoader ) {
  75855. this.gltfLoader = new GLTFLoader();
  75856. }
  75857. }
  75858. XRControllerModelFactory.prototype = {
  75859. constructor: XRControllerModelFactory,
  75860. createControllerModel: function ( controller ) {
  75861. const controllerModel = new XRControllerModel();
  75862. let scene = null;
  75863. controller.addEventListener( 'connected', ( event ) => {
  75864. const xrInputSource = event.data;
  75865. if ( xrInputSource.targetRayMode !== 'tracked-pointer' || ! xrInputSource.gamepad ) return;
  75866. fetchProfile( xrInputSource, this.path, DEFAULT_PROFILE ).then( ( { profile, assetPath } ) => {
  75867. controllerModel.motionController = new MotionController(
  75868. xrInputSource,
  75869. profile,
  75870. assetPath
  75871. );
  75872. const cachedAsset = this._assetCache[ controllerModel.motionController.assetUrl ];
  75873. if ( cachedAsset ) {
  75874. scene = cachedAsset.scene.clone();
  75875. addAssetSceneToControllerModel( controllerModel, scene );
  75876. } else {
  75877. if ( ! this.gltfLoader ) {
  75878. throw new Error( 'GLTFLoader not set.' );
  75879. }
  75880. this.gltfLoader.setPath( '' );
  75881. this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => {
  75882. this._assetCache[ controllerModel.motionController.assetUrl ] = asset;
  75883. scene = asset.scene.clone();
  75884. addAssetSceneToControllerModel( controllerModel, scene );
  75885. },
  75886. null,
  75887. () => {
  75888. throw new Error( `Asset ${controllerModel.motionController.assetUrl} missing or malformed.` );
  75889. } );
  75890. }
  75891. } ).catch( ( err ) => {
  75892. console.warn( err );
  75893. } );
  75894. } );
  75895. controller.addEventListener( 'disconnected', () => {
  75896. controllerModel.motionController = null;
  75897. controllerModel.remove( scene );
  75898. scene = null;
  75899. } );
  75900. return controllerModel;
  75901. }
  75902. };
  75903. return XRControllerModelFactory;
  75904. } )();
  75905. let fakeCam = new PerspectiveCamera();
  75906. function toScene(vec, ref){
  75907. let node = ref.clone();
  75908. node.updateMatrix();
  75909. node.updateMatrixWorld();
  75910. let result = vec.clone().applyMatrix4(node.matrix);
  75911. result.z -= 0.8 * node.scale.x;
  75912. return result;
  75913. };
  75914. function computeMove(vrControls, controller){
  75915. if(!controller || !controller.inputSource || !controller.inputSource.gamepad){
  75916. return null;
  75917. }
  75918. let pad = controller.inputSource.gamepad;
  75919. let axes = pad.axes;
  75920. // [0,1] are for touchpad, [2,3] for thumbsticks?
  75921. let y = 0;
  75922. if(axes.length === 2){
  75923. y = axes[1];
  75924. }else if(axes.length === 4){
  75925. y = axes[3];
  75926. }
  75927. y = Math.sign(y) * (2 * y) ** 2;
  75928. let maxSize = 0;
  75929. for(let pc of viewer.scene.pointclouds){
  75930. let size = pc.boundingBox.min.distanceTo(pc.boundingBox.max);
  75931. maxSize = Math.max(maxSize, size);
  75932. }
  75933. let multiplicator = Math.pow(maxSize, 0.5) / 2;
  75934. let scale = vrControls.node.scale.x;
  75935. let moveSpeed = viewer.getMoveSpeed();
  75936. let amount = multiplicator * y * (moveSpeed ** 0.5) / scale;
  75937. let rotation = new Quaternion().setFromEuler(controller.rotation);
  75938. let dir = new Vector3(0, 0, -1);
  75939. dir.applyQuaternion(rotation);
  75940. let move = dir.clone().multiplyScalar(amount);
  75941. let p1 = vrControls.toScene(controller.position);
  75942. let p2 = vrControls.toScene(controller.position.clone().add(move));
  75943. move = p2.clone().sub(p1);
  75944. return move;
  75945. };
  75946. class FlyMode{
  75947. constructor(vrControls){
  75948. this.moveFactor = 1;
  75949. this.dbgLabel = null;
  75950. }
  75951. start(vrControls){
  75952. if(!this.dbgLabel){
  75953. /* this.dbgLabel = new Potree.TextSprite("abc");
  75954. this.dbgLabel.name = "debug label";
  75955. vrControls.viewer.sceneVR.add(this.dbgLabel);
  75956. this.dbgLabel.visible = false; */
  75957. }
  75958. }
  75959. end(){
  75960. }
  75961. update(vrControls, delta){
  75962. let primary = vrControls.cPrimary;
  75963. let secondary = vrControls.cSecondary;
  75964. let move1 = computeMove(vrControls, primary);
  75965. let move2 = computeMove(vrControls, secondary);
  75966. if(!move1){
  75967. move1 = new Vector3();
  75968. }
  75969. if(!move2){
  75970. move2 = new Vector3();
  75971. }
  75972. let move = move1.clone().add(move2);
  75973. move.multiplyScalar(-delta * this.moveFactor);
  75974. vrControls.node.position.add(move);
  75975. let scale = vrControls.node.scale.x;
  75976. let camVR = vrControls.viewer.renderer.xr.getCamera(fakeCam);
  75977. let vrPos = camVR.getWorldPosition(new Vector3());
  75978. let vrDir = camVR.getWorldDirection(new Vector3());
  75979. let vrTarget = vrPos.clone().add(vrDir.multiplyScalar(scale));
  75980. let scenePos = toScene(vrPos, vrControls.node);
  75981. let sceneDir = toScene(vrPos.clone().add(vrDir), vrControls.node).sub(scenePos);
  75982. sceneDir.normalize().multiplyScalar(scale);
  75983. let sceneTarget = scenePos.clone().add(sceneDir);
  75984. vrControls.viewer.scene.view.setView(scenePos, sceneTarget);
  75985. if(Potree.debug.message){
  75986. this.dbgLabel.visible = true;
  75987. this.dbgLabel.setText(Potree.debug.message);
  75988. this.dbgLabel.scale.set(0.1, 0.1, 0.1);
  75989. this.dbgLabel.position.copy(primary.position);
  75990. }
  75991. }
  75992. };
  75993. class TranslationMode{
  75994. constructor(){
  75995. this.controller = null;
  75996. this.startPos = null;
  75997. this.debugLine = null;
  75998. }
  75999. start(vrControls){
  76000. this.controller = vrControls.triggered.values().next().value;
  76001. this.startPos = vrControls.node.position.clone();
  76002. }
  76003. end(vrControls){
  76004. }
  76005. update(vrControls, delta){
  76006. let start = this.controller.start.position;
  76007. let end = this.controller.position;
  76008. start = vrControls.toScene(start);
  76009. end = vrControls.toScene(end);
  76010. let diff = end.clone().sub(start);
  76011. diff.set(-diff.x, -diff.y, -diff.z);
  76012. let pos = new Vector3().addVectors(this.startPos, diff);
  76013. vrControls.node.position.copy(pos);
  76014. }
  76015. };
  76016. class RotScaleMode{
  76017. constructor(){
  76018. this.line = null;
  76019. this.startState = null;
  76020. }
  76021. start(vrControls){
  76022. if(!this.line){
  76023. this.line = Potree.Utils.debugLine(
  76024. vrControls.viewer.sceneVR,
  76025. new Vector3(0, 0, 0),
  76026. new Vector3(0, 0, 0),
  76027. 0xffff00,
  76028. );
  76029. this.dbgLabel = new Potree.TextSprite("abc");
  76030. this.dbgLabel.scale.set(0.1, 0.1, 0.1);
  76031. vrControls.viewer.sceneVR.add(this.dbgLabel);
  76032. }
  76033. this.line.node.visible = true;
  76034. this.startState = vrControls.node.clone();
  76035. }
  76036. end(vrControls){
  76037. this.line.node.visible = false;
  76038. this.dbgLabel.visible = false;
  76039. }
  76040. update(vrControls, delta){
  76041. let start_c1 = vrControls.cPrimary.start.position.clone();
  76042. let start_c2 = vrControls.cSecondary.start.position.clone();
  76043. let start_center = start_c1.clone().add(start_c2).multiplyScalar(0.5);
  76044. let start_c1_c2 = start_c2.clone().sub(start_c1);
  76045. let end_c1 = vrControls.cPrimary.position.clone();
  76046. let end_c2 = vrControls.cSecondary.position.clone();
  76047. let end_center = end_c1.clone().add(end_c2).multiplyScalar(0.5);
  76048. let end_c1_c2 = end_c2.clone().sub(end_c1);
  76049. let d1 = start_c1_c2.length();
  76050. let d2 = end_c1_c2.length();
  76051. let angleStart = new Vector2$1(start_c1_c2.x, start_c1_c2.z).angle();
  76052. let angleEnd = new Vector2$1(end_c1_c2.x, end_c1_c2.z).angle();
  76053. let angleDiff = angleEnd - angleStart;
  76054. let scale = d2 / d1;
  76055. let node = this.startState.clone();
  76056. node.updateMatrix();
  76057. node.matrixAutoUpdate = false;
  76058. let mToOrigin = new Matrix4().makeTranslation(...toScene(start_center, this.startState).multiplyScalar(-1).toArray());
  76059. let mToStart = new Matrix4().makeTranslation(...toScene(start_center, this.startState).toArray());
  76060. let mRotate = new Matrix4().makeRotationZ(angleDiff);
  76061. let mScale = new Matrix4().makeScale(1 / scale, 1 / scale, 1 / scale);
  76062. node.applyMatrix4(mToOrigin);
  76063. node.applyMatrix4(mRotate);
  76064. node.applyMatrix4(mScale);
  76065. node.applyMatrix4(mToStart);
  76066. let oldScenePos = toScene(start_center, this.startState);
  76067. let newScenePos = toScene(end_center, node);
  76068. let toNew = oldScenePos.clone().sub(newScenePos);
  76069. let mToNew = new Matrix4().makeTranslation(...toNew.toArray());
  76070. node.applyMatrix4(mToNew);
  76071. node.matrix.decompose(node.position, node.quaternion, node.scale );
  76072. vrControls.node.position.copy(node.position);
  76073. vrControls.node.quaternion.copy(node.quaternion);
  76074. vrControls.node.scale.copy(node.scale);
  76075. vrControls.node.updateMatrix();
  76076. {
  76077. let scale = vrControls.node.scale.x;
  76078. let camVR = vrControls.viewer.renderer.xr.getCamera(fakeCam);
  76079. let vrPos = camVR.getWorldPosition(new Vector3());
  76080. let vrDir = camVR.getWorldDirection(new Vector3());
  76081. let vrTarget = vrPos.clone().add(vrDir.multiplyScalar(scale));
  76082. let scenePos = toScene(vrPos, this.startState);
  76083. let sceneDir = toScene(vrPos.clone().add(vrDir), this.startState).sub(scenePos);
  76084. sceneDir.normalize().multiplyScalar(scale);
  76085. let sceneTarget = scenePos.clone().add(sceneDir);
  76086. vrControls.viewer.scene.view.setView(scenePos, sceneTarget);
  76087. vrControls.viewer.setMoveSpeed(scale);
  76088. }
  76089. { // update "GUI"
  76090. this.line.set(end_c1, end_c2);
  76091. let scale = vrControls.node.scale.x;
  76092. this.dbgLabel.visible = true;
  76093. this.dbgLabel.position.copy(end_center);
  76094. this.dbgLabel.setText(`scale: 1 : ${scale.toFixed(2)}`);
  76095. this.dbgLabel.scale.set(0.05, 0.05, 0.05);
  76096. }
  76097. }
  76098. };
  76099. class VRControls extends EventDispatcher{
  76100. constructor(viewer){
  76101. super(viewer);
  76102. this.viewer = viewer;
  76103. viewer.addEventListener("vr_start", this.onStart.bind(this));
  76104. viewer.addEventListener("vr_end", this.onEnd.bind(this));
  76105. this.node = new Object3D();
  76106. this.node.up.set(0, 0, 1);
  76107. this.triggered = new Set();
  76108. let xr = viewer.renderer.xr;
  76109. { // lights
  76110. const light = new PointLight( 0xffffff, 5, 0, 1 );
  76111. light.position.set(0, 2, 0);
  76112. this.viewer.sceneVR.add(light);
  76113. }
  76114. this.menu = null;
  76115. const controllerModelFactory = new XRControllerModelFactory();
  76116. let sg = new SphereGeometry(1, 32, 32);
  76117. let sm = new MeshNormalMaterial();
  76118. { // setup primary controller
  76119. let controller = xr.getController(0);
  76120. let grip = xr.getControllerGrip(0);
  76121. grip.name = "grip(0)";
  76122. // ADD CONTROLLERMODEL
  76123. grip.add( controllerModelFactory.createControllerModel( grip ) );
  76124. this.viewer.sceneVR.add(grip);
  76125. // ADD SPHERE
  76126. let sphere = new Mesh(sg, sm);
  76127. sphere.scale.set(0.005, 0.005, 0.005);
  76128. controller.add(sphere);
  76129. controller.visible = true;
  76130. this.viewer.sceneVR.add(controller);
  76131. { // ADD LINE
  76132. let lineGeometry = new LineGeometry();
  76133. lineGeometry.setPositions([
  76134. 0, 0, -0.15,
  76135. 0, 0, 0.05,
  76136. ]);
  76137. let lineMaterial = new LineMaterial({
  76138. color: 0xff0000,
  76139. lineWidth: 2,
  76140. resolution: new Vector2$1(1000, 1000),
  76141. });
  76142. const line = new Line2(lineGeometry, lineMaterial);
  76143. controller.add(line);
  76144. }
  76145. controller.addEventListener( 'connected', function ( event ) {
  76146. const xrInputSource = event.data;
  76147. controller.inputSource = xrInputSource;
  76148. // initInfo(controller);
  76149. });
  76150. controller.addEventListener( 'selectstart', () => {this.onTriggerStart(controller);});
  76151. controller.addEventListener( 'selectend', () => {this.onTriggerEnd(controller);});
  76152. this.cPrimary = controller;
  76153. }
  76154. { // setup secondary controller
  76155. let controller = xr.getController(1);
  76156. let grip = xr.getControllerGrip(1);
  76157. // ADD CONTROLLER MODEL
  76158. let model = controllerModelFactory.createControllerModel( grip );
  76159. grip.add(model);
  76160. this.viewer.sceneVR.add( grip );
  76161. // ADD SPHERE
  76162. let sphere = new Mesh(sg, sm);
  76163. sphere.scale.set(0.005, 0.005, 0.005);
  76164. controller.add(sphere);
  76165. controller.visible = true;
  76166. this.viewer.sceneVR.add(controller);
  76167. { // ADD LINE
  76168. let lineGeometry = new LineGeometry();
  76169. lineGeometry.setPositions([
  76170. 0, 0, -0.15,
  76171. 0, 0, 0.05,
  76172. ]);
  76173. let lineMaterial = new LineMaterial({
  76174. color: 0xff0000,
  76175. lineWidth: 2,
  76176. resolution: new Vector2$1(1000, 1000),
  76177. });
  76178. const line = new Line2(lineGeometry, lineMaterial);
  76179. controller.add(line);
  76180. }
  76181. controller.addEventListener( 'connected', (event) => {
  76182. const xrInputSource = event.data;
  76183. controller.inputSource = xrInputSource;
  76184. this.initMenu(controller);
  76185. });
  76186. controller.addEventListener( 'selectstart', () => {this.onTriggerStart(controller);});
  76187. controller.addEventListener( 'selectend', () => {this.onTriggerEnd(controller);});
  76188. this.cSecondary = controller;
  76189. }
  76190. this.mode_fly = new FlyMode();
  76191. this.mode_translate = new TranslationMode();
  76192. this.mode_rotScale = new RotScaleMode();
  76193. this.setMode(this.mode_fly);
  76194. }
  76195. createSlider(label, min, max){
  76196. let sg = new SphereGeometry(1, 8, 8);
  76197. let cg = new CylinderGeometry(1, 1, 1, 8);
  76198. let matHandle = new MeshBasicMaterial({color: 0xff0000});
  76199. let matScale = new MeshBasicMaterial({color: 0xff4444});
  76200. let matValue = new MeshNormalMaterial();
  76201. let node = new Object3D("slider");
  76202. let nLabel = new Potree.TextSprite(`${label}: 0`);
  76203. let nMax = new Mesh(sg, matHandle);
  76204. let nMin = new Mesh(sg, matHandle);
  76205. let nValue = new Mesh(sg, matValue);
  76206. let nScale = new Mesh(cg, matScale);
  76207. nLabel.scale.set(0.2, 0.2, 0.2);
  76208. nLabel.position.set(0, 0.35, 0);
  76209. nMax.scale.set(0.02, 0.02, 0.02);
  76210. nMax.position.set(0, 0.25, 0);
  76211. nMin.scale.set(0.02, 0.02, 0.02);
  76212. nMin.position.set(0, -0.25, 0);
  76213. nValue.scale.set(0.02, 0.02, 0.02);
  76214. nValue.position.set(0, 0, 0);
  76215. nScale.scale.set(0.005, 0.5, 0.005);
  76216. node.add(nLabel);
  76217. node.add(nMax);
  76218. node.add(nMin);
  76219. node.add(nValue);
  76220. node.add(nScale);
  76221. return node;
  76222. }
  76223. createInfo(){
  76224. let texture = new TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  76225. let plane = new PlaneBufferGeometry(1, 1, 1, 1);
  76226. let infoMaterial = new MeshBasicMaterial({map: texture});
  76227. let infoNode = new Mesh(plane, infoMaterial);
  76228. return infoNode;
  76229. }
  76230. initMenu(controller){
  76231. if(this.menu){
  76232. return;
  76233. }
  76234. let node = new Object3D("vr menu");
  76235. // let nSlider = this.createSlider("speed", 0, 1);
  76236. // let nInfo = this.createInfo();
  76237. // // node.add(nSlider);
  76238. // node.add(nInfo);
  76239. // {
  76240. // node.rotation.set(-1.5, 0, 0)
  76241. // node.scale.set(0.3, 0.3, 0.3);
  76242. // node.position.set(-0.2, -0.002, -0.1)
  76243. // // nInfo.position.set(0.5, 0, 0);
  76244. // nInfo.scale.set(0.8, 0.6, 0);
  76245. // // controller.add(node);
  76246. // }
  76247. // node.position.set(-0.3, 1.2, 0.2);
  76248. // node.scale.set(0.3, 0.2, 0.3);
  76249. // node.lookAt(new THREE.Vector3(0, 1.5, 0.1));
  76250. // this.viewer.sceneVR.add(node);
  76251. this.menu = node;
  76252. // window.vrSlider = nSlider;
  76253. window.vrMenu = node;
  76254. }
  76255. toScene(vec){
  76256. let camVR = this.getCamera();
  76257. let mat = camVR.matrixWorld;
  76258. let result = vec.clone().applyMatrix4(mat);
  76259. return result;
  76260. }
  76261. toVR(vec){
  76262. let camVR = this.getCamera();
  76263. let mat = camVR.matrixWorld.clone();
  76264. mat.invert();
  76265. let result = vec.clone().applyMatrix4(mat);
  76266. return result;
  76267. }
  76268. setMode(mode){
  76269. if(this.mode === mode){
  76270. return;
  76271. }
  76272. if(this.mode){
  76273. this.mode.end(this);
  76274. }
  76275. for(let controller of [this.cPrimary, this.cSecondary]){
  76276. let start = {
  76277. position: controller.position.clone(),
  76278. rotation: controller.rotation.clone(),
  76279. };
  76280. controller.start = start;
  76281. }
  76282. this.mode = mode;
  76283. this.mode.start(this);
  76284. }
  76285. onTriggerStart(controller){
  76286. this.triggered.add(controller);
  76287. if(this.triggered.size === 0){
  76288. this.setMode(this.mode_fly);
  76289. }else if(this.triggered.size === 1){
  76290. this.setMode(this.mode_translate);
  76291. }else if(this.triggered.size === 2){
  76292. this.setMode(this.mode_rotScale);
  76293. }
  76294. }
  76295. onTriggerEnd(controller){
  76296. this.triggered.delete(controller);
  76297. if(this.triggered.size === 0){
  76298. this.setMode(this.mode_fly);
  76299. }else if(this.triggered.size === 1){
  76300. this.setMode(this.mode_translate);
  76301. }else if(this.triggered.size === 2){
  76302. this.setMode(this.mode_rotScale);
  76303. }
  76304. }
  76305. onStart(){
  76306. let position = this.viewer.scene.view.position.clone();
  76307. let direction = this.viewer.scene.view.direction;
  76308. direction.multiplyScalar(-1);
  76309. let target = position.clone().add(direction);
  76310. target.z = position.z;
  76311. let scale = this.viewer.getMoveSpeed();
  76312. this.node.position.copy(position);
  76313. this.node.lookAt(target);
  76314. this.node.scale.set(scale, scale, scale);
  76315. this.node.updateMatrix();
  76316. this.node.updateMatrixWorld();
  76317. }
  76318. onEnd(){
  76319. }
  76320. setScene(scene){
  76321. this.scene = scene;
  76322. }
  76323. getCamera(){
  76324. let reference = this.viewer.scene.getActiveCamera();
  76325. let camera = new PerspectiveCamera();
  76326. // let scale = this.node.scale.x;
  76327. let scale = this.viewer.getMoveSpeed();
  76328. //camera.near = 0.01 / scale;
  76329. camera.near = 0.1;
  76330. camera.far = 1000;
  76331. // camera.near = reference.near / scale;
  76332. // camera.far = reference.far / scale;
  76333. camera.up.set(0, 0, 1);
  76334. camera.lookAt(new Vector3(0, -1, 0));
  76335. camera.updateMatrix();
  76336. camera.updateMatrixWorld();
  76337. camera.position.copy(this.node.position);
  76338. camera.rotation.copy(this.node.rotation);
  76339. camera.scale.set(scale, scale, scale);
  76340. camera.updateMatrix();
  76341. camera.updateMatrixWorld();
  76342. camera.matrixAutoUpdate = false;
  76343. camera.parent = camera;
  76344. return camera;
  76345. }
  76346. update(delta){
  76347. // if(this.mode === this.mode_fly){
  76348. // let ray = new THREE.Ray(origin, direction);
  76349. // for(let object of this.selectables){
  76350. // if(object.intersectsRay(ray)){
  76351. // object.onHit(ray);
  76352. // }
  76353. // }
  76354. // }
  76355. this.mode.update(this, delta);
  76356. }
  76357. };
  76358. // Adapted from three.js VRButton
  76359. class VRButton {
  76360. constructor(){
  76361. this.onStartListeners = [];
  76362. this.onEndListeners = [];
  76363. this.element = null;
  76364. }
  76365. onStart(callback){
  76366. this.onStartListeners.push(callback);
  76367. }
  76368. onEnd(callback){
  76369. this.onEndListeners.push(callback);
  76370. }
  76371. static async createButton( renderer, options ) {
  76372. if ( options ) {
  76373. console.error( 'THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.' );
  76374. }
  76375. const button = new VRButton();
  76376. const element = document.createElement( 'button' );
  76377. button.element = element;
  76378. function setEnter(){
  76379. button.element.innerHTML = `
  76380. <div style="font-size: 0.5em;">ENTER</div>
  76381. <div style="font-weight: bold;">VR</div>
  76382. `;
  76383. }
  76384. function setExit(){
  76385. button.element.innerHTML = `
  76386. <div style="font-size: 0.5em;">EXIT</div>
  76387. <div style="font-weight: bold;">VR</div>
  76388. `;
  76389. }
  76390. function showEnterVR( /*device*/ ) {
  76391. let currentSession = null;
  76392. function onSessionStarted( session ) {
  76393. session.addEventListener( 'end', onSessionEnded );
  76394. for(let listener of button.onStartListeners){
  76395. listener();
  76396. }
  76397. renderer.xr.setSession( session );
  76398. setExit();
  76399. currentSession = session;
  76400. }
  76401. function onSessionEnded( /*event*/ ) {
  76402. currentSession.removeEventListener( 'end', onSessionEnded );
  76403. for(let listener of button.onEndListeners){
  76404. listener();
  76405. }
  76406. setEnter();
  76407. currentSession = null;
  76408. }
  76409. //
  76410. button.element.style.display = '';
  76411. button.element.style.cursor = 'pointer';
  76412. setEnter();
  76413. button.element.onmouseenter = function () {
  76414. button.element.style.opacity = '1.0';
  76415. };
  76416. button.element.onmouseleave = function () {
  76417. button.element.style.opacity = '0.7';
  76418. };
  76419. button.element.onclick = function () {
  76420. if ( currentSession === null ) {
  76421. // WebXR's requestReferenceSpace only works if the corresponding feature
  76422. // was requested at session creation time. For simplicity, just ask for
  76423. // the interesting ones as optional features, but be aware that the
  76424. // requestReferenceSpace call will fail if it turns out to be unavailable.
  76425. // ('local' is always available for immersive sessions and doesn't need to
  76426. // be requested separately.)
  76427. const sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor', 'hand-tracking' ] };
  76428. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  76429. } else {
  76430. currentSession.end();
  76431. }
  76432. };
  76433. }
  76434. function stylizeElement( element ) {
  76435. element.style.position = 'absolute';
  76436. element.style.bottom = '20px';
  76437. element.style.padding = '12px 6px';
  76438. element.style.border = '1px solid #fff';
  76439. element.style.borderRadius = '4px';
  76440. element.style.background = 'rgba(0,0,0,0.1)';
  76441. element.style.color = '#fff';
  76442. element.style.font = 'normal 13px sans-serif';
  76443. element.style.textAlign = 'center';
  76444. element.style.opacity = '0.7';
  76445. element.style.outline = 'none';
  76446. element.style.zIndex = '999';
  76447. }
  76448. if ( 'xr' in navigator ) {
  76449. button.element.id = 'VRButton';
  76450. button.element.style.display = 'none';
  76451. stylizeElement( button.element );
  76452. let supported = await navigator.xr.isSessionSupported( 'immersive-vr' );
  76453. if(supported){
  76454. showEnterVR();
  76455. return button;
  76456. }else {
  76457. return null;
  76458. }
  76459. } else {
  76460. if ( window.isSecureContext === false ) {
  76461. console.log("WEBXR NEEDS HTTPS");
  76462. } else {
  76463. console.log("WEBXR not available");
  76464. }
  76465. return null;
  76466. }
  76467. }
  76468. }
  76469. //处理cursor优先级
  76470. var CursorDeal = {
  76471. priorityEvent : [//在前面的优先级高
  76472. {'zoomInCloud':'zoom-in'},
  76473. {'hoverPano':'pointer'},
  76474. {'connectPano':`url({Potree.resourcePath}/images/connect.png),auto`},
  76475. {'disconnectPano':`url({Potree.resourcePath}/images/connect-dis.png),auto`},
  76476. {'hoverLine':'pointer'},
  76477. {"movePointcloud":'move'},
  76478. {"polygon_isIntersectSelf":'not-allowed'},
  76479. {"polygon_AtWrongPlace":'not-allowed'},
  76480. {"markerMove":'grab'},
  76481. {'mapClipMove':'move'},
  76482. {'mapClipRotate':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76483. {'rotatePointcloud':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76484. {'siteModelFloorDrag':'row-resize'},
  76485. {'addSth':'cell'},//or crosshair
  76486. ],
  76487. list:[], //当前存在的cursor状态
  76488. currentCursorIndex:null,
  76489. init : function(viewer, viewers){
  76490. this.priorityEvent.forEach(e=>{//刚开始Potree.resourcePath没值,现在换
  76491. for(let i in e){
  76492. e[i] = Common.replaceAll(e[i],'{Potree.resourcePath}',Potree.resourcePath);
  76493. }
  76494. });
  76495. this.domElements = viewers.map(e=>e.renderArea);
  76496. viewer.addEventListener("CursorChange",(e)=>{
  76497. if(e.action == 'add'){
  76498. this.add(e.name);
  76499. }else {
  76500. this.remove(e.name);
  76501. }
  76502. });
  76503. },
  76504. add : function(name){
  76505. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76506. if(!priorityItem){
  76507. console.error('CursorDeal 未定义优先级 name:'+ name);
  76508. return
  76509. }
  76510. if(!this.list.includes(name)){
  76511. this.judge({addItem: priorityItem, name});
  76512. this.list.push(name);
  76513. }
  76514. },
  76515. remove : function(name){
  76516. var index = this.list.indexOf(name);
  76517. if(index > -1){
  76518. this.list.splice(index, 1);
  76519. this.judge();
  76520. }
  76521. },
  76522. judge:function(o={}){
  76523. //console.log(o,this.list)
  76524. if(o.addItem){
  76525. var addIndex = this.priorityEvent.indexOf(o.addItem);
  76526. if(addIndex < this.currentCursorIndex || this.currentCursorIndex == void 0){
  76527. this.domElements.forEach(e=>e.style.cursor = o.addItem[o.name] );
  76528. this.currentCursorIndex = addIndex;
  76529. }
  76530. }else {
  76531. var levelMax = {index:Infinity, cursor:null };
  76532. this.list.forEach(name=>{
  76533. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76534. var index = this.priorityEvent.indexOf(priorityItem);
  76535. if(index < levelMax.index){
  76536. levelMax.index = index;
  76537. levelMax.cursor = priorityItem[name];
  76538. }
  76539. });
  76540. this.currentCursorIndex = levelMax.index;
  76541. this.domElements.forEach(e=>e.style.cursor = levelMax.cursor || '');
  76542. }
  76543. }
  76544. };
  76545. let texLoader$6 = new TextureLoader();
  76546. let color$1 = new Color(config$1.clip.color);
  76547. let markerMats$1;
  76548. let markerSizeInfo$1 = {width2d:30};
  76549. class mapClipBox extends ctrlPolygon {
  76550. constructor (center, scale) {
  76551. center = center.clone().setZ(0);//所有Z都为0
  76552. let prop = {
  76553. points : getPoints(center, scale, 0),
  76554. closed : true,
  76555. isRect : true,
  76556. dimension : '2d'
  76557. };
  76558. super('mapClipBox', prop);
  76559. this.angle = 0;
  76560. this.createRotateBar();
  76561. this.edgeMarkers = [];
  76562. //addMarkers:
  76563. this.initData(prop);
  76564. {//areaPlane event 能拖动
  76565. this.areaPlane.addEventListener('mouseover',()=>{
  76566. viewer.dispatchEvent({
  76567. type : "CursorChange", action : "add", name:"mapClipMove"
  76568. });
  76569. });
  76570. this.areaPlane.addEventListener('mouseleave',()=>{
  76571. viewer.dispatchEvent({
  76572. type : "CursorChange", action : "remove", name:"mapClipMove"
  76573. });
  76574. });
  76575. let lastPos;
  76576. let drag = (e)=>{
  76577. let intersect = e.intersect.orthoIntersect;
  76578. if(lastPos){
  76579. let moveVec = new Vector3().subVectors(intersect, lastPos).setZ(0);
  76580. this.center.add(moveVec);
  76581. this.updatePoints();
  76582. this.dispatchEvent({type:'repos'});
  76583. }
  76584. lastPos = intersect.clone();
  76585. };
  76586. let drop = (e)=>{
  76587. lastPos = null;
  76588. };
  76589. this.areaPlane.addEventListener('drag', drag);
  76590. this.areaPlane.addEventListener('drop', drop);
  76591. }
  76592. /* this.addEventListener('dragChange',()=>{
  76593. this.updateTwoMidMarker(index+1)
  76594. }) */
  76595. viewer.setObjectLayers(this, 'mapObjects' );
  76596. }
  76597. getScale(){
  76598. return new Vector3(this.points[0].distanceTo(this.points[1]), this.points[1].distanceTo(this.points[2]) ,1)
  76599. }
  76600. addMarker(o={} ){
  76601. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_marker", } );
  76602. marker.renderOrder = 3;
  76603. //marker.markerSelectStates = {}
  76604. let edge = LineDraw.createLine([new Vector3,new Vector3],{color: color$1 });
  76605. let edgeMarker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_edgePoint"} );
  76606. let mouseover = (e) => {
  76607. this.setMarkerSelected(e.object, true, 'single');
  76608. viewer.dispatchEvent({
  76609. type : "CursorChange", action : "add", name:"markerMove"
  76610. });
  76611. };
  76612. let mouseleave = (e) => {
  76613. this.setMarkerSelected(e.object, false, 'single');
  76614. viewer.dispatchEvent({
  76615. type : "CursorChange", action : "remove", name:"markerMove"
  76616. });
  76617. };
  76618. edgeMarker.addEventListener('mouseover', mouseover);
  76619. edgeMarker.addEventListener('mouseleave', mouseleave);
  76620. let dragInfo = {lastPos:null};
  76621. edgeMarker.addEventListener('drag', this.dragEdge.bind(this,dragInfo));
  76622. edgeMarker.addEventListener('drop', this.dropEdge.bind(this,dragInfo));
  76623. this.edgeMarkers.push(edgeMarker);
  76624. this.add(edgeMarker);
  76625. marker.dispatchEvent('addHoverEvent');
  76626. super.addMarker({point:o.point, marker:marker, edge});
  76627. }
  76628. dragEdge(dragInfo, e){//拖拽一个边(或一个边类型的marker),带动它的两个端点。 可以转化为拖拽marker往法线方向
  76629. var I, atMap;
  76630. atMap = e.dragViewport.name == 'mapViewport';
  76631. I = e.intersect.orthoIntersect;
  76632. if (I && dragInfo.lastPos) {
  76633. let i = this.edgeMarkers.indexOf(e.drag.object);
  76634. if (i !== -1) {
  76635. let lineNormal = math.getNormal2d({p1:this.points[i], p2:this.points[(i+1)%4]});
  76636. let moveVec = new Vector3().subVectors(I, dragInfo.lastPos).setZ(0);//移动的向量
  76637. let dragVec = moveVec.projectOnVector(lineNormal).setZ(0);//在法线上移动的向量
  76638. let newPos = new Vector3().addVectors(this.points[i], dragVec); //marker应到的位置
  76639. this.dragChange(newPos, i, atMap); //转化为这个marker的拖拽
  76640. }
  76641. }
  76642. dragInfo.lastPos = I.clone();
  76643. }
  76644. dropEdge(dragInfo, e){
  76645. dragInfo.lastPos = null;
  76646. this.setMarkerSelected(e.drag.object, false, 'single'); //拖拽时似乎没有触发mouseout
  76647. }
  76648. createAreaPlane(){
  76649. var planeMat = new MeshBasicMaterial({
  76650. color: color$1,//"#00eeff",
  76651. side:DoubleSide,
  76652. opacity:0.3,
  76653. transparent:true,
  76654. depthTest:false
  76655. });
  76656. return super.createAreaPlane(planeMat)
  76657. }
  76658. getMarkerMaterial(type) {
  76659. if(!markerMats$1){
  76660. markerMats$1 = {
  76661. default: new MeshBasicMaterial({
  76662. transparent: !0,
  76663. color: color$1,
  76664. opacity: 0.8,
  76665. map: texLoader$6.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76666. }),
  76667. select: new MeshBasicMaterial({
  76668. transparent: !0,
  76669. color: color$1,
  76670. opacity: 1,
  76671. map: texLoader$6.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76672. }),
  76673. };
  76674. mapClipBox.markerMats = markerMats$1;
  76675. }
  76676. return markerMats$1[type]
  76677. }
  76678. setMarkerSelected(marker, state, hoverObject){
  76679. //console.warn(marker.id , state, hoverObject)
  76680. if(state == 'hover'){
  76681. marker.material = this.getMarkerMaterial('select');
  76682. }else {
  76683. marker.material = this.getMarkerMaterial('default');
  76684. }
  76685. /* marker.markerSelectStates[hoverObject] = state
  76686. let absoluteState = false
  76687. for(var i in marker.markerSelectStates){
  76688. if(marker.markerSelectStates[i]){
  76689. absoluteState = true; break;
  76690. }
  76691. }
  76692. if(absoluteState){
  76693. marker.material = this.getMarkerMaterial('select')
  76694. }else{
  76695. marker.material = this.getMarkerMaterial('default')
  76696. }
  76697. marker.selected = absoluteState */
  76698. viewer.mapViewer.dispatchEvent('content_changed');
  76699. }
  76700. createRotateBar(){
  76701. //中心点在线的一端,整体初始在box上方
  76702. const lineLen = 1.5, circleWidth = 2, barOpacity = 0.7;
  76703. let object = new Object3D;
  76704. let bar = new Sprite$1({mat:new MeshBasicMaterial({
  76705. side:DoubleSide,
  76706. opacity: barOpacity,
  76707. transparent:true,
  76708. depthTest:false,
  76709. map: texLoader$6.load(Potree.resourcePath+'/textures/rotation_circle.png' ),
  76710. }) ,
  76711. root:object,
  76712. sizeInfo: markerSizeInfo$1,
  76713. dontFixOrient: true,
  76714. viewports:viewer.mapViewer.viewports,
  76715. name:"mapClipRotateBar"
  76716. });
  76717. bar.position.set(0,lineLen+circleWidth/2,0);
  76718. bar.scale.set(circleWidth,circleWidth,circleWidth);
  76719. bar.addEventListener('mouseover',()=>{
  76720. bar.material.opacity = 1;
  76721. viewer.dispatchEvent({
  76722. type : "CursorChange", action : "add", name:"mapClipRotate"
  76723. });
  76724. viewer.mapViewer.dispatchEvent('content_changed');
  76725. });
  76726. let leave = ()=>{
  76727. bar.material.opacity = barOpacity;
  76728. viewer.dispatchEvent({
  76729. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76730. });
  76731. viewer.mapViewer.dispatchEvent('content_changed');
  76732. };
  76733. bar.addEventListener('mouseleave',leave);
  76734. this.addEventListener('dispose', leave);
  76735. let lastPos;
  76736. bar.addEventListener('drag',(e)=>{
  76737. var intersect = e.intersect.orthoIntersect;
  76738. if(lastPos){
  76739. let vec1 = new Vector3().subVectors(lastPos, this.center).setZ(0);
  76740. let vec2 = new Vector3().subVectors(intersect, this.center).setZ(0);
  76741. let angle = math.getAngle(vec1,vec2,'z');
  76742. this.angle += angle;
  76743. this.rotateBar.rotation.z = this.angle;
  76744. this.updatePoints();
  76745. this.dispatchEvent({type:'rotate', angle: this.angle});
  76746. }
  76747. lastPos = intersect.clone();
  76748. });
  76749. bar.addEventListener('drop',()=>{
  76750. lastPos = null;
  76751. viewer.dispatchEvent({
  76752. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76753. });
  76754. });
  76755. let line = LineDraw.createLine([new Vector3, new Vector3(0,lineLen,0)],{color: color$1});
  76756. object.add(bar);
  76757. object.add(line);
  76758. this.add(object);
  76759. this.rotateBar = object;
  76760. this.rotateBar.bar = bar;
  76761. }
  76762. updatePoints(scale){
  76763. this.points = getPoints(this.center, scale || this.getScale(), this.angle);
  76764. this.getPoint2dInfo(this.points);
  76765. this.update({ifUpdateMarkers:true});
  76766. }
  76767. update(options={}){
  76768. super.update(options);
  76769. {//update rotateBar
  76770. let center = new Vector3().addVectors(this.points[0], this.points[1]).multiplyScalar(0.5);
  76771. this.rotateBar.position.copy(center);
  76772. this.rotateBar.bar.update();//更新sprite matrix
  76773. }
  76774. {
  76775. for(let i=0;i<4;i++){
  76776. let current = this.points[i];
  76777. let next = this.points[(i+1)%4];
  76778. let mid = new Vector3().addVectors(current, next).multiplyScalar(0.5);
  76779. this.updateMarker(this.edgeMarkers[i], mid);
  76780. }
  76781. }
  76782. }
  76783. dispose(){
  76784. super.dispose();
  76785. this.dispatchEvent('dispose');
  76786. }
  76787. }
  76788. function getPoints(center, scale, angle=0){
  76789. let points = [
  76790. new Vector3(-scale.x/2, +scale.y/2, 0),
  76791. new Vector3(+scale.x/2, +scale.y/2, 0),
  76792. new Vector3(+scale.x/2, -scale.y/2, 0),
  76793. new Vector3(-scale.x/2, -scale.y/2, 0),
  76794. ];
  76795. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  76796. points.forEach(e=>{
  76797. e.applyMatrix4(rotMatrix);
  76798. e.add(center);
  76799. });
  76800. return points
  76801. }
  76802. const defaultBoxWidth = 6; //navvis: 10
  76803. //navvis position: si {x: 0, y: 0, z: 0}
  76804. var Clip = {
  76805. bus : new EventDispatcher,
  76806. selectedDatasets : [],
  76807. changeCallback(force){
  76808. if(Potree.settings.isOfficial){
  76809. Common.intervalTool.isWaiting('clipSelectedDatasets', ()=>{ //延时update,防止卡顿
  76810. let pointclouds = this.getIntersectPointcloud();
  76811. if(force || Common.getDifferenceSet(pointclouds,this.selectedDatasets).length){
  76812. this.selectedDatasets = pointclouds;
  76813. //console.error('clipSelectedDatasets',selectedDatasets)
  76814. this.bus.dispatchEvent({type:'updateSelectedDatasets', selectedDatasets:pointclouds.map(e=>e.dataset_id) });
  76815. force = false;
  76816. return true
  76817. }
  76818. }, 300);
  76819. }
  76820. },
  76821. enter:function(){
  76822. this.previousView = {
  76823. position: viewer.images360.position,
  76824. target: viewer.scene.view.getPivot(),
  76825. displayMode : Potree.settings.displayMode,
  76826. //---
  76827. ifShowMarker : Potree.settings.ifShowMarker,
  76828. };
  76829. let pointcloud = this.getPointcloud();
  76830. let bound = pointcloud.bound; //只选取其中一个数据集的bound,而非整体,是因为担心两个数据集中间有空隙,于是刚好落在没有点云的地方。
  76831. let boundSize = bound.getSize(new Vector3());
  76832. let target = this.getTarget(bound.getCenter(new Vector3())); //navvis的位置xy是用相机位置 this.ViewService.mainView.getCamera().position 我觉得也可以用第一个漫游点的,或者最接近bound中心的漫游点
  76833. let scale = new Vector3(defaultBoxWidth,defaultBoxWidth, boundSize.z);//z和navvis一样
  76834. let eyeDir = viewer.scene.view.direction.clone().setZ(0/* -boundSize.z/3 */).multiplyScalar(-defaultBoxWidth); //为了使所在楼层不变,不修改z
  76835. //let eyeDir = scale.clone().setZ(boundSize.z/3).multiplyScalar(1.3)
  76836. let position = new Vector3().addVectors(target, eyeDir);
  76837. Potree.settings.displayMode = 'showPointCloud';
  76838. viewer.setView({
  76839. position ,
  76840. target,
  76841. duration:300,
  76842. callback:function(){
  76843. }
  76844. });
  76845. viewer.setControls(viewer.orbitControls);
  76846. viewer.setLimitFar(false);
  76847. {
  76848. this.box = new BoxVolume({
  76849. clip:true
  76850. });
  76851. this.box.name = "ClipBox";
  76852. this.box.position.copy(target);
  76853. this.box.scale.copy(scale);
  76854. //带动mapBox
  76855. this.box.addEventListener('position_changed',e=>{
  76856. this.mapBox.center.setX(this.box.position.x);
  76857. this.mapBox.center.setY(this.box.position.y);
  76858. this.mapBox.updatePoints();
  76859. this.changeCallback();
  76860. });
  76861. this.box.addEventListener('scale_changed',e=>{
  76862. var scale = this.box.scale;
  76863. this.mapBox.updatePoints(scale);
  76864. this.changeCallback();
  76865. });
  76866. this.box.addEventListener('orientation_changed',e=>{
  76867. this.mapBox.angle = this.box.rotation.z;
  76868. this.mapBox.rotateBar.rotation.z = this.mapBox.angle;
  76869. this.mapBox.updatePoints();
  76870. this.changeCallback();
  76871. });
  76872. viewer.scene.addVolume(this.box);
  76873. }
  76874. {//map
  76875. let boxRotateBack = ()=>{//不知道是不是这么写。 因为可能z的旋转不一定都在z
  76876. this.box.rotation.x = 0;
  76877. this.box.rotation.y = 0;
  76878. };
  76879. this.mapBox = new mapClipBox(target, scale);
  76880. viewer.mapViewer.scene.add(this.mapBox);
  76881. //带动box
  76882. this.mapBox.addEventListener('repos',e=>{
  76883. this.box.position.setX(this.mapBox.center.x);
  76884. this.box.position.setY(this.mapBox.center.y);
  76885. boxRotateBack();
  76886. this.changeCallback();
  76887. });
  76888. this.mapBox.addEventListener('dragChange',e=>{
  76889. var scale = this.mapBox.getScale();
  76890. this.box.scale.setX(scale.x);
  76891. this.box.scale.setY(scale.y);
  76892. this.box.position.setX(this.mapBox.center.x);
  76893. this.box.position.setY(this.mapBox.center.y);
  76894. boxRotateBack();
  76895. this.changeCallback();
  76896. });
  76897. this.mapBox.addEventListener('rotate',e=>{
  76898. this.box.rotation.z = this.mapBox.angle;
  76899. boxRotateBack();
  76900. this.changeCallback();
  76901. });
  76902. }
  76903. {
  76904. viewer.setClipTask(ClipTask["SHOW_INSIDE"]);
  76905. //viewer.setClipMethod(ClipMethod["INSIDE_ANY"])
  76906. }
  76907. Potree.settings.unableNavigate = true;
  76908. Potree.settings.ifShowMarker = false;
  76909. viewer.updateVisible(viewer.measuringTool.scene, 'clipModel', false);
  76910. //viewer.updateVisible(viewer.mapViewer.cursor, 'clipModel', false)//隐藏地图游标
  76911. viewer.inputHandler.toggleSelection(this.box);
  76912. viewer.inputHandler.fixSelection = true;
  76913. viewer.transformationTool.frame.material.color.set(Potree.config.clip.color);//navvis 15899953
  76914. viewer.setPointStandardMat(true);
  76915. {
  76916. this.events = {
  76917. flyToPos : (e)=>{
  76918. let dis = 2;
  76919. let target = e.position;
  76920. //position = new THREE.Vector3().subVectors(target, this.scene.view.direction)
  76921. //永远朝向框的中心
  76922. /* let dir = new THREE.Vector3().subVectors(this.box.position, e.position).normalize()
  76923. position = new THREE.Vector3().subVectors(target, dir) */
  76924. target = this.box.position;
  76925. position = e.position;
  76926. //为了方便缩放操作,直接使用box中心作为target
  76927. let duration = 1000;
  76928. viewer.scene.view.setView({position, duration, target});
  76929. }
  76930. };
  76931. this.bus.addEventListener('flyToPos',this.events.flyToPos);
  76932. }
  76933. this.editing = true;
  76934. setTimeout(()=>{this.changeCallback(true);},1);
  76935. },
  76936. leave:function(){
  76937. viewer.inputHandler.fixSelection = false;
  76938. viewer.scene.removeVolume(this.box);
  76939. this.mapBox.dispose();
  76940. viewer.setControls(viewer.fpControls);
  76941. Potree.settings.unableNavigate = false;
  76942. Potree.settings.ifShowMarker = this.previousView.ifShowMarker;
  76943. viewer.updateVisible(viewer.measuringTool.scene, 'clipModel', true);
  76944. //viewer.updateVisible(viewer.mapViewer.cursor, 'clipModel', true)
  76945. viewer.setView(this.previousView);
  76946. viewer.setLimitFar(true);
  76947. viewer.setPointStandardMat(false);
  76948. {
  76949. this.bus.removeEventListener('flyToPos',this.events.flyToPos);
  76950. this.events = null;
  76951. }
  76952. this.editing = false;
  76953. },
  76954. getPointcloud:function(){ //找一个离当前最近的点云,且最好有漫游点
  76955. let pointclouds = viewer.scene.pointclouds.filter(e=>e.panos.length>0);
  76956. if(pointclouds.length == 0)pointclouds = viewer.scene.pointclouds;
  76957. let result = Common.sortByScore(pointclouds,[],[e=>{
  76958. let center = e.bound.getCenter(new Vector3);
  76959. let size = e.bound.getSize(new Vector3).length() / 2;
  76960. let posToCenter = viewer.images360.position.distanceTo(center);
  76961. return size / posToCenter
  76962. }]);
  76963. return result[0].item
  76964. },
  76965. getTarget:function(boundCenter){//box位置。要找一个有点云的地方。方案1相机位置, 方案2接近相机的漫游点, 方案3接近中心的漫游点。选择方案2,因最大概率有点云
  76966. var target = new Vector3();
  76967. var cameraPos = viewer.images360.position;
  76968. var pano = Common.find(viewer.images360.panos , [], [Images360.sortFunctions.floorDisSquaredToPoint(cameraPos)]);
  76969. if(pano){
  76970. target.copy(pano.position);
  76971. target.setZ(boundCenter.z);
  76972. }else {
  76973. target.copy(boundCenter);
  76974. }
  76975. return target
  76976. },
  76977. /* switchMap:function(state){
  76978. }, */
  76979. download:function( ){
  76980. if(this.getIntersectPointcloud().length == 0){
  76981. return null
  76982. }
  76983. var visiPointclouds = viewer.scene.pointclouds.filter(e=> viewer.getObjVisiByReason(e, 'datasetSelection'));
  76984. let data = {
  76985. transformation_matrix: visiPointclouds.map((cloud)=>{
  76986. let data = {
  76987. id: cloud.dataset_id,
  76988. matrix : this.getTransformationMatrix(cloud).elements,
  76989. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  76990. };
  76991. return data
  76992. }) ,
  76993. aabb: "b-0.5 -0.5 -0.5 0.5 0.5 0.5" //剪裁空间( 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的
  76994. };
  76995. return data
  76996. //https://testlaser.4dkankan.com/indoor/t-ia44BhY/api/pointcloud/crop
  76997. },
  76998. downloadNoCrop(){//不剪裁 下载整个点云
  76999. var visiPointclouds = viewer.scene.pointclouds.filter(e=> viewer.getObjVisiByReason(e, 'datasetSelection'));
  77000. let data = {
  77001. transformation_matrix: visiPointclouds.map((cloud)=>{
  77002. let data = {
  77003. id: cloud.dataset_id,
  77004. matrix : new Matrix4().elements, //固定值
  77005. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  77006. };
  77007. return data
  77008. }) ,
  77009. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //固定剪裁空间
  77010. };
  77011. console.log(data);
  77012. return data
  77013. },
  77014. getTransformationMatrix:function(pointcloud) {//剪裁矩阵
  77015. var invMatrix = new Matrix4().getInverse(this.box.matrixWorld);
  77016. return (new Matrix4).multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose()
  77017. },
  77018. getIntersectPointcloud(){
  77019. var boxBound = new Box3(
  77020. new Vector3(-0.5,-0.5,-0.5), new Vector3(0.5,0.5,0.5),
  77021. ).applyMatrix4(this.box.matrixWorld); //large boundingbox
  77022. /* var boxTightPoints = this.box.children[0].geometry.vertices.map(e=>e.clone().applyMatrix4(this.matrixWorld))
  77023. console.log(boxTightPoints)
  77024. */
  77025. let boxMatrixInverse = new Matrix4().copy(this.box.matrixWorld).invert();
  77026. let boxPoints = [
  77027. new Vector3(boxBound.min.x, boxBound.min.y,0),
  77028. new Vector3(boxBound.max.x, boxBound.min.y,0),
  77029. new Vector3(boxBound.max.x, boxBound.max.y,0),
  77030. new Vector3(boxBound.min.x, boxBound.max.y,0)
  77031. ];
  77032. var intersect = (pointcloud)=>{
  77033. if(!pointcloud.bound.intersectsBox(boxBound))return false
  77034. //判断box和点云的tight bound是否相交(因为box可以任意旋转,且实在找不到三维中的立方体相交的函数,所以直接用boxBound)
  77035. var points = pointcloud.getUnrotBoundPoint('all');
  77036. let rings = math.getPolygonsMixedRings([points.slice(0,4), boxPoints] , true);
  77037. //console.log(pointcloud.dataset_id, pointcloud.name, rings.length)
  77038. if(rings.length > 1 )return false
  77039. {//再用frustum和数据集的sphere相交试试,能排除一些错误
  77040. let a = Potree.Utils.isInsideBox(points, boxMatrixInverse);
  77041. if(!a){
  77042. console.log('没能经过isInsideBox测试');
  77043. }
  77044. return a
  77045. }
  77046. return true
  77047. };
  77048. return viewer.scene.pointclouds.filter(e=>intersect(e))
  77049. }
  77050. /*
  77051. 裁剪点云时,2D界面显示全部平面图,按楼层切换显示。
  77052. */
  77053. };
  77054. class SplitScreen extends EventDispatcher{
  77055. constructor (args = {}) {
  77056. super();
  77057. }
  77058. splitStart(cameraProps){
  77059. let viewports = [];
  77060. let subViewports = [viewer.mainViewport];
  77061. if(viewer.mapViewer){
  77062. subViewports.push(viewer.mapViewer.viewports[0]);
  77063. }
  77064. let length = cameraProps.length;
  77065. for(let i=0;i<length;i++){
  77066. let prop = cameraProps[i];
  77067. let viewport;
  77068. let v = subViewports.find(e=>e.name == (prop.name2||prop.name));
  77069. if(v){
  77070. viewport = v;
  77071. viewport.left = prop.left; viewport.bottom = prop.bottom; viewport.width = prop.width; viewport.height = prop.height;
  77072. }
  77073. if(!viewport){
  77074. let view = new View();
  77075. if(prop.limitBound)view.limitBound = prop.limitBound;
  77076. prop.direction && (view.direction = prop.direction);
  77077. viewport = new Viewport(view , this.getOrthoCamera(), prop );
  77078. if(prop.viewContainsPoints)viewport.viewContainsPoints = prop.viewContainsPoints;
  77079. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  77080. }
  77081. if(viewport.camera.type == 'OrthographicCamera' ){
  77082. viewport.targetPlane = new Plane();
  77083. viewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  77084. }
  77085. viewport.fitMargin = prop.margin;
  77086. viewports.push(viewport);
  77087. }
  77088. viewer.viewports = viewports;
  77089. viewer.updateScreenSize({forceUpdateSize:true});
  77090. viewports.forEach(viewport=>{
  77091. if(viewport.name == 'MainView')return
  77092. this.viewportFitBound(viewport, viewer.bound.boundingBox , viewer.bound.center , 0, viewport.fitMargin);
  77093. });
  77094. return viewports
  77095. }
  77096. unSplit(){
  77097. this.unfocusViewport();
  77098. viewer.viewports = [viewer.mainViewport];
  77099. viewer.mainViewport.width = 1;
  77100. viewer.mainViewport.height = 1;
  77101. viewer.mainViewport.left = 0;
  77102. viewer.mainViewport.bottom = 0;
  77103. viewer.updateScreenSize({forceUpdateSize:true});
  77104. }
  77105. viewportFitBound(viewport, bound, center, duration=0, margin){
  77106. let view = viewport.view;
  77107. let info = {bound};
  77108. let {boundSize, boundCenter} = this.getViewBound(viewport);
  77109. viewport.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), boundCenter );
  77110. viewport.targetPlane.projectPoint(center, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  77111. info.endPosition = this.getPosOutOfModel(viewport, boundSize);
  77112. //if(viewport.name == 'mapViewport')info.endPosition.z = Math.max(Potree.config.map.cameraHeight, info.endPosition.z)
  77113. info.margin = margin || {x:30, y:30};
  77114. view.moveOrthoCamera(viewport, info , duration );
  77115. }
  77116. getViewBound(viewport){
  77117. let {boundSize, center} = viewer.bound;
  77118. if(viewport.viewContainsPoints){//视野范围内必须要包含的点,直接算入模型区域。这时候得到的boundCenter和模型中心不重合
  77119. let boundingBox = viewer.bound.boundingBox.clone();
  77120. viewport.viewContainsPoints.forEach(point=>{
  77121. boundingBox.expandByPoint(point);
  77122. });
  77123. boundSize = boundingBox.getSize(new Vector3);
  77124. center = boundingBox.getCenter(new Vector3);
  77125. }
  77126. return {boundSize, boundCenter:center }
  77127. }
  77128. getPosOutOfModel(viewport, boundSize){
  77129. //let {boundSize, center} = viewer.bound
  77130. boundSize = boundSize || this.getViewBound(viewport).boundSize;
  77131. let expand = 10;
  77132. let radius = boundSize.length(); // / 2
  77133. let position = viewport.shiftTarget.clone().sub(viewport.view.direction.clone().multiplyScalar(radius + expand));
  77134. return position
  77135. }
  77136. updateCameraOutOfModel(){//因为移动模型导致模型超出相机外,所以更新位置
  77137. viewer.viewports.forEach((viewport, i )=>{
  77138. if(viewport != viewer.mainViewport){
  77139. let {boundSize, boundCenter} = this.getViewBound(viewport);
  77140. viewport.targetPlane.setFromNormalAndCoplanarPoint( viewport.view.direction.clone(), boundCenter);
  77141. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  77142. let endPosition = this.getPosOutOfModel(viewport, boundSize);
  77143. //if(viewport.name == 'mapViewport')endPosition.z = Math.max(Potree.config.map.cameraHeight, endPosition.z)
  77144. viewport.view.position.copy(endPosition);
  77145. }
  77146. });
  77147. }
  77148. rotateSideCamera(viewport, angle){//侧视图绕模型中心水平旋转
  77149. //let {boundSize, center} = viewer.bound
  77150. let {boundSize, boundCenter } = this.getViewBound(viewport);
  77151. let center = this.focusCenter || boundCenter; //旋转中心,一般是所有模型的中心,除非想指定中心点
  77152. //找到平移向量
  77153. viewport.targetPlane.setFromNormalAndCoplanarPoint(viewport.view.direction , center );
  77154. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  77155. let vec = new Vector3().subVectors(center, viewport.shiftTarget);//相对于中心的偏移值,旋转后偏移值也旋转
  77156. //旋转
  77157. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  77158. viewport.view.direction = viewport.view.direction.applyMatrix4(rotMatrix);
  77159. vec.applyMatrix4(rotMatrix);
  77160. viewport.shiftTarget.subVectors(center,vec); //新的
  77161. viewport.view.position = this.getPosOutOfModel(viewport, boundSize);
  77162. }
  77163. getOrthoCamera(){
  77164. return new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000)
  77165. }
  77166. focusOnViewport(name){//全屏
  77167. viewer.viewports.forEach((viewport, i )=>{
  77168. if(viewport.name == name){
  77169. this.focusInfo = {
  77170. name,
  77171. left : viewport.left, bottom : viewport.bottom, height : viewport.height, width : viewport.width
  77172. };
  77173. viewport.left = 0; viewport.bottom = 0; viewport.height = 1; viewport.width = 1;
  77174. }else {
  77175. viewport.active = false;
  77176. }
  77177. });
  77178. viewer.updateScreenSize({forceUpdateSize:true});
  77179. }
  77180. unfocusViewport(){
  77181. if(!this.focusInfo)return
  77182. viewer.viewports.forEach((viewport, i )=>{
  77183. if(this.focusInfo.name == viewport.name){//全屏的恢复
  77184. viewport.left = this.focusInfo.left;
  77185. viewport.bottom = this.focusInfo.bottom;
  77186. viewport.height = this.focusInfo.height;
  77187. viewport.width = this.focusInfo.width;
  77188. }
  77189. viewport.active = true;
  77190. });
  77191. viewer.updateScreenSize({forceUpdateSize:true});
  77192. this.focusInfo = null;
  77193. }
  77194. }
  77195. const viewportProps = [
  77196. {
  77197. left:0.5,
  77198. bottom:0.5,
  77199. width: 0.5,height:0.5,
  77200. name : 'MainView',
  77201. //view: viewer.scene.view,
  77202. active: true,
  77203. },
  77204. {
  77205. left:0,
  77206. bottom:0.5,
  77207. width: 0.5,height:0.5,
  77208. name : 'top',
  77209. name2 : 'mapViewport',
  77210. axis:["x","y"],
  77211. direction : new Vector3(0,0,-1), //镜头朝向
  77212. //axisSign:[1,1],
  77213. active: true,
  77214. //相机位置在z轴正向
  77215. },
  77216. {
  77217. left:0.5,
  77218. bottom:0,
  77219. width: 0.5,height:0.5,
  77220. name : 'right',
  77221. axis:["y","z"],
  77222. direction : new Vector3(1,0,0),
  77223. //axisSign:[1,1],
  77224. active: true,
  77225. //相机位置在x轴负向 右下角屏
  77226. },
  77227. {
  77228. left:0,
  77229. bottom:0,
  77230. width: 0.5,height:0.5,
  77231. name : 'back',
  77232. axis:["x","z"],
  77233. direction : new Vector3(0,-1,0),
  77234. //axisSign:[-1,1], // 从镜头方向看 x向左 所以取负
  77235. active: true,
  77236. //相机位置在y轴正向 左下角屏
  77237. },
  77238. ];
  77239. var SplitScreen4Views = new SplitScreen();
  77240. SplitScreen4Views.split = function(o={}){
  77241. var defaultCamera = viewer.scene.getActiveCamera();
  77242. let {boundSize, center} = viewer.bound;
  77243. viewer.setLimitFar(false);
  77244. viewer.mapViewer.attachToMainViewer(true,'split4Screens','dontSet');
  77245. let viewports = this.splitStart(viewportProps);
  77246. //覆盖在map上、点云等其他物体之下的一层背景
  77247. let mapViewport = viewer.mapViewer.viewports[0];
  77248. mapViewport.noPointcloud = false;
  77249. //隐藏地图游标
  77250. //viewer.updateVisible(viewer.mapViewer.cursor, 'split4Screens', false)
  77251. /* viewer.images360.panos.forEach(pano=>{
  77252. viewer.updateVisible(pano.mapMarker, 'split4Screens', false) //希望这时候mapMarker已经建好了吧
  77253. }) */
  77254. //材质
  77255. this.statesBefore = {
  77256. pointDensity : Potree.settings.pointDensity,
  77257. displayMode : Potree.settings.displayMode,
  77258. position: viewer.images360.position,
  77259. target: viewer.scene.view.getPivot(),
  77260. //---
  77261. //ifShowMarker : Potree.settings.ifShowMarker,
  77262. };
  77263. viewer.setPointStandardMat(true,null,true); //切换到标准模式(主要为了mainViewport) 点云使用标准大小
  77264. var matBefore = {
  77265. opacity : new Map()
  77266. };
  77267. var newOpacityMap = new Map();
  77268. viewer.scene.pointclouds.forEach(e=>{
  77269. matBefore.opacity.set(e, e.temp.pointOpacity);
  77270. matBefore.colorType = e.material.activeAttributeName;
  77271. /* {
  77272. var map = new Map()
  77273. newOpacityMap.set(e, map )
  77274. var size = e.bound.getSize()
  77275. viewports.forEach(viewport=>{//根据bound设置opacity,越小的要靠越近,需要大的opacity。但似乎影响太大了
  77276. if(viewport.name == 'MainView')return;
  77277. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77278. let axis = prop.axis
  77279. var width = size[axis[0]]
  77280. var height = size[axis[1]]
  77281. var area = width * height
  77282. map.set(viewport, 5000/area);
  77283. })
  77284. } */
  77285. });
  77286. let beforeRender = function(){
  77287. viewer.scene.pointclouds.forEach(e=>{
  77288. if(this.name == "MainView"){
  77289. e.material.activeAttributeName = matBefore.colorType; // 'rgba'
  77290. e.material.useFilterByNormal = false;
  77291. e.changePointOpacity(matBefore.opacity.get(e)); //1 //恢复下 e.temp.pointOpacity 其实就是1
  77292. Potree.settings.pointDensity = 'fourViewportsMain';/* 'fourViewports' */ //本来想比另外三屏高一点质量,结果发现会闪烁,因为点云加载需要时间 (navvis仿版也是一样,以后看看能否优化)
  77293. }else {
  77294. e.material.activeAttributeName = "color";
  77295. e.material.useFilterByNormal = true;
  77296. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  77297. e.changePointOpacity(0.6/* newOpacityMap.get(e).get(viewport), true */); //多数据集有的数据集很小,放大后显示特别淡
  77298. //console.log(e.name, viewport.name, e.temp.pointOpacity, e.material.opacity)
  77299. }
  77300. });
  77301. };
  77302. viewports.forEach(viewport=>{viewport.beforeRender = beforeRender;});
  77303. this.enableMap(false);
  77304. this.enableFloorplan(false);
  77305. viewer.mapViewer.setViewLimit('expand'); //多数据集距离远时可以任意远,所以不限制了。但是这样就会看到地图边界了怎么办?
  77306. //viewer.dispatchEvent({'type': 'beginSplitView' })
  77307. //viewer.updateScreenSize({forceUpdateSize:true})
  77308. //this.viewportFitBound(mapViewport, boundSize, center)
  77309. //Potree.settings.ifShowMarker = false
  77310. Potree.settings.displayMode = 'showPointCloud';
  77311. };
  77312. SplitScreen4Views.recover = function(){
  77313. this.unSplit();
  77314. /* const {width, height} = viewer.renderer.getSize(new THREE.Vector2());
  77315. viewer.renderer.setViewport(0,0,width,height)
  77316. viewer.renderer.setScissorTest( false ); */
  77317. viewer.setView({
  77318. position: this.statesBefore.position,
  77319. target: this.statesBefore.target,
  77320. duration:300,
  77321. callback:function(){
  77322. }
  77323. });
  77324. viewer.mainViewport.beforeRender = null;
  77325. viewer.setLimitFar(true);
  77326. let mapViewport = viewer.mapViewer.viewports[0];
  77327. viewer.mapViewer.attachToMainViewer(false);
  77328. //viewer.updateVisible(viewer.mapViewer.cursor, 'split4Screens', true)
  77329. /* viewer.images360.panos.forEach(pano=>{
  77330. viewer.updateVisible(pano.mapMarker, 'split4Screens', true)
  77331. }) */
  77332. mapViewport.noPointcloud = true;
  77333. {
  77334. this.enableMap(Potree.settings.mapEnable);
  77335. this.enableFloorplan(Potree.settings.floorplanEnable);
  77336. if(this.floorplanListener){
  77337. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77338. this.floorplanListener = null;
  77339. }
  77340. }
  77341. Potree.settings.pointDensity = this.statesBefore.pointDensity;
  77342. if(!Potree.settings.isOfficial){
  77343. Potree.settings.displayMode = this.statesBefore.displayMode;
  77344. }
  77345. viewer.scene.pointclouds.forEach(e=>{
  77346. //e.material.color.set(this.statesBefore.mat.color)
  77347. //e.material.activeAttributeName = this.statesBefore.mat.colorType
  77348. e.material.useFilterByNormal = false;
  77349. //e.material.opacity = this.statesBefore.mat.opacity
  77350. });
  77351. viewer.setPointStandardMat(false);
  77352. viewer.mapViewer.setViewLimit('standard');
  77353. //Potree.settings.ifShowMarker = this.statesBefore.ifShowMarker
  77354. //viewer.dispatchEvent({'type': 'finishSplitView' })
  77355. //viewer.updateScreenSize({forceUpdateSize:true})
  77356. };
  77357. SplitScreen4Views.updateMapViewerBG = function(){
  77358. let mapViewport = viewer.mapViewer.viewports[0];
  77359. if(this.floorplanEnabled || this.mapEnabled){
  77360. mapViewport.background = 'overlayColor';
  77361. mapViewport.backgroundColor = new Color(0,0,0);
  77362. mapViewport.backgroundOpacity = 0.5;
  77363. }else {
  77364. mapViewport.background = null;
  77365. mapViewport.backgroundColor = null;
  77366. mapViewport.backgroundOpacity = null;
  77367. }
  77368. };
  77369. SplitScreen4Views.setFloorplanDisplay = function(e, show=false){
  77370. //viewer.updateVisible(e.floorplan.objectGroup, 'splitScreen', !!show)
  77371. //e.floorplan.objectGroup.visible = !!show
  77372. //viewer.mapViewer.mapLayer.needUpdate = true
  77373. e.floorplan.setEnable(show);
  77374. };
  77375. SplitScreen4Views.enableMap = function(enable){
  77376. let map = viewer.mapViewer.mapLayer.maps.find(e=>e.name == 'map');
  77377. //viewer.updateVisible(map.objectGroup, 'splitScreen', !!enable)
  77378. //map.objectGroup.visible = !!enable
  77379. //if(enable)viewer.mapViewer.mapLayer.needUpdate = true //加载地图
  77380. map.setEnable(!!enable);
  77381. //viewer.mapViewer.mapGradientBG = viewer.background == 'gradient' && !enable
  77382. this.mapEnabled = enable;
  77383. this.updateMapViewerBG();
  77384. },
  77385. //直接覆盖原设置
  77386. SplitScreen4Views.enableFloorplan = function(enable){ //是否让自定义的平面图显示
  77387. let floorplans = viewer.mapViewer.mapLayer.maps.filter(e=>e.name.includes('floorplan'));
  77388. if(this.floorplanListener){
  77389. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77390. }
  77391. this.floorplanListener = (e)=>{
  77392. this.setFloorplanDisplay(e, enable);
  77393. };
  77394. viewer.mapViewer.mapLayer.addEventListener( 'floorplanLoaded', this.floorplanListener ); //万一之后才加载
  77395. if(!enable){
  77396. //隐藏平面图
  77397. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},false));
  77398. }else {
  77399. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},true));
  77400. }
  77401. if (enable && floorplans.length == 0) Potree.loadMapEntity('all',true);
  77402. this.floorplanEnabled = enable;
  77403. this.updateMapViewerBG();
  77404. },
  77405. /* viewportFitBound:function(viewport, boundSize, center){ //使一个viewport聚焦在某个范围
  77406. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77407. let axis = prop.axis
  77408. let expand = 10;
  77409. let position = center.clone()
  77410. var moveAtAxis = ['x','y','z'].find(e=>!(axis.includes(e)))
  77411. if(viewport.name == 'mapViewport'){
  77412. let ori = viewport.view.position[moveAtAxis]
  77413. position[moveAtAxis] = ori //不改变这个值,尤其是mapViewer中的z
  77414. }else{
  77415. position[moveAtAxis] += boundSize[moveAtAxis]/2+expand//移动到bounding边缘外
  77416. }
  77417. viewport.view.position.copy(position)
  77418. var width = Math.max(boundSize[axis[0]], boundSize[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  77419. var margin = 50 //px
  77420. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  77421. viewport.camera.updateProjectionMatrix()
  77422. },
  77423. */
  77424. SplitScreen4Views.focusOnPointCloud = function(pointcloud){//三个屏都聚焦在这个点云
  77425. var boundSize = pointcloud.bound.getSize(new Vector3);
  77426. var center = pointcloud.bound.getCenter(new Vector3);
  77427. let target = pointcloud.panosBound && pointcloud.panosBound.center; //看向pano集中的地方,也就是真正有点云的地方。(因为需要展示所有点云,所以没办法用这个做为center)
  77428. this.focusOnObject(pointcloud.bound, center,target);
  77429. viewer.flyToDataset({pointcloud, dontMoveMap:true, duration:0});
  77430. };
  77431. SplitScreen4Views.focusOnObject = function(bound, center, target, duration=0){
  77432. viewer.viewports.forEach(e=>{
  77433. if(e.name == 'MainView'){
  77434. /* let len = boundSize.length()
  77435. let distance = THREE.Math.clamp(e.view.position.distanceTo(center), len * 0.01, len*0.3 ) //距离限制
  77436. //viewer.focusOnObject({position:center}, 'point', duration, {distance, direction: e.view.direction,dontMoveMap:true} )//平移镜头
  77437. //为了方便定位,直接飞到中心位置:
  77438. e.view.setView({
  77439. position:center, duration, target
  77440. }) */
  77441. }else {
  77442. this.viewportFitBound(e, bound, center);
  77443. }
  77444. });
  77445. };
  77446. class History extends EventDispatcher{
  77447. constructor(o){
  77448. super();
  77449. this.list = [];
  77450. this.callback = o.callback;
  77451. }
  77452. undo(){
  77453. let last = this.list.pop();
  77454. last && this.callback && this.callback(last);
  77455. }
  77456. redo(){//暂时不写
  77457. }
  77458. writeIn(item){
  77459. this.list.push(item);
  77460. }
  77461. clear(){
  77462. this.list.length = 0;
  77463. }
  77464. }
  77465. var Alignment = {
  77466. SplitScreen: SplitScreen4Views,
  77467. handleState:null, //操作状态 'translate'|'rotate'
  77468. bus: new EventDispatcher(),
  77469. prepareRecord : true,
  77470. writeToHistory(content){
  77471. if(!this.prepareRecord)return;
  77472. this.prepareRecord = false;
  77473. this.history.writeIn(content);
  77474. },
  77475. /* undo(){//撤销一步
  77476. let last = this.history.pop();
  77477. last && last.forEach(item=>{
  77478. this.applyTemp(item)
  77479. })
  77480. }, */
  77481. applyTemp(item){
  77482. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id+p.name == item.sid);
  77483. pointcloud.orientationUser = item.orientationUser;
  77484. pointcloud.translateUser = item.translateUser;
  77485. this.setMatrix( pointcloud );
  77486. },
  77487. getTemp(pointclouds){//记录最近一次保存后的状态,便于恢复
  77488. pointclouds = pointclouds || viewer.scene.pointclouds;
  77489. return pointclouds.map(e=>{
  77490. return {
  77491. sid : e.dataset_id+e.name,
  77492. orientationUser : e.orientationUser,
  77493. translateUser : e.translateUser.clone(),
  77494. }
  77495. } )
  77496. },
  77497. init:function(){
  77498. let rotateInfo;
  77499. viewer.fpControls.addEventListener("transformPointcloud",(e)=>{
  77500. if(e.pointclouds[0].dataset_id == Potree.settings.originDatasetId){//禁止手动移动初始数据集
  77501. return this.bus.dispatchEvent('forbitMoveOriginDataset')
  77502. }
  77503. this.writeToHistory(this.getTemp(e.pointclouds) );
  77504. if(this.handleState == 'translate'){
  77505. e.pointclouds.forEach(cloud=>Alignment.translate(cloud, e.moveVec));
  77506. }else if(this.handleState == 'rotate'){
  77507. if(Potree.settings.editType == 'pano'){
  77508. let center = e.intersectStart; //旋转中心是mousedown的位置
  77509. if(e.intersect.equals(center))return
  77510. if(!rotateInfo){
  77511. rotateInfo = {
  77512. orientationUser : e.pointclouds[0].orientationUser,
  77513. //vecStart : e.moveVec, // 首次移动向量 只有八个方向,精度太小,所以延迟
  77514. pointclouds: e.pointclouds
  77515. };
  77516. this.bus.dispatchEvent({type:'rotateStart', startPoint:center});
  77517. return
  77518. }else if(!rotateInfo.vecStart){
  77519. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77520. if(vec.length() * e.camera.zoom > 30){ //在屏幕上距离初始点有一定距离后开始算
  77521. //console.log('moveVec',vec)
  77522. rotateInfo.vecStart = vec;
  77523. }
  77524. }else {
  77525. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77526. let angle = math.getAngle(rotateInfo.vecStart,vec,'z');
  77527. let diffAngle = rotateInfo.orientationUser + angle - rotateInfo.pointclouds[0].orientationUser;
  77528. rotateInfo.pointclouds.forEach(cloud=>{
  77529. /* let centerNoTranfrom = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:cloud, position: center }) //中心点在数据集中的位置
  77530. Alignment.rotate(cloud, null, diffAngle)
  77531. let centerNow = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:cloud, position: centerNoTranfrom }) //中心点的现在位置
  77532. let shift = new THREE.Vector3().subVectors( center, centerNow); //偏移量
  77533. Alignment.translate(cloud,shift) //使center还保留在原位
  77534. //let centerNow1 = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:rotateInfo.pointcloud, position: centerNoTranfrom }) //中心点的现在位置
  77535. */
  77536. Alignment.rotateAround(center, cloud, null, diffAngle);
  77537. });
  77538. }
  77539. this.bus.dispatchEvent({type:'rotate', endPoint: e.intersect});
  77540. }else {
  77541. let center = e.pointclouds[0].translateUser; //移动到的位置就是中心
  77542. if(e.intersect.equals(center))return
  77543. if(!rotateInfo){
  77544. rotateInfo = {
  77545. orientationUser : e.pointclouds[0].orientationUser,
  77546. vecStart : new Vector3().subVectors(e.intersectStart, center).setZ(0),
  77547. //pointclouds: e.pointclouds
  77548. pointcloud: e.pointclouds[0]
  77549. };
  77550. }else {
  77551. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77552. let angle = math.getAngle(rotateInfo.vecStart,vec,'z');
  77553. let diffAngle = rotateInfo.orientationUser + angle - rotateInfo.pointcloud.orientationUser;
  77554. Alignment.rotate(rotateInfo.pointcloud, null, diffAngle);
  77555. }
  77556. }
  77557. }
  77558. });
  77559. viewer.fpControls.addEventListener("end",(e)=>{
  77560. rotateInfo = null;
  77561. this.prepareRecord = true;
  77562. });
  77563. viewer.inputHandler.addEventListener('keydown',e=>{
  77564. if(e.keyCode == 90 && e.event.ctrlKey){//Z
  77565. this.history.undo();
  77566. }
  77567. });
  77568. // cursor:
  77569. let updateCursor = (e)=>{
  77570. if(e.drag || !this.editing)return //仅在鼠标不按下时更新:
  77571. let handleState = Alignment.handleState;
  77572. if(e.hoverViewport.alignment && handleState && e.hoverViewport.alignment[handleState]){
  77573. if(handleState == 'translate'){
  77574. if( e.intersect && e.intersect.location ){
  77575. viewer.dispatchEvent({
  77576. type : "CursorChange", action : "add", name:"movePointcloud"
  77577. });
  77578. }else {
  77579. viewer.dispatchEvent({
  77580. type : "CursorChange", action : "remove", name:"movePointcloud"
  77581. });
  77582. }
  77583. }else if(handleState == 'rotate'){
  77584. if( e.intersect && e.intersect.location ){
  77585. viewer.dispatchEvent({
  77586. type : "CursorChange", action : "add", name:"rotatePointcloud"
  77587. });
  77588. }else {
  77589. viewer.dispatchEvent({
  77590. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77591. });
  77592. }
  77593. }
  77594. }else {
  77595. //清空:
  77596. viewer.dispatchEvent({
  77597. type : "CursorChange", action : "remove", name:"movePointcloud"
  77598. });
  77599. viewer.dispatchEvent({
  77600. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77601. });
  77602. }
  77603. };
  77604. viewer.addEventListener('global_mousemove',updateCursor);
  77605. viewer.addEventListener('global_drop',updateCursor);//拖拽结束
  77606. viewer.addEventListener('updateModelBound', (e)=>{
  77607. if(this.editing){
  77608. this.SplitScreen.updateCameraOutOfModel();
  77609. }
  77610. });
  77611. },
  77612. setMatrix : function(pointcloud){
  77613. var vec1 = pointcloud.position; //position为数据集内部的偏移,在navvis中对应的是dataset.pointCloudSceneNode的children[0].position
  77614. var vec2 = pointcloud.translateUser;
  77615. var angle = pointcloud.orientationUser;
  77616. var pos1Matrix = new Matrix4().setPosition(vec1);//先移动到点云本身应该在的初始位置(在4dkk里和其他应用中都是在这个位置的,也能和漫游点对应上)
  77617. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  77618. var pos2Matrix = new Matrix4().setPosition(vec2);//最后是平移
  77619. var matrix = new Matrix4().multiplyMatrices(pos2Matrix, rotMatrix);
  77620. pointcloud.transformMatrix = matrix.clone();//为该数据集的变化矩阵。 对应navvis的m2w_
  77621. pointcloud.transformInvMatrix.copy(matrix).invert();
  77622. pointcloud.rotateMatrix = rotMatrix;
  77623. pointcloud.rotateInvMatrix.copy(rotMatrix).invert();
  77624. pointcloud.panos.forEach(e=>e.transformByPointcloud());
  77625. matrix = new Matrix4().multiplyMatrices(matrix, pos1Matrix);
  77626. pointcloud.matrix = matrix;
  77627. //pointcloud.matrixWorldNeedsUpdate = true //更新matrixWorld (非计算,直接赋值)
  77628. pointcloud.updateMatrixWorld(true);
  77629. if(this.editing){
  77630. Alignment.changeCallBack && Alignment.changeCallBack();
  77631. }
  77632. if(pointcloud.spriteNodeRoot){
  77633. pointcloud.spriteNodeRoot.matrixWorld.copy(pointcloud.matrixWorld);//.multiplyMatrices(pointcloud.matrixWorld, pointcloud.matrixWorld);
  77634. }
  77635. viewer.updateModelBound();
  77636. //pointcloud.updateBound()
  77637. pointcloud.getPanosBound();
  77638. },
  77639. rotateAround(center, pointcloud, deg, angle){//绕center点转动
  77640. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg);
  77641. let vec1 = new Vector3().subVectors(pointcloud.translateUser, center);
  77642. let rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  77643. let vec2 = vec1.clone().applyMatrix4(rotMatrix); //将到旋转中心的偏差也转动
  77644. let vec3 = new Vector3().subVectors(vec2,vec1); //这个就是多出来的一步translateUser
  77645. this.rotate(pointcloud, deg, angle);
  77646. this.translate(pointcloud, vec3);
  77647. //绕点转动就是比普通转动多一步移动到相对center的某个位置。 1 初始点云移动到自己的position; 2 移动一个vec1 3绕原点旋转 4再移动一个原本的translateUser。 绘制出来后发现移动量就是第二步vec旋转后的偏移
  77648. },
  77649. rotate:function(pointcloud, deg, angle){//绕各自中心转动(各自的position) 假设点云位移position后0,0,0就是它的中心了(根据navvis观察这样做是绕同一个点旋转的)
  77650. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); //正逆负顺
  77651. pointcloud.orientationUser += angle;
  77652. Alignment.setMatrix(pointcloud);
  77653. },
  77654. translate:function(pointcloud, vec){
  77655. pointcloud.translateUser.add(vec);
  77656. Alignment.setMatrix(pointcloud);
  77657. },
  77658. enter:function(){
  77659. //this.saveTemp()
  77660. this.originData = this.getTemp();
  77661. this.SplitScreen.split({alignment:true});
  77662. viewer.images360.panos.forEach(pano=>{
  77663. viewer.updateVisible(pano.mapMarker, 'split4Screens', false);
  77664. });
  77665. viewer.viewports.find(e=>e.name == 'mapViewport').alignment = {rotate:true,translate:true};
  77666. viewer.viewports.find(e=>e.name == 'right').alignment = {translate:true};
  77667. viewer.viewports.find(e=>e.name == 'back').alignment = {translate:true};
  77668. this.editing = true;
  77669. viewer.updateFpVisiDatasets();
  77670. },
  77671. leave:function(){
  77672. this.switchHandle(null);
  77673. /* this.originData.forEach(e=>{//恢复
  77674. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.id)
  77675. this.translate(pointcloud, new THREE.Vector3().subVectors(e.translateUser , pointcloud.translateUser))
  77676. this.rotate(pointcloud, null, e.orientationUser - pointcloud.orientationUser)
  77677. }) */
  77678. this.originData.forEach(e=>{//恢复
  77679. this.applyTemp(e);
  77680. });
  77681. this.SplitScreen.recover();
  77682. viewer.images360.panos.forEach(pano=>{
  77683. viewer.updateVisible(pano.mapMarker, 'split4Screens', true);
  77684. });
  77685. this.editing = false;
  77686. this.history.clear();
  77687. viewer.updateFpVisiDatasets();
  77688. viewer.dispatchEvent({
  77689. type : "CursorChange", action : "remove", name:"movePointcloud"
  77690. });
  77691. viewer.dispatchEvent({
  77692. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77693. });
  77694. }
  77695. ,
  77696. switchHandle:function(state){
  77697. this.handleState = state;
  77698. //清空:
  77699. viewer.dispatchEvent({
  77700. type : "CursorChange", action : "remove", name:"movePointcloud"
  77701. });
  77702. viewer.dispatchEvent({
  77703. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77704. });
  77705. this.bus.dispatchEvent({type:'switchHandle' , state });
  77706. },
  77707. save: function(){//保存所有数据集的位置和旋转
  77708. let callback = ()=>{//保存成功后
  77709. this.originData = this.getTemp(); //this.saveTemp();
  77710. //需要修改 测量线的position。漫游点已经实时修改了
  77711. viewer.scene.measurements.forEach(e=>e.transformByPointcloud());
  77712. viewer.images360.updateCube(viewer.bound);
  77713. };
  77714. var data = viewer.scene.pointclouds.map(e=>{
  77715. let pos = viewer.transform.lonlatToLocal.inverse(e.translateUser.clone());
  77716. return {
  77717. id: e.dataset_id,
  77718. orientation : e.orientationUser,
  77719. location:[pos.x, pos.y, pos.z],
  77720. //transformMatrix: e.transformMatrix.elements,
  77721. }
  77722. });
  77723. //data = JSON.stringify(data)
  77724. //test: 退出后保留结果
  77725. if(!Potree.settings.isOfficial){
  77726. callback();
  77727. }
  77728. return {data, callback}
  77729. }
  77730. };
  77731. Alignment.history = new History({
  77732. callback: (data)=>{
  77733. data.forEach(item=>{
  77734. Alignment.applyTemp(item);
  77735. });
  77736. }
  77737. });
  77738. let texLoader$7 = new TextureLoader();
  77739. let markerMats$2;
  77740. let markerSizeInfo$2 = {width2d:35};
  77741. let color$2 = new Color('#FFF');
  77742. let faceMats;
  77743. let getFaceMat = (name)=>{
  77744. if(!faceMats){ //navvis材质可以搜gridTexture
  77745. let gridTex = texLoader$7.load( Potree.resourcePath+'/textures/gridmap.png' );
  77746. gridTex.wrapS = gridTex.wrapT = RepeatWrapping;
  77747. //gridTex.repeat.set(0.5,0.5)//放大一些
  77748. faceMats = {
  77749. dataset: new MeshStandardMaterial({
  77750. color:812922,
  77751. side:DoubleSide,
  77752. opacity:0.2,
  77753. transparent:true,
  77754. depthTest:false,
  77755. wireframe:true
  77756. }),
  77757. building: new MeshStandardMaterial({
  77758. color:812922, metalness: 0.2, roughness:0.8,
  77759. side:DoubleSide,
  77760. opacity:0.1,
  77761. transparent:true,
  77762. depthTest:true
  77763. }),
  77764. buildingSelect: new MeshStandardMaterial({
  77765. color:36582, metalness: 0, roughness:1,
  77766. side:DoubleSide,
  77767. opacity:0.1,
  77768. transparent:true,
  77769. depthTest:true
  77770. }),
  77771. floor: new MeshStandardMaterial({
  77772. color:11708469, metalness: 0.1, roughness:1,
  77773. side:DoubleSide,//BackSide,
  77774. opacity:0.05,
  77775. transparent:true,
  77776. depthTest:true,
  77777. }),
  77778. /* floorSelect: new THREE.MeshStandardMaterial({
  77779. color:16707151, metalness: 0, roughness:1,
  77780. side:THREE.DoubleSide,
  77781. opacity:1,
  77782. transparent:true,
  77783. depthTest:true,
  77784. polygonOffset : true,//是否开启多边形偏移
  77785. polygonOffsetFactor : -0.75,//多边形偏移因子
  77786. polygonOffsetUnits : -4.0,//多边形偏移单位
  77787. map: gridTex,
  77788. }), */
  77789. floorSelect: new DepthBasicMaterial({
  77790. map: gridTex,
  77791. color:16707151,
  77792. side:DoubleSide,//BackSide,
  77793. opacity:1,
  77794. transparent:true,
  77795. useDepth : true,
  77796. /* polygonOffset : true,//是否开启多边形偏移
  77797. polygonOffsetFactor : -0.75,//多边形偏移因子
  77798. polygonOffsetUnits : -4.0,//多边形偏移单位 */
  77799. clipDistance : 1, occlusionDistance:1, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77800. maxClipFactor:0.4, backColor:'#efe' //backColor:"#669988" ,
  77801. }),
  77802. room: new MeshStandardMaterial({
  77803. color:"#ff44ee", metalness: 0, roughness:1,
  77804. side:DoubleSide,//BackSide,
  77805. opacity:0.08,
  77806. transparent:true,
  77807. depthTest:false,
  77808. }),
  77809. /* roomSelect: new THREE.MeshStandardMaterial({
  77810. color:"#ff44ee", metalness: 0.3, roughness:1,
  77811. side:THREE.DoubleSide,//BackSide,
  77812. opacity:1,
  77813. transparent:true,
  77814. depthTest:true,
  77815. polygonOffset : true,//是否开启多边形偏移.(开启是因为和floor重叠了会闪烁)
  77816. polygonOffsetFactor : -0.75,//多边形偏移因子
  77817. polygonOffsetUnits : -4.0,//多边形偏移单位
  77818. map: gridTex,
  77819. }), */
  77820. roomSelect: new DepthBasicMaterial({
  77821. map: gridTex,
  77822. color:"#ff44ee",
  77823. side:DoubleSide,//BackSide,
  77824. opacity:1,
  77825. transparent:true,
  77826. useDepth : true,
  77827. /* polygonOffset : true,//是否开启多边形偏移
  77828. polygonOffsetFactor : -0.75,//多边形偏移因子
  77829. polygonOffsetUnits : -4.0,//多边形偏移单位 */
  77830. clipDistance : 1, occlusionDistance:0.5, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77831. maxClipFactor:0.6, backColor:'#ff88dd'//"#cc99c2" ,
  77832. })
  77833. };
  77834. }
  77835. return faceMats[name]
  77836. };
  77837. class BuildingBox extends ctrlPolygon{//建筑实体,包括building, floor, room
  77838. constructor(prop) {
  77839. prop.dimension = '3d';
  77840. //prop.name = Potree.config.siteModel.names[prop.buildType] +
  77841. super('siteModel_'+prop.buildType, prop);
  77842. this.midMarkers = [];
  77843. this.buildChildren = [];//子实体
  77844. this.holes = []; //在这创建的hole
  77845. this.parentHoles = [];//floor从building那得到的当层holes
  77846. this.mats = {}; //材质
  77847. this.panos = this.panos || [];
  77848. this.center; //中心点
  77849. if(this.buildType=='floor'){
  77850. this.points = prop.points = this.buildParent.points;//完全等于建筑的点
  77851. this.buildParent.holes.forEach(hole=>{//从building获取holes
  77852. let floorHole = new BuildingBox({
  77853. buildType : 'hole',
  77854. buildParent:this,
  77855. originHole : hole, //整栋大楼在当层的hole
  77856. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77857. });
  77858. this.parentHoles.push(floorHole);
  77859. this.add(floorHole);
  77860. floorHole.points = hole.points;//完全等于建筑的点
  77861. });
  77862. }
  77863. if(this.buildType == 'room' || this.buildType == 'hole'){
  77864. this.restrictArea = this.buildParent; //不能超出的区域
  77865. }
  77866. if(this.ifDraw){ //只存储空间模型信息,不绘制
  77867. if(this.buildType != 'hole'){
  77868. this.box = this.createBox();
  77869. this.add(this.box);
  77870. }
  77871. {
  77872. this.lineMesh = LineDraw.createLine([],{color: color$2});
  77873. this.lineMesh.name = 'buildingLines';
  77874. this.lineMesh.visible = false;
  77875. this.add(this.lineMesh);
  77876. viewer.setObjectLayers(this.lineMesh, 'bothMapAndScene' );
  77877. }
  77878. this.addEventListener('dragChange',(e)=>{ //修改中点
  77879. this.updateTwoMidMarker(e.index);
  77880. });
  77881. }
  77882. this.initData(prop);
  77883. }
  77884. initData(prop){
  77885. if(prop.ifDraw){
  77886. super.initData(prop);
  77887. }else {
  77888. if(prop.points){
  77889. this.points = prop.points;
  77890. }
  77891. }
  77892. }
  77893. intersectPointcloudVolume(pointcloud){//和pointcloud的重叠体积
  77894. var bound = this.getBound();
  77895. let bound2 = pointcloud.bound;
  77896. if(!bound.intersectsBox(bound2)) return 0;
  77897. let {zMin , zMax} = this.getRealZ();
  77898. let min = Math.min(zMin, bound2.min.z);
  77899. let max = Math.max(zMax, bound2.max.z);
  77900. let height1 = zMax - zMin;
  77901. let height2 = bound2.max.z-bound2.min.z;
  77902. let coverHeight = height1 + height2 - (max-min);//重叠高度 <=0是没重叠
  77903. let boxPoints = pointcloud.getUnrotBoundPoint(); //获取tightBound的四个点。 如果是有旋转角度的点云,这个和pointcloud.bound的四个点是不一致的,覆盖面积小于pointcloud.bound
  77904. let areaWhole = 0;
  77905. let area1 = this.getArea();
  77906. let area2 = Math.abs(math.getArea(boxPoints));
  77907. {//计算points与点云总面积 (但是把hole也加入了面积)(并集,重叠部分只算一次)
  77908. let rings = math.getPolygonsMixedRings([this.points, boxPoints] );
  77909. rings.forEach(e=>{
  77910. areaWhole+=e.area;
  77911. });
  77912. }
  77913. let coverHoleArea = 0; //holes与数据集重叠的部分
  77914. let holes = this.holes.concat(this.parentHoles);
  77915. let holesArea = 0; //所有holes面积相加
  77916. let areaHoleWithPointcloud = 0; //hole和点云的面积并集
  77917. if(holes.length>0){//还要再扣除holes与数据集重叠的部分。其中holes为mix轮廓
  77918. let outHoles = [];//没有重合的holes的外轮廓
  77919. /* if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  77920. let holes_ = holes.map(e=>e.points)
  77921. outHoles = math.getPolygonsMixedRings(holes_, true )
  77922. outHoles.forEach(e=>{
  77923. holesArea+=e.area
  77924. })
  77925. outHoles = outHoles.map(e=>e.points)
  77926. }else{
  77927. outHoles = holes.map(e=>e.points)
  77928. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)))
  77929. } */
  77930. holesArea = this.getHolesArea();
  77931. //holes与数据集重叠的部分
  77932. {
  77933. let polygons = outHoles.concat([boxPoints]);
  77934. let rings = math.getPolygonsMixedRings(polygons);
  77935. rings.forEach(e=>{
  77936. areaHoleWithPointcloud+=e.area;
  77937. });
  77938. coverHoleArea = holesArea + area2 - areaHoleWithPointcloud;//hole和点云的交集
  77939. }
  77940. }
  77941. let coverArea = area1 + area2 - areaWhole - coverHoleArea; //重叠面积
  77942. return coverArea * coverHeight
  77943. }
  77944. addHole(points=[]){
  77945. let prop = {
  77946. buildType : 'hole',
  77947. zMin : this.zMin,
  77948. zMax : this.zMax,
  77949. points,
  77950. buildParent:this,
  77951. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77952. };
  77953. //hole的zMin zMax跟随buildParent
  77954. var hole = new BuildingBox(prop);
  77955. this.holes.push(hole);
  77956. if(this.buildType == 'building'){//为每一层添加对应的hole
  77957. this.buildChildren.forEach(floor=>{
  77958. let floorHole = new BuildingBox({
  77959. buildType : 'hole',
  77960. zMin : this.zMin,
  77961. zMax : this.zMax,
  77962. buildParent:floor,
  77963. originHole : hole, //整栋大楼在当层的hole
  77964. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77965. });
  77966. floor.parentHoles.push(floorHole);
  77967. floor.add(floorHole);
  77968. floorHole.points = hole.points;//完全等于建筑的点
  77969. });
  77970. }
  77971. this.add(hole);//直接加在这,不加meshGroup了
  77972. this.update(); //update box mesh
  77973. return hole
  77974. //hole不创建box,只有它的buildParent需要更新box。 但有线条和marker. hole不在buildChildren里,但有buildParent
  77975. }
  77976. removeHole(hole){// 这个hole不会是parentHoles里的。
  77977. hole.dispose();
  77978. if(this.buildType == 'building'){ //若是整栋大楼的hole,在每层去除它的对应hole
  77979. this.buildChildren.forEach(floor=>{
  77980. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  77981. let index = floor.parentHoles.indexOf(holeAtFloor);
  77982. index > -1 && floor.parentHoles.splice(index, 1);
  77983. holeAtFloor.dispose();
  77984. });
  77985. }
  77986. let index = this.holes.indexOf(hole);
  77987. if(index>-1){
  77988. this.holes.splice(index, 1);
  77989. }
  77990. this.remove(hole);
  77991. this.update();
  77992. }
  77993. createBox(){
  77994. var geometry = new Geometry();
  77995. this.mats.boxDefault = getFaceMat(this.buildType);
  77996. this.mats.boxSelected = getFaceMat(this.buildType+'Select');
  77997. var mesh = new Mesh(geometry, this.mats.boxDefault);
  77998. mesh.name = 'buildingBox';
  77999. if(this.buildType == 'floor'){
  78000. viewer.setObjectLayers(mesh, 'siteModelMapUnvisi' ); //楼层默认在地图不显示,为了不会叠加透明度
  78001. }else {
  78002. viewer.setObjectLayers(mesh, 'bothMapAndScene' );
  78003. }
  78004. //mesh.frustumCulled = false;
  78005. return mesh
  78006. }
  78007. addMarker(o={} ){
  78008. if(this.buildType=='floor')return; //楼层不需要marker
  78009. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), renderOrder : 3, sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_marker"} );
  78010. viewer.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  78011. o.marker = marker;
  78012. super.addMarker(o);
  78013. if(!this.selected)viewer.updateVisible(marker,'select',false);
  78014. let addClickEvent = (e)=>{
  78015. let click = (e) => {
  78016. this.dispatchEvent({type:'clickMarker', marker } ); //由entity发送给sitemodel统一处理
  78017. };
  78018. marker.addEventListener('click', click);
  78019. marker.addEventListener('clickSelect', (e)=>{
  78020. this.setMarkerSelected(marker, e.state ? 'select' : 'unselect' );
  78021. });
  78022. marker.removeEventListener('addHoverEvent',addClickEvent);
  78023. };
  78024. marker.addEventListener('addHoverEvent',addClickEvent);//当非isNew时才添加事件
  78025. if(!this.isNew){
  78026. marker.dispatchEvent('addHoverEvent');
  78027. }
  78028. return marker
  78029. }
  78030. removeMarker(index){
  78031. super.removeMarker(index);
  78032. if(!this.isNew){
  78033. //重新添加midMarkers
  78034. this.midMarkers.forEach(e=>this.remove(e));
  78035. this.midMarkers = [];
  78036. this.addMidMarkers();
  78037. }
  78038. this.update();
  78039. if(this.points.length == 2 && this.box){//清除原先length>=3时候的
  78040. this.box.geometry = new Geometry();
  78041. }
  78042. }
  78043. addMidMarker(index, point){
  78044. if(this.buildType=='floor')return; //楼层不需要marker
  78045. let marker = new Sprite$1({mat:this.getMarkerMaterial('midPrepare'), sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_midMarker"} );
  78046. this.midMarkers = [...this.midMarkers.slice(0,index), marker, ...this.midMarkers.slice(index,this.midMarkers.length)];
  78047. marker.renderOrder = 3;
  78048. viewer.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  78049. { // Event Listeners
  78050. let mouseover = (e) => {
  78051. this.setMarkerSelected(e.object, 'hover', 'single');
  78052. viewer.dispatchEvent({
  78053. type : "CursorChange", action : "add", name:"markerMove"
  78054. });
  78055. };
  78056. let mouseleave = (e) => {
  78057. this.setMarkerSelected(e.object, 'unhover', 'single');
  78058. viewer.dispatchEvent({
  78059. type : "CursorChange", action : "remove", name:"markerMove"
  78060. });
  78061. };
  78062. let drag = (e) => {
  78063. let index = this.midMarkers.indexOf(marker);
  78064. let newMarker = this.addMarker({index:(index+1), point:marker.position.clone() });
  78065. this.addMidMarker(index+1, new Vector3 );
  78066. this.updateTwoMidMarker(index+1);
  78067. this.setMarkerSelected(marker, 'unhover');
  78068. viewer.inputHandler.startDragging(newMarker , {/* dragViewport:viewer.mapViewer.viewports[0], */ } ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78069. };
  78070. marker.addEventListener('drag', drag );
  78071. //marker.addEventListener('drop', drop);
  78072. marker.addEventListener('mouseover', mouseover);
  78073. marker.addEventListener('mouseleave', mouseleave);
  78074. }
  78075. this.add(marker);
  78076. this.updateMarker(marker, point);
  78077. if(!this.selected)viewer.updateVisible(marker,'select',false);
  78078. return marker
  78079. }
  78080. addMidMarkers(){//第一次画好所有marker后,一次性为线段增加中点marker
  78081. let length = this.points.length;
  78082. this.points.forEach((point,index)=>{
  78083. let nextPoint = this.points[(index+1)%length];
  78084. let midPoint = new Vector3().addVectors(point, nextPoint).multiplyScalar(0.5);
  78085. this.addMidMarker(index, midPoint );
  78086. });
  78087. }
  78088. updateTwoMidMarker(index){//更新第index个marker两边的midMarker
  78089. if(!this.midMarkers.length)return
  78090. let length = this.points.length;
  78091. let last = this.points[(index-1+length)%length]; //它之前的marker位置
  78092. let next = this.points[(index+1)%length];//它之后的marker位置
  78093. let current = this.points[index];//当前位置
  78094. let lastMid = new Vector3().addVectors(last, current).multiplyScalar(0.5);//上一个中点
  78095. let nextMid = new Vector3().addVectors(next, current).multiplyScalar(0.5);//下一个中点
  78096. let lastMidMarker = this.midMarkers[(index-1+length)%length];
  78097. let nextMidMarker = this.midMarkers[index];
  78098. this.updateMarker(lastMidMarker, lastMid);
  78099. this.updateMarker(nextMidMarker, nextMid);
  78100. }
  78101. dispose(){//销毁geo、remove from parent
  78102. super.dispose();
  78103. this.box && this.box.geometry.dispose();
  78104. this.lineMesh && this.lineMesh.geometry.dispose();
  78105. this.holes.forEach(e=>e.dispose());
  78106. this.parentHoles.forEach(e=>e.dispose());
  78107. //this.buildChildren.forEach(e=>e.dispose())
  78108. this.dispatchEvent('dispose');
  78109. }
  78110. updateBox(){
  78111. if(!this.box)return
  78112. this.box.geometry.dispose();
  78113. var shrink = this.buildType == 'room' ? 0.11 : this.buildType == 'floor' ? 0.082 : 0.2 ;//防止mesh重叠冲突(给一个不寻常的数字) 但离远了还是会有点闪烁
  78114. if(this.points.length >= 3){
  78115. let holes = this.holes.concat(this.parentHoles);
  78116. let holesPoints = holes.filter(e=>e.points.length>2).map(e=>e.points);
  78117. this.box.geometry = MeshDraw.getExtrudeGeo(this.points, holesPoints, {
  78118. depth:this.zMax-this.zMin-shrink,
  78119. UVGenerator: new MetricUVGenerator()
  78120. });
  78121. if(this.buildType == 'building' ){
  78122. this.box.position.z = this.zMin - shrink / 2;
  78123. }else {
  78124. this.box.position.z = this.zMin + shrink / 2;
  78125. }
  78126. }
  78127. }
  78128. update(options={}){
  78129. super.update(this.buildType != 'floor' && options.ifUpdateMarkers);
  78130. let length = this.points.length;
  78131. {//确保一下一样
  78132. if(this.originHole){
  78133. this.points = this.originHole.points; //完全等于building的hole
  78134. }
  78135. if(this.buildType == 'hole'){
  78136. this.zMin = this.buildParent.zMin;
  78137. this.zMax = this.buildParent.zMax;
  78138. }
  78139. }
  78140. if(!options.dontUpdateBox){
  78141. let boxOwner;
  78142. if(this.buildType == 'hole'){
  78143. if(this.buildParent.buildType == 'building'){ //若是整栋大楼的hole,在每层都要更新下它的对应hole
  78144. this.buildParent.buildChildren.forEach(floor=>{
  78145. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  78146. holeAtFloor && holeAtFloor.update(); //刚开始创建时还没创建对应的 holeAtFloor会为null
  78147. });
  78148. }
  78149. boxOwner = this.buildParent;
  78150. }else {
  78151. boxOwner = this;
  78152. }
  78153. boxOwner.updateBox();
  78154. }
  78155. {//update lines
  78156. let positions = [];
  78157. this.points.forEach((point, index)=>{
  78158. //竖线:
  78159. positions.push(point.clone().setZ(this.zMin), point.clone().setZ(this.zMax));
  78160. //横线
  78161. let nextPoint = this.points[(index+1)%length];
  78162. if(!nextPoint)return;//when length==1
  78163. positions.push(point.clone().setZ(this.zMax), nextPoint.clone().setZ(this.zMax));//上横线
  78164. positions.push(point.clone().setZ(this.zMin), nextPoint.clone().setZ(this.zMin));//下横线
  78165. });
  78166. LineDraw.moveLine(this.lineMesh,positions);
  78167. }
  78168. if(!options.dontUpdateChildren){
  78169. if(this.buildType == 'building' ){
  78170. this.buildChildren.forEach(floor=>{
  78171. floor.points = this.points;
  78172. floor.update();
  78173. });
  78174. }
  78175. {
  78176. let holes = this.holes.concat(this.parentHoles);
  78177. holes.forEach(hole=> {
  78178. hole.update({dontUpdateBox:true});//父级更新了box,hole就不需要更新box了
  78179. });
  78180. }
  78181. }
  78182. }
  78183. getHolesArea(){
  78184. let holes = this.holes.concat(this.parentHoles);
  78185. let outHoles, holesArea = 0;
  78186. if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  78187. let holes_ = holes.map(e=>e.points);
  78188. outHoles = math.getPolygonsMixedRings(holes_, true );
  78189. outHoles.forEach(e=>{
  78190. holesArea+=e.area;
  78191. });
  78192. outHoles = outHoles.map(e=>e.points);
  78193. }else {
  78194. outHoles = holes.map(e=>e.points);
  78195. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)));
  78196. }
  78197. return holesArea
  78198. }
  78199. getArea(ifRidOfHoles){//面积
  78200. //不排除hole
  78201. return Math.abs(math.getArea(this.points)) - (ifRidOfHoles ? this.getHolesArea() : 0)
  78202. }
  78203. getVolume(ifRidOfHoles){//体积
  78204. let {zMin , zMax} = this.getRealZ();
  78205. let height = zMax - zMin;
  78206. if(isNaN(height))height = 0;
  78207. return this.getArea(ifRidOfHoles) * height
  78208. }
  78209. getRealZ(){//求真实高度时用到的
  78210. let zMin , zMax;
  78211. if (this.buildType == 'building') {
  78212. //building的zMax和zMin一样的所以要算
  78213. let top = this.buildChildren[this.buildChildren.length - 1];
  78214. let btm = this.buildChildren[0];
  78215. zMin = btm ? btm.zMin : 0; //建好的建筑不加楼的话是0
  78216. zMax = top ? top.zMax : 0;
  78217. }else if(this.buildType == 'hole'){
  78218. return this.buildParent.getRealZ()
  78219. }else {
  78220. zMin = this.zMin, zMax = this.zMax;
  78221. }
  78222. return {zMin,zMax}
  78223. }
  78224. /* getDrawZ(){ //画线和box时用到的z
  78225. let zMin , zMax
  78226. if(this.buildType == 'hole'){
  78227. if(this.buildParent.buildType == 'building' && atFloor){
  78228. zMin = atFloor.zMin, zMax = atFloor.zMax
  78229. }else{
  78230. zMin = this.buildParent.zMin, zMax = this.buildParent.zMax
  78231. }
  78232. }else{
  78233. zMin = this.zMin, zMax = this.zMax
  78234. }
  78235. return {zMin, zMax}
  78236. } */
  78237. getBound(){
  78238. let bound = new Box3;
  78239. let {zMin , zMax} = this.getRealZ();
  78240. let points = this.buildType == 'floor' ? this.buildParent.points : this.points;
  78241. points.forEach(p=>{
  78242. bound.expandByPoint(p.clone().setZ(zMin));
  78243. bound.expandByPoint(p.clone().setZ(zMax));
  78244. });
  78245. return bound
  78246. }
  78247. getMarkerMaterial(type) {
  78248. if(!markerMats$2){
  78249. markerMats$2 = {
  78250. default: new MeshBasicMaterial({
  78251. transparent: !0,
  78252. color: color$2,
  78253. opacity: 0.8,
  78254. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78255. depthTest:false,
  78256. }),
  78257. midPrepare: new MeshBasicMaterial({ //线中心的半透明点
  78258. transparent: !0,
  78259. color: color$2,
  78260. opacity: 0.4,
  78261. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78262. depthTest:false,
  78263. }),
  78264. hover: new MeshBasicMaterial({
  78265. transparent: !0,
  78266. color: color$2,
  78267. opacity: 1,
  78268. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78269. depthTest:false,
  78270. }),
  78271. select: new MeshBasicMaterial({
  78272. transparent: !0,
  78273. color:new Color('#00C8AF'),
  78274. opacity: 1,
  78275. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78276. depthTest:false,
  78277. }),
  78278. };
  78279. }
  78280. return markerMats$2[type]
  78281. }
  78282. setMarkerSelected(marker, state, hoverObject){
  78283. //console.warn(marker.id , state, hoverObject)
  78284. if(state == 'select'){
  78285. marker.selected = true;
  78286. marker.material = this.getMarkerMaterial('select');
  78287. }else if(state == 'unselect'){
  78288. marker.selected = false;
  78289. marker.material = this.getMarkerMaterial('default');
  78290. }else {
  78291. if(marker.selected)return //选中时不允许修改为除了'unselect'以外的状态
  78292. if(state == 'hover'){
  78293. marker.material = this.getMarkerMaterial('hover');
  78294. }else if(state == 'unhover'){
  78295. if(marker.name.includes('mid')){
  78296. marker.material = this.getMarkerMaterial('midPrepare');
  78297. }else {
  78298. marker.material = this.getMarkerMaterial('default');
  78299. }
  78300. }
  78301. }
  78302. }
  78303. select(){
  78304. //最多再显示一层子级的线,如building不会显示room中的hole的线
  78305. //box是一直显示的,但会切换材质
  78306. /*
  78307. 选中 box 线
  78308. building 自己(底盘)选中 自己, floor不带hole
  78309. floor 自己选中 自己, room不带hole
  78310. room 自己选中 自己
  78311. */ //注:自己的就代表定包括hole,如果有parentHoles的也(building上的hole的对应)
  78312. //console.log('select '+this.name, this.selected)
  78313. if(this.selected)return
  78314. if(this.box){
  78315. this.box.material = this.mats.boxSelected;
  78316. }
  78317. if(this.buildType == 'building'|| this.buildType == 'floor'){
  78318. this.buildChildren.forEach(e=>{
  78319. e.lineMesh.visible = true;
  78320. });
  78321. if(this.buildType == 'floor'){
  78322. viewer.setObjectLayers(this.box, 'bothMapAndScene' );
  78323. viewer.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' ); //当选中floor或room时,building在地图不可见
  78324. }
  78325. }else if(this.buildType == 'room'){
  78326. viewer.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78327. viewer.setObjectLayers(this.buildParent.buildParent.box, 'siteModelMapUnvisi' );
  78328. }
  78329. this.lineMesh.visible = true;
  78330. this.markers && this.markers.forEach(e=>viewer.updateVisible(e,'select',true) );
  78331. this.midMarkers && this.midMarkers.forEach(e=>e.visible = true);
  78332. let holes = this.holes.concat(this.parentHoles);
  78333. holes.forEach(e=>e.select());
  78334. this.selected = true;
  78335. this.dispatchEvent({type:'select'});
  78336. }
  78337. unselect(){
  78338. if(!this.selected)return
  78339. //console.log('unselect '+this.name )
  78340. if(this.box){
  78341. this.box.material = this.mats.boxDefault;
  78342. }
  78343. if(this.buildType == 'building' || this.buildType == 'floor'){
  78344. this.buildChildren.forEach(e=>{ //(这里要保证选中前要先取消选中,否则如选中房间后取消了楼层,房间线就隐藏了)
  78345. e.lineMesh.visible = false;
  78346. });
  78347. if(this.buildType == 'floor'){
  78348. viewer.setObjectLayers(this.box, 'siteModelMapUnvisi' );
  78349. viewer.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78350. }
  78351. }else if(this.buildType == 'room'){
  78352. viewer.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' );
  78353. viewer.setObjectLayers(this.buildParent.buildParent.box, 'bothMapAndScene' );
  78354. }
  78355. this.lineMesh.visible = false;
  78356. this.markers && this.markers.forEach(e=>viewer.updateVisible(e,'select',false) );
  78357. this.midMarkers && this.midMarkers.forEach(e=>e.visible = false);
  78358. let holes = this.holes.concat(this.parentHoles);
  78359. holes.forEach(e=>e.unselect());
  78360. this.selected = false;
  78361. this.dispatchEvent({type:'unselect'});
  78362. }
  78363. ifContainsPoint(position){//看它所定义的空间是否包含某个坐标(要排除hole)
  78364. let {zMin , zMax} = this.getRealZ();
  78365. if(position.z < zMin || position.z > zMax ) return
  78366. let holes = this.holes.concat(this.parentHoles);
  78367. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  78368. let inShape = math.isPointInArea(this.points, holesPoints, position);
  78369. return !!inShape
  78370. }
  78371. }
  78372. class MetricUVGenerator{
  78373. constructor(){
  78374. this.a = new Vector3,
  78375. this.b = new Vector3,
  78376. this.c = new Vector3,
  78377. this.d = new Vector3;
  78378. }
  78379. generateTopUV(t, e, n, r, o) {
  78380. return [new Vector2$1(e[3 * n],e[3 * n + 1]), new Vector2$1(e[3 * r],e[3 * r + 1]), new Vector2$1(e[3 * o],e[3 * o + 1])]
  78381. }
  78382. generateSideWallUV(t, e, n, r, o, a) {
  78383. var s = e;
  78384. this.a.set(s[3 * n], s[3 * n + 1], s[3 * n + 2]),
  78385. this.b.set(s[3 * r], s[3 * r + 1], s[3 * r + 2]),
  78386. this.c.set(s[3 * o], s[3 * o + 1], s[3 * o + 2]),
  78387. this.d.set(s[3 * a], s[3 * a + 1], s[3 * a + 2]);
  78388. var c = this.a.x !== this.b.x
  78389. , l = c ? this.b : this.d
  78390. , u = this.a.distanceTo(l)
  78391. , d = l.distanceTo(this.c);
  78392. return [new Vector2$1(this.a.x,0), c ? new Vector2$1(this.a.x + u,0) : new Vector2$1(this.a.x,d), new Vector2$1(this.a.x + u,d), c ? new Vector2$1(this.a.x,d) : new Vector2$1(this.a.x + u,0)]
  78393. }
  78394. }
  78395. const minFloorHeight = 0.5;
  78396. const ifDrawDatasetBound = true; //显示一下数据集的tightBound线框
  78397. const minMarkers = 3;
  78398. const Limit = {zMin:-config$1.map.cameraHeight, zMax:config$1.map.cameraHeight,}; //不能超过camera的高度,为了对称所以也限制了最低
  78399. var SiteModel = {
  78400. bus: new EventDispatcher(),
  78401. entities:[], //所有实体
  78402. buildings:[], //所有建筑父集
  78403. meshGroup: new Object3D,
  78404. inEntity : null,
  78405. lastPos: new Vector3(Infinity,Infinity,Infinity),
  78406. init: function(){
  78407. viewer.scene.scene.add(this.meshGroup);
  78408. this.meshGroup.name = 'siteModel';
  78409. this.SplitScreen = SplitScreen4Views;
  78410. if(Potree.settings.editType == 'pano'){
  78411. return
  78412. }
  78413. this.createHeightPull();
  78414. if(Potree.settings.isTest && ifDrawDatasetBound){
  78415. viewer.addEventListener('allLoaded',()=>{
  78416. viewer.scene.pointclouds.forEach(pointcloud=>{
  78417. let boxPoints = pointcloud.getUnrotBoundPoint();
  78418. let boundingBox = new BuildingBox({
  78419. name: '数据集tightBound_'+pointcloud.dataset_id,
  78420. points: boxPoints,
  78421. buildType : 'dataset',
  78422. zMax: pointcloud.bound.max.z,
  78423. zMin: pointcloud.bound.min.z,
  78424. ifDraw:true
  78425. });
  78426. this.meshGroup.add(boundingBox);
  78427. //boundingBox.markers.forEach(e=>e.visible = false)
  78428. });
  78429. });
  78430. }
  78431. if(Potree.settings.isOfficial){
  78432. viewer.addEventListener('camera_changed', e => {
  78433. if(e.changeInfo.positionChanged){
  78434. this.updateEntityAt();
  78435. }
  78436. });
  78437. }
  78438. {
  78439. let pressDelete = (e)=>{
  78440. if(e.keyCode == KeyCodes.BACKSPACE || e.keyCode == KeyCodes.DELETE){
  78441. if(this.selectedMarker){
  78442. let entity = this.selectedMarker.parent;
  78443. let index = entity.markers.indexOf(this.selectedMarker);
  78444. entity.removeMarker(index);
  78445. if(entity.points.length<2){//删到只剩一个点时重新画(如果是hole的点,直接删除hole吧?)
  78446. this.startInsertion('resume',entity);
  78447. }
  78448. }
  78449. }
  78450. };
  78451. viewer.inputHandler.addEventListener('keydown', pressDelete);
  78452. }
  78453. },
  78454. updateEntityAt(force){
  78455. //if(!this.entities.length || this.editing) return //编辑时也要根据位置显示不同楼层的漫游点与cad
  78456. let fun = ()=>{ //延时update,防止卡顿
  78457. let currPos = viewer.mainViewport.view.position;
  78458. //if(force || !currPos.equals(this.lastPos) ){
  78459. //console.log('currPos ', currPos.toArray())
  78460. this.lastPos.copy(currPos);
  78461. let entity;
  78462. let searchPos = Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : currPos;
  78463. entity = this.pointInWhichEntity(searchPos, 'room');
  78464. if(force || this.inEntity != entity ){
  78465. let oldEntity = this.inEntity;
  78466. this.inEntity = entity;
  78467. //console.log('buildingChange', entity)
  78468. this.bus.dispatchEvent({type:'buildingChange',entity});
  78469. //this.updatePanosVisible(oldEntity, this.inEntity)
  78470. let lastFloor = this.currentFloor; //oldEntity ? oldEntity.buildType == 'floor' ? oldEntity : oldEntity.buildType == 'room' ? oldEntity.buildParent : null : null; //基本只会是floor或room
  78471. let currentFloor = entity ? entity.buildType == 'floor' ? entity : entity.buildType == 'room' ? entity.buildParent : null : null; //基本只会是floor或room
  78472. if(force || currentFloor != lastFloor){
  78473. //console.log('改变了floor',lastFloor,currentFloor)
  78474. this.currentFloor = currentFloor;
  78475. this.bus.dispatchEvent({type:'FloorChange',currentFloor});
  78476. }
  78477. }
  78478. force = false;
  78479. return true
  78480. //}
  78481. };
  78482. if(force)fun();
  78483. else Common.intervalTool.isWaiting('sitemodelCameraInterval', fun , 500);
  78484. },
  78485. enter:function(){
  78486. Potree.Log('sitemodel enter');
  78487. this.clear(); //确保全部清空
  78488. this.editing = true;
  78489. //this.updatePanosVisible(null, null, true)//show all
  78490. viewer.updateFpVisiDatasets();
  78491. let mapViewport = viewer.mapViewer.viewports[0];
  78492. this.SplitScreen.split({siteModel:true/* , viewports:[{name:'Top',viewport : mapViewport }] */});
  78493. viewer.viewports.forEach(e=>{
  78494. if(e.name != 'mapViewport'){
  78495. e.layersAdd('siteModelMapUnvisi');
  78496. }
  78497. if(e.name == 'right' || e.name == 'back'){
  78498. e.layersAdd('siteModeSideVisi');
  78499. }
  78500. });
  78501. viewer.images360.panos.forEach(pano=>{
  78502. viewer.setObjectLayers(pano.marker, 'siteModelMapUnvisi' );
  78503. });
  78504. mapViewport.layersAdd('siteModeOnlyMapVisi'); //只有mapViewport能看到marker
  78505. },
  78506. leave:function(){
  78507. Potree.Log('sitemodel leave');
  78508. let mapViewport = viewer.mapViewer.viewports[0];
  78509. this.SplitScreen.recover();
  78510. viewer.viewports.forEach(e=>{
  78511. if(e.name != 'mapViewport'){
  78512. e.layersRemove('siteModelMapUnvisi');
  78513. }
  78514. if(e.name == 'right' || e.name == 'back'){
  78515. e.layersRemove('siteModeSideVisi');
  78516. }
  78517. });
  78518. viewer.images360.panos.forEach(pano=>{
  78519. viewer.setObjectLayers(pano.marker, 'sceneObjects' );
  78520. });
  78521. mapViewport.layersRemove('siteModeOnlyMapVisi');
  78522. this.clear();
  78523. this.editing = false;
  78524. this.updateEntityAt(true);
  78525. viewer.updateFpVisiDatasets();
  78526. } ,
  78527. addFloor:function(parent, dirType, sid, name){//dirType:'top'|'bottom'在上方建还是下方。如果建筑中没有楼层,默认在基底建一个
  78528. let buildType = 'floor';
  78529. let zMin, zMax;
  78530. if(parent.buildChildren.length == 0){
  78531. zMin = parent.zMin;
  78532. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78533. }else {
  78534. if(dirType == 'bottom'){
  78535. //var btm = Common.find(parent.buildChildren,null,[e=>e.zMin])
  78536. var btm = parent.buildChildren[0];
  78537. zMax = btm.zMin;
  78538. zMin = zMax - Potree.config.siteModel.floorHeightDefault;
  78539. }else {
  78540. //var top = Common.find(parent.buildChildren,null,[e=>e.zMax])
  78541. var top = parent.buildChildren[parent.buildChildren.length - 1];
  78542. zMin = top.zMax;
  78543. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78544. }
  78545. }
  78546. let prop = {
  78547. buildType,
  78548. //name : Potree.config.siteModel.names[buildType],
  78549. zMin,
  78550. zMax,
  78551. buildParent:parent,
  78552. sid, name,
  78553. ifDraw:true
  78554. };
  78555. var floor = new BuildingBox(prop);
  78556. /* parent.buildChildren.push(floor)
  78557. this.meshGroup.add(floor);
  78558. this.entities.push(floor) */
  78559. floor.update();
  78560. this.addEntity(floor,parent);
  78561. //this.selectEntity(floor)
  78562. if(this.selected == parent){//重新选择下,为了显示新楼层线框
  78563. parent.unselect();
  78564. parent.select();
  78565. }
  78566. return floor
  78567. },
  78568. startInsertion:function(buildType, parent, sid, name, callback, cancelFun){
  78569. let zMin, zMax, entity, resume;
  78570. let mapViewport = viewer.mapViewer.viewports[0];
  78571. if(buildType == 'resume'){//继续画(使用最后一个点或者新加的点)
  78572. resume = true;
  78573. entity = parent;
  78574. buildType = parent.buildType;
  78575. //删除原先所有的点,因为它们已经添加了事件,会很麻烦:
  78576. entity.reDraw(0);
  78577. entity.isNew = true; //当作新的来画
  78578. }
  78579. if(!resume){
  78580. if(buildType == 'hole' || buildType == 'room'){
  78581. zMin = parent.zMin;
  78582. zMax = parent.zMax;
  78583. }else if(buildType == 'building'){
  78584. parent = null;
  78585. zMin = viewer.bound.boundingBox.min.z;
  78586. zMax = viewer.bound.boundingBox.min.z;
  78587. }
  78588. if(buildType == 'hole'){
  78589. entity = parent.addHole();
  78590. entity.isNew = true;
  78591. this.selectEntity(parent);
  78592. entity.select();
  78593. console.log('挖洞 ',entity.uuid);
  78594. }else {
  78595. let prop = {
  78596. buildType,
  78597. //name : Potree.config.siteModel.names[buildType],//'building',
  78598. zMin,
  78599. zMax,
  78600. buildParent:parent,
  78601. sid, name,
  78602. ifDraw:true
  78603. };
  78604. entity = new BuildingBox(prop);
  78605. entity.isNew = true;
  78606. this.selectEntity(entity);
  78607. }
  78608. this.addEntity(entity, parent);
  78609. }
  78610. let timer;
  78611. let endDragFun = (e) => {
  78612. if (e.button == MOUSE.LEFT ) {
  78613. var marker = entity.addMarker({point:entity.points[entity.points.length - 1].clone()});
  78614. //entity.editStateChange(true) //重新激活reticule状态
  78615. entity.continueDrag(marker, e);
  78616. } else if (e.button === MOUSE.RIGHT ) {
  78617. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  78618. else entity.continueDrag(null, e/* .drag.object */);
  78619. }
  78620. };
  78621. let finish = ()=>{//结束绘画
  78622. viewer.removeEventListener('cancel_insertions', Exit);
  78623. entity.removeEventListener('unselect', Exit);
  78624. clearTimeout(timer);
  78625. entity.editStateChange(false);
  78626. //pressExit && viewer.inputHandler.removeEventListener('keydown', pressExit);
  78627. callback && callback(entity);
  78628. };
  78629. let end = (e={}) => {//尝试结束
  78630. /* 退出的三种形式:
  78631. 1 普通:如果大于三个marker,结束且保留;否则重新画。()
  78632. 2 删除:直接结束且删除。(remove)
  78633. 3 结束:如果大于三个marker,结束且保留;否则结束且删除。 (finish)
  78634. 4 保留:无论几个marker,都保留着,结束。(remain)
  78635. */
  78636. if(e.remove){
  78637. finish();
  78638. return this.removeEntity(entity)
  78639. }
  78640. if(!e.remain && !e.finish && !e.remove && entity.markers.length<=minMarkers){//右键 当个数不够时取消
  78641. //重新开始画
  78642. entity.reDraw(1);
  78643. viewer.updateVisible(entity.markers[0],'unMove',false);
  78644. var f = ()=>{
  78645. viewer.updateVisible(entity.markers[0],'unMove',true);
  78646. entity.removeEventListener('dragChange',f);
  78647. };
  78648. entity.addEventListener('dragChange',f);
  78649. //console.log('waitcontinue')
  78650. entity.continueDrag(entity.markers[0], e);
  78651. return
  78652. }
  78653. finish();
  78654. if (e.remain || !e.remove && entity.markers.length > 3) {//保留
  78655. entity.removeMarker(entity.points.length - 1);
  78656. entity.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  78657. if(buildType == 'room'){
  78658. this.fitPullBox();
  78659. }
  78660. entity.isNew = false;
  78661. entity.addMidMarkers();
  78662. }else {
  78663. this.removeEntity(entity); //直接删除没画好的,比较简单。这样就不用担心旧的continueDrag仍旧触发了
  78664. }
  78665. return entity
  78666. };
  78667. let Exit = (e)=>{ //强制结束
  78668. entity.removeEventListener('unselect', Exit);
  78669. if(viewer.inputHandler.drag){//还未触发drop的话
  78670. viewer.inputHandler.drag.object.dispatchEvent({
  78671. type: 'drop',
  78672. drag: viewer.inputHandler.drag,
  78673. viewer: viewer,
  78674. pressDistance:0,
  78675. button : MOUSE.RIGHT
  78676. });
  78677. viewer.inputHandler.drag = null;
  78678. }else {
  78679. end({remain:true});
  78680. }
  78681. viewer.inputHandler.drag = null;
  78682. };
  78683. viewer.dispatchEvent( 'cancel_insertions' );//取消之前的
  78684. viewer.addEventListener('cancel_insertions', Exit);
  78685. entity.addEventListener('unselect', Exit);
  78686. var marker = entity.addMarker({point:new Vector3(0, 0, 0)});
  78687. viewer.updateVisible(marker,'unMove',false);//这时候的位置是假的(0,0,0)所以先不可见
  78688. var f = ()=>{
  78689. viewer.updateVisible(marker,'unMove',true);
  78690. entity.removeEventListener('dragChange',f);
  78691. };
  78692. entity.addEventListener('dragChange',f);
  78693. marker.isDragging = true;
  78694. viewer.inputHandler.startDragging(marker , {dragViewport:mapViewport, endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78695. return entity;
  78696. },
  78697. getPreDealData(points, zMin, zMax, initial, buildType, parent){
  78698. /* if( buildType == 'building' ){
  78699. zMax = zMin //强制变得一样,作为基底。如果有必要,保存时再算真实的zMax。目前zMin没有保存所以数据是错的,会直接根据floor计算
  78700. } */
  78701. var bound = viewer.bound.boundingBox;
  78702. if(buildType == 'building' && initial){//初始数据错的,要自己建(只有一个building和floor) 原posIsLonlat
  78703. console.log('空间模型未编辑过, 初始化了一个');
  78704. points = [
  78705. new Vector3(bound.min.x, bound.min.y,0),
  78706. new Vector3(bound.max.x, bound.min.y,0),
  78707. new Vector3(bound.max.x, bound.max.y,0),
  78708. new Vector3(bound.min.x, bound.max.y,0),
  78709. ];
  78710. zMin = bound.min.z;
  78711. zMax = bound.max.z;
  78712. /* points = points.map(e=>{
  78713. return viewer.transform.lonlatToLocal.forward(e)
  78714. }) */
  78715. }else {//相对于初始数据集的模型内坐标
  78716. points = points.map(e=> this.transform(e, 'fromDataset'));
  78717. if(buildType == 'floor' && initial){
  78718. zMin = bound.min.z;
  78719. zMax = bound.max.z;
  78720. }
  78721. }
  78722. return {points, zMax, zMin }
  78723. },
  78724. resetFromData:function(entity, points=[], holes=[], zMin, zMax ){
  78725. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , this.autoBuild , entity.buildType, entity.buildParent );
  78726. if(entity.buildType != 'floor' )entity.points = points;
  78727. if(entity.buildType == 'room'){
  78728. entity.zMin = zMin;
  78729. entity.zMax = zMax;
  78730. }else if(entity.buildType == 'floor'){//改楼高
  78731. let height = zMax - zMin;
  78732. let zMax2 = entity.zMin + height;
  78733. SiteModel.changeZ(entity, 'zMax', zMax2);
  78734. }
  78735. {
  78736. //删除旧的holes重新添加
  78737. let holesOld = entity.holes;
  78738. holesOld.forEach(e=>{
  78739. entity.removeHole(e);
  78740. });
  78741. holes.forEach(points =>{
  78742. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78743. let hole = entity.addHole(ps);
  78744. hole.addMidMarkers();
  78745. });
  78746. }
  78747. entity.update();
  78748. return entity
  78749. }
  78750. ,
  78751. createFromData:function( buildType, parent ,sid, name, points=[], holes=[], zMin, zMax, initial,panos_,flagPano){
  78752. if(buildType != 'building' && buildType != 'floor' && buildType != 'room' ) return
  78753. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , initial, buildType, parent );
  78754. let panos = [];
  78755. {
  78756. if(panos_){
  78757. panos_.forEach(sid=>{
  78758. let pano = viewer.images360.getPano(sid,'sid');
  78759. if(pano)panos.push(pano);
  78760. });
  78761. }
  78762. flagPano = flagPano != void 0 ? viewer.images360.getPano(flagPano,'sid') : null ; //最中心的pano 或者 最靠近该实体的pano(当panos为空时)
  78763. if(!this.editing && buildType == 'floor' && !flagPano){//没有的话可能是自动添加的floor,直接用parent的吧
  78764. panos = parent.panos;
  78765. flagPano = parent.flagPano;
  78766. }
  78767. }
  78768. let prop = {
  78769. buildType,
  78770. points,
  78771. name,
  78772. sid,
  78773. zMin,
  78774. zMax,
  78775. buildParent:parent,
  78776. ifDraw:this.editing || Potree.settings.drawEntityData,
  78777. panos, flagPano,
  78778. autoBuild : initial
  78779. };
  78780. let entity = new BuildingBox(prop);
  78781. SiteModel.addEntity(entity, parent );
  78782. if(this.editing){
  78783. if(buildType == 'building'|| buildType == 'room'){
  78784. entity.addMidMarkers();
  78785. }
  78786. }
  78787. holes.forEach(points =>{
  78788. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78789. let hole = entity.addHole(ps);
  78790. this.editing && hole.addMidMarkers();
  78791. });
  78792. /* if(buildType == 'floor'){
  78793. this.updateBuildingZ(parent)
  78794. } */
  78795. return entity
  78796. },
  78797. transform:function(pos, type){
  78798. if(Potree.settings.editType == 'pano'){ // 模型不经转换
  78799. return new Vector3().copy(pos).setZ(0);
  78800. }
  78801. if(type == 'toDataset'){
  78802. let point = Potree.Utils.datasetPosTransform({ toDataset: true, position: pos.clone(), datasetId: Potree.settings.originDatasetId });
  78803. return new Vector2$1().copy(point)
  78804. }else {
  78805. let position = new Vector3().copy(pos).setZ(0);
  78806. return Potree.Utils.datasetPosTransform({ fromDataset: true, position, datasetId: Potree.settings.originDatasetId })
  78807. }
  78808. },
  78809. addEntity:function(entity, parent){
  78810. this.meshGroup.add(entity);
  78811. this.entities.push(entity);
  78812. if(entity.buildType == 'building'){
  78813. this.buildings.push(entity);
  78814. }else {
  78815. parent.buildChildren.push(entity);
  78816. }
  78817. if(entity.buildType == 'room'){
  78818. entity.addEventListener('marker_dropped',()=>{
  78819. this.fitPullBox();
  78820. });
  78821. }else if(entity.buildType == 'floor'){
  78822. this.updateBuildingZ(parent);
  78823. parent.dispatchEvent({type:'addFloor'});
  78824. }
  78825. {//仅能存在一个marker被选中。选中的点可以被删除
  78826. entity.addEventListener('clickMarker', (e)=>{
  78827. if(this.selectedMarker == e.marker){
  78828. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78829. this.selectedMarker = null;
  78830. }else {
  78831. if(this.selectedMarker){
  78832. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78833. }
  78834. this.selectedMarker = e.marker;
  78835. this.selectedMarker.dispatchEvent({type:'clickSelect',state:true});
  78836. }
  78837. });
  78838. entity.addEventListener('removeMarker', (e)=>{
  78839. if(this.selectedMarker == e.marker){
  78840. this.selectedMarker = null;
  78841. }
  78842. });
  78843. let unselect = (e)=>{//取消选中实体或删除后
  78844. if(this.selectedMarker && entity.markers.includes(this.selectedMarker)){
  78845. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78846. this.selectedMarker = null;
  78847. }
  78848. };
  78849. entity.addEventListener('dispose', unselect);
  78850. entity.addEventListener('unselect', unselect);
  78851. }
  78852. //console.log('添加实体:', entity.buildType, entity.sid, entity.uuid)
  78853. },
  78854. removeEntity : function(entity){
  78855. if(!this.entities.includes(entity))return
  78856. console.log('删除实体:', entity.buildType, entity.sid);
  78857. if(this.selected == entity){
  78858. this.height_pull_box.visible = false;
  78859. this.selectEntity(null);
  78860. }
  78861. if(entity.buildType == 'building'){
  78862. var index = this.buildings.indexOf(entity);
  78863. if(index>-1){
  78864. this.buildings.splice(index,1);
  78865. }
  78866. }else {
  78867. var index = entity.buildParent.buildChildren.indexOf(entity);
  78868. if(index>-1){
  78869. entity.buildParent.buildChildren.splice(index,1);
  78870. }
  78871. }
  78872. var index = this.entities.indexOf(entity);
  78873. if(index>-1){
  78874. this.entities.splice(index,1);
  78875. }
  78876. entity.dispose();
  78877. let buildChildren = entity.buildChildren.slice();
  78878. buildChildren.forEach(e=>this.removeEntity(e));
  78879. },
  78880. updateBuildingZ:function(building){
  78881. building.buildChildren = building.buildChildren.sort((e,a)=>e.zMin-a.zMin);//从低到高排序
  78882. building.zMin = building.zMax = building.buildChildren[0].zMin; //基底高度
  78883. //building.zMax = building.buildChildren[building.buildChildren.length-1].zMax
  78884. if(this.editing) building.update({dontUpdateChildren:true});
  78885. building.dispatchEvent('updateBuildingZ');
  78886. },
  78887. selectEntity : function(entity, state=true){
  78888. if(state === false){
  78889. entity.unselect();
  78890. if(this.selected == entity)this.selected = null;
  78891. return
  78892. }
  78893. if(this.selected == entity || entity && entity.buildType == 'hole')return
  78894. //this.buildings.forEach(e=>e.unselect())
  78895. this.selected && this.selected.unselect();
  78896. this.height_pull_box.visible = false;
  78897. if(entity){
  78898. entity.select();
  78899. }
  78900. this.selected = entity;
  78901. if(entity && (entity.buildType == 'floor' || entity.buildType == 'room' )){
  78902. this.height_pull_box.visible = true;
  78903. this.fitPullBox();
  78904. }
  78905. if(entity && !entity.isNew && (entity.buildType == 'building' || entity.buildType == 'room' ) && entity.points.length<2){
  78906. this.startInsertion('resume',entity); //继续画
  78907. }
  78908. },
  78909. fitPullBox: function(){ //自适应拖拽楼层的pullMesh
  78910. if(!this.selected || this.selected.buildType!= 'floor' && this.selected.buildType!= 'room')return
  78911. let bound = new Box3();
  78912. bound.expandByObject(this.selected.box);
  78913. let center = bound.getCenter(new Vector3() );
  78914. let size = bound.getSize(new Vector3() );
  78915. this.height_pull_box.scale.copy(size);
  78916. this.height_pull_box.position.copy(center);
  78917. },
  78918. changeZ:function(entity, dirType, value){ // floor or room 修改zMin or zMax
  78919. let max, min; //limit
  78920. if(entity.buildType == 'floor'){//楼层
  78921. let index = entity.buildParent.buildChildren.indexOf(entity);
  78922. if(dirType == 'zMax'){
  78923. let upper = entity.buildParent.buildChildren[index+1];
  78924. entity.zMax = Math.min(Limit.zMax, value);
  78925. min = entity.zMin + minFloorHeight;
  78926. if(entity.zMax < min){
  78927. entity.zMax = min;
  78928. }else {
  78929. if(upper){
  78930. max = upper.zMax - minFloorHeight;
  78931. if(entity.zMax > max){
  78932. entity.zMax = max;
  78933. }
  78934. }
  78935. }
  78936. if(upper){
  78937. upper.zMin = entity.zMax;
  78938. upper.update();
  78939. upper.dispatchEvent({type:'changeHeight'});
  78940. }
  78941. }else {
  78942. let lower = entity.buildParent.buildChildren[index-1];
  78943. entity.zMin = Math.max(Limit.zMin, value);
  78944. max = entity.zMax - minFloorHeight;
  78945. if(entity.zMin > max){
  78946. entity.zMin = max;
  78947. }else {
  78948. if(lower){
  78949. min = lower.zMin + minFloorHeight;
  78950. if(entity.zMin < min){
  78951. entity.zMin = min;
  78952. }
  78953. }
  78954. }
  78955. if(lower){
  78956. lower.zMax = entity.zMin;
  78957. lower.update();
  78958. lower.dispatchEvent({type:'changeHeight'});
  78959. }
  78960. if(index == 0)this.updateBuildingZ(entity.buildParent);
  78961. }
  78962. }else if(entity.buildType == 'room'){//房间
  78963. //按照navvis的是不一定限制在当前楼层,只要高度不超过当前楼层即可。
  78964. let maxHeight = entity.buildParent.zMax - entity.buildParent.zMin;
  78965. if(dirType == 'zMax'){
  78966. min = entity.zMin + minFloorHeight;
  78967. max = entity.zMin + maxHeight;
  78968. entity.zMax = MathUtils.clamp(value, min, max);
  78969. }else {
  78970. min = entity.zMax - maxHeight;
  78971. max = entity.zMax - minFloorHeight;
  78972. entity.zMin = MathUtils.clamp(value, min, max);
  78973. }
  78974. }
  78975. entity.update();
  78976. entity.dispatchEvent({type:'changeHeight'});
  78977. //this.selected.emit('update')
  78978. this.fitPullBox();
  78979. },
  78980. createHeightPull:function(){ //拖拽楼层的bounding box
  78981. let boxGeo = new BoxBufferGeometry( 1, 1, 1/4 );
  78982. let boxMat = new MeshBasicMaterial({
  78983. color:"#F00",
  78984. opacity:0,
  78985. transparent:true,
  78986. depthTest:false,
  78987. side:2
  78988. });
  78989. let height_pull_box_up = new Mesh(boxGeo,boxMat);
  78990. let height_pull_box_down = new Mesh(boxGeo,boxMat);
  78991. height_pull_box_up.name = 'height_pull_box_up';
  78992. height_pull_box_down.name = 'height_pull_box_down';
  78993. this.height_pull_box = new Object3D();
  78994. this.height_pull_box.name = 'height_pull_box';
  78995. this.height_pull_box.add(height_pull_box_up);
  78996. this.height_pull_box.add(height_pull_box_down);
  78997. this.height_pull_box.visible = false;
  78998. this.meshGroup.add(this.height_pull_box);
  78999. height_pull_box_up.position.set(0,0,1/2/* 3/8 */);
  79000. height_pull_box_down.position.set(0,0,-1/2/* -3/8 */);
  79001. viewer.setObjectLayers(this.height_pull_box, 'siteModeSideVisi' );
  79002. let mouseover = (e)=>{
  79003. viewer.dispatchEvent({
  79004. type : "CursorChange", action : "add", name:"siteModelFloorDrag"
  79005. });
  79006. };
  79007. let mouseleave = (e)=>{
  79008. viewer.dispatchEvent({
  79009. type : "CursorChange", action : "remove", name:"siteModelFloorDrag"
  79010. });
  79011. };
  79012. let firstZ, firstIntersect;
  79013. let drag = (e)=>{
  79014. var intersect = e.intersect.orthoIntersect; //不要点云的intersect,只要orthocamera算出的平面intersect
  79015. if(firstIntersect != void 0){
  79016. let moveZ = intersect.z - firstIntersect;
  79017. if(this.selected.buildType == 'floor'){//楼层
  79018. //限制高度不能超过上下
  79019. if(e.target == height_pull_box_up){
  79020. if(firstZ == void 0)firstZ = this.selected.zMax;
  79021. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  79022. }else {
  79023. if(firstZ == void 0)firstZ = this.selected.zMin;
  79024. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  79025. }
  79026. }else if(this.selected.buildType == 'room'){//房屋
  79027. if(e.target == height_pull_box_up){
  79028. if(firstZ == void 0)firstZ = this.selected.zMax;
  79029. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  79030. }else {
  79031. if(firstZ == void 0)firstZ = this.selected.zMin;
  79032. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  79033. }
  79034. }
  79035. }else {
  79036. firstIntersect = intersect.z;
  79037. }
  79038. };
  79039. let drop = (e)=>{
  79040. firstZ = firstIntersect = null;
  79041. };
  79042. height_pull_box_up.addEventListener('mousemove',mouseover);
  79043. height_pull_box_down.addEventListener('mousemove',mouseover);
  79044. height_pull_box_up.addEventListener('mouseleave',mouseleave);
  79045. height_pull_box_down.addEventListener('mouseleave',mouseleave);
  79046. height_pull_box_up.addEventListener('drag',drag);
  79047. height_pull_box_down.addEventListener('drag',drag);
  79048. height_pull_box_up.addEventListener('drop',drop);
  79049. height_pull_box_down.addEventListener('drop',drop);
  79050. },
  79051. pointInWhichEntity(location, buildType, ifIgnoreHole){//buildType是要找的建筑类型
  79052. //location 可以是pano或者坐标
  79053. //由于房间可能在building外,所以房间要另外单独识别。
  79054. let lastResult; //最接近的上一层结果,如果没有result返回这个
  79055. let result;
  79056. let level = {
  79057. building: 0, floor: 1, room: 2
  79058. };
  79059. let traverse = (parent, buildType)=>{//返回第一个符合标准的实体
  79060. let contains;
  79061. if(location instanceof Vector3){
  79062. contains = parent.ifContainsPoint(location);
  79063. }else {//is pano
  79064. contains = parent.panos.includes(location);
  79065. }
  79066. if(contains){
  79067. if(!lastResult || level[lastResult.buildType] < level[parent.buildType] )lastResult = parent;
  79068. if(parent.buildType == buildType){
  79069. return parent
  79070. }else {
  79071. for(let i=0,len=parent.buildChildren.length; i<len; i++){
  79072. let result1 = traverse(parent.buildChildren[i]);
  79073. if(result1) return result1
  79074. }
  79075. }
  79076. }
  79077. };
  79078. //因为建筑可能重叠,所以需要先找到最接近其中心的建筑物
  79079. result = Common.sortByScore(this.buildings, [(building)=>{
  79080. return traverse(building, 'building') //在building中
  79081. }], [(building)=>{ //写法类似pointInWhichPointcloud
  79082. let boundingBox = building.getBound();
  79083. let center = boundingBox.getCenter(new Vector3());
  79084. let position = location instanceof Vector3 ? location : location.position;
  79085. let dis = position.distanceTo(center);
  79086. let size = boundingBox.getSize(new Vector3());
  79087. let length = size.length() / 2;
  79088. return length / dis
  79089. }]);
  79090. let building = result && result[0] && result[0].score > 1 && result[0].item;
  79091. if(buildType == 'building' || !building)return building
  79092. result = traverse(building, buildType);
  79093. /* if(!result && buildType == 'room'){//如果要找的是room, 且按刚才的顺序找不到的话,就单独从所有rooms中找一遍。因为room可能不在floor和building内。
  79094. let rooms = this.entities.filter(e=>e.buildType == 'room');
  79095. result = rooms.find(e=>e.ifContainsPoint(position))
  79096. }*/
  79097. //虽然房间可以画到上级之外,但是为了方便起见,假定房间绝对在楼层之内。找不到的话要调整空间模型了。
  79098. return result || lastResult
  79099. }
  79100. ,
  79101. findPanos: function(){
  79102. {
  79103. this.entities.forEach(entity=>{
  79104. //清空:
  79105. entity.panos = [];
  79106. entity.flagPano = null;
  79107. viewer.images360.panos.forEach(pano=>{
  79108. if(entity.ifContainsPoint(pano.position)){
  79109. entity.panos.push(pano);
  79110. }
  79111. });
  79112. });
  79113. }
  79114. /* viewer.images360.panos.forEach(pano=>{ //一个漫游点只对应一个实体的话
  79115. let result = this.pointInWhichEntity(pano.position, 'room');
  79116. {//get panos for every entities
  79117. let entity = result
  79118. while(entity){
  79119. entity.panos.push(pano);
  79120. entity = entity.buildParent
  79121. }
  79122. }
  79123. }) */
  79124. {//search center pano
  79125. this.entities.forEach(entity=>{
  79126. let panos = entity.panos;
  79127. if(panos.length == 0)return
  79128. let bound = entity.getBound();
  79129. let center = bound.getCenter(new Vector3);
  79130. let request = [];
  79131. let rank = [
  79132. Images360.scoreFunctions.distanceSquared({position: center})
  79133. ];
  79134. //let panos = entity.panos && entity.panos.length ? entity.panos : viewer.images360.panos //entity没有panos的话,就扩大到所有panos
  79135. let r = Common.sortByScore(panos, request, rank);
  79136. if(r && r.length){
  79137. entity.flagPano = r[0].item;
  79138. }else {
  79139. console.error('no flagPano??');
  79140. }
  79141. });
  79142. }
  79143. }
  79144. ,
  79145. findEntityForDataset:function(){//为每一个数据集寻找它所属的最小实体
  79146. /* var entities = this.entities.filter(e=>e.buildType == 'room' || e.buildType == 'floor' && e.buildChildren.length == 0)
  79147. viewer.scene.pointclouds.forEach(pointcloud=>{
  79148. let cloudVolume = pointcloud.getVolume()
  79149. let scores = []
  79150. entities.forEach(entity=>{
  79151. let volume = entity.intersectPointcloudVolume(pointcloud)
  79152. //注:默认已经findPanos过
  79153. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  79154. let panoCount = panos.length
  79155. let score = volume / cloudVolume + panoCount / pointcloud.panos.length
  79156. scores.push({entity, volume, panoCount, score})
  79157. })
  79158. scores.sort((a,b)=>{ return b.score-a.score })
  79159. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  79160. pointcloud.belongToEntity = null
  79161. }else{
  79162. pointcloud.belongToEntity = scores[0].entity;
  79163. }
  79164. }) */
  79165. let getScores = (pointcloud, entities, cloudVolume)=>{
  79166. let scores = [];
  79167. entities.forEach(entity=>{
  79168. let volume = entity.intersectPointcloudVolume(pointcloud);
  79169. //注:默认已经findPanos过
  79170. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  79171. let panoCount = panos.length;
  79172. let score = volume / cloudVolume;
  79173. if(pointcloud.panos.length > 0){
  79174. score += panoCount / pointcloud.panos.length;
  79175. }else {
  79176. //score += 1
  79177. }
  79178. scores.push({entity, volume, panoCount, score});
  79179. });
  79180. scores.sort((a,b)=>{ return b.score-a.score });
  79181. return scores
  79182. };
  79183. viewer.scene.pointclouds.forEach(pointcloud=>{ //先判断父级,如果父集不通过就不判断子级。
  79184. let cloudVolume = pointcloud.getVolume();
  79185. let entities = this.buildings;
  79186. while(1){
  79187. let scores = getScores(pointcloud, entities, cloudVolume);
  79188. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  79189. if(scores[0] && scores[0].entity.buildType == 'room'){
  79190. pointcloud.belongToEntity = scores[0].entity; //当该数据集在楼层中,但不在楼层中的任意一个房间时,任意挂载在其中一个房间上。
  79191. break
  79192. }
  79193. pointcloud.belongToEntity = null;
  79194. break;
  79195. }else {
  79196. entities = scores[0].entity.buildChildren;
  79197. if(entities.length == 0){
  79198. pointcloud.belongToEntity = scores[0].entity;
  79199. break;
  79200. }
  79201. }
  79202. }
  79203. });
  79204. /*
  79205. 旧版:
  79206. 只需要考虑 floor 和 room, 因为building的只有一个基底没高度
  79207. floor 和 room 在空间中没有完全的从属关系,因为room可以超出floor之外。所以直接混在一起来查找,但要排除有房间的楼层。
  79208. (现在改为层层递进查找,否则数据集包含entity多的,会直接挂载到体积最大的房间里,即使看起来主体点云并不在该房间)
  79209. 有的数据集虽然很高,但只有近地面的部分才是主体,这部分一般含有全部漫游点。为了防止上层的实体因体积较大而分数高,就把包含漫游点的个数也加入考虑。
  79210. 重叠体积大、且包含漫游点最多的最小实体将会拥有该点云。
  79211. 期望: 最好不挂载到最小子级,因为现在有房间都到房间里了。
  79212. */
  79213. }
  79214. ,
  79215. clear:function(){//清空
  79216. /* entities:[], //所有实体
  79217. buildings:[], //所有建筑父集
  79218. meshGroup: new THREE.Object3D, */
  79219. this.selectEntity(null);
  79220. let length = this.entities.length;
  79221. for(let i=0;i<length;i++){
  79222. this.entities[i].dispose();
  79223. }
  79224. this.entities = [];
  79225. this.buildings = [];
  79226. this.inEntity = null;
  79227. }
  79228. ,
  79229. gotoEntity(id, isNearBy, duration=1000) {
  79230. var entity = this.entities.find(e => e.sid == id);
  79231. let aimPano;
  79232. if (!entity) {
  79233. return console.error('没找到entity ')
  79234. }
  79235. if(Potree.settings.displayMode == 'showPanos'){
  79236. if (isNearBy && entity.panos.length) {
  79237. if(entity.panos.includes(viewer.images360.currentPano)) return 'posNoChange' //已在当前实体中
  79238. let position = viewer.scene.getActiveCamera().position;
  79239. let request = [];
  79240. let rank = [Images360.scoreFunctions.distanceSquared({ position })];
  79241. let r = Common.sortByScore(entity.panos, request, rank);
  79242. aimPano = r[0].item;
  79243. } else {
  79244. if (!entity.flagPano) {
  79245. return console.log('没有flagPano')
  79246. }
  79247. aimPano = entity.flagPano;
  79248. }
  79249. if(aimPano == viewer.images360.currentPano) return 'posNoChange'
  79250. viewer.images360.flyToPano(aimPano);
  79251. }else {
  79252. if(isNearBy && entity.ifContainsPoint(viewer.images360.position) ){
  79253. return 'posNoChange' //已在当前实体中
  79254. }
  79255. let boundingBox = entity.getBound();
  79256. let position = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  79257. if(viewer.modules.Clip && viewer.modules.Clip.editing){
  79258. viewer.modules.Clip.bus.dispatchEvent({type:'flyToPos', position});
  79259. }else {
  79260. if(math.closeTo(position, viewer.images360.position)) return 'posNoChange'
  79261. let size = boundingBox.getSize(new Vector3());
  79262. viewer.scene.view.setView({position, duration});
  79263. viewer.mapViewer.moveTo(position, size, duration);
  79264. }
  79265. }
  79266. return true
  79267. },
  79268. focusEntity(id){
  79269. var entity = this.entities.find(e => e.sid == id);
  79270. let boundingBox = entity.getBound();
  79271. //let boundSize = boundingBox.getSize(new THREE.Vector3())
  79272. let center = boundingBox.getCenter(new Vector3());
  79273. this.SplitScreen.focusOnObject(boundingBox, center);
  79274. this.gotoEntity(id, false, 0);
  79275. },
  79276. removeIlligalArchi(){//删除marker数量小于3个的建筑,当保存时
  79277. let needDelete = [];
  79278. this.entities.forEach(e=>{
  79279. if(e.points.length<3){
  79280. needDelete.push(e);
  79281. }
  79282. });
  79283. needDelete.forEach(e=>this.removeEntity(e));
  79284. },
  79285. };
  79286. // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)
  79287. class InfiniteGridHelper extends Mesh{
  79288. constructor(size1, size2, color, distance, opacity1=0.2, opacity2=1){
  79289. color = color || new Color('white');
  79290. size1 = size1 || 10;
  79291. size2 = size2 || 100;
  79292. distance = distance || 8000; //可视距离?越远越模糊
  79293. const geometry = new PlaneBufferGeometry(2, 2, 1, 1);
  79294. const material = new ShaderMaterial({
  79295. side: DoubleSide,
  79296. uniforms: {
  79297. uSize1: {
  79298. value: size1
  79299. },
  79300. uSize2: {
  79301. value: size2
  79302. },
  79303. opacity1:{//线条1的
  79304. value: opacity1
  79305. },
  79306. opacity2:{//线条2的
  79307. value: opacity2
  79308. },
  79309. uColor: {
  79310. value: color
  79311. },
  79312. uDistance: {
  79313. value: distance
  79314. }
  79315. },
  79316. transparent: true,
  79317. vertexShader: `
  79318. varying vec3 worldPosition;
  79319. uniform float uDistance;
  79320. void main() {
  79321. vec3 pos = position.xyz * uDistance;
  79322. pos.xy += cameraPosition.xy;
  79323. worldPosition = pos;
  79324. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
  79325. }
  79326. `,
  79327. fragmentShader: `
  79328. varying vec3 worldPosition;
  79329. uniform float uSize1;
  79330. uniform float uSize2;
  79331. uniform float opacity1;
  79332. uniform float opacity2;
  79333. uniform vec3 uColor;
  79334. uniform float uDistance;
  79335. float getGrid(float size) {
  79336. vec2 r = worldPosition.xy / size;
  79337. vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
  79338. float line = min(grid.x, grid.y);
  79339. return 1.0 - min(line, 1.0);
  79340. }
  79341. //为何侧面看不到线,因为mesh的正侧面都看不到?
  79342. void main() {
  79343. float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);
  79344. float g1 = getGrid(uSize1);
  79345. float g2 = getGrid(uSize2);
  79346. gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
  79347. //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
  79348. gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);
  79349. if ( gl_FragColor.a <= 0.0 ) discard;
  79350. }
  79351. `,
  79352. extensions: {
  79353. derivatives: true
  79354. }
  79355. });
  79356. super(geometry, material);
  79357. this.frustumCulled = false;
  79358. }
  79359. };
  79360. /*
  79361. THREE.InfiniteGridHelper.prototype = {
  79362. ...THREE.Mesh.prototype,
  79363. ...THREE.Object3D.prototype,
  79364. ...THREE.EventDispatcher.prototype
  79365. };
  79366. */
  79367. //import {Utils} from "../../utils.js";
  79368. var TransformControls = function ( camera, domElement, options ) {
  79369. if ( domElement === undefined ) {
  79370. console.warn( 'THREE.TransformControls: The second parameter "domElement" is now mandatory.' );
  79371. domElement = document;
  79372. }
  79373. Object3D.call( this );
  79374. this.visible = false;
  79375. this.domElement = domElement;
  79376. var _gizmo = new TransformControlsGizmo(options);
  79377. this.add( _gizmo );
  79378. this._gizmo = _gizmo;
  79379. var _plane = new TransformControlsPlane(options);
  79380. this.add( _plane );
  79381. /* this.linesAssistance = new TransformControlsLines(options); //水平 垂直 辅助
  79382. this.add( this.linesAssistance ); */
  79383. var scope = this;
  79384. //this.player = options.player;//xzw add
  79385. this.options = options;//xzw add
  79386. // Define properties with getters/setter
  79387. // Setting the defined property will automatically trigger change event
  79388. // Defined properties are passed down to gizmo and plane
  79389. defineProperty( "camera", camera );
  79390. defineProperty( "object", undefined );
  79391. defineProperty( "enabled", true );
  79392. defineProperty( "axis", null );
  79393. defineProperty( "mode", "translate" );
  79394. defineProperty( "translationSnap", null );
  79395. defineProperty( "rotationSnap", null );
  79396. defineProperty( "scaleSnap", null );
  79397. defineProperty( "space", "world" );
  79398. defineProperty( "size", 1 );
  79399. defineProperty( "dragging", false );
  79400. defineProperty( "showX", true );
  79401. defineProperty( "showY", true );
  79402. defineProperty( "showZ", true );
  79403. var changeEvent = { type: "change" };
  79404. var mouseDownEvent = { type: "mouseDown" };
  79405. var mouseUpEvent = { type: "mouseUp", mode: scope.mode };
  79406. var objectChangeEvent = { type: "objectChange" };
  79407. // Reusable utility variables
  79408. var ray = new Raycaster();
  79409. var _tempVector = new Vector3();
  79410. var _tempVector2 = new Vector3();
  79411. var _tempQuaternion = new Quaternion();
  79412. var _unit = {
  79413. X: new Vector3( 1, 0, 0 ),
  79414. Y: new Vector3( 0, 1, 0 ),
  79415. Z: new Vector3( 0, 0, 1 )
  79416. };
  79417. var pointStart = new Vector3();
  79418. var pointEnd = new Vector3();
  79419. var offset = new Vector3();
  79420. var rotationAxis = new Vector3();
  79421. var startNorm = new Vector3();
  79422. var endNorm = new Vector3();
  79423. var rotationAngle = 0;
  79424. var cameraPosition = new Vector3();
  79425. var cameraQuaternion = new Quaternion();
  79426. var cameraScale = new Vector3();
  79427. var parentPosition = new Vector3();
  79428. var parentQuaternion = new Quaternion();
  79429. var parentQuaternionInv = new Quaternion();
  79430. var parentScale = new Vector3();
  79431. var worldPositionStart = new Vector3();
  79432. var worldQuaternionStart = new Quaternion();
  79433. var worldScaleStart = new Vector3();
  79434. var worldPosition = new Vector3();
  79435. var worldQuaternion = new Quaternion();
  79436. var worldQuaternionInv = new Quaternion();
  79437. var worldScale = new Vector3();
  79438. var eye = new Vector3();
  79439. var positionStart = new Vector3();
  79440. var quaternionStart = new Quaternion();
  79441. var scaleStart = new Vector3();
  79442. // TODO: remove properties unused in plane and gizmo
  79443. defineProperty( "worldPosition", worldPosition );
  79444. defineProperty( "worldPositionStart", worldPositionStart );
  79445. defineProperty( "worldQuaternion", worldQuaternion );
  79446. defineProperty( "worldQuaternionStart", worldQuaternionStart );
  79447. defineProperty( "cameraPosition", cameraPosition );
  79448. defineProperty( "cameraQuaternion", cameraQuaternion );
  79449. defineProperty( "pointStart", pointStart );
  79450. defineProperty( "pointEnd", pointEnd );
  79451. defineProperty( "rotationAxis", rotationAxis );
  79452. defineProperty( "rotationAngle", rotationAngle );
  79453. defineProperty( "eye", eye );
  79454. {
  79455. domElement.addEventListener( "mousedown", onPointerDown, false );
  79456. domElement.addEventListener( "touchstart", onPointerDown, false );
  79457. domElement.addEventListener( "mousemove", onPointerHover, false );
  79458. domElement.addEventListener( "touchmove", onPointerHover, false );
  79459. domElement.addEventListener( "touchmove", onPointerMove, false );
  79460. document.addEventListener( "mouseup", onPointerUp, false );
  79461. domElement.addEventListener( "touchend", onPointerUp, false );
  79462. domElement.addEventListener( "touchcancel", onPointerUp, false );
  79463. domElement.addEventListener( "touchleave", onPointerUp, false );
  79464. viewer.addEventListener('global_drag',(e)=>{
  79465. if(this.dragging){
  79466. this.pointerMove();
  79467. return {stopContinue:true}
  79468. }
  79469. },10);
  79470. }
  79471. this.dispose = function () {
  79472. domElement.removeEventListener( "mousedown", onPointerDown );
  79473. domElement.removeEventListener( "touchstart", onPointerDown );
  79474. domElement.removeEventListener( "mousemove", onPointerHover );
  79475. domElement.removeEventListener( "mousemove", onPointerMove );
  79476. domElement.removeEventListener( "touchmove", onPointerHover );
  79477. domElement.removeEventListener( "touchmove", onPointerMove );
  79478. document.removeEventListener( "mouseup", onPointerUp );
  79479. domElement.removeEventListener( "touchend", onPointerUp );
  79480. domElement.removeEventListener( "touchcancel", onPointerUp );
  79481. domElement.removeEventListener( "touchleave", onPointerUp );
  79482. this.traverse( function ( child ) {
  79483. if ( child.geometry ) child.geometry.dispose();
  79484. if ( child.material ) child.material.dispose();
  79485. } );
  79486. };
  79487. // Set current object
  79488. this.attach = function ( object ) {
  79489. this.object = object;
  79490. this.visible = true;
  79491. //Config.keyCon = false;//add
  79492. //this.linesAssistance.setVisible(true)
  79493. return this;
  79494. };
  79495. // Detatch from object
  79496. this.detach = function () {
  79497. this.object = undefined;
  79498. this.visible = false;
  79499. this.axis = null;
  79500. //Config.keyCon = true;//add
  79501. //this.linesAssistance.setVisible(false)
  79502. return this;
  79503. };
  79504. /* this.hideAxis = function ( mode, axis=[] ) {//xzw add 设置不可见的axis
  79505. var handles = [];
  79506. handles = handles.concat( this._gizmo.picker[ mode ].children );
  79507. handles = handles.concat( this._gizmo.gizmo[ mode ].children );
  79508. handles = handles.concat( this._gizmo.helper[ mode ].children );
  79509. handles.forEach(e=>e.visible = false)
  79510. axis.forEach(name=>{
  79511. handles.filter(handle =>!handle.name.includes(name))
  79512. })
  79513. handles.forEach(e=>e.visible = true)
  79514. }; */
  79515. // Defined getter, setter and store for a property
  79516. function defineProperty( propName, defaultValue ) {
  79517. var propValue = defaultValue;
  79518. Object.defineProperty( scope, propName, {
  79519. get: function () {
  79520. return propValue !== undefined ? propValue : defaultValue;
  79521. },
  79522. set: function ( value ) {
  79523. if ( propValue !== value ) {
  79524. propValue = value;
  79525. _plane[ propName ] = value;
  79526. _gizmo[ propName ] = value;
  79527. scope.dispatchEvent( { type: propName + "-changed", value: value } );
  79528. scope.dispatchEvent( changeEvent );
  79529. }
  79530. }
  79531. } );
  79532. scope[ propName ] = defaultValue;
  79533. _plane[ propName ] = defaultValue;
  79534. _gizmo[ propName ] = defaultValue;
  79535. }
  79536. // updateMatrixWorld updates key transformation variables
  79537. this.updateMatrixWorld = function () {
  79538. if ( this.object !== undefined ) {
  79539. this.object.updateMatrixWorld();
  79540. this.object.parent.matrixWorld.decompose( parentPosition, parentQuaternion, parentScale );
  79541. this.object.matrixWorld.decompose( worldPosition, worldQuaternion, worldScale );
  79542. //add 使坐标轴在boundingBox中心
  79543. this.object.boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  79544. parentQuaternionInv.copy( parentQuaternion ).invert();
  79545. worldQuaternionInv.copy( worldQuaternion ).invert();
  79546. }
  79547. this.camera.updateMatrixWorld();
  79548. this.camera.matrixWorld.decompose( cameraPosition, cameraQuaternion, cameraScale );
  79549. if(this.camera.type == "OrthographicCamera"){//xzw add
  79550. eye.copy( this.view.direction);
  79551. }else {
  79552. eye.copy( cameraPosition ).sub( worldPosition ).normalize();
  79553. }
  79554. Object3D.prototype.updateMatrixWorld.call( this );
  79555. };
  79556. this.pointerHover = function () {
  79557. let pointer = viewer.inputHandler.pointer;
  79558. if ( this.object === undefined)return
  79559. //if(this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return;
  79560. if(!this.dragging){
  79561. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79562. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79563. ray.set(origin, direction);
  79564. viewer.setCameraLayers(ray, //设置能识别到的layers
  79565. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79566. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79567. );
  79568. var intersect = ray.intersectObjects( _gizmo.picker[ this.mode ].children, true )[ 0 ] || false;
  79569. if ( intersect ) {
  79570. this.axis = intersect.object.name;
  79571. } else {
  79572. this.axis = null;
  79573. }
  79574. }else {
  79575. //this.pointerMove()
  79576. }
  79577. };
  79578. this.pointerDown = function ( /* pointer */ ) {
  79579. let pointer = viewer.inputHandler.pointer;
  79580. if ( this.object === undefined || this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */ ) return;
  79581. if ( /* ( pointer.button === 0 || pointer.button === undefined ) && */ this.axis !== null ) {
  79582. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79583. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79584. ray.set(origin, direction);
  79585. viewer.setCameraLayers(ray, //设置能识别到的layers
  79586. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79587. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79588. );
  79589. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79590. if ( planeIntersect ) {
  79591. var space = this.space;
  79592. if ( this.mode === 'scale' ) {
  79593. space = 'local';
  79594. } else if ( this.axis === 'E' || this.axis === 'XYZE' || this.axis === 'XYZ' ) {
  79595. space = 'world';
  79596. }
  79597. if ( space === 'local' && this.mode === 'rotate' ) {
  79598. var snap = this.rotationSnap;
  79599. if ( this.axis === 'X' && snap ) this.object.rotation.x = Math.round( this.object.rotation.x / snap ) * snap;
  79600. if ( this.axis === 'Y' && snap ) this.object.rotation.y = Math.round( this.object.rotation.y / snap ) * snap;
  79601. if ( this.axis === 'Z' && snap ) this.object.rotation.z = Math.round( this.object.rotation.z / snap ) * snap;
  79602. }
  79603. this.object.updateMatrixWorld();
  79604. this.object.parent.updateMatrixWorld();
  79605. positionStart.copy( this.object.position );
  79606. quaternionStart.copy( this.object.quaternion );
  79607. scaleStart.copy( this.object.scale );
  79608. this.object.matrixWorld.decompose( worldPositionStart, worldQuaternionStart, worldScaleStart );
  79609. //add: 使坐标轴在boundingBox中心
  79610. this.object.boundingBox && this.object.boundingBox.getCenter(worldPositionStart).applyMatrix4(this.object.matrixWorld);
  79611. pointStart.copy( planeIntersect.point ).sub( worldPositionStart );
  79612. /* if(this.player.cameraControls.activeControl){
  79613. //this.player.cameraControls.activeControl.locked = true; //add
  79614. this.player.cameraControls.activeControl.enabled = false; //add
  79615. } */
  79616. }
  79617. this.dragging = true;
  79618. mouseDownEvent.mode = this.mode;
  79619. this.dispatchEvent( mouseDownEvent );
  79620. }
  79621. };
  79622. this.pointerMove = function ( /* pointer */ ) {
  79623. let pointer = viewer.inputHandler.pointer;
  79624. var axis = this.axis;
  79625. var mode = this.mode;
  79626. var object = this.object;
  79627. var space = this.space;
  79628. if ( mode === 'scale' ) {
  79629. space = 'local';
  79630. } else if ( axis === 'E' || axis === 'XYZE' || axis === 'XYZ' ) {
  79631. space = 'world';
  79632. }
  79633. if ( object === undefined || axis === null || this.dragging === false || ( pointer.button !== undefined && pointer.button !== 0 ) ) return;
  79634. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79635. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79636. ray.set(origin, direction);
  79637. viewer.setCameraLayers(ray, //设置能识别到的layers
  79638. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79639. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79640. );
  79641. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79642. if ( planeIntersect === false ) return;
  79643. pointEnd.copy( planeIntersect.point ).sub( worldPositionStart );
  79644. if ( mode === 'translate' ) {
  79645. // Apply translate
  79646. offset.copy( pointEnd ).sub( pointStart );
  79647. if ( space === 'local' && axis !== 'XYZ' ) {
  79648. offset.applyQuaternion( worldQuaternionInv );
  79649. }
  79650. if ( axis.indexOf( 'X' ) === - 1 ) offset.x = 0;
  79651. if ( axis.indexOf( 'Y' ) === - 1 ) offset.y = 0;
  79652. if ( axis.indexOf( 'Z' ) === - 1 ) offset.z = 0;
  79653. if ( space === 'local' && axis !== 'XYZ' ) {
  79654. //xzw 加,否则会反向---------------
  79655. object.scale.x < 0 && (offset.x *= -1);
  79656. object.scale.y < 0 && (offset.y *= -1);
  79657. object.scale.z < 0 && (offset.z *= -1);
  79658. //---------------------------------
  79659. offset.applyQuaternion( quaternionStart ).divide( parentScale );
  79660. } else {
  79661. offset.applyQuaternion( parentQuaternionInv ).divide( parentScale );
  79662. }
  79663. object.position.copy( offset ).add( positionStart );
  79664. // Apply translation snap
  79665. if ( this.translationSnap ) {
  79666. if ( space === 'local' ) {
  79667. object.position.applyQuaternion( _tempQuaternion.copy( quaternionStart ).invert() );
  79668. if ( axis.search( 'X' ) !== - 1 ) {
  79669. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79670. }
  79671. if ( axis.search( 'Y' ) !== - 1 ) {
  79672. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79673. }
  79674. if ( axis.search( 'Z' ) !== - 1 ) {
  79675. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79676. }
  79677. object.position.applyQuaternion( quaternionStart );
  79678. }
  79679. if ( space === 'world' ) {
  79680. if ( object.parent ) {
  79681. object.position.add( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79682. }
  79683. if ( axis.search( 'X' ) !== - 1 ) {
  79684. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79685. }
  79686. if ( axis.search( 'Y' ) !== - 1 ) {
  79687. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79688. }
  79689. if ( axis.search( 'Z' ) !== - 1 ) {
  79690. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79691. }
  79692. if ( object.parent ) {
  79693. object.position.sub( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79694. }
  79695. }
  79696. }
  79697. //add:
  79698. object.dispatchEvent({
  79699. type: "position_changed"
  79700. });
  79701. } else if ( mode === 'scale' ) {
  79702. if ( axis.search( 'XYZ' ) !== - 1 ) {
  79703. var d = pointEnd.length() / pointStart.length();
  79704. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79705. if(options.NoScaleZ){//xzw add
  79706. _tempVector2.set( d, d, 1 );
  79707. }else {
  79708. _tempVector2.set( d, d, d );
  79709. }
  79710. }else if ( axis.search( 'XY' ) !== - 1 ) { //add 等比例for plane
  79711. var d = pointEnd.length() / pointStart.length();
  79712. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79713. _tempVector2.set( d, d, 1 );
  79714. }else {
  79715. _tempVector.copy( pointStart );
  79716. _tempVector2.copy( pointEnd );
  79717. _tempVector.applyQuaternion( worldQuaternionInv );
  79718. _tempVector2.applyQuaternion( worldQuaternionInv );
  79719. _tempVector2.divide( _tempVector );
  79720. if ( axis.search( 'X' ) === - 1 ) {
  79721. _tempVector2.x = 1;
  79722. }
  79723. if ( axis.search( 'Y' ) === - 1 ) {
  79724. _tempVector2.y = 1;
  79725. }
  79726. if ( axis.search( 'Z' ) === - 1 ) {
  79727. _tempVector2.z = 1;
  79728. }
  79729. }
  79730. // Apply scale
  79731. object.scale.copy( scaleStart ).multiply( _tempVector2 );
  79732. if ( this.scaleSnap ) {
  79733. if ( axis.search( 'X' ) !== - 1 ) {
  79734. object.scale.x = Math.round( object.scale.x / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79735. }
  79736. if ( axis.search( 'Y' ) !== - 1 ) {
  79737. object.scale.y = Math.round( object.scale.y / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79738. }
  79739. if ( axis.search( 'Z' ) !== - 1 ) {
  79740. object.scale.z = Math.round( object.scale.z / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79741. }
  79742. }
  79743. //add:
  79744. object.dispatchEvent({
  79745. type: "scale_changed"
  79746. });
  79747. } else if ( mode === 'rotate' ) {
  79748. offset.copy( pointEnd ).sub( pointStart );
  79749. var ROTATION_SPEED = 2 / worldPosition.distanceTo( _tempVector.setFromMatrixPosition( this.camera.matrixWorld ) );
  79750. if ( axis === 'E' ) {
  79751. rotationAxis.copy( eye );
  79752. rotationAngle = pointEnd.angleTo( pointStart );
  79753. startNorm.copy( pointStart ).normalize();
  79754. endNorm.copy( pointEnd ).normalize();
  79755. rotationAngle *= ( endNorm.cross( startNorm ).dot( eye ) < 0 ? 1 : - 1 );
  79756. } else if ( axis === 'XYZE' ) {
  79757. rotationAxis.copy( offset ).cross( eye ).normalize();
  79758. rotationAngle = offset.dot( _tempVector.copy( rotationAxis ).cross( this.eye ) ) * ROTATION_SPEED;
  79759. } else if ( axis === 'X' || axis === 'Y' || axis === 'Z' ) {
  79760. rotationAxis.copy( _unit[ axis ] );
  79761. _tempVector.copy( _unit[ axis ] );
  79762. if ( space === 'local' ) {
  79763. _tempVector.applyQuaternion( worldQuaternion );
  79764. }
  79765. rotationAngle = offset.dot( _tempVector.cross( eye ).normalize() ) * ROTATION_SPEED;
  79766. }
  79767. // Apply rotation snap
  79768. if ( this.rotationSnap ) rotationAngle = Math.round( rotationAngle / this.rotationSnap ) * this.rotationSnap;
  79769. this.rotationAngle = rotationAngle;
  79770. // Apply rotate
  79771. if ( space === 'local' && axis !== 'E' && axis !== 'XYZE' ) {
  79772. object.scale[axis.toLowerCase()] < 0 && (rotationAngle *= -1); //xzw 加,否则会反向
  79773. object.quaternion.copy( quaternionStart );
  79774. object.quaternion.multiply( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) ).normalize();
  79775. } else {
  79776. rotationAxis.applyQuaternion( parentQuaternionInv );
  79777. object.quaternion.copy( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) );
  79778. object.quaternion.multiply( quaternionStart ).normalize();
  79779. }
  79780. //add:
  79781. object.dispatchEvent({
  79782. type: "rotation_changed"
  79783. });
  79784. }
  79785. this.dispatchEvent( changeEvent );
  79786. this.dispatchEvent( objectChangeEvent );
  79787. };
  79788. this.pointerUp = function ( pointer ) {
  79789. //if ( pointer.button !== undefined && pointer.button !== 0 ) return;
  79790. if ( this.dragging && ( this.axis !== null ) ) {
  79791. mouseUpEvent.mode = this.mode;
  79792. this.dispatchEvent( mouseUpEvent );
  79793. /* if(this.player.cameraControls.activeControl){
  79794. //this.player.cameraControls.activeControl.locked = false; //add
  79795. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79796. this.player.cameraControls.activeControl.enabled = true
  79797. } */
  79798. }
  79799. this.dragging = false;
  79800. //if ( pointer.button === undefined ) this.axis = null;
  79801. /* if(this.player.cameraControls.activeControl){
  79802. //this.player.cameraControls.activeControl.locked = false; //add
  79803. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79804. this.player.cameraControls.activeControl.enabled = true
  79805. } */
  79806. };
  79807. // normalize mouse / touch pointer and remap {x,y} to view space.
  79808. function getPointer( event ) {
  79809. if(!event){
  79810. console.log('hhahhhahah');
  79811. return;
  79812. }
  79813. if ( document.pointerLockElement ) {
  79814. return {
  79815. x: 0,
  79816. y: 0,
  79817. button: event.button
  79818. };
  79819. } else {
  79820. var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event;
  79821. var rect = domElement.getBoundingClientRect();
  79822. return {
  79823. x: ( pointer.clientX - rect.left ) / rect.width * 2 - 1,
  79824. y: - ( pointer.clientY - rect.top ) / rect.height * 2 + 1,
  79825. button: event.button
  79826. };
  79827. }
  79828. }
  79829. // mouse / touch event handlers
  79830. function onPointerHover( event ) {
  79831. if ( ! scope.enabled ) return;
  79832. //scope.pointerHover( getPointer( event ) );
  79833. scope.pointerHover( );
  79834. }
  79835. function onPointerDown( event ) {
  79836. if ( ! scope.enabled ) return;
  79837. //document.addEventListener( "mousemove", onPointerMove, false );
  79838. /* scope.pointerHover( getPointer( event ) );
  79839. scope.pointerDown( getPointer( event ) ); */
  79840. scope.pointerHover( );
  79841. scope.pointerDown();
  79842. }
  79843. this.onPointerDown = onPointerDown;
  79844. function onPointerMove( event ) {
  79845. if ( ! scope.enabled || !this.dragging) return; //xzw change
  79846. //scope.pointerMove( getPointer( event ) );
  79847. scope.pointerMove( );
  79848. }
  79849. this.onPointerMove = onPointerMove;
  79850. function onPointerUp( event ) {
  79851. if ( ! scope.enabled ) return;
  79852. //document.removeEventListener( "mousemove", onPointerMove, false );
  79853. //scope.pointerUp( getPointer( event ) );
  79854. scope.pointerUp( );
  79855. }
  79856. this.onPointerUp = onPointerUp;
  79857. // TODO: deprecate
  79858. this.getMode = function () {
  79859. return scope.mode;
  79860. };
  79861. this.setMode = function ( mode ) {
  79862. scope.mode = mode;
  79863. };
  79864. this.setTranslationSnap = function ( translationSnap ) {
  79865. scope.translationSnap = translationSnap;
  79866. };
  79867. this.setRotationSnap = function ( rotationSnap ) {
  79868. scope.rotationSnap = rotationSnap;
  79869. };
  79870. this.setScaleSnap = function ( scaleSnap ) {
  79871. scope.scaleSnap = scaleSnap;
  79872. };
  79873. this.setSize = function ( size ) {
  79874. scope.size = size;
  79875. };
  79876. this.setSpace = function ( space ) {
  79877. scope.space = space;
  79878. };
  79879. this.update = function () {
  79880. console.warn( 'THREE.TransformControls: update function has no more functionality and therefore has been deprecated.' );
  79881. };
  79882. };
  79883. var TransformControlsGizmo = function (options) {
  79884. 'use strict';
  79885. Object3D.call( this );
  79886. this.type = 'TransformControlsGizmo';
  79887. // shared materials
  79888. this.hideAxis = {};
  79889. var gizmoMaterial = new MeshBasicMaterial( {
  79890. depthTest: false,
  79891. depthWrite: false,
  79892. transparent: true,
  79893. side: DoubleSide,
  79894. fog: false
  79895. } );
  79896. var gizmoLineMaterial = new LineBasicMaterial( {
  79897. depthTest: false,
  79898. depthWrite: false,
  79899. transparent: true,
  79900. fog: false
  79901. } );
  79902. // Make unique material for each axis/color
  79903. var matInvisible = gizmoMaterial.clone();
  79904. matInvisible.opacity = 0.15;
  79905. var matHelper = gizmoMaterial.clone();
  79906. matHelper.opacity = 0.1;
  79907. var matRed = gizmoMaterial.clone();
  79908. matRed.color.set( 0xff0000 );
  79909. var matGreen = gizmoMaterial.clone();
  79910. matGreen.color.set( 0x00ff00 );
  79911. var matBlue = gizmoMaterial.clone();
  79912. matBlue.color.set( 0x0000ff );
  79913. var matWhiteTransparent = gizmoMaterial.clone();
  79914. matWhiteTransparent.opacity = 0.35;
  79915. matWhiteTransparent.color.set( 0x00d0fd );//xzw add
  79916. var matYellowTransparent = matWhiteTransparent.clone();
  79917. matYellowTransparent.color.set( 0xffff00 );
  79918. var matCyanTransparent = matWhiteTransparent.clone();
  79919. matCyanTransparent.color.set( 0x00ffff );
  79920. var matMagentaTransparent = matWhiteTransparent.clone();
  79921. matMagentaTransparent.color.set( 0xff00ff );
  79922. var matYellow = gizmoMaterial.clone();
  79923. matYellow.color.set( 0xffff00 );
  79924. var matLineRed = gizmoLineMaterial.clone();
  79925. matLineRed.color.set( 0xff0000 );
  79926. var matLineGreen = gizmoLineMaterial.clone();
  79927. matLineGreen.color.set( 0x00ff00 );
  79928. var matLineBlue = gizmoLineMaterial.clone();
  79929. matLineBlue.color.set( 0x0000ff );
  79930. var matLineCyan = gizmoLineMaterial.clone();
  79931. matLineCyan.color.set( 0x00ffff );
  79932. var matLineMagenta = gizmoLineMaterial.clone();
  79933. matLineMagenta.color.set( 0xff00ff );
  79934. var matLineYellow = gizmoLineMaterial.clone();
  79935. matLineYellow.color.set( 0xffff00 );
  79936. var matLineGray = gizmoLineMaterial.clone();
  79937. matLineGray.color.set( 0x787878 );
  79938. var matLineYellowTransparent = matLineYellow.clone();
  79939. matLineYellowTransparent.opacity = 0.25;
  79940. // reusable geometry
  79941. var arrowGeometry = new CylinderBufferGeometry( 0, 0.05, 0.2, 12, 1, false );
  79942. var scaleHandleGeometry = new BoxBufferGeometry( 0.125, 0.125, 0.125 );
  79943. var lineGeometry = new BufferGeometry( );
  79944. //lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) );
  79945. lineGeometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 0, 0]), 3 ));
  79946. var CircleGeometry = function ( radius, arc ) {
  79947. var geometry = new BufferGeometry( );
  79948. var vertices = [];
  79949. for ( var i = 0; i <= 64 * arc; ++ i ) {
  79950. vertices.push( 0, Math.cos( i / 32 * Math.PI ) * radius, Math.sin( i / 32 * Math.PI ) * radius );
  79951. }
  79952. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  79953. geometry.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3 ));
  79954. return geometry;
  79955. };
  79956. // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position
  79957. var TranslateHelperGeometry = function () {
  79958. var geometry = new BufferGeometry();
  79959. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) );
  79960. geometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 1, 1 ]), 3 ));
  79961. return geometry;
  79962. };
  79963. // Gizmo definitions - custom hierarchy definitions for setupGizmo() function
  79964. var gizmoTranslate = {
  79965. X: [
  79966. [ new Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, - Math.PI / 2 ], null, 'fwd' ],
  79967. //[ new THREE.Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, Math.PI / 2 ], null, 'bwd' ],
  79968. [ new Line( lineGeometry, matLineRed ) ]
  79969. ],
  79970. Y: [
  79971. [ new Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], null, null, 'fwd' ],
  79972. //[ new THREE.Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], [ Math.PI, 0, 0 ], null, 'bwd' ],
  79973. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ]]
  79974. ],
  79975. Z: [
  79976. [ new Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ Math.PI / 2, 0, 0 ], null, 'fwd' ],
  79977. //[ new THREE.Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ - Math.PI / 2, 0, 0 ], null, 'bwd' ],
  79978. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ]]
  79979. ],
  79980. /* XYZ: [
  79981. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
  79982. ], */
  79983. XY: [
  79984. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent.clone() ), [ 0.15, 0.15, 0 ]],
  79985. [ new Line( lineGeometry, matLineYellow ), [ 0.18, 0.3, 0 ], null, [ 0.125, 1, 1 ]],
  79986. [ new Line( lineGeometry, matLineYellow ), [ 0.3, 0.18, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  79987. ],
  79988. YZ: [
  79989. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matCyanTransparent.clone() ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]],
  79990. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.18, 0.3 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  79991. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.3, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  79992. ],
  79993. XZ: [
  79994. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matMagentaTransparent.clone() ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]],
  79995. [ new Line( lineGeometry, matLineMagenta ), [ 0.18, 0, 0.3 ], null, [ 0.125, 1, 1 ]],
  79996. [ new Line( lineGeometry, matLineMagenta ), [ 0.3, 0, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  79997. ]
  79998. };
  79999. var pickerTranslate = {
  80000. X: [
  80001. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0.6, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  80002. ],
  80003. Y: [
  80004. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0.6, 0 ]]
  80005. ],
  80006. Z: [
  80007. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0, 0.6 ], [ Math.PI / 2, 0, 0 ]]
  80008. ],
  80009. /* XYZ: [
  80010. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.2, 0 ), matInvisible ) ]
  80011. ], */
  80012. XY: [
  80013. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0.2, 0 ]]
  80014. ],
  80015. YZ: [
  80016. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0, 0.2, 0.2 ], [ 0, Math.PI / 2, 0 ]]
  80017. ],
  80018. XZ: [
  80019. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0, 0.2 ], [ - Math.PI / 2, 0, 0 ]]
  80020. ]
  80021. };
  80022. var helperTranslate = {
  80023. START: [
  80024. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  80025. ],
  80026. END: [
  80027. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  80028. ],
  80029. DELTA: [
  80030. [ new Line( TranslateHelperGeometry(), matHelper ), null, null, null, 'helper' ]
  80031. ],
  80032. X: [
  80033. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80034. ],
  80035. Y: [
  80036. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  80037. ],
  80038. Z: [
  80039. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  80040. ]
  80041. };
  80042. var gizmoRotate = {
  80043. X: [
  80044. [ new Line( CircleGeometry( 1, 0.5 ), matLineRed ) ],
  80045. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matRed ), [ 0, 0, 0.99 ], null, [ 1, 3, 1 ]],
  80046. ],
  80047. Y: [
  80048. [ new Line( CircleGeometry( 1, 0.5 ), matLineGreen ), null, [ 0, 0, - Math.PI / 2 ]],
  80049. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matGreen ), [ 0, 0, 0.99 ], null, [ 3, 1, 1 ]],
  80050. ],
  80051. Z: [
  80052. [ new Line( CircleGeometry( 1, 0.5 ), matLineBlue ), null, [ 0, Math.PI / 2, 0 ]],
  80053. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matBlue ), [ 0.99, 0, 0 ], null, [ 1, 3, 1 ]],
  80054. ],
  80055. E: [
  80056. [ new Line( CircleGeometry( 1.25, 1 ), matLineYellowTransparent ), null, [ 0, Math.PI / 2, 0 ]],
  80057. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ 1.17, 0, 0 ], [ 0, 0, - Math.PI / 2 ], [ 1, 1, 0.001 ]],
  80058. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ - 1.17, 0, 0 ], [ 0, 0, Math.PI / 2 ], [ 1, 1, 0.001 ]],
  80059. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ 0, - 1.17, 0 ], [ Math.PI, 0, 0 ], [ 1, 1, 0.001 ]],
  80060. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ 0, 1.17, 0 ], [ 0, 0, 0 ], [ 1, 1, 0.001 ]],
  80061. ],
  80062. XYZE: [
  80063. [ new Line( CircleGeometry( 1, 1 ), matLineGray ), null, [ 0, Math.PI / 2, 0 ]]
  80064. ]
  80065. };
  80066. var helperRotate = {
  80067. AXIS: [
  80068. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80069. ]
  80070. };
  80071. var pickerRotate = {
  80072. X: [
  80073. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, - Math.PI / 2, - Math.PI / 2 ]],
  80074. ],
  80075. Y: [
  80076. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ]],
  80077. ],
  80078. Z: [
  80079. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  80080. ],
  80081. E: [
  80082. [ new Mesh( new TorusBufferGeometry( 1.25, 0.1, 2, 24 ), matInvisible ) ]
  80083. ],
  80084. XYZE: [
  80085. [ new Mesh( new SphereBufferGeometry( 0.7, 10, 8 ), matInvisible ) ]
  80086. ]
  80087. };
  80088. var gizmoScale = {
  80089. X: [
  80090. [ new Mesh( scaleHandleGeometry, matRed ), [ 0.8, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  80091. [ new Line( lineGeometry, matLineRed ), null, null, [ 0.8, 1, 1 ]]
  80092. ],
  80093. Y: [
  80094. [ new Mesh( scaleHandleGeometry, matGreen ), [ 0, 0.8, 0 ]],
  80095. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ], [ 0.8, 1, 1 ]]
  80096. ],
  80097. Z: [
  80098. [ new Mesh( scaleHandleGeometry, matBlue ), [ 0, 0, 0.8 ], [ Math.PI / 2, 0, 0 ]],
  80099. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ], [ 0.8, 1, 1 ]]
  80100. ],
  80101. XY: [
  80102. [ new Mesh( scaleHandleGeometry, matYellowTransparent ), [ 0.85, 0.85, 0 ], null, [ 2, 2, 0.2 ]],
  80103. [ new Line( lineGeometry, matLineYellow ), [ 0.855, 0.98, 0 ], null, [ 0.125, 1, 1 ]],
  80104. [ new Line( lineGeometry, matLineYellow ), [ 0.98, 0.855, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  80105. ],
  80106. /* YZ: [
  80107. [ new THREE.Mesh( scaleHandleGeometry, matCyanTransparent ), [ 0, 0.85, 0.85 ], null, [ 0.2, 2, 2 ]],
  80108. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.855, 0.98 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  80109. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.98, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80110. ],
  80111. XZ: [
  80112. [ new THREE.Mesh( scaleHandleGeometry, matMagentaTransparent ), [ 0.85, 0, 0.85 ], null, [ 2, 0.2, 2 ]],
  80113. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.855, 0, 0.98 ], null, [ 0.125, 1, 1 ]],
  80114. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80115. ],
  80116. XYZX: [
  80117. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 1.1, 0, 0 ]],
  80118. ],*/
  80119. XYZY: [
  80120. [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 1.1, 0 ]],
  80121. ]/* ,
  80122. XYZZ: [
  80123. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 0, 1.1 ]],
  80124. ] */
  80125. };
  80126. var pickerScale = {
  80127. X: [
  80128. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0.5, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  80129. ],
  80130. Y: [
  80131. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0.5, 0 ]]
  80132. ],
  80133. Z: [
  80134. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ]]
  80135. ],
  80136. XY: [
  80137. [ new Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0.85, 0 ], null, [ 3, 3, 0.2 ]],
  80138. ],
  80139. /*YZ: [
  80140. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0, 0.85, 0.85 ], null, [ 0.2, 3, 3 ]],
  80141. ],
  80142. XZ: [
  80143. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0, 0.85 ], null, [ 3, 0.2, 3 ]],
  80144. ],
  80145. XYZX: [
  80146. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 1.1, 0, 0 ]],
  80147. ],*/
  80148. XYZY: [
  80149. [ new Mesh( new BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 1.1, 0 ]],
  80150. ]/* ,
  80151. XYZZ: [
  80152. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 1.1 ]],
  80153. ] */
  80154. };
  80155. var helperScale = {
  80156. X: [
  80157. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80158. ],
  80159. Y: [
  80160. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  80161. ],
  80162. Z: [
  80163. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  80164. ]
  80165. };
  80166. // Creates an THREE.Object3D with gizmos described in custom hierarchy definition.
  80167. var setupGizmo = function ( gizmoMap ) {
  80168. var gizmo = new Object3D();
  80169. for ( var name in gizmoMap ) {
  80170. for ( var i = gizmoMap[ name ].length; i --; ) {
  80171. var object = gizmoMap[ name ][ i ][ 0 ].clone();
  80172. var position = gizmoMap[ name ][ i ][ 1 ];
  80173. var rotation = gizmoMap[ name ][ i ][ 2 ];
  80174. var scale = gizmoMap[ name ][ i ][ 3 ];
  80175. var tag = gizmoMap[ name ][ i ][ 4 ];
  80176. // name and tag properties are essential for picking and updating logic.
  80177. object.name = name;
  80178. object.tag = tag;
  80179. if ( position ) {
  80180. object.position.set( position[ 0 ], position[ 1 ], position[ 2 ] );
  80181. }
  80182. if ( rotation ) {
  80183. object.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ] );
  80184. }
  80185. if ( scale ) {
  80186. object.scale.set( scale[ 0 ], scale[ 1 ], scale[ 2 ] );
  80187. }
  80188. object.updateMatrix();
  80189. var tempGeometry = object.geometry.clone();
  80190. tempGeometry.applyMatrix4( object.matrix );
  80191. object.geometry = tempGeometry;
  80192. object.renderOrder = Infinity;
  80193. object.position.set( 0, 0, 0 );
  80194. object.rotation.set( 0, 0, 0 );
  80195. object.scale.set( 1, 1, 1 );
  80196. gizmo.add( object );
  80197. }
  80198. }
  80199. return gizmo;
  80200. };
  80201. // Reusable utility variables
  80202. var tempVector = new Vector3( 0, 0, 0 );
  80203. var tempEuler = new Euler();
  80204. var alignVector = new Vector3( 0, 1, 0 );
  80205. var zeroVector = new Vector3( 0, 0, 0 );
  80206. var lookAtMatrix = new Matrix4();
  80207. var tempQuaternion = new Quaternion();
  80208. var tempQuaternion2 = new Quaternion();
  80209. var identityQuaternion = new Quaternion();
  80210. var unitX = new Vector3( 1, 0, 0 );
  80211. var unitY = new Vector3( 0, 1, 0 );
  80212. var unitZ = new Vector3( 0, 0, 1 );
  80213. // Gizmo creation
  80214. this.gizmo = {};
  80215. this.picker = {};
  80216. this.helper = {};
  80217. this.add( this.gizmo[ "translate" ] = setupGizmo( gizmoTranslate ) );
  80218. this.add( this.gizmo[ "rotate" ] = setupGizmo( gizmoRotate ) );
  80219. this.add( this.gizmo[ "scale" ] = setupGizmo( gizmoScale ) );
  80220. this.add( this.picker[ "translate" ] = setupGizmo( pickerTranslate ) );
  80221. this.add( this.picker[ "rotate" ] = setupGizmo( pickerRotate ) );
  80222. this.add( this.picker[ "scale" ] = setupGizmo( pickerScale ) );
  80223. this.add( this.helper[ "translate" ] = setupGizmo( helperTranslate ) );
  80224. this.add( this.helper[ "rotate" ] = setupGizmo( helperRotate ) );
  80225. this.add( this.helper[ "scale" ] = setupGizmo( helperScale ) );
  80226. // Pickers should be hidden always
  80227. this.picker[ "translate" ].visible = false;
  80228. this.picker[ "rotate" ].visible = false;
  80229. this.picker[ "scale" ].visible = false;
  80230. // updateMatrixWorld will update transformations and appearance of individual handles
  80231. this.updateMatrixWorld = function () {
  80232. var space = this.space;
  80233. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80234. var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion;
  80235. // Show only gizmos for current transform mode
  80236. this.gizmo[ "translate" ].visible = this.mode === "translate";
  80237. this.gizmo[ "rotate" ].visible = this.mode === "rotate";
  80238. this.gizmo[ "scale" ].visible = this.mode === "scale";
  80239. this.helper[ "translate" ].visible = this.mode === "translate";
  80240. this.helper[ "rotate" ].visible = this.mode === "rotate";
  80241. this.helper[ "scale" ].visible = this.mode === "scale";
  80242. var handles = [];
  80243. handles = handles.concat( this.picker[ this.mode ].children );
  80244. handles = handles.concat( this.gizmo[ this.mode ].children );
  80245. handles = handles.concat( this.helper[ this.mode ].children );
  80246. for ( var i = 0; i < handles.length; i ++ ) {
  80247. var handle = handles[ i ];
  80248. //add
  80249. if(this.hideAxis[this.mode] && this.hideAxis[this.mode].some(e=>handle.name.includes(e.toUpperCase()))){
  80250. viewer.updateVisible(handle, 'hidden', false);
  80251. continue
  80252. }
  80253. let visible = true;
  80254. // hide aligned to camera
  80255. handle.rotation.set( 0, 0, 0 );
  80256. handle.position.copy( this.worldPosition );
  80257. if(this.camera.type == "OrthographicCamera"){
  80258. var eyeDistance = 800 / this.camera.zoom;
  80259. }else {
  80260. var eyeDistance = this.worldPosition.distanceTo( this.cameraPosition );
  80261. }
  80262. handle.scale.set( 1, 1, 1 ).multiplyScalar( eyeDistance * this.size / 7 );
  80263. // TODO: simplify helpers and consider decoupling from gizmo
  80264. if ( handle.tag === 'helper' ) {
  80265. visible = false;
  80266. if ( handle.name === 'AXIS' ) {
  80267. handle.position.copy( this.worldPositionStart );
  80268. visible = !!this.axis;
  80269. if ( this.axis === 'X' ) {
  80270. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, 0 ) );
  80271. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80272. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80273. visible = false;
  80274. }
  80275. }
  80276. if ( this.axis === 'Y' ) {
  80277. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, Math.PI / 2 ) );
  80278. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80279. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80280. visible = false;
  80281. }
  80282. }
  80283. if ( this.axis === 'Z' ) {
  80284. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  80285. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80286. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80287. visible = false;
  80288. }
  80289. }
  80290. if ( this.axis === 'XYZE' ) {
  80291. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  80292. alignVector.copy( this.rotationAxis );
  80293. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( zeroVector, alignVector, unitY ) );
  80294. handle.quaternion.multiply( tempQuaternion );
  80295. visible = this.dragging;
  80296. }
  80297. if ( this.axis === 'E' ) {
  80298. visible = false;
  80299. }
  80300. } else if ( handle.name === 'START' ) {
  80301. handle.position.copy( this.worldPositionStart );
  80302. visible = this.dragging;
  80303. } else if ( handle.name === 'END' ) {
  80304. handle.position.copy( this.worldPosition );
  80305. visible = this.dragging;
  80306. } else if ( handle.name === 'DELTA' ) {
  80307. handle.position.copy( this.worldPositionStart );
  80308. handle.quaternion.copy( this.worldQuaternionStart );
  80309. tempVector.set( 1e-10, 1e-10, 1e-10 ).add( this.worldPositionStart ).sub( this.worldPosition ).multiplyScalar( - 1 );
  80310. tempVector.applyQuaternion( this.worldQuaternionStart.clone().invert() );
  80311. handle.scale.copy( tempVector );
  80312. visible = this.dragging;
  80313. } else {
  80314. handle.quaternion.copy( quaternion );
  80315. if ( this.dragging ) {
  80316. handle.position.copy( this.worldPositionStart );
  80317. } else {
  80318. handle.position.copy( this.worldPosition );
  80319. }
  80320. if ( this.axis ) {
  80321. visible = this.axis.search( handle.name ) !== - 1;
  80322. }
  80323. }
  80324. // If updating helper, skip rest of the loop
  80325. viewer.updateVisible(handle, 'hidden', !!visible);
  80326. continue;
  80327. }
  80328. // Align handles to current local or world rotation
  80329. handle.quaternion.copy( quaternion );
  80330. if ( this.mode === 'translate' || this.mode === 'scale' ) {
  80331. // Hide translate and scale axis facing the camera
  80332. var AXIS_HIDE_TRESHOLD = 0.99;
  80333. var PLANE_HIDE_TRESHOLD = 0.2;
  80334. var AXIS_FLIP_TRESHOLD = 0.0;
  80335. if(options.dontHideWhenFaceCamera){//xzw add
  80336. //正对镜头时不隐藏箭头
  80337. }else {
  80338. if ( handle.name === 'X' || handle.name === 'XYZX' ) {
  80339. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80340. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80341. visible = false;
  80342. }
  80343. }
  80344. if ( handle.name === 'Y' || handle.name === 'XYZY' ) {
  80345. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80346. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80347. visible = false;
  80348. }
  80349. }
  80350. if ( handle.name === 'Z' || handle.name === 'XYZZ' ) {
  80351. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80352. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80353. visible = false;
  80354. }
  80355. }
  80356. if ( handle.name === 'XY' ) {
  80357. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80358. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80359. visible = false;
  80360. }
  80361. }
  80362. if ( handle.name === 'YZ' ) {
  80363. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80364. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80365. visible = false;
  80366. }
  80367. }
  80368. if ( handle.name === 'XZ' ) {
  80369. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80370. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80371. visible = false;
  80372. }
  80373. }
  80374. }
  80375. // Flip translate and scale axis ocluded behind another axis
  80376. //xzw 改 去掉反向箭头
  80377. if ( handle.name.search( 'X' ) !== - 1 ) {
  80378. if ( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80379. /* if ( handle.tag === 'fwd' ) {
  80380. handle.visible = false;
  80381. } else {
  80382. handle.scale.x *= - 1;
  80383. }
  80384. } else if ( handle.tag === 'bwd' ) {
  80385. handle.visible = false;*/
  80386. handle.scale.x *= - 1;
  80387. }
  80388. }
  80389. if ( handle.name.search( 'Y' ) !== - 1 ) {
  80390. if ( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80391. /* if ( handle.tag === 'fwd' ) {
  80392. handle.visible = false;
  80393. } else {
  80394. handle.scale.y *= - 1;
  80395. }
  80396. } else if ( handle.tag === 'bwd' ) {
  80397. handle.visible = false;
  80398. */
  80399. handle.scale.y *= - 1;
  80400. }
  80401. }
  80402. if ( handle.name.search( 'Z' ) !== - 1 ) {
  80403. if ( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80404. /* if ( handle.tag === 'fwd' ) {
  80405. handle.visible = false;
  80406. } else {
  80407. handle.scale.z *= - 1;
  80408. }
  80409. } else if ( handle.tag === 'bwd' ) {
  80410. handle.visible = false; */
  80411. handle.scale.z *= - 1;
  80412. }
  80413. }
  80414. } else if ( this.mode === 'rotate' ) {
  80415. // Align handles to current local or world rotation
  80416. tempQuaternion2.copy( quaternion );
  80417. alignVector.copy( this.eye ).applyQuaternion( tempQuaternion.copy( quaternion ).invert() );
  80418. if ( handle.name.search( "E" ) !== - 1 ) {
  80419. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( this.eye, zeroVector, unitY ) );
  80420. }
  80421. if ( handle.name === 'X' ) {
  80422. tempQuaternion.setFromAxisAngle( unitX, Math.atan2( - alignVector.y, alignVector.z ) );
  80423. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80424. handle.quaternion.copy( tempQuaternion );
  80425. }
  80426. if ( handle.name === 'Y' ) {
  80427. tempQuaternion.setFromAxisAngle( unitY, Math.atan2( alignVector.x, alignVector.z ) );
  80428. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80429. handle.quaternion.copy( tempQuaternion );
  80430. }
  80431. if ( handle.name === 'Z' ) {
  80432. tempQuaternion.setFromAxisAngle( unitZ, Math.atan2( alignVector.y, alignVector.x ) );
  80433. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80434. handle.quaternion.copy( tempQuaternion );
  80435. }
  80436. }
  80437. // Hide disabled axes
  80438. visible = visible && ( handle.name.indexOf( "X" ) === - 1 || this.showX );
  80439. visible = visible && ( handle.name.indexOf( "Y" ) === - 1 || this.showY );
  80440. visible = visible && ( handle.name.indexOf( "Z" ) === - 1 || this.showZ );
  80441. visible = visible && ( handle.name.indexOf( "E" ) === - 1 || ( this.showX && this.showY && this.showZ ) );
  80442. viewer.updateVisible(handle, 'hidden', !!visible);
  80443. // highlight selected axis
  80444. handle.material._opacity = handle.material._opacity || handle.material.opacity;
  80445. handle.material._color = handle.material._color || handle.material.color.clone();
  80446. handle.material.color.copy( handle.material._color );
  80447. handle.material.opacity = handle.material._opacity;
  80448. if ( ! this.enabled ) {
  80449. handle.material.opacity *= 0.5;
  80450. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80451. } else if ( this.axis ) {
  80452. if ( handle.name === this.axis ) {
  80453. handle.material.opacity = 1.0;
  80454. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80455. } else if ( this.axis.split( '' ).some( function ( a ) {
  80456. return handle.name === a;
  80457. } ) ) {
  80458. handle.material.opacity = 1.0;
  80459. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80460. } else {
  80461. handle.material.opacity *= 0.25;
  80462. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80463. }
  80464. }
  80465. }
  80466. Object3D.prototype.updateMatrixWorld.call( this );
  80467. };
  80468. };
  80469. /* var TransformControlsLines = function (options) {
  80470. THREE.Object3D.call( this)
  80471. let label1 = new Label2D({ innerHTML:`<div>与相机水平距离</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80472. let label2 = new Label2D({ innerHTML:`<div>与相机高度差</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80473. let css = {'opacity': 0.7, 'color': '#07fceb', transform:'translate(-50%, -50%)'}
  80474. label1.elem.css(css);
  80475. label2.elem.css(css)
  80476. //for(let i=0;i<2;i++){
  80477. // let line = LineDraw.createLine([new THREE.THREE.Vector3, new THREE.THREE.Vector3],{color:'#07fceb', opacity:0.7 })
  80478. // this.add(line)
  80479. //}
  80480. this.updateTransform = function(object){
  80481. object = object || this.parent.object;
  80482. let A = player.position.clone(); //当前相机位置
  80483. let B = object.position //物体位置
  80484. let C = B.clone().setY(A.y); //物体在相机的高度的位置
  80485. let D = A.clone().setY(B.y); //相机在物体的高度的位置
  80486. //LineDraw.moveLine(this.children[0], [B, C]) // 垂直线
  80487. //LineDraw.moveLine(this.children[1], [D, B]) // 水平线
  80488. let dis1 = toPrecision(D.distanceTo(B),1)
  80489. let dis2 = C.y - B.y
  80490. label1.elem.text('与相机水平距离: '+dis1+'米')
  80491. label2.elem.text('在相机之'+ (dis2>0?'下' : '上') +' :'+ toPrecision(dis2 , 1) +'米')
  80492. label1.setPos(new THREE.THREE.Vector3().addVectors(D,B).multiplyScalar(0.5))
  80493. label2.setPos(new THREE.THREE.Vector3().addVectors(B,C).multiplyScalar(0.5))
  80494. }
  80495. this.setVisible = (v,reason)=>{
  80496. label1.setVisible(v, reason || 'unvisi')
  80497. label2.setVisible(v, reason || 'unvisi')
  80498. this.visible = label1.visible
  80499. if(this.visible){
  80500. this.updateTransform()
  80501. }
  80502. }
  80503. this.setVisible(false)
  80504. player.on("mode.changing",(currentMode, mode, pano, duration)=>{
  80505. if(mode != 'panorama'){
  80506. this.setVisible(false, 'isPanorama')
  80507. }else{
  80508. this.setVisible(true, 'isPanorama')
  80509. }
  80510. })
  80511. player.on("flying.started",( )=>{
  80512. this.setVisible(false, 'flying')
  80513. })
  80514. player.on("flying.ended",( )=>{
  80515. this.setVisible(true, 'flying')
  80516. })
  80517. }
  80518. */
  80519. var TransformControlsPlane = function (options) {
  80520. 'use strict';
  80521. Mesh.call( this,
  80522. new PlaneBufferGeometry( 100000, 100000, 2, 2 ),
  80523. new MeshBasicMaterial( { color: "#ff0000", visible: false, wireframe: false, side: DoubleSide, transparent: true, opacity: 0.2 } )
  80524. );
  80525. this.type = 'TransformControlsPlane';
  80526. var unitX = new Vector3( 1, 0, 0 );
  80527. var unitY = new Vector3( 0, 1, 0 );
  80528. var unitZ = new Vector3( 0, 0, 1 );
  80529. var tempVector = new Vector3();
  80530. var dirVector = new Vector3();
  80531. var alignVector = new Vector3();
  80532. var tempMatrix = new Matrix4();
  80533. var identityQuaternion = new Quaternion();
  80534. this.updateMatrixWorld = function () {
  80535. var space = this.space;
  80536. this.position.copy( this.worldPosition );
  80537. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80538. unitX.set( 1, 0, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80539. unitY.set( 0, 1, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80540. unitZ.set( 0, 0, 1 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80541. // Align the plane for current transform mode, axis and space.
  80542. alignVector.copy( unitY );
  80543. switch ( this.mode ) {
  80544. case 'translate':
  80545. case 'scale':
  80546. switch ( this.axis ) {
  80547. case 'X':
  80548. alignVector.copy( this.eye ).cross( unitX );
  80549. dirVector.copy( unitX ).cross( alignVector );
  80550. break;
  80551. case 'Y':
  80552. alignVector.copy( this.eye ).cross( unitY );
  80553. dirVector.copy( unitY ).cross( alignVector );
  80554. break;
  80555. case 'Z':
  80556. alignVector.copy( this.eye ).cross( unitZ );
  80557. dirVector.copy( unitZ ).cross( alignVector );
  80558. break;
  80559. case 'XY':
  80560. dirVector.copy( unitZ );
  80561. break;
  80562. case 'YZ':
  80563. dirVector.copy( unitX );
  80564. break;
  80565. case 'XZ':
  80566. alignVector.copy( unitZ );
  80567. dirVector.copy( unitY );
  80568. break;
  80569. case 'XYZ':
  80570. case 'E':
  80571. default: //xzw add for scale xyzz
  80572. dirVector.set( 0, 0, 0 );
  80573. break;
  80574. }
  80575. break;
  80576. case 'rotate':
  80577. default:
  80578. // special case for rotate
  80579. dirVector.set( 0, 0, 0 );
  80580. }
  80581. if ( dirVector.length() === 0 ) {
  80582. // If in rotate mode, make the plane parallel to camera
  80583. this.quaternion.copy( this.cameraQuaternion );
  80584. } else {
  80585. tempMatrix.lookAt( tempVector.set( 0, 0, 0 ), dirVector, alignVector );
  80586. this.quaternion.setFromRotationMatrix( tempMatrix );
  80587. }
  80588. Object3D.prototype.updateMatrixWorld.call( this );
  80589. };
  80590. };
  80591. TransformControls.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80592. constructor: TransformControls,
  80593. isTransformControls: true
  80594. } );
  80595. TransformControlsGizmo.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80596. constructor: TransformControlsGizmo,
  80597. isTransformControlsGizmo: true
  80598. } );
  80599. TransformControlsPlane.prototype = Object.assign( Object.create( Mesh.prototype ), {
  80600. constructor: TransformControlsPlane,
  80601. isTransformControlsPlane: true
  80602. } );
  80603. /*
  80604. 备注:
  80605. //这里虽然 使坐标轴在boundingBox中心
  80606. boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  80607. 但是旋转中心并不是这个坐标轴显示的位置,需要再执行 MergeEditor.maintainBoundXY()才能维持在这个中心
  80608. */
  80609. const texLoader$8 = new TextureLoader();
  80610. texLoader$8.crossOrigin = "anonymous";
  80611. const edgeStrengths = {
  80612. pointcloud: 4,
  80613. glb: 100
  80614. };
  80615. const viewportProps$1 = [{
  80616. left:0,
  80617. bottom:0,
  80618. width: 0.5,height:1,
  80619. name : 'top',
  80620. axis:["x","y"],
  80621. direction : new Vector3(0,0,-1), //镜头朝向
  80622. active: true,
  80623. //相机位置在z轴正向
  80624. limitBound: new Box3(new Vector3(-Infinity,-Infinity, 1),new Vector3(Infinity,Infinity,5000)), //在地面以上
  80625. margin:{x:50, y:150} ,
  80626. },
  80627. {
  80628. left:0.5,
  80629. bottom:0,
  80630. width: 0.5,height:1,
  80631. name : 'right',
  80632. axis:["y","z"],
  80633. direction : new Vector3(1,0,0),
  80634. active: true,
  80635. //相机位置在x轴负向 右下角屏
  80636. viewContainsPoints:[new Vector3(0,0,0)],
  80637. margin:{x:300, y:250} ,
  80638. } ];
  80639. let MergeEditor = {
  80640. bus:new EventDispatcher(),
  80641. SplitScreen : new SplitScreen(),
  80642. init(){
  80643. {
  80644. let ground = this.ground = new InfiniteGridHelper(1, 10000, new Color('#fff'), 10000, 0.2, 0.3);
  80645. viewer.scene.scene.add(ground);
  80646. //再加两条线否则在正侧边看不到
  80647. let line1 = LineDraw.createLine([new Vector3(-10000, 0, 0),new Vector3(10000, 0, 0) ], {color:'#666', dontAlwaysSeen:true});
  80648. let line2 = LineDraw.createLine([new Vector3(0, -10000, 0),new Vector3(0, 10000, 0) ], {mat:line1.material});
  80649. ground.renderOrder = Potree.config.renderOrders.model + 1;//line1.renderOrder + 1 //要比模型低,否则模型透明时效果不对
  80650. ground.add(line1);
  80651. ground.add(line2);
  80652. ground.material.polygonOffset = true; //多边形偏移(视觉上没有移动模型位置),防止闪烁
  80653. ground.material.polygonOffsetFactor = 100; //多边形偏移因子
  80654. ground.material.polygonOffsetUnits = 10; //多边形偏移单位
  80655. ground.material.depthWrite = false;
  80656. //ground.material.depthTest = false
  80657. line1.material.polygonOffset = true;
  80658. line1.material.polygonOffsetFactor = 130;
  80659. line1.material.polygonOffsetUnits = 10;
  80660. line1.material.depthWrite = false;
  80661. //见笔记:透明物体的材质设置
  80662. }
  80663. {
  80664. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80665. dontHideWhenFaceCamera: true,
  80666. });
  80667. //this.transformControls.space = 'local'//为了在当前方向上平移
  80668. this.transformControls.setSize(1.5);
  80669. viewer.scene.scene.add(this.transformControls);
  80670. //右屏
  80671. this.transformControls2 = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80672. dontHideWhenFaceCamera: true,
  80673. });
  80674. this.transformControls.setSize(1.5);
  80675. viewer.scene.scene.add(this.transformControls2);
  80676. viewer.setObjectLayers(this.transformControls2, 'layer2' );
  80677. let mouseDown = (e)=>{
  80678. viewer.outlinePass.edgeStrength = 0;//暂时消失线
  80679. };
  80680. let mouseUp = (e)=>{
  80681. this.updateEdgeStrength();
  80682. };
  80683. this.transformControls.addEventListener('mouseDown',mouseDown);
  80684. this.transformControls2.addEventListener('mouseDown',mouseDown);
  80685. this.transformControls.addEventListener('mouseUp',mouseUp);
  80686. this.transformControls2.addEventListener('mouseUp',mouseUp);
  80687. }
  80688. {
  80689. this.secondCompass = new Compass(null);
  80690. }
  80691. viewer.setControls(viewer.orbitControls);
  80692. //viewer.mainViewport.view.fixZWhenPan = true
  80693. viewer.orbitControls.constantlyForward = true;
  80694. viewer.addEventListener('global_single_click',(e)=>{
  80695. if(
  80696. this.noNeedSelection //如模型查看页
  80697. || viewer.scene.cameraAnimations.some(c=>c.onUpdate) //正在播放
  80698. || e.drag && e.drag.notPressMouse //在加测量线
  80699. || viewer.mainViewport.view.isFlying() //有其他校准
  80700. || this.split //分屏中
  80701. || e.clickElement //触发别的点击事件,如测量时click marker /* && e.clickElement != e.intersect.object */
  80702. ){
  80703. return
  80704. }
  80705. if(e.intersect){
  80706. let object = e.intersect.object || e.intersect.pointcloud;
  80707. let objects = this.getAllObjects();
  80708. if(objects.includes(object)){
  80709. this.selectModel(object);
  80710. }else {
  80711. //if(!viewer.inputHandler.selection[0]){//正在平移和旋转,不允许取消
  80712. this.selectModel(null);
  80713. //}
  80714. }
  80715. }else {
  80716. //if(!viewer.inputHandler.selection[0]){
  80717. this.selectModel(null);
  80718. //}
  80719. }
  80720. });
  80721. viewer.inputHandler.addEventListener('keydown', (e)=>{
  80722. if((e.event.key).toLowerCase() == "h" ){
  80723. this.fadeOutlineAuto = !this.fadeOutlineAuto;
  80724. this.showModelOutline(this.selected,!!this.selected);
  80725. }
  80726. });
  80727. viewer.ssaaRenderPass.enabled = false;
  80728. viewer.outlinePass.enabled = true;
  80729. //Potree.settings.intersectWhenHover = false
  80730. //viewer.updateVisible(viewer.reticule, 'force', false)
  80731. viewer.mainViewport.camera.near = 0.05; // too small will result in z-fighting
  80732. viewer.addEventListener('updateModelBound', (e)=>{
  80733. if(this.split){
  80734. this.SplitScreen.updateCameraOutOfModel(/* this.selected && [this.selected] */);
  80735. }
  80736. });
  80737. {//校准页面拖拽
  80738. //左右屏都可以拖拽模型,旋转只能左屏
  80739. let dragInfo;
  80740. let drag = (e)=>{
  80741. if(this.split && this.selected && this.transformState && (e.dragViewport.name == 'top' || this.transformState == 'translate') ){
  80742. if(e.type == 'global_mousedown' ){ //开始
  80743. //if((e.intersect.object || e.intersect.pointcloud) == this.selected){
  80744. if(e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected)){
  80745. dragInfo = {};
  80746. //if(this.selected.isPointcloud){
  80747. viewer.outlinePass.edgeStrength = 0;//暂时消失线
  80748. //}
  80749. }
  80750. }
  80751. if(e.type == 'global_drag' && dragInfo ){
  80752. if(this.transformState == 'translate'){
  80753. let moveVec = Potree.Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, e.dragViewport.camera );//最近一次移动向量
  80754. this.selected.position.add(moveVec);
  80755. this.selected.dispatchEvent("position_changed");
  80756. }else if(this.transformState == 'rotate'){
  80757. let vec = new Vector3().subVectors(e.intersect.orthoIntersect || e.intersect.location, this.selected.boundCenter).setZ(0);
  80758. if(dragInfo.lastVec == void 0){//global_mousedown
  80759. dragInfo.lastVec = vec;
  80760. return
  80761. }
  80762. let angle = math.getAngle(dragInfo.lastVec, vec, 'z');
  80763. dragInfo.lastVec = vec;
  80764. //this.selected.rotation.z += angle //局部
  80765. /* object.quaternion.copy( .setFromAxisAngle( new THREE.Vector3(0,0,1), angle ) );
  80766. object.quaternion.multiply( quaternionStart ).normalize(); */
  80767. let diffQua = new Quaternion().setFromAxisAngle( new Vector3(0,0,1), angle );
  80768. this.selected.quaternion.premultiply(diffQua); //世界
  80769. this.selected.dispatchEvent("rotation_changed");
  80770. }
  80771. return {stopContinue:true}
  80772. }
  80773. }
  80774. };
  80775. viewer.addEventListener('global_mousedown', drag);
  80776. viewer.addEventListener('global_drag', drag, 10);
  80777. viewer.addEventListener('global_mousemove', (e)=>{
  80778. if(this.split && this.transformState && !e.drag && (e.hoverViewport.name == 'top' || this.transformState == 'translate')){
  80779. /* if(this.lastHoverViewport != e.hoverViewport){
  80780. this.lastHoverViewport = e.hoverViewport
  80781. this.transformControls.view = e.hoverViewport.view
  80782. this.transformControls.camera = e.hoverViewport.camera
  80783. this.transformControls.hideAxis( this.transformState, e.hoverViewport.name == 'top' ? [z] : [x,y]);
  80784. } */
  80785. let mouseover = e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected);
  80786. //let mouseover = (e.intersect.object || e.intersect.pointcloud) == this.selected
  80787. if(mouseover){
  80788. if(this.transformState == 'translate'){
  80789. viewer.dispatchEvent({
  80790. type : "CursorChange", action : "add", name:"movePointcloud"
  80791. });
  80792. }else {
  80793. viewer.dispatchEvent({
  80794. type : "CursorChange", action : "add", name:"rotatePointcloud"
  80795. });
  80796. }
  80797. }else {
  80798. this.clearTranCursor();
  80799. }
  80800. }
  80801. });
  80802. viewer.addEventListener('global_drop', (e)=>{
  80803. dragInfo = null;
  80804. this.clearTranCursor();
  80805. this.updateEdgeStrength();
  80806. });
  80807. }
  80808. },
  80809. clearTranCursor(){
  80810. viewer.dispatchEvent({
  80811. type : "CursorChange", action : "remove", name:"movePointcloud"
  80812. });
  80813. viewer.dispatchEvent({
  80814. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  80815. });
  80816. },
  80817. enterSplit(){
  80818. this.split = true;
  80819. if(this.selected) this.SplitScreen.focusCenter = this.selected.boundCenter; //旋转中心。注意 boundCenter不能直接赋值,否则改变后focusCenter也要改
  80820. else this.SplitScreen.focusCenter = null;
  80821. this.SplitScreen.splitStart(viewportProps$1);
  80822. this.beforeSplit = {
  80823. pointDensity: Potree.settings.pointDensity,
  80824. };
  80825. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  80826. /* viewer.scene.pointclouds.forEach(e=>{
  80827. e.material.activeAttributeName = "color"
  80828. e.material.useFilterByNormal = true
  80829. }) */
  80830. //取消outline,改点云颜色为和outline一样的颜色
  80831. /* if(this.selected && this.selected.isPointcloud){
  80832. this.showModelOutline(this.selected, false)
  80833. this.selected.material.activeAttributeName = "color"
  80834. this.selected.material.color = viewer.outlinePass.visibleEdgeColor
  80835. } */
  80836. viewer.setControls(viewer.fpControls);
  80837. viewer.viewports.find(e=>e.name == 'right').rotateSide = true;
  80838. viewer.viewports.find(e=>e.name == 'top').alignment = true;
  80839. viewer.viewports[1].layersAdd('layer2');
  80840. viewer.viewports[0].layersAdd('layer1');
  80841. viewer.setObjectLayers(this.transformControls, 'layer1' );
  80842. this.transformControls.view = viewer.viewports[0].view;
  80843. this.transformControls.camera = viewer.viewports[0].camera;
  80844. this.transformControls._gizmo.hideAxis = {translate:['z'], rotate:['x','y','z'] };
  80845. this.transformControls2.view = viewer.viewports[1].view;
  80846. this.transformControls2.camera = viewer.viewports[1].camera;
  80847. this.transformControls2._gizmo.hideAxis = {translate:['x','y'], rotate:['x','y','z'] };
  80848. this.secondCompass.changeViewport(viewer.viewports[0]);
  80849. this.secondCompass.setDomPos();
  80850. this.secondCompass.setDisplay(true);
  80851. viewer.compass.changeViewport(viewer.viewports[1]);
  80852. viewer.compass.setDomPos();
  80853. },
  80854. leaveSplit(){
  80855. this.split = false;
  80856. this.SplitScreen.unSplit();
  80857. viewer.setControls(viewer.orbitControls);
  80858. Potree.settings.pointDensity = this.beforeSplit.pointDensity;
  80859. /* if(this.selected && this.selected.isPointcloud){
  80860. this.showModelOutline(this.selected, true)
  80861. this.selected.material.activeAttributeName = "rgba"
  80862. } */
  80863. this.transformControls.camera = viewer.viewports[0].camera;
  80864. this.transformControls.view = viewer.viewports[0].view;
  80865. this.transformControls._gizmo.hideAxis = {};
  80866. viewer.setObjectLayers(this.transformControls, 'sceneObjects' ); //恢复
  80867. viewer.compass.changeViewport(viewer.viewports[0]); //恢复
  80868. viewer.compass.setDomPos();
  80869. this.secondCompass.setDisplay(false);
  80870. },
  80871. rotateSideCamera(angle){
  80872. this.SplitScreen.rotateSideCamera(viewer.viewports.find(e=>e.name == 'right'), angle);
  80873. },
  80874. setTransformState(state){//校准时
  80875. this.transformState = state;
  80876. this.clearTranCursor();
  80877. },
  80878. //---------------------------
  80879. /* writeToHistory(content){
  80880. if(!this.prepareRecord)return;
  80881. this.prepareRecord = false
  80882. this.history.push(content)
  80883. }, */
  80884. //---------------------------
  80885. getAllObjects(){
  80886. return viewer.objs.children.concat(viewer.scene.pointclouds)
  80887. },
  80888. getModel(id){
  80889. let models = this.getAllObjects();
  80890. return models.find(e=>e.dataset_id == id)
  80891. },
  80892. removeModel(model){
  80893. if(this.selected == model) this.selectModel(null);
  80894. let dispose = (e)=>{
  80895. e.geometry && e.geometry.dispose();
  80896. e.material && e.material.dispose();
  80897. };
  80898. if(model.isPointcloud){
  80899. dispose(model);
  80900. viewer.scene.removePointCloud(model);
  80901. }else {
  80902. model.traverse(e=>{
  80903. dispose(e);
  80904. });
  80905. viewer.objs.remove(model);
  80906. }
  80907. },
  80908. selectModel(model, state=true, fitBound, by2d){
  80909. if(!model) {
  80910. model = this.selected;
  80911. state = false;
  80912. }
  80913. if(state){
  80914. if(this.selected){
  80915. if(this.selected == model) return
  80916. else {
  80917. let transToolAttached = !!this.transformControls.object;
  80918. this.selectModel(this.selected, false, fitBound, by2d);
  80919. transToolAttached && this.transformControls.attach(model);
  80920. }
  80921. }
  80922. this.selected = model;
  80923. MergeEditor.focusOn(model, 500, !!fitBound); //通过在场景里点击模型的话,不focus
  80924. this.showModelOutline(model);
  80925. this.updateEdgeStrength();
  80926. //console.log('selectModel', model)
  80927. }else {
  80928. if(this.selected != model)return //model本来就没选中,不需要处理(防止2d先选中新的再取消旧的)
  80929. this.showModelOutline(model, false);
  80930. this.selected = null;
  80931. this.transformControls.detach(); //viewer.transformObject(null);
  80932. //console.log('selectModel', null)
  80933. }
  80934. if(!by2d && model){
  80935. model.dispatchEvent({type:'changeSelect', selected : state});
  80936. }
  80937. },
  80938. showModelOutline(model, state){
  80939. if(this.fadeOutlineAuto){
  80940. if(state === false){
  80941. viewer.outlinePass.selectedObjects = [];
  80942. clearTimeout(this.timer);
  80943. return
  80944. }
  80945. viewer.outlinePass.selectedObjects = [model];
  80946. if(this.timer){
  80947. clearTimeout(this.timer);
  80948. }
  80949. this.timer = setTimeout(()=>{
  80950. viewer.outlinePass.selectedObjects = [];
  80951. }, 1000);
  80952. }else {
  80953. if(state === false){
  80954. viewer.outlinePass.selectedObjects = [];
  80955. }else {
  80956. viewer.outlinePass.selectedObjects = [model];
  80957. }
  80958. }
  80959. },
  80960. updateEdgeStrength(){
  80961. if(!this.selected)return
  80962. if(this.selected.isPointcloud){
  80963. viewer.outlinePass.edgeStrength = edgeStrengths.pointcloud;// / this.selected.material.opacity
  80964. }else {
  80965. viewer.outlinePass.edgeStrength = edgeStrengths.glb;
  80966. }
  80967. },
  80968. focusOn(objects, duration = 400, fitBound=true, dontLookUp){
  80969. if(!(objects instanceof Array)){
  80970. objects = [objects];
  80971. }
  80972. let boundingBox = new Box3;
  80973. objects.forEach(object=>{
  80974. boundingBox.union(object.boundingBox.clone().applyMatrix4(object.matrixWorld));
  80975. });
  80976. if(fitBound){
  80977. viewer.focusOnObject({boundingBox}, 'boundingBox', duration, {dontLookUp, dontChangeCamDir:true});
  80978. }else {
  80979. /*
  80980. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new THREE.Vector3)
  80981. position && viewer.focusOnObject({position}, 'point', duration, {dontChangePos: true})
  80982. */
  80983. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new Vector3);
  80984. if(!position)return
  80985. /* let targetOld = viewer.mainViewport.view.getPivot()
  80986. let projected1 = targetOld.clone().project(viewer.mainViewport.camera);
  80987. let projected2 = position.clone().project(viewer.mainViewport.camera); //使用其z
  80988. let targetNew = projected1.clone().setZ(projected2.z).unproject(viewer.mainViewport.camera);
  80989. viewer.mainViewport.view.lookAt(targetNew) */
  80990. viewer.mainViewport.view.radius = viewer.mainViewport.camera.position.distanceTo(position);
  80991. //为了不改画面,不调节方向了,只能调调radius,一定程度将target靠近model
  80992. }
  80993. },
  80994. moveBoundCenterTo(model,pos){ //使boundCenter在所要的位置
  80995. let diff = new Vector3().subVectors(pos, model.boundCenter);
  80996. model.position.add(diff);
  80997. },
  80998. getBoundCenter(model){
  80999. if(!model.boundCenter) model.boundCenter = new Vector3;
  81000. model.boundingBox.getCenter(model.boundCenter).applyMatrix4(model.matrixWorld);
  81001. },
  81002. setModelBtmHeight(model, z ){
  81003. //无论模型怎么缩放、旋转,都使最低点为z
  81004. if(z == void 0) z = model.btmHeight; //维持离地高度
  81005. else model.btmHeight = z;
  81006. model.updateMatrixWorld();
  81007. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  81008. let size = boundingBox2.getSize(new Vector3);
  81009. let center = boundingBox2.getCenter(new Vector3);
  81010. let hopeZ = z + size.z / 2;
  81011. //model.position.z = z + size.z / 2 - center.z
  81012. model.position.z += (hopeZ - center.z);
  81013. },
  81014. computeBtmHeight(model){ //位移之后重新计算btmHeight
  81015. model.updateMatrixWorld();
  81016. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  81017. let size = boundingBox2.getSize(new Vector3);
  81018. let center = boundingBox2.getCenter(new Vector3);
  81019. model.btmHeight = center.z - size.z / 2;
  81020. },
  81021. maintainBoundXY(model){ //在旋转和缩放后,立即执行这个函数,使boundCenter保持原位
  81022. model.updateMatrixWorld();
  81023. let center1 = model.boundCenter.clone();//还未更新的
  81024. this.getBoundCenter(model);//更新
  81025. let center2 = model.boundCenter.clone();
  81026. let diff = new Vector2$1().subVectors(center1,center2);
  81027. model.position.x += diff.x;
  81028. model.position.y += diff.y;
  81029. model.boundCenter.copy(center1);
  81030. },
  81031. maintainBoundCenter(model){
  81032. model.updateMatrixWorld();
  81033. let center1 = model.boundCenter.clone();//还未更新的
  81034. this.getBoundCenter(model);//更新
  81035. let center2 = model.boundCenter.clone();
  81036. let diff = new Vector3().subVectors(center1,center2);
  81037. model.position.add(diff);
  81038. model.boundCenter.copy(center1);
  81039. },
  81040. modelTransformCallback(model){
  81041. model.updateMatrixWorld();
  81042. if(model.matrixWorld.equals(model.lastMatrixWorld))return
  81043. viewer.scene.measurements.forEach(measure=>{
  81044. let changed;
  81045. measure.points_datasets.forEach((dataset_id,i)=>{
  81046. if(dataset_id == model.dataset_id){
  81047. changed = true;
  81048. measure.points[i] = Potree.Utils.datasetPosTransform({fromDataset:true,datasetId:dataset_id, position:measure.dataset_points[i].clone()});
  81049. measure.updateMarker(measure.markers[i], measure.points[i]);
  81050. }
  81051. });
  81052. if(changed){//仿transformByPointcloud
  81053. measure.getPoint2dInfo(measure.points);
  81054. measure.update();
  81055. measure.setSelected(false);//隐藏edgelabel
  81056. }
  81057. });
  81058. model.lastMatrixWorld = model.matrixWorld.clone();
  81059. }
  81060. };
  81061. /*
  81062. note:
  81063. 要注意getHoveredElements只在getIntersect时才使interactables包含加载的model, 也就是model上不能有使之成为interactables的事件,否则在鼠标hover到模型上开始转动的一瞬间很卡。
  81064. */
  81065. const texLoader$9 = new TextureLoader();
  81066. const circleGeo = new CircleGeometry(1.45,100);
  81067. const sphereGeo = new SphereBufferGeometry(0.018,10,10);
  81068. const magDistance_ = 1;//相机离目标位置的距离的分界线,当离得远时要缩小fov以使看到的视野固定(望远镜效果)
  81069. /* const radius_ = 0.2; //当相机离目标位置的距离>magDistance_时,希望看到的视野的半径
  81070. const maxFov = THREE.Math.radToDeg(Math.atan(radius_ / magDistance_ )) * 2//提前计算出当相机离目标位置的距离<magDistance_时的fov,均使用=magDistance_时的fov。只要保证该fov大于主相机的fov就会有放大效果
  81071. */
  81072. let w$2 = 200/1.43;
  81073. let maxPX = 1366*1024; //ipad pro. 大于这个分辨率的就直接用devicePixelRatio, 如macbook也是
  81074. const width2dPX = Math.round(window.devicePixelRatio >= 2 ? ( window.screen.width * window.screen.height >= maxPX ? window.devicePixelRatio/1.2 : window.devicePixelRatio/1.5)*w$2 : w$2); //触屏或高分辨率的可能要放大些。但在手机上不能太大
  81075. console.log('width2dPX', width2dPX);
  81076. class Magnifier extends Object3D {//放大镜or望远镜
  81077. constructor (viewer) {
  81078. super();
  81079. this.width = this.height = width2dPX/* * window.devicePixelRatio */;
  81080. this.camera = new PerspectiveCamera(50, 1, 0.01, 10000); //fov aspect near far
  81081. this.camera.up = new Vector3(0,0,1);
  81082. this.viewport = new Viewport( null, this.camera, {
  81083. left:0, bottom:0, width:1, height: 1, name:'magnifier' , cameraLayers:['magnifierContent'],
  81084. pixelRatio:1
  81085. });
  81086. this.viewport.setResolution(this.width, this.height,0,0);
  81087. {
  81088. let density;
  81089. let sizeType;
  81090. let colorType;
  81091. let opacityBefore = new Map();
  81092. this.viewport.beforeRender = ()=>{
  81093. viewer.scene.pointclouds.forEach(e=>{//因为更改pointDensity时会自动变opacity,所以这项最先获取
  81094. opacityBefore.set(e,e.temp.pointOpacity);
  81095. });
  81096. //使放大镜里的pointDensity是'magnifier' 最高质量。
  81097. density = Potree.settings.pointDensity;
  81098. Potree.settings.pointDensity = 'magnifier';
  81099. viewer.scene.pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  81100. sizeType = e.material.pointSizeType;
  81101. e.material.pointSizeType = Potree.config.material.pointSizeType;
  81102. //材质
  81103. colorType = e.material.activeAttributeName;
  81104. e.material.activeAttributeName = 'rgba';
  81105. e.changePointOpacity(1);
  81106. });
  81107. };
  81108. this.viewport.afterRender = ()=>{
  81109. Potree.settings.pointDensity = density;
  81110. viewer.scene.pointclouds.forEach(e=>{
  81111. e.material.pointSizeType = sizeType;
  81112. e.material.activeAttributeName = colorType;
  81113. e.changePointOpacity(opacityBefore.get(e));
  81114. });
  81115. };
  81116. }
  81117. this.renderTarget = new WebGLRenderTarget(this.width,this.height, {
  81118. minFilter: LinearFilter, magFilter: LinearFilter,
  81119. format: RGBAFormat ,
  81120. /* type: THREE.FloatType,
  81121. minFilter: THREE.NearestFilter,
  81122. magFilter: THREE.NearestFilter,
  81123. */
  81124. } );
  81125. this.rtEDL = new WebGLRenderTarget(this.width, this.height, { //好像没用到? 因为这里不绘制测量线
  81126. minFilter: NearestFilter,
  81127. magFilter: NearestFilter,
  81128. format: RGBAFormat,
  81129. type: FloatType,
  81130. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  81131. });
  81132. this.mesh = new Mesh(circleGeo, new MeshBasicMaterial({
  81133. side: DoubleSide ,
  81134. map: this.renderTarget.texture ,
  81135. transparent:true,
  81136. depthTest: !1,
  81137. //depthWrite: !1,
  81138. }));
  81139. this.overlayMesh = new Mesh(circleGeo, new MeshBasicMaterial({
  81140. side: DoubleSide ,
  81141. map:texLoader$9.load(Potree.resourcePath+'/textures/crosshair.png') ,
  81142. transparent:true,
  81143. depthTest: !1,
  81144. //depthWrite: !1,
  81145. }));
  81146. this.targetPoint = new Object3D;
  81147. this.targetPoint.add(new Mesh(sphereGeo, new MeshBasicMaterial({
  81148. color:"#ff0000",
  81149. transparent:true,
  81150. opacity:0.5,
  81151. })));
  81152. this.targetPoint.add(new Mesh(sphereGeo, new MeshBasicMaterial({
  81153. color:"#ff0000",
  81154. transparent:true,
  81155. opacity:0.2,
  81156. depthTest:false //被遮挡层
  81157. })));
  81158. this.targetPoint.name = 'magnifierPointTarget';
  81159. viewer.scene.scene.add(this.targetPoint);
  81160. viewer.setObjectLayers(this.targetPoint, 'magnifierContent' );
  81161. this.add(this.mesh);
  81162. this.add(this.overlayMesh);
  81163. this.position.set(-1000,-1000,-100000);//令它看不见
  81164. this.mesh.renderOrder = 10;
  81165. this.overlayMesh.renderOrder = 11;
  81166. this.aimPos;
  81167. viewer.setObjectLayers(this, 'magnifier' );
  81168. //viewer.inputHandler.addInputListener(this)
  81169. viewer.addEventListener('camera_changed',(e)=>{ // 平移、滚轮时更新
  81170. if(e.viewport == viewer.mainViewport) this.update(); //不过intersectPoint没更新
  81171. });
  81172. this.mesh.layers.set(Potree.config.renderLayers.magnifier);
  81173. this.overlayMesh.layers.set(Potree.config.renderLayers.magnifier);
  81174. //this.layers.set(Potree.config.renderLayers.magnifier);//这句在外层写没用
  81175. this.dontRender = false;
  81176. viewer.addEventListener('global_drag', (e)=>{//拖拽时不渲染。主要是右键平移时渲染延迟了,会闪烁。
  81177. this.dontRender = true;
  81178. });
  81179. viewer.addEventListener('global_drop', (e)=>{
  81180. this.dontRender = false;
  81181. });
  81182. viewer.addEventListener('global_mouseup', (e)=>{//测量时拖拽场景再mouseup
  81183. this.dontRender = false;
  81184. });
  81185. var updateVisi = (e)=>{
  81186. if(e.hoverViewport == viewer.mainViewport){
  81187. viewer.updateVisible(this,"atViewport", true);
  81188. this.update(e.intersect && e.intersect.location);
  81189. }else {
  81190. viewer.updateVisible(this,"atViewport", false); //小地图不显示
  81191. }
  81192. };
  81193. viewer.addEventListener('global_mousemove', updateVisi);
  81194. viewer.addEventListener('global_touchstart', updateVisi);
  81195. /* viewer.addEventListener("beginSplitView",()=>{
  81196. this.updateVisible("splitView", false)
  81197. })
  81198. viewer.addEventListener("finishSplitView",()=>{
  81199. this.updateVisible("splitView", true)
  81200. }) */
  81201. this.addEventListener("setEnable",(e)=>{
  81202. viewer.updateVisible(this, "enable", e.value); //界面开关
  81203. /* if(Potree.settings.displayMode == 'showPanos') && e.value){
  81204. Potree.settings.pointDensity = 'magnifier'
  81205. }else if() */
  81206. });
  81207. if(Potree.settings.isOfficial){
  81208. viewer.updateVisible(this, "enable", false);
  81209. }else {
  81210. viewer.updateVisible(this, "measure", false);
  81211. viewer.addEventListener("measureMovePoint",()=>{//测量开始
  81212. viewer.updateVisible(this, "measure", true);
  81213. });
  81214. viewer.addEventListener("endMeasureMove",()=>{
  81215. viewer.updateVisible(this, "measure", false);
  81216. });
  81217. }
  81218. viewer.scene.view.addEventListener('flyingDone',()=>{
  81219. if(!this.visible)return
  81220. let pickWindowSize = 100;
  81221. let intersect = viewer.inputHandler.getIntersect(viewer.mainViewport, viewer.mainViewport.camera, true, pickWindowSize );
  81222. this.update(intersect && intersect.location);
  81223. });
  81224. }
  81225. //注意:在鼠标没有移动的时候,无法获取到最新的intersect, 放大镜内的内容可能是错误的。全景模式下更奇怪,原因未知
  81226. update(aimPos){//相机靠近 navvis的做法
  81227. var dontRender = this.dontRender || !(aimPos instanceof Vector3) || Potree.settings.displayMode == 'showPanos' && viewer.images360.flying;
  81228. aimPos = aimPos instanceof Vector3 ? aimPos : this.aimPos;
  81229. if(!aimPos || !this.visible)return
  81230. var playerCamera = viewer.scene.getActiveCamera();
  81231. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  81232. var dis = playerPos.distanceTo(aimPos);
  81233. var dirToCamera = new Vector3().subVectors(playerPos, aimPos ).normalize();
  81234. //相机位置
  81235. var finalDisToAim = dis>magDistance_ ? magDistance_ : dis / 2;
  81236. this.camera.position.copy(aimPos).add(dirToCamera.multiplyScalar(finalDisToAim));
  81237. this.camera.lookAt(aimPos);
  81238. this.camera.fov = playerCamera.fov / 2;
  81239. this.camera.updateProjectionMatrix();
  81240. //自身位置
  81241. //let pos2d = viewer.inputHandler.pointer.clone(); //跟随鼠标
  81242. let pos2d = Potree.Utils.getPos2d(aimPos, playerCamera, viewer.renderArea, viewer.mainViewport).vector; //更新目标点的实时二维位置
  81243. let margin = 0.4, maxY = 0.4;
  81244. let screenPos = pos2d.clone().setY(pos2d.y + (pos2d.y>maxY ? -margin : margin ));
  81245. let newPos = new Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  81246. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  81247. let s = dis>magDistance_ ? 1 : dis / magDistance_ ;
  81248. this.position.copy(playerPos.clone().add(dir));
  81249. this.quaternion.copy(playerCamera.quaternion);
  81250. this.targetPoint.position.copy(aimPos);
  81251. this.targetPoint.scale.set(s,s,s);
  81252. this.aimPos = aimPos;
  81253. var scale = math.getScaleForConstantSize({//
  81254. width2d : width2dPX,
  81255. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new Vector3()),
  81256. resolution: viewer.mainViewport.resolution2
  81257. });
  81258. this.scale.set(scale, scale, scale);
  81259. if(!dontRender){
  81260. this.waitRender = true;
  81261. }
  81262. }
  81263. /* update(aimPos){ //仅改fov的版本
  81264. aimPos = aimPos instanceof THREE.Vector3 ? aimPos : this.aimPos
  81265. if(!aimPos || !this.visible)return
  81266. //相机位置
  81267. var playerCamera = viewer.scene.getActiveCamera()
  81268. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  81269. var dis = playerPos.distanceTo(aimPos);
  81270. if(dis<magDistance_){
  81271. this.camera.fov = maxFov
  81272. }else{
  81273. this.camera.fov = THREE.Math.radToDeg(Math.atan(radius_ / dis )) * 2 //radius_是能看到的范围半径。当dis大于magDistance_时就放大,否则维持fov为maxFov
  81274. }
  81275. this.camera.updateProjectionMatrix()
  81276. this.camera.position.copy(playerPos)
  81277. this.camera.lookAt(aimPos)
  81278. this.quaternion.copy(playerCamera.quaternion);
  81279. let pointer = viewer.inputHandler.pointer.clone();
  81280. let margin = 0.4, maxY = 0.4
  81281. let screenPos = pointer.clone().setY(pointer.y + (pointer.y>maxY ? -margin : margin ))
  81282. let newPos = new THREE.Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  81283. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  81284. this.position.copy(playerPos.clone().add(dir))
  81285. this.aimPos = aimPos
  81286. this.targetPoint.position.copy(aimPos);
  81287. var scale = math.getScaleForConstantSize({//
  81288. width2d : width2dPX,
  81289. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new THREE.Vector3()),
  81290. resolution: viewer.mainViewport.resolution2
  81291. })
  81292. this.scale.set(scale, scale, scale);
  81293. if(!this.dontRender){
  81294. this.waitRender = true
  81295. }
  81296. }//位置需要计算,不仅仅是点云,所以需要深度图
  81297. */
  81298. render(){
  81299. if(!this.waitRender)return
  81300. //this.visible = false;//防止放大镜里有自己
  81301. viewer.render({
  81302. target : this.renderTarget,
  81303. viewports : [this.viewport],
  81304. camera : this.camera,
  81305. magnifier : true,
  81306. rtEDL: this.rtEDL
  81307. /* width :this.renderTarget.width,
  81308. height: this.renderTarget.height, */
  81309. });
  81310. //this.visible = true;
  81311. this.waitRender = false;
  81312. }
  81313. }
  81314. let texLoader$a = new TextureLoader();
  81315. let defaultOpacity = 0.7;
  81316. //鼠标指示小圆片
  81317. class Reticule extends Mesh{
  81318. constructor(viewer){
  81319. var defaultTex = texLoader$a.load(Potree.resourcePath+'/textures/whiteCircle.png'/* reticule-256x256.png' */);
  81320. super(new PlaneBufferGeometry(0.11,0.11,1,1),new MeshBasicMaterial({
  81321. side: DoubleSide ,
  81322. map: defaultTex,
  81323. transparent:true,
  81324. depthTest: !1,
  81325. opacity: defaultOpacity,
  81326. //depthWrite: !1,
  81327. }));
  81328. this.name = 'reticule';
  81329. this.defaultTex = defaultTex;
  81330. this.crosshairTex = texLoader$a.load(Potree.resourcePath+'/textures/reticule_cross_hair.png');
  81331. this.forbitTex = texLoader$a.load(Potree.resourcePath+'/textures/pic-forbid.png');
  81332. //this.layers.set(0/* RenderLayers.RETICULE */);
  81333. this.renderOrder = 100;
  81334. this.layers.set(Potree.config.renderLayers.marker);
  81335. this.direction = new Vector3;
  81336. this.mouseLastMoveTime = Date.now();
  81337. this.hoverViewport;
  81338. this.matrixMap = new Map;
  81339. this.matrixAutoUpdate = false;
  81340. this.hide(0);
  81341. //viewer.inputHandler.addInputListener(this);
  81342. Potree.settings.intersectWhenHover && viewer.addEventListener('global_mousemove',this.move.bind(this));
  81343. //viewer.addEventListener('global_click',this.move.bind(this))
  81344. viewer.addEventListener('global_mousedown',this.move.bind(this));//主要针对触屏
  81345. this.state = {};
  81346. let startCrossStyle = ()=>{
  81347. this.state.cross = true;
  81348. this.judgeTex();
  81349. };
  81350. let endCrossStyle = ()=>{
  81351. this.state.cross = false;
  81352. this.judgeTex();
  81353. };
  81354. viewer.addEventListener('measureMovePoint',startCrossStyle);
  81355. viewer.addEventListener('endMeasureMove',endCrossStyle);
  81356. viewer.addEventListener('start_inserting_tag',startCrossStyle);
  81357. viewer.addEventListener('endTagMove',endCrossStyle);
  81358. viewer.addEventListener('reticule_forbit',(e)=>{
  81359. if(this.state.forbit != e.v){
  81360. console.log('change forbit ',e.v);
  81361. }
  81362. this.state.forbit = e.v;
  81363. this.judgeTex();
  81364. });
  81365. viewer.setObjectLayers(this, 'sceneObjects' );
  81366. }
  81367. judgeTex(){
  81368. if(this.state.forbit){
  81369. this.material.map = this.forbitTex;
  81370. }else if(this.state.cross){
  81371. this.material.map = this.crosshairTex;
  81372. }else {
  81373. this.material.map = this.defaultTex;
  81374. }
  81375. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  81376. }
  81377. move(e){
  81378. if(e.type == "global_mousemove" && (e.isTouch || e.buttons != Buttons.NONE) && this.state != 'crosshair'){
  81379. return//按下时不更新,除非拖拽测量
  81380. }
  81381. this.mouseLastMoveTime = Date.now();
  81382. this.updatePosition(e.intersect, e.hoverViewport);
  81383. }
  81384. hide(duration = 500){
  81385. if(this.hidden)return
  81386. this.hidden = !0;
  81387. transitions.start(lerp.property(this.material , "opacity", 0), duration);
  81388. this.dispatchEvent({type:'update', visible:false});
  81389. setTimeout(()=>{
  81390. this.dispatchEvent({type:'update', visible:false});
  81391. },duration);
  81392. }
  81393. show(duration = 300){
  81394. if(!viewer.getObjVisiByReason(this, 'force'))return
  81395. //console.log("show Reticule")
  81396. this.hidden = !1;
  81397. if(this.material.opacity <= 0){
  81398. transitions.start(lerp.property(this.material, "opacity", defaultOpacity), duration);
  81399. this.dispatchEvent({type:'update', visible:true});
  81400. setTimeout(()=>{
  81401. this.dispatchEvent({type:'update', visible:false});
  81402. },duration);
  81403. }
  81404. }
  81405. //鼠标静止一段时间它就会消失
  81406. updateVisible(){
  81407. Date.now() - this.mouseLastMoveTime > 1500 && !this.hidden && this.hide();
  81408. }
  81409. updateScale(viewport){
  81410. let s, camera = viewport.camera;
  81411. if(camera.type == "OrthographicCamera"){
  81412. var sizeInfo = this.state.cross ? {width2d:500} : {minSize : 100, maxSize : 400, nearBound : 100 , farBound : 700};
  81413. s = math.getScaleForConstantSize($.extend( sizeInfo ,
  81414. {position:this.position, camera, resolution:viewport.resolution/* 2 */} ));
  81415. }else {
  81416. let n = camera.position.distanceTo(this.position);
  81417. s = 1 + .1 * n;
  81418. n < 1 && (s -= 1 - n);
  81419. }
  81420. this.scale.set(s, s, s);
  81421. }
  81422. updateAtViewports(viewport){//当多个viewports时更新。更新大小等
  81423. if(viewport.name == 'magnifier' )return
  81424. if(this.hoverViewport && this.hoverViewport.name == 'mapViewport' && viewport != this.hoverViewport){
  81425. //若是在地图上更新,在其他viewport要隐藏。因为在地图上无法得知高度。
  81426. viewer.updateVisible(this, 'hoverMap', false);
  81427. return;
  81428. }
  81429. viewer.updateVisible(this, 'hoverMap', true);
  81430. var matrix = this.matrixMap.get(viewport);
  81431. if(!matrix){
  81432. this.updateScale(viewport);
  81433. this.updateMatrix();
  81434. //this.updateMatrixWorld()
  81435. this.matrixMap.set(viewport, this.matrix.clone());
  81436. }else {
  81437. this.matrix.copy(matrix);
  81438. //this.updateMatrixWorld()
  81439. }
  81440. }
  81441. updatePosition(intersect, viewport ){ //在地图(当地图融合到viewer时)和场景里都显示且完全相同(大小可能不同)
  81442. if (viewer.getObjVisiByReason(this, 'force')) {//没有被强制隐藏,如进入某个页面后强制不显示
  81443. if (!intersect /* || !intersect.point.normal */){
  81444. return //this.hide();
  81445. }
  81446. var atMap = !intersect.location;
  81447. let location = intersect.location || intersect.orthoIntersect.clone();
  81448. let normal;
  81449. //地图上要瞬间变化 , 因为要使needRender为true很麻烦
  81450. this.show(atMap ? 0 : 300);
  81451. if(atMap){
  81452. normal = new Vector3(0,0,1);//地图无normal
  81453. location.setZ(0);//低于相机高度即可
  81454. this.direction = normal.clone();
  81455. }else {
  81456. /* if(intersect.point){
  81457. if(intersect.pointcloud){
  81458. normal = new THREE.Vector3().fromArray(intersect.point.normal ).applyMatrix4( intersect.pointcloud.rotateMatrix );
  81459. }else{//mesh
  81460. normal = new THREE.Vector3().copy(intersect.point.normal).applyQuaternion(intersect.object.quaternion)
  81461. }
  81462. }else{
  81463. normal = intersect.normal //when showPanos
  81464. } */
  81465. normal = intersect.normal;
  81466. if(normal){
  81467. let ratio = /* Potree.settings.useDepthTex ? 1 : */ 0.2;
  81468. this.direction = this.direction.multiplyScalar(1-ratio);
  81469. this.direction.add(normal.clone().multiplyScalar(ratio));
  81470. }
  81471. //this.direction = normal.clone() //改为瞬间变化,否则刚hover上某个点时看起来不太对
  81472. }
  81473. this.position.copy(location);/* .add(normal.clone().multiplyScalar(.01)); */
  81474. this.updateMatrix(); //lookAt之前要保证得到matrix
  81475. this.lookAt(this.position.clone().add(this.direction));
  81476. this.hoverViewport = viewport; //记录下最近一次hover过的viewport
  81477. this.updateScale(viewport);
  81478. {//存储matrix,节省计算
  81479. this.updateMatrix();
  81480. //this.updateMatrixWorld()
  81481. this.matrixMap.clear();//重新计算
  81482. this.matrixMap.set(viewport, this.matrix.clone());
  81483. //别处会updateMatrixWorld
  81484. }
  81485. this.dispatchEvent({type:'update'});
  81486. //为什么navvis在校准数据集时每个viewport里reticule的朝向都刚好垂直于屏幕,似乎限定在了一定范围内,还是在pick时就只pick范围内的点?
  81487. }
  81488. }
  81489. //navvis在地图等地方看reticule是有厚度的
  81490. /* updateMatrixWorld(force){
  81491. console.log('updateMatrixWorld', force)
  81492. super.updateMatrixWorld(force)
  81493. } */
  81494. }
  81495. const FEET_TO_INCHES_FACTOR = 12;
  81496. const EIGHTHS_SYMBOLS = ["", "⅛", "¼", "⅜", "½", "⅝", "¾", "⅞"];//eighths 八分之……
  81497. class UnitOfMeasurement{//转化单位工具
  81498. constructor(t, e, n, i){
  81499. this.name = t,
  81500. this.symbol = e,
  81501. this.base = n,
  81502. this.factor = i;
  81503. }
  81504. toBase(t) {//换算到base
  81505. return t * this.factor
  81506. }
  81507. fromBase(t) {//换算到当前
  81508. return t / this.factor
  81509. }
  81510. }
  81511. /* var o = function t(e) {
  81512. this.gettext = e,
  81513. t.METRIC = this.gettext("metric", void 0, "measurement system"),
  81514. t.IMPERIAL = this.gettext("imperial", void 0, "measurement system")
  81515. };
  81516. e.UoMSystem = o;
  81517. let UoMSystem = {
  81518. } */
  81519. /* var MeasurementDomain = {
  81520. DISTANCE : "DISTANCE",
  81521. t.AREA = "AREA",
  81522. t.VOLUME = "VOLUME",
  81523. t.DATA = "DATA",
  81524. t
  81525. }
  81526. */
  81527. var UnitsOfMeasurement = {
  81528. MILLIMETER : ["Millimeter", "mm"],
  81529. CENTIMETER : ["Centimeter", "cm"],
  81530. METER : ["Meter", "m"],
  81531. KILOMETER : ["Kilometer", "km"],
  81532. INCH : ["Inch", "in"],
  81533. FOOT : ["Foot", "ft"],
  81534. MILE : ["Mile", "mi"],
  81535. SQUAREMETER : ["SquareMeter", "m²"],
  81536. SQUAREFOOT : ["SquareFoot", "ft²"],
  81537. CUBICMETER : ["CubicMeter", "m³"],
  81538. CUBICFOOT : ["CubicFoot", "ft³"],
  81539. BYTE : ["Byte", "B"],
  81540. KILOBYTE : ["Kilobyte", "kB"],
  81541. MEGABYTE : ["Megabyte", "MB"],
  81542. GIGABYTE : ["Gigabyte", "GB"],
  81543. TERABYTE : ["Terabyte", "TB"],
  81544. PETABYTE : ["Petabyte", "PB"],
  81545. init : function() {
  81546. var e, n, i, a, s, c, l, u, d, p, h,
  81547. f = new UnitOfMeasurement(UnitsOfMeasurement.METER[0],UnitsOfMeasurement.METER[1],void 0,1),
  81548. g = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREMETER[0],UnitsOfMeasurement.SQUAREMETER[1],void 0,1),
  81549. m = new UnitOfMeasurement(UnitsOfMeasurement.CUBICMETER[0],UnitsOfMeasurement.CUBICMETER[1],void 0,1),
  81550. v = new UnitOfMeasurement(UnitsOfMeasurement.BYTE[0],UnitsOfMeasurement.BYTE[1],void 0,1);
  81551. UnitsOfMeasurement.DISTANCE = (
  81552. (e = {})['metric'] = ((n = {})[UnitsOfMeasurement.MILLIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILLIMETER[0],UnitsOfMeasurement.MILLIMETER[1],f,.001),
  81553. n[UnitsOfMeasurement.CENTIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CENTIMETER[0],UnitsOfMeasurement.CENTIMETER[1],f,.01),
  81554. n[UnitsOfMeasurement.METER[0]] = f,
  81555. n[UnitsOfMeasurement.KILOMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOMETER[0],UnitsOfMeasurement.KILOMETER[1],f,1e3),
  81556. n),
  81557. e['imperial'] = ((i = {})[UnitsOfMeasurement.INCH[0]] = new UnitOfMeasurement(UnitsOfMeasurement.INCH[0],UnitsOfMeasurement.INCH[1],f,.0254),
  81558. i[UnitsOfMeasurement.FOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.FOOT[0],UnitsOfMeasurement.FOOT[1],f,.3048),
  81559. i[UnitsOfMeasurement.MILE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILE[0],UnitsOfMeasurement.MILE[1],f,1609.344),
  81560. i),
  81561. e);
  81562. UnitsOfMeasurement.AREA = ((a = {})['metric'] = ((s = {})[UnitsOfMeasurement.SQUAREMETER[0]] = g,
  81563. s),
  81564. a['imperial'] = ((c = {})[UnitsOfMeasurement.SQUAREFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREFOOT[0],UnitsOfMeasurement.SQUAREFOOT[1],g,.092903),
  81565. c),
  81566. a);
  81567. UnitsOfMeasurement.VOLUME = ((l = {})['metric'] = ((u = {})[UnitsOfMeasurement.CUBICMETER[0]] = m,
  81568. u),
  81569. l['imperial'] = ((d = {})[UnitsOfMeasurement.CUBICFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CUBICFOOT[0],UnitsOfMeasurement.CUBICFOOT[1],m,.0283168),
  81570. d),
  81571. l);
  81572. //数据大小
  81573. var y = ((p = {})[UnitsOfMeasurement.BYTE[0]] = v,
  81574. p[UnitsOfMeasurement.KILOBYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOBYTE[0],UnitsOfMeasurement.KILOBYTE[1],v,1e3),
  81575. p[UnitsOfMeasurement.MEGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MEGABYTE[0],UnitsOfMeasurement.MEGABYTE[1],v,1e6),
  81576. p[UnitsOfMeasurement.GIGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.GIGABYTE[0],UnitsOfMeasurement.GIGABYTE[1],v,1e9),
  81577. p[UnitsOfMeasurement.TERABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.TERABYTE[0],UnitsOfMeasurement.TERABYTE[1],v,1e12),
  81578. p[UnitsOfMeasurement.PETABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.PETABYTE[0],UnitsOfMeasurement.PETABYTE[1],v,1e15),
  81579. p);
  81580. UnitsOfMeasurement.DATA = ((h = {})['metric'] = y,
  81581. h['imperial'] = y,
  81582. h);
  81583. }
  81584. ,
  81585. getUnitsOfMeasurementByDomain : function(e) {
  81586. return this[e.toUpperCase()]
  81587. /* switch (e.toUpperCase()) {
  81588. case a.DISTANCE:
  81589. return t.DISTANCE;
  81590. case a.AREA:
  81591. return t.AREA;
  81592. case a.VOLUME:
  81593. return t.VOLUME;
  81594. case a.DATA:
  81595. return t.DATA;
  81596. default:
  81597. console.error(e + " measurement domain is not supported.")
  81598. } */
  81599. }
  81600. ,
  81601. getUnitsOfMeasurementByDomainAndSystem : function(domain, system) {
  81602. var r = this.getUnitsOfMeasurementByDomain(domain);
  81603. if (r.hasOwnProperty(system.toLowerCase()))
  81604. return r[system.toLowerCase()];
  81605. console.error(n + " measurement system is not supported.");
  81606. }
  81607. ,
  81608. getDefaultUnitByDomainAndSystem : function(e, n) {
  81609. switch (e.toUpperCase()) {
  81610. case 'DISTANCE':
  81611. switch (n.toLowerCase()) {
  81612. case 'metric':
  81613. return this.DISTANCE['metric'][this.METER[0]];
  81614. case 'imperial':
  81615. return this.DISTANCE['imperial'][this.FOOT[0]];
  81616. default:
  81617. console.error(n + " measurement system is not supported.");
  81618. }
  81619. case 'AREA':
  81620. switch (n.toLowerCase()) {
  81621. case 'metric':
  81622. return this.AREA['metric'][this.SQUAREMETER[0]];
  81623. case 'imperial':
  81624. return this.AREA['imperial'][this.SQUAREFOOT[0]];
  81625. default:
  81626. console.error(n + " measurement system is not supported.");
  81627. }
  81628. case 'VOLUME':
  81629. switch (n.toLowerCase()) {
  81630. case 'metric':
  81631. return this.VOLUME['metric'][this.CUBICMETER[0]];
  81632. case 'imperial':
  81633. return this.VOLUME['imperial'][this.CUBICFOOT[0]];
  81634. default:
  81635. console.error(n + " measurement system is not supported.");
  81636. }
  81637. case 'DATA':
  81638. switch (n.toLowerCase()) {
  81639. case 'metric':
  81640. return this.DATA['metric'][this.BYTE[0]];
  81641. case 'imperial':
  81642. return this.DATA['imperial'][this.BYTE[0]];
  81643. default:
  81644. console.error(n + " measurement system is not supported.");
  81645. }
  81646. default:
  81647. console.error(e + " measurement domain is not supported.");
  81648. }
  81649. }
  81650. };
  81651. class UnitService{
  81652. constructor(/* e, n, i */){
  81653. //this.LanguageService = e,
  81654. //this.localStorageService = n,
  81655. //this.gettext = i,
  81656. //this.unitChanged = new r.Signal,
  81657. this.LOCAL_STORAGE_KEY = "iv_unit_key";//?
  81658. UnitsOfMeasurement.init();
  81659. this.unitSystems = ['metric', 'imperial'];//[o.UoMSystem.METRIC, o.UoMSystem.IMPERIAL],
  81660. this.defaultSystem = 'metric';//'imperial'
  81661. //var a = this.LanguageService.getBrowserLocaleString().toLowerCase();
  81662. //this.defaultSystem = t.isLocaleImperial(a) ? o.UoMSystem.IMPERIAL : o.UoMSystem.METRIC,
  81663. //this.initUnit()
  81664. }
  81665. /* initUnit() {
  81666. var t = this.localStorageService.get(this.LOCAL_STORAGE_KEY);
  81667. if (t)
  81668. for (var e = 0, n = this.unitSystems; e < n.length; e++) {
  81669. var i = n[e];
  81670. if (i === t)
  81671. return void this.setUnit(i, !0)
  81672. }
  81673. this.setUnit(this.defaultSystem, !1)
  81674. }
  81675. setUnit(t, e) {
  81676. this.currentSystem !== t && (this.currentSystem = t,
  81677. this.unitChanged.emit()),
  81678. e && this.localStorageService.set(this.LOCAL_STORAGE_KEY, t)
  81679. } */
  81680. /*isLocaleImperial(e) {
  81681. return t.IMPERIAL_LOCALES.indexOf(e.toLowerCase()) >= 0
  81682. }
  81683. ,
  81684. t.IMPERIAL_LOCALES = ["en_us"],
  81685. t.ɵfac(e) {
  81686. return new (e || t)(c.ɵɵinject(l.LanguageService),
  81687. c.ɵɵinject("localStorageService"),c.ɵɵinject("gettext"))
  81688. }
  81689. ,
  81690. t.ɵprov = c.ɵɵdefineInjectable({
  81691. token: t,
  81692. factory: t.ɵfac,
  81693. providedIn: "root"
  81694. }), */
  81695. }
  81696. class UoMService{
  81697. constructor(/* UnitService */){
  81698. this.UnitService = new UnitService();/* UnitService */
  81699. }
  81700. scopedConvert (t, n, precision = 2, r, minFactor) {
  81701. return this.convert(t, n, precision, r, minFactor)
  81702. }
  81703. convert(number, domain, precision = 2, system, minFactor, ifEighths = !1) {
  81704. if (!number) return "";
  81705. var s = this.getMostRelevantMeasurement(domain, system || this.UnitService.currentSystem, number, minFactor);
  81706. return this.getFormattedMeasurementString(s[0], s[1], precision, ifEighths)
  81707. }
  81708. convertBack(number, domain, precision = 2, fromSystem, minFactor ) { //从英制转到'metric'
  81709. if (!number) return "";
  81710. var d = UnitsOfMeasurement.getDefaultUnitByDomainAndSystem(domain,'metric');
  81711. var s = this.getMostRelevantMeasurement2(domain, fromSystem, number, minFactor);
  81712. return this.getFormattedMeasurementString(s[0], d, precision )
  81713. /* 栗子:
  81714. viewer.unitConvert.convertBack(1, 'area', 5, 'imperial')
  81715. '0.09290 m²'
  81716. viewer.unitConvert.convertBack(1, 'Distance', 2, 'imperial')
  81717. '0.03 m'
  81718. */
  81719. }
  81720. getFormattedMeasurementString(number, unit, precision, ifEighths) {
  81721. var result;
  81722. if(ifEighths && unit.name === UnitsOfMeasurement.FOOT[0]){
  81723. result = this.formatImperialDistance(number * FEET_TO_INCHES_FACTOR);
  81724. }else if(ifEighths && unit.name === UnitsOfMeasurement.INCH[0]){
  81725. result = this.formatImperialDistance(number);
  81726. }else {
  81727. result = number.toLocaleString(void 0, {
  81728. minimumFractionDigits: precision,
  81729. maximumFractionDigits: precision
  81730. }) + " " + unit.symbol;
  81731. }
  81732. return result
  81733. }
  81734. formatImperialDistance(e) {
  81735. var n = Math.round(8 * e)
  81736. , i = Math.floor(n / 8)
  81737. , r = Math.floor(i / FEET_TO_INCHES_FACTOR)
  81738. , o = i - r * FEET_TO_INCHES_FACTOR
  81739. , a = EIGHTHS_SYMBOLS[n % 8]
  81740. , s = 0 === o && "" !== a ? "" : o;
  81741. "" !== s && "" !== a && (a = " " + a);
  81742. return 0 !== r ? r + "' " + s + a + '"' : "" + s + a + '"'
  81743. }
  81744. getMostRelevantMeasurement(domain, system, number, minFactor=0) {
  81745. /* var a = r.values(UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system))
  81746. , s = r.filter(a, function(t) {
  81747. return t.factor >= i
  81748. })
  81749. , c = r.reduce(s, function(t, e) {
  81750. return e.fromBase(number) < t.fromBase(number) && e.fromBase(number) >= 1 ? e : t
  81751. }); */
  81752. let a = [];
  81753. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  81754. for(let i in u){a.push(u[i]);}
  81755. let s = a.filter(m=>m.factor >= minFactor);
  81756. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  81757. return currentValue.fromBase(number) < prev.fromBase(number) && currentValue.fromBase(number) >= 1 ? currentValue : prev
  81758. });
  81759. return c ? [c.fromBase(number), c] : void 0
  81760. }
  81761. getMostRelevantMeasurement2(domain, system, number, minFactor=0) {//add
  81762. let a = [];
  81763. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  81764. for(let i in u){a.push(u[i]);}
  81765. let s = a.filter(m=>m.factor >= minFactor);
  81766. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  81767. return currentValue.toBase(number) < prev.toBase(number) && currentValue.toBase(number) >= 1 ? currentValue : prev
  81768. });
  81769. return c ? [c.toBase(number), c] : void 0
  81770. }
  81771. /* ɵfac(e){
  81772. return new (e || t)(c.ɵɵinject(l.UnitService))
  81773. }
  81774. ɵprov = c.ɵɵdefineInjectable({
  81775. token: t,
  81776. factory: t.ɵfac,
  81777. providedIn: "root"
  81778. }) */
  81779. }
  81780. const texLoader$b = new TextureLoader();
  81781. const arrowSpacing = 1; //间隔
  81782. const arrowSize = arrowSpacing * 0.5;
  81783. const planeGeo$4 = new PlaneBufferGeometry(1,1);
  81784. const sphereSizeInfo = {
  81785. nearBound : 2, scale:arrowSize, restricMeshScale : true,
  81786. };
  81787. //const arrowsShowingCount = 25; //场景里最多展示多少个箭头
  81788. const arrowShowMinDis = 10;
  81789. class RouteGuider extends EventDispatcher{
  81790. constructor () {
  81791. super();
  81792. this.route = [];
  81793. this.curve = [];
  81794. this.scenePoints = [];
  81795. this.sceneMeshGroup = new Object3D;
  81796. this.mapMeshGroup = new Object3D;
  81797. this.generateDeferred;
  81798. viewer.addEventListener('loadPointCloudDone',this.init.bind(this));
  81799. this.lastResult;//保存上一个的结果,以便于反向
  81800. this.datasetIds = [];//起始和终点的datasetId
  81801. }
  81802. init(){
  81803. if(this.inited) return;
  81804. let zoom;
  81805. viewer.mapViewer.addEventListener('camera_changed', e => {
  81806. if(!this.routeStart || !this.routeEnd) return
  81807. var camera = e.viewport.camera;
  81808. Common.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81809. if(camera.zoom != zoom){
  81810. //console.log('updateMapArrows')
  81811. this.updateMapArrows(true);
  81812. zoom = camera.zoom;
  81813. return true
  81814. }
  81815. }, browser.isMobile()?500:200);
  81816. });
  81817. //let lastPos = new THREE.Vector3
  81818. viewer.addEventListener('camera_changed', e => {
  81819. if(!this.routeStart || !this.routeEnd || !e.changeInfo.positionChanged) return
  81820. Common.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81821. //let currPos = viewer.scene.getActiveCamera().position
  81822. //if(!currPos.equals(lastPos)){
  81823. // lastPos.copy(currPos)
  81824. this.updateArrowDisplay();
  81825. return true
  81826. //}
  81827. }, 1000);
  81828. });
  81829. var polesMats = {
  81830. shadowMat: new MeshBasicMaterial({
  81831. transparent:true, depthTest:false,
  81832. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_bottomMarker.png' )
  81833. }),
  81834. sphereMat : new MeshBasicMaterial({
  81835. transparent:true, depthTest:false,
  81836. map: texLoader$b.load(Potree.resourcePath+'/textures/whiteCircle.png' )
  81837. }),
  81838. hatMats:{
  81839. start: new MeshBasicMaterial({
  81840. transparent:true, depthTest:false,
  81841. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_start_route.png' )
  81842. }),
  81843. end: new MeshBasicMaterial({
  81844. transparent:true, depthTest:false,
  81845. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_target_reached.png' )
  81846. })
  81847. }
  81848. };
  81849. polesMats.shadowMat.map.anisotropy = 4;
  81850. this.poleStart = this.createPole(polesMats, 'start');
  81851. this.poleEnd = this.createPole(polesMats, 'end');
  81852. this.sceneMeshGroup.add(this.poleStart);
  81853. this.sceneMeshGroup.add(this.poleEnd);
  81854. let map = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_panorama.png' );
  81855. map.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  81856. this.arrow = new Mesh(planeGeo$4, new MeshBasicMaterial({
  81857. transparent:true,
  81858. depthTest:false,
  81859. map
  81860. }));
  81861. this.arrow.scale.set(arrowSize,arrowSize,arrowSize);
  81862. viewer.setObjectLayers(this.arrow, 'sceneObjects' );
  81863. /* this.testArrow = this.arrow.clone();
  81864. this.testArrow.material = this.arrow.material.clone()
  81865. this.testArrow.material.color = 'red' */
  81866. this.arrows = new Object3D;
  81867. this.sceneMeshGroup.add(this.arrows);
  81868. viewer.setObjectLayers(this.sceneMeshGroup, 'sceneObjects' );
  81869. //this.sceneMeshGroup.traverse(e=>e.renderOrder = 90)
  81870. viewer.scene.scene.add(this.sceneMeshGroup);
  81871. this.sceneMeshGroup.visible = /* this.poleStart.visibile = this.poleEnd.visibile = */ false;
  81872. //-------------map---------------------
  81873. /* this.mapMarkStart = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81874. transparent:true, depthTest:false,
  81875. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_start_route.png' )
  81876. }))
  81877. this.mapMarkEnd = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81878. transparent:true, depthTest:false,
  81879. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_target_reached.png' )
  81880. }))
  81881. this.mapMarkStart.renderOrder = this.mapMarkEnd.renderOrder = 2//在箭头之上 */
  81882. let map2 = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_map_fsna.png' );
  81883. this.mapArrowMats = {
  81884. default: new MeshBasicMaterial({
  81885. transparent:true, depthTest:false,
  81886. map:map2,
  81887. }),
  81888. fade: new MeshBasicMaterial({
  81889. transparent:true, depthTest:false,
  81890. map:map2,
  81891. opacity:0.4
  81892. }),
  81893. };
  81894. this.mapArrow = new Mesh( planeGeo$4, this.mapArrowMats.default);
  81895. this.mapArrow.scale.set(arrowSize,arrowSize,arrowSize);
  81896. this.mapArrows = new Object3D;
  81897. this.mapArrows.name = 'mapArrows';
  81898. this.mapMeshGroup.add(this.mapArrows);
  81899. this.mapMeshGroup.name = 'mapRouteLayer';
  81900. this.mapMeshGroup.visible = false;
  81901. viewer.mapViewer.dispatchEvent({type:'add', object:this.mapMeshGroup, name:'route'});
  81902. this.mapArrow.layers.mask = this.mapArrows.layers.mask; // 修改成和map中的layer一样的
  81903. viewer.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  81904. if(this.routeStart && this.routeEnd){
  81905. this.updateOpacityAtMap();
  81906. }
  81907. });
  81908. this.inited = true;
  81909. }
  81910. updateOpacityAtMap(){//只有当前楼层的透明度为1
  81911. var currentFloor = viewer.modules.SiteModel.currentFloor;
  81912. //console.log('updateOpacityAtMap', currentFloor && currentFloor.name)
  81913. const lift = 0.3; // 因为发送请求时用的是floorPosition的高度,而它可能会到画好的floor之下,所以有误差
  81914. this.mapArrows.children.forEach((arrow,index)=>{
  81915. let pos = this.mapPoints[index].clone();
  81916. pos.z += lift;
  81917. let inSide = currentFloor && currentFloor.ifContainsPoint(pos);
  81918. arrow.material = inSide ? this.mapArrowMats.default : this.mapArrowMats.fade;
  81919. //console.log('arrow',index, arrow.material.opacity)
  81920. });
  81921. viewer.mapViewer.dispatchEvent('content_changed');
  81922. }//但是如果楼层刚好只框柱相机位置而没框住地面位置就不好了……
  81923. createPole(polesMats, name){
  81924. const height = 1.5, sphereCount = 6, shadowSize = sphereSizeInfo.scale, sphereSize = 0.04;
  81925. var group = new Object3D;
  81926. group.name = 'pole_'+name;
  81927. var shadow = new Mesh(planeGeo$4,polesMats.shadowMat);
  81928. shadow.scale.set(shadowSize,shadowSize,shadowSize);
  81929. var sliceDis = height / (sphereCount+1);
  81930. group.add(shadow);
  81931. for(let i=0;i<sphereCount;i++){
  81932. var sphere = new Sprite$1({mat: polesMats.sphereMat});
  81933. sphere.position.set(0,0,sliceDis*(i+1));
  81934. sphere.scale.set(sphereSize,sphereSize,sphereSize);
  81935. sphere.visible = false;
  81936. group.add(sphere);
  81937. }
  81938. var hatSphere = new Sprite$1({mat: polesMats.hatMats[name], sizeInfo:sphereSizeInfo});
  81939. sphere.visible = false;
  81940. hatSphere.position.set(0,0,height);
  81941. hatSphere.scale.copy(shadow.scale);
  81942. group.add(hatSphere);
  81943. return group
  81944. }
  81945. addTestArrow(){
  81946. }
  81947. addArrow(position){
  81948. var arrow = this.arrow.clone();
  81949. arrow.position.copy(position);
  81950. this.arrows.add(arrow);
  81951. }
  81952. addMapArrow(position){
  81953. var mapArrow = this.mapArrow.clone();
  81954. mapArrow.position.copy(position).setZ(0);
  81955. this.mapArrows.add(mapArrow);
  81956. }
  81957. setArrowDir(arrows,index){
  81958. let arrow = arrows[index];
  81959. var nextOne = arrows[index+1];
  81960. var nextPos = nextOne ? nextOne.position : this.endPolePos; //routeEnd
  81961. var direction = new Vector3().subVectors(arrow.position, nextPos).setZ(0);
  81962. //direction.normalize();
  81963. //console.log(direction.toArray())
  81964. var angle = Math.atan2(direction.y, direction.x ) + Math.PI/2; //Math.PI/2是因为贴图本身箭头方向不朝x
  81965. arrow.rotation.z = angle;
  81966. //console.log(angle)
  81967. }
  81968. setRouteStart(pos, dealZ , datasetId ){
  81969. if(this.routeStart && pos && this.routeStart.equals(pos)) return //可能重复设置
  81970. this.routeStart = pos && new Vector3().copy(pos);
  81971. if(dealZ && this.routeStart){
  81972. this.routeStart.setZ(this.getZAtMap());
  81973. this.bus && this.bus.emit('reposStartMarker', this.routeStart);
  81974. }
  81975. console.log('setRouteStart',this.routeStart&&this.routeStart.toArray());
  81976. this.datasetIds[0] = datasetId;
  81977. //this.setStartPole(pos)
  81978. this.generateRoute();
  81979. }
  81980. setStartPole(pos){
  81981. this.startPolePos = pos;
  81982. this.bus && this.bus.emit('reposStartMarker', pos);
  81983. }
  81984. setRouteEnd(pos, dealZ , datasetId ){
  81985. if(this.routeEnd && pos && this.routeEnd.equals(pos)) return
  81986. this.routeEnd = pos && new Vector3().copy(pos);
  81987. if(dealZ && this.routeEnd){
  81988. this.routeEnd.setZ(this.getZAtMap());
  81989. this.bus && this.bus.emit('reposEndMarker', this.routeEnd);
  81990. }
  81991. console.log('setRouteEnd',this.routeEnd&&this.routeEnd.toArray());
  81992. this.datasetIds[1] = datasetId;
  81993. //this.setEndPole(pos)
  81994. this.generateRoute();
  81995. }
  81996. getZAtMap(){
  81997. //找到position.z与当前高度最接近的漫游点
  81998. let result = Common.sortByScore(viewer.images360.panos,[],[e=> -(Math.abs(e.position.z - viewer.images360.position.z)) ]);
  81999. let pano = result && result[0] && result[0].item;
  82000. return pano ? pano.floorPosition.z : viewer.bound.boundingBox.min.z + 1
  82001. //若在平面图上画实在得不到当前楼层的,大概率是楼层画得不好,那就只能去获取当前楼层的了
  82002. //navvis的高度取的是主视图所在楼层的中心高度(可能再高些)
  82003. }
  82004. setEndPole(pos){
  82005. this.endPolePos = pos;
  82006. this.bus && this.bus.emit('reposEndMarker', pos);
  82007. }
  82008. getSourceProjectionIndex(route) {//真正的起始
  82009. var e = route.findIndex(function(t) {
  82010. return t.instruction && t.instruction.type === 'source_projection_to_navgraph'
  82011. });
  82012. return e < 0 ? 0 : e
  82013. }
  82014. getDestinationProjectionIndex(route) {//真正的终点
  82015. var e = route.findIndex(function(t) {
  82016. return t.instruction && t.instruction.type === "destination_projection_to_navgraph"
  82017. });
  82018. return e < 0 ? route.length - 1 : e
  82019. }
  82020. generateRoute(){
  82021. if(!this.routeStart || !this.routeEnd){
  82022. return
  82023. }
  82024. //array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  82025. let create = ()=>{
  82026. this.routeLength = this.route.reduce((total, currentValue, currentIndex, arr)=>{
  82027. if(currentIndex == 0)return 0
  82028. return total + currentValue.distanceTo(arr[currentIndex-1]);
  82029. },0);
  82030. let count = Math.max(2,Math.round(this.routeLength / arrowSpacing));//点数
  82031. const curve = new CatmullRomCurve3( this.route );
  82032. curve.curveType = 'chordal';//'centripetal' 'catmullrom'这个可能会超出路径外
  82033. this.curve = curve;
  82034. const scenePoints = curve.getSpacedPoints( count );//更平均
  82035. //const scenePoints = curve.getPoints( count );
  82036. scenePoints.splice(0,1);//去掉首尾
  82037. scenePoints.pop();
  82038. this.scenePoints = scenePoints;
  82039. this.updateMapArrows();
  82040. this.displayRoute();
  82041. {//map focus on this area
  82042. const minBound = new Vector2$1(1,1);//针对垂直线,在地图上只有一个点
  82043. let bound = new Box2;
  82044. this.route.forEach(e=>{
  82045. bound.expandByPoint(e);
  82046. });
  82047. let size = bound.getSize(new Vector2$1);
  82048. let markerSize = new Vector2$1(115,40); //起始和终点的标识呈长方形
  82049. let areaSize = viewer.mapViewer.viewports[0].resolution2;
  82050. let areaArea = areaSize.x * areaSize.y;
  82051. if(areaArea> 800 * 400){//是放大的
  82052. markerSize.multiplyScalar(areaArea / (800 * 400) /* / (size.x * size.y) */);
  82053. }
  82054. let margin = size.clone().divide(viewer.mapViewer.viewports[0].resolution2).multiply(markerSize); ///边距 重点是起始和终点的标识占据较大
  82055. size.add(margin);
  82056. let center = bound.getCenter(new Vector2$1);
  82057. size.x = Math.max(size.x, minBound.x );
  82058. size.y = Math.max(size.y, minBound.y );
  82059. let duration = 1000;
  82060. viewer.mapViewer.moveTo(center, size, duration);
  82061. }
  82062. this.bus.emit('gotResult', {dis:this.routeLength});
  82063. /* this.generateDeferred && this.generateDeferred.resolve({dis:this.routeLength})
  82064. this.generateDeferred = null */
  82065. };
  82066. if(Potree.fileServer){
  82067. let dealData = (data)=>{
  82068. if(!data.data){
  82069. console.log('没有数据');
  82070. let result;
  82071. if(data && data.code == 4002){
  82072. result = data;//正被修改数据集
  82073. }else if(this.routeStart.distanceTo(this.routeEnd) < 1){
  82074. result = { code: 500, msg: '距离太短,无法规划路线' };
  82075. }else {
  82076. result = { code: 500, msg: '超出数据集范围,无法规划路线' };
  82077. }
  82078. this.clearRoute();
  82079. this.setStartPole(this.routeStart);
  82080. this.setEndPole(this.routeEnd);
  82081. this.displayRoute(); //还是要显示一下起始
  82082. this.bus && this.bus.emit('gotResult', result );
  82083. return //this.generateDeferred && this.generateDeferred.resolve()
  82084. }
  82085. data = data.data;
  82086. this.clearRoute();
  82087. let length = data.length;
  82088. if(length < 2){//可能距离太短
  82089. console.log('路径点数为'+length+',直接取起点和终点连线');
  82090. this.route = [this.routeStart, this.routeEnd];
  82091. }else {
  82092. let startIndex = this.getSourceProjectionIndex(data);
  82093. let endIndex = this.getDestinationProjectionIndex(data);
  82094. let effectiveItems = data.slice(startIndex, endIndex + 1 );//只要点云范围内的点
  82095. effectiveItems.forEach((item,i)=>{
  82096. let pos = viewer.transform.lonlatToLocal.forward(item.location.slice(0));
  82097. pos = new Vector3().fromArray(pos);//.setZ(item.z)
  82098. this.route.push(pos);
  82099. });
  82100. console.log(this.route);
  82101. }
  82102. this.setStartPole(this.route[0]);
  82103. this.setEndPole(this.route[this.route.length-1]);
  82104. create();
  82105. /*
  82106. distance: 0.17581000000000116
  82107. distance_to_previous: 0.17581000000000116
  82108. id: 567
  82109. instruction: {type: 'source_projection_to_navgraph'}
  82110. latitude: 22.366605927999238
  82111. location: (3) [113.5957510575092, 22.366605927999238, -1.12419]
  82112. longitude: 113.5957510575092
  82113. z: -1.12419
  82114. */
  82115. };
  82116. if(this.lastResult && (this.lastResult.data || this.lastResult.data.code != 4002)){//正被修改数据集的话要重新计算
  82117. let data = Common.CloneObject(this.lastResult.data) , use; //直接用上次的结果
  82118. if(this.lastResult.routeStart.equals(this.routeStart) && this.lastResult.routeEnd.equals(this.routeEnd)){//和上次请求相同
  82119. use = true;
  82120. }else if(this.lastResult.routeStart.equals(this.routeEnd) && this.lastResult.routeEnd.equals(this.routeStart)){//..反向
  82121. use = true;
  82122. if(data.data){
  82123. data.data = this.lastResult.data.data.slice(0).reverse();
  82124. }
  82125. }
  82126. if(use){
  82127. console.log('直接用上次的结果');
  82128. return setTimeout(()=>{dealData(data);}, 1)//延迟是为了等待获得 RouteGuider.generateDeferred
  82129. }
  82130. }
  82131. let start = this.routeStart.clone();
  82132. let end = this.routeEnd.clone();
  82133. let startLonlat = viewer.transform.lonlatToLocal.inverse(start);
  82134. let endLonlat = viewer.transform.lonlatToLocal.inverse(end);
  82135. var query = {
  82136. source_longitude: startLonlat.x,
  82137. source_latitude: startLonlat.y,
  82138. source_z: start.z,
  82139. destination_longitude: endLonlat.x,
  82140. destination_latitude: endLonlat.y,
  82141. destination_z: end.z
  82142. };
  82143. //let url = `/laser/route/${Potree.settings.number}/getRoute/${this.datasetIds[0]}/${this.datasetIds[1]}?`
  82144. let url = `/laser/route/${Potree.settings.number}/getRoute/${Potree.settings.originDatasetId}?`;
  82145. for(let i in query){
  82146. url+= (i + '='+ query[i] +'&');
  82147. }
  82148. Potree.fileServer.get(url).then((data)=>{
  82149. console.log(data.data);
  82150. if(!this.routeStart || !this.routeEnd)return
  82151. this.lastResult = {//保存数据
  82152. routeStart : this.routeStart.clone(),
  82153. routeEnd: this.routeEnd.clone(),
  82154. data,
  82155. };
  82156. dealData(data);
  82157. });
  82158. }else {
  82159. //创个直线
  82160. /* const sliceDis = 1
  82161. let dis = this.routeStart.distanceTo(this.routeEnd);
  82162. let count = Math.max(2,Math.round(dis / sliceDis))//点数
  82163. let realSlideDis = dis / (count-1);
  82164. let dir = new THREE.Vector3().subVectors(this.routeEnd, this.routeStart).normalize().multiplyScalar(realSlideDis);
  82165. this.route = [this.routeStart];
  82166. for(let i=0;i<count-1;i++){
  82167. let lastOne = this.route[i];
  82168. this.route.push(new THREE.Vector3().addVectors(lastOne,dir))
  82169. }
  82170. this.route.splice(0,1) //route不用包含收尾 */
  82171. this.clearRoute();
  82172. this.route = [this.routeStart, this.routeEnd];
  82173. create();
  82174. }
  82175. }
  82176. updateMapArrows(ifReset){
  82177. if(this.route.length == 0)return
  82178. var zoom = viewer.mapViewer.camera.zoom;
  82179. let count = Math.max(2,Math.round(this.routeLength * zoom / arrowSpacing / 25));//点数
  82180. if(count == this.mapPoints.length+1)return//没变
  82181. const mapPoints = this.curve.getSpacedPoints( count );
  82182. mapPoints.splice(0,1);//去掉首尾
  82183. mapPoints.pop();
  82184. this.mapPoints = mapPoints;
  82185. var scale = 25/zoom;
  82186. this.mapArrow.scale.set(scale*0.6,scale*0.6,scale*0.6);
  82187. /* this.mapMarkStart.scale.set(scale,scale,scale)
  82188. this.mapMarkEnd.scale.set(scale,scale,scale) */
  82189. if(ifReset){//因为缩放而重新排布箭头
  82190. this.clearRoute({resetMap:true});
  82191. this.displayRoute({resetMap:true});
  82192. }
  82193. this.updateOpacityAtMap();
  82194. }
  82195. updateArrowDisplay(){//根据当前位置更新显示一定范围内的箭头'
  82196. if(this.scenePoints.length == 0)return
  82197. /* var a = Common.sortByScore(this.scenePoints , null, [(point)=>{ //是否还要再requires里限制最远距离?
  82198. var playerPos = viewer.scene.getActiveCamera().position.clone().setZ(0)
  82199. var pos = point.clone().setZ(0)
  82200. return -pos.distanceTo(playerPos);
  82201. }]);
  82202. //获得展示的起始点
  82203. let start = a[0].item
  82204. let startIndex = this.scenePoints.indexOf(start)
  82205. this.arrows.children.forEach((e,i)=>{
  82206. if(i<startIndex || i>startIndex+arrowsShowingCount)e.visible = false
  82207. else e.visible = true
  82208. }) */
  82209. let cameraPos = viewer.scene.getActiveCamera().position;
  82210. this.arrows.children.forEach((e,i)=>{
  82211. if(e.position.distanceTo(cameraPos) < arrowShowMinDis) e.visible = true;
  82212. else e.visible = false;
  82213. });
  82214. }
  82215. displayRoute(o={}){
  82216. if(!o.resetMap){
  82217. this.poleStart.position.copy(this.startPolePos || this.routeStart);
  82218. this.poleEnd.position.copy(this.endPolePos || this.routeEnd);
  82219. /* this.mapMarkStart.position.copy(this.routeStart).setZ(0)
  82220. this.mapMarkEnd.position.copy(this.routeEnd).setZ(0) */
  82221. this.scenePoints.forEach(e=>this.addArrow(e));
  82222. this.arrows.children.forEach((e,i)=>this.setArrowDir(this.arrows.children,i));
  82223. }
  82224. this.sceneMeshGroup.traverse(e=>e.visible = true);
  82225. this.mapMeshGroup.visible = true;
  82226. this.mapPoints.forEach(e=>this.addMapArrow(e));
  82227. this.mapArrows.children.forEach((e,i)=>this.setArrowDir(this.mapArrows.children,i));
  82228. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  82229. this.updateArrowDisplay();
  82230. }
  82231. clearRoute(o={}){
  82232. if(!o.resetMap){
  82233. this.routeLength = 0;
  82234. this.route = [];
  82235. this.scenePoints = [];
  82236. this.mapPoints = [];
  82237. let arrows = this.arrows.children.slice(0);
  82238. arrows.forEach(e=>{
  82239. this.arrows.remove(e);
  82240. });
  82241. }
  82242. let mapArrows = this.mapArrows.children.slice(0);
  82243. mapArrows.forEach(e=>{
  82244. this.mapArrows.remove(e);
  82245. });
  82246. this.sceneMeshGroup.traverse(e=>e.visible = false); //包括sprite也要设置,防止update
  82247. this.mapMeshGroup.visible = false;
  82248. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  82249. }
  82250. clear(){//退出
  82251. console.log('导航clear');
  82252. this.routeStart = null;
  82253. this.routeEnd = null;
  82254. this.clearRoute();
  82255. }
  82256. }
  82257. //大概每十米要花一秒
  82258. /*
  82259. 存在的问题:
  82260. 路径不准确。起始点和终点偏移。
  82261. */
  82262. const vertexShader = `
  82263. attribute float randam;
  82264. attribute float sprite;
  82265. attribute float centerHeight; //add
  82266. //uniform float fireHeight; //add
  82267. uniform float time;
  82268. uniform float size;
  82269. uniform float heightOfNearPlane;
  82270. //varying float heightRatio;
  82271. varying float vSprite;
  82272. varying float vOpacity;
  82273. float PI = 3.14;
  82274. float quadraticIn( float t )
  82275. {
  82276. float tt = t * t;
  82277. return tt * tt;
  82278. //变化曲线 越来越快
  82279. }
  82280. void main() {
  82281. float progress = fract( time + ( 2.0 * randam - 1.0 ) );
  82282. float progressNeg = 1.0 - progress;
  82283. float ease = quadraticIn( progress );
  82284. float influence = sin( PI * ease );
  82285. //vec3 newPosition = position * vec3( 1.0, 1.0 , ease);
  82286. vec3 newPosition = position;
  82287. newPosition.z = (newPosition.z - centerHeight) * ease + centerHeight;
  82288. gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
  82289. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  82290. vOpacity = min( influence * 4.0, 1.0 ) * progressNeg;
  82291. vSprite = sprite;
  82292. //heightRatio = (newPosition.z - centerHeight) / fireHeight ;
  82293. }
  82294. `;
  82295. const fragmentShader = `
  82296. uniform vec3 color;
  82297. uniform sampler2D u_sampler;
  82298. varying float vSprite;
  82299. varying float vOpacity;
  82300. //varying float heightRatio;
  82301. void main()
  82302. {
  82303. vec2 texCoord = vec2(gl_PointCoord.x * 0.25 + vSprite, gl_PointCoord.y);
  82304. gl_FragColor = vec4( texture2D( u_sampler, texCoord ).xyz * color * vOpacity, 1.0 );
  82305. }
  82306. `;
  82307. // import { vertexShader, fragmentShader } from './shaders'
  82308. let ONE_SPRITE_ROW_LENGTH = 0.25; //对应着色器的0.25
  82309. let texture;
  82310. const getTexture = ()=>{
  82311. if(!texture){
  82312. texture = new TextureLoader().load( Potree.resourcePath+'/textures/fire.png');
  82313. }
  82314. return texture
  82315. };
  82316. const boxGeo = new BoxBufferGeometry(1,1,1,1);
  82317. const boxMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82318. class FireParticle extends Points{
  82319. constructor (prop) {
  82320. super();
  82321. for ( var key in prop ){
  82322. this[key] = prop[key];
  82323. }
  82324. this.strength = this.strength || 1;
  82325. this.radius = prop.radius || 1;
  82326. this.height = prop.height || 5;
  82327. this.computeParams();
  82328. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82329. if(this.color == void 0) this.color = 0xff3200;
  82330. this.createMaterial( ); //小蓝火:0x00338f
  82331. //---?:
  82332. this.velocity = new Vector3();
  82333. this.acceleration = new Vector3();
  82334. this.angle = 0;
  82335. this.angleVelocity = 0;
  82336. this.angleAcceleration = 0;
  82337. this.size = 16;
  82338. this.opacity = 1;
  82339. this.age = 0;
  82340. this.alive = 0;
  82341. this.sizeTween = null;
  82342. this.colorTween = null;
  82343. this.opacityTween = null;
  82344. this.setSize({viewport:viewer.mainViewport});
  82345. this.setFov(viewer.fov);
  82346. let setSize = (e)=>{
  82347. if(e.viewport.name != "MainView")return
  82348. this.setSize(e);
  82349. };
  82350. let setFov = (e)=>{
  82351. this.setFov(e.fov);
  82352. };
  82353. viewer.addEventListener('resize',setSize);
  82354. viewer.addEventListener('fov_changed',setFov);
  82355. this.addEventListener('dispose',()=>{
  82356. viewer.removeEventListener('resize',setSize);
  82357. viewer.removeEventListener('fov_changed',setFov);
  82358. });
  82359. }
  82360. computeParams(){
  82361. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82362. const minSize = 0.3, maxSize = 3, minRadiusBound = 0.3, maxRadiusBound = 10;
  82363. this.size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius, minRadiusBound, maxRadiusBound);
  82364. //console.log('fire material particle size:', size )
  82365. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height ) * this.radius / (this.size * this.size) * 25 );
  82366. //console.log('fire particleCount',this.particleCount)
  82367. }
  82368. getPointsForBound(){
  82369. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82370. }
  82371. getBound(points){ // points为生成点(圆心)
  82372. this.boundPoints = [];
  82373. let boundingBox = new Box3();
  82374. let margin = this.size * 0.13 + 0.3;
  82375. points.forEach(bottom=>{
  82376. let top = bottom.clone();
  82377. top.z += this.height;
  82378. boundingBox.expandByPoint(bottom);
  82379. boundingBox.expandByPoint(top);
  82380. this.boundPoints.push(bottom,top);
  82381. });
  82382. let xyExpand = this.radius+margin;
  82383. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,margin));
  82384. this.boundingBox = boundingBox;
  82385. /* if(!this.debugBox){
  82386. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82387. this.add(this.debugBox)
  82388. }
  82389. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82390. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82391. }
  82392. createGeometry( radius, height, particleCount){
  82393. let geometry = new BufferGeometry();
  82394. let count , points;
  82395. if(this.positions.length>1){
  82396. const spaceDis = 0.2;//间隔距离
  82397. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82398. //console.log('count', count)
  82399. points = this.curve.getSpacedPoints( count ); //得到的数量会比count多一个
  82400. count = points.length;
  82401. //得到的点不太均匀,两端容易点少。
  82402. this.getBound(points);
  82403. }else {
  82404. this.getBound(this.positions);
  82405. }
  82406. var position = new Float32Array(particleCount * 3);
  82407. var randam = new Float32Array(particleCount);
  82408. var sprite = new Float32Array(particleCount);
  82409. var centerHeight = new Float32Array(particleCount);
  82410. for (var i = 0; i < particleCount; i++) {
  82411. var center = new Vector3().copy(this.positions.length>1 ? points[Math.floor(i/particleCount * count)] : this.positions[0]);
  82412. centerHeight[i] = center.z;
  82413. if (i === 0) {
  82414. // to avoid going out of Frustum
  82415. position[i * 3 + 0] = center.x;
  82416. position[i * 3 + 1] = center.y;
  82417. position[i * 3 + 2] = center.z;
  82418. }else {
  82419. var r = Math.sqrt(Math.random()) * radius;
  82420. var angle = Math.random() * 2 * Math.PI;
  82421. position[i * 3 + 0] = center.x + Math.cos(angle) * r;
  82422. position[i * 3 + 1] = center.y + Math.sin(angle) * r;
  82423. position[i * 3 + 2] = center.z + (radius - r) / radius * height/2 + height/2; //不太明白这句为什么能达到height高度
  82424. sprite[i] = 0.25 * (Math.random() * 4 | 0);
  82425. randam[i] = Math.random();
  82426. //center在底部
  82427. }
  82428. }
  82429. geometry.setAttribute('centerHeight', new BufferAttribute(centerHeight, 1));
  82430. geometry.setAttribute('position', new BufferAttribute(position, 3));
  82431. geometry.setAttribute('randam', new BufferAttribute(randam, 1));
  82432. geometry.setAttribute('sprite', new BufferAttribute(sprite, 1));
  82433. return geometry;
  82434. }
  82435. updateGeometry(){
  82436. this.computeParams();
  82437. this.geometry.dispose();
  82438. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82439. this.material.uniforms.size.value = this.size;
  82440. }
  82441. createMaterial(){
  82442. const material = new ShaderMaterial( {
  82443. uniforms:{
  82444. color: { type: "c", value: new Color(this.color) },
  82445. size: { type: "f", value: this.size},
  82446. u_sampler: { type: "t", value: getTexture() },
  82447. time: { type: "f", value: 0.0 },
  82448. heightOfNearPlane: { type: "f", value:0}, //相对far ,以确保画面缩放时点的大小也会缩放
  82449. height :{ type: "f", value:this.height} ,
  82450. },
  82451. vertexShader,
  82452. fragmentShader,
  82453. blending: AdditiveBlending, //加法融合模式 glBlendFunc(GL_ONE, GL_ONE)
  82454. depthTest: true,
  82455. depthWrite: false,
  82456. transparent: true
  82457. } );
  82458. this.material = material;
  82459. this.setPerspective(this.fov, this.screenHeight);
  82460. }
  82461. setSize(e){
  82462. let viewport = e.viewport;
  82463. this.screenHeight = viewport.resolution.y;
  82464. this.setPerspective(this.fov, this.screenHeight);
  82465. }
  82466. setFov(fov){
  82467. this.fov = fov;
  82468. this.setPerspective(this.fov, this.screenHeight);
  82469. }
  82470. setPerspective(fov, height){
  82471. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  82472. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  82473. this.material.uniforms.heightOfNearPlane.value = far;
  82474. }
  82475. update(delta){
  82476. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82477. return
  82478. }
  82479. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82480. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82481. //console.log('unvi')
  82482. return
  82483. }else {
  82484. viewer.updateVisible(this,'isInsideFrustum', true );
  82485. }
  82486. delta *= 1;//更改速度
  82487. this.material.uniforms.time.value = (this.material.uniforms.time.value + delta) % 1;
  82488. }
  82489. dispose(){
  82490. this.geometry.dispose();
  82491. this.material.dispose();
  82492. this.dispatchEvent('dispose');
  82493. }
  82494. }
  82495. class Tween {
  82496. constructor(times, values) {
  82497. this.times = times || [];
  82498. this.values = values || [];
  82499. }
  82500. lerp(t) {
  82501. if(this.times.length == 0) return
  82502. let i = 0, n = this.times.length;
  82503. while(i < n && t > this.times[i]) i++;
  82504. if(i == 0) return this.values[0]
  82505. if(i == n) return this.values[n-1]
  82506. const ratio = (t - this.times[i-1]) / (this.times[i] - this.times[i-1]);
  82507. if(this.values[0] instanceof Vector3) {
  82508. return this.values[i-1].clone().lerp(this.values[i], ratio)
  82509. } else {
  82510. return this.values[i-1] + ratio * (this.values[i] - this.values[i-1])
  82511. }
  82512. }
  82513. clone () {
  82514. return Common.CloneClassObject(this)
  82515. }
  82516. }
  82517. class Particle$1{
  82518. constructor(prop={}){
  82519. this.position = new Vector3();
  82520. this.velocity = new Vector3(); // units per second
  82521. this.angle = 0;
  82522. this.angleVelocity = 0; // degrees per second
  82523. this.angleAcceleration = 0; // degrees per second, per second
  82524. this.size = 16.0;
  82525. this.color = new Color();
  82526. this.opacity = 1.0;
  82527. this.age = 0;
  82528. this.alive = 0; // use float instead of boolean for shader purposes
  82529. this.lastChangeVage = 0; //add
  82530. this.sizeTween = prop.sizeTween || new Tween( [0, 1], [32, 128] );
  82531. this.opacityTween = prop.opacityTween || new Tween( [0.8, 2], [0.5, 0] );
  82532. this.colorTween = prop.colorTween || new Tween( [0.4, 1], [ new Vector3(0,0,0.2), new Vector3(0, 0, 0.5) ] );
  82533. }
  82534. update(dt)
  82535. {
  82536. this.position.add(this.velocity.clone().multiplyScalar(dt));
  82537. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  82538. // convert from degrees to radians: 0.01745329251 = Math.PI/180
  82539. this.angle += this.angleVelocity * 0.01745329251 * dt;
  82540. this.angleVelocity += this.angleAcceleration * 0.01745329251 * dt;
  82541. this.age += dt;
  82542. // if the tween for a given attribute is nonempty,
  82543. // then use it to update the attribute's value
  82544. if ( this.sizeTween.times.length > 0 )
  82545. this.size = this.sizeTween.lerp( this.age/this.deathAge );
  82546. if ( this.colorTween.times.length > 0 )
  82547. {
  82548. var colorHSL = this.colorTween.lerp( this.age/this.deathAge );
  82549. this.color = new Color().setHSL( colorHSL.x, colorHSL.y, colorHSL.z );
  82550. }
  82551. if ( this.opacityTween.times.length > 0 )
  82552. {
  82553. this.opacity = this.opacityTween.lerp( this.age/this.deathAge);
  82554. }
  82555. }
  82556. }
  82557. const vertexShader$1 = `
  82558. attribute vec3 customColor;
  82559. attribute float customOpacity;
  82560. attribute float customSize;
  82561. attribute float customAngle;
  82562. attribute float customVisible;
  82563. uniform float heightOfNearPlane;
  82564. varying vec4 vColor;
  82565. varying float vAngle;
  82566. void main()
  82567. {
  82568. if ( customVisible > 0.5 )
  82569. vColor = vec4( customColor, customOpacity );
  82570. else
  82571. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  82572. vAngle = customAngle;
  82573. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  82574. //gl_PointSize = customSize * ( 300.0 / length( mvPosition.xyz ) );
  82575. gl_Position = projectionMatrix * mvPosition;
  82576. gl_PointSize = ( heightOfNearPlane * customSize ) / gl_Position.w;
  82577. }
  82578. `;
  82579. const fragmentShader$1 = `
  82580. uniform sampler2D u_sampler;
  82581. varying vec4 vColor;
  82582. varying float vAngle;
  82583. void main()
  82584. {
  82585. gl_FragColor = vColor;
  82586. float c = cos(vAngle);
  82587. float s = sin(vAngle);
  82588. vec2 rotatedUV = vec2(c * (gl_PointCoord.x - 0.5) + s * (gl_PointCoord.y - 0.5) + 0.5, c * (gl_PointCoord.y - 0.5) - s * (gl_PointCoord.x - 0.5) + 0.5);
  82589. vec4 rotatedTexture = texture2D( u_sampler, rotatedUV );
  82590. gl_FragColor = gl_FragColor * rotatedTexture;
  82591. }
  82592. `;
  82593. const Type = Object.freeze({ "CUBE":1, "SPHERE":2 });
  82594. let particleTexture;
  82595. const getTexture$1 = ()=>{
  82596. if(!particleTexture){
  82597. particleTexture = new TextureLoader().load( Potree.resourcePath+'/textures/smokeparticle.png');
  82598. }
  82599. return particleTexture
  82600. };
  82601. const boxGeo$1 = new BoxBufferGeometry(1,1,1,1);
  82602. const boxMat$1 = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82603. const defaults =
  82604. {
  82605. positions: [],
  82606. positionStyle : "sphere",
  82607. positionBase : new Vector3( 0, 0, 0 ),
  82608. positionSpread : new Vector3( 1, 1, 0), //cube
  82609. radius : 1, // sphere
  82610. velocityStyle : 'cube',
  82611. velocityBase : new Vector3( 0, 0, 0.5), // cube 基础速度
  82612. velocitySpread : new Vector3( 1, 1, 0.3),
  82613. accelerationBase : 0.3, //基础加速度
  82614. accelerationSpread : 0.6,
  82615. //没使用
  82616. speedBase : 0.1, //sphere
  82617. speedSpread : 0.5,
  82618. angleBase : 0,
  82619. angleSpread : 360,
  82620. angleVelocityBase : 1,
  82621. angleVelocitySpread : 30,
  82622. angleAccelerationBase : 1,
  82623. angleAccelerationSpread : 5,
  82624. sizeBase : 0,
  82625. sizeSpread : 0,
  82626. sizeTween : [[0, 0.3, 1], [0.3, 1.4, 6 ]],
  82627. colorBase : new Vector3(0.0, 1.0, 0.5),
  82628. colorSpread : new Vector3(0.0, 0.0, 0.0),
  82629. colorTween : new Tween( [0.2, 1], [ new Vector3(0,0,0.4), new Vector3(0, 0, 0.1) ] ),
  82630. opacityBase : 0.1,//1.0,
  82631. opacitySpread : 0.2,
  82632. opacityTween :[ [0, 0.1, 0.9, 1], [0.1, 0.4 , 0.03, 0 ] ],
  82633. //particlesPerSecond : 20,
  82634. strength : 1,
  82635. particleDeathAge : 3, //从底下升起后能持续的时间
  82636. //emitterDeathAge : 60 // time (seconds) at which to stop creating particles.
  82637. height : 3,
  82638. };
  82639. const debugSphere = new Mesh(new SphereBufferGeometry(0.03, 5,5), new MeshBasicMaterial({color:'white',depthTest:false}));
  82640. class SmokeParticle extends Points{
  82641. constructor(prop={}) {
  82642. super();
  82643. this.blendStyle = NormalBlending; // false;
  82644. this.emitterAge = 0.0;
  82645. //this.emitterAlive = true;
  82646. prop = $.extend({}, defaults, prop);
  82647. for ( var key in prop ){
  82648. let value = prop[key];
  82649. if(value instanceof Array && value[0] instanceof Array ) this[ key ] = new Tween(...value);
  82650. else if(value instanceof Vector3 || value instanceof Color){
  82651. this[ key ] = value.clone();
  82652. }else {
  82653. this[ key ] = value;
  82654. }
  82655. }
  82656. this.defaultSizeTween = this.sizeTween.clone();
  82657. this.defaultOpacityTween = this.opacityTween.clone();
  82658. this.geometry = new BufferGeometry();
  82659. this.computeParams();
  82660. this.createMaterial();
  82661. this.createGeometry();
  82662. this.dynamic = true;
  82663. this.sortParticles = true;
  82664. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  82665. prop.position && this.position.copy(prop.position);
  82666. //---------------------------------------
  82667. this.setSize({viewport:viewer.mainViewport});
  82668. this.setFov(viewer.fov);
  82669. let setSize = (e)=>{
  82670. if(e.viewport.name != "MainView")return
  82671. this.setSize(e);
  82672. };
  82673. let setFov = (e)=>{
  82674. this.setFov(e.fov);
  82675. };
  82676. /* let reStart = (e)=>{
  82677. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  82678. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  82679. //console.log('归零')
  82680. //this.reStart()
  82681. },1)
  82682. }
  82683. } */
  82684. viewer.addEventListener('resize',setSize);
  82685. viewer.addEventListener('fov_changed',setFov);
  82686. //viewer.addEventListener('pageVisible', reStart)
  82687. this.addEventListener('dispose',()=>{
  82688. viewer.removeEventListener('resize',setSize);
  82689. viewer.removeEventListener('fov_changed',setFov);
  82690. //viewer.removeEventListener('pageVisible', reStart)
  82691. });
  82692. }
  82693. computeParams(){
  82694. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82695. //注意:烟最低高度一米, 0<strength<1
  82696. if(this.positionStyle == 'cube'){
  82697. this.positionSpread.set(this.radius,this.radius,0);
  82698. }
  82699. this.velocityBase.set(0,0, (this.height - 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge) / this.particleDeathAge );
  82700. //let height = this.velocityBase.z * this.particleDeathAge + 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge;//s = V0 * t + 0.5 * a * t*t ;
  82701. this.velocityBase.z = Math.max(0,this.velocityBase.z);
  82702. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height * this.radius ) );
  82703. this.particleCount = Math.max(5,this.particleCount);
  82704. {
  82705. const minSize = 1, maxSize = 2, minBound = 0.01, maxBound = 1;
  82706. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82707. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  82708. }
  82709. {
  82710. const minSize = 1 , maxSize = 1.5, minBound = 0.01, maxBound = 1;
  82711. let opac = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82712. this.opacityTween.values = this.defaultOpacityTween.values.map(e=> e*opac );
  82713. }
  82714. //console.log('smoke particleCount',this.particleCount)
  82715. }
  82716. reStart(){
  82717. this.emitterAge = 0;
  82718. this.createGeometry();
  82719. }
  82720. updateGeometry(){
  82721. this.computeParams();
  82722. this.reStart();
  82723. }
  82724. createParticle(center)
  82725. {
  82726. var particle = new Particle$1({
  82727. sizeTween : this.sizeTween,
  82728. opacityTween : this.opacityTween,
  82729. colorTween : this.colorTween,
  82730. });
  82731. particle.deathAge = this.particleDeathAge;
  82732. particle.center = center;
  82733. if (this.positionStyle == 'cube')
  82734. particle.position = this.randomVector3( this.positionBase, this.positionSpread );
  82735. if (this.positionStyle == 'sphere')
  82736. {
  82737. /* var z = 2 * Math.random() - 1
  82738. var t = Math.PI * 2 * Math.random();
  82739. var r = Math.sqrt( 1 - z*z ) ;
  82740. var vec3 = new THREE.Vector3( r * Math.cos(t), r * Math.sin(t), z );
  82741. particle.position = new THREE.Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82742. */
  82743. //怎么改半径
  82744. let y = 2 * Math.random() - 1;
  82745. let t = Math.PI * 2 * Math.random();
  82746. let r = Math.sqrt( 1 - y*y ) ; //因为 r*r = 1-y*y = x*x + z*z = r*r(cos^2 + sin^2 );
  82747. let lowDownRatio = 0.2; //压低近平面
  82748. let vec3 = new Vector3( r * Math.cos(t), y, Math.abs(r * Math.sin(t) ) * lowDownRatio);
  82749. particle.position = new Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82750. }
  82751. particle.position.add(center);//add
  82752. if ( this.velocityStyle == 'cube' )
  82753. {
  82754. particle.velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82755. }
  82756. if ( this.velocityStyle == 'sphere' )
  82757. {
  82758. //var direction = particle.position.clone()
  82759. var direction = new Vector3(0,0,1); //烟应该都是向上的
  82760. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82761. particle.velocity = direction.normalize().multiplyScalar( speed );
  82762. }
  82763. particle.acceleration = this.randomValue( this.accelerationBase, this.accelerationSpread );
  82764. particle.angle = this.randomValue( this.angleBase, this.angleSpread );
  82765. particle.angleVelocity = this.randomValue( this.angleVelocityBase, this.angleVelocitySpread );
  82766. particle.angleAcceleration = this.randomValue( this.angleAccelerationBase, this.angleAccelerationSpread );
  82767. particle.size = this.randomValue( this.sizeBase, this.sizeSpread );
  82768. var color = this.randomVector3( this.colorBase, this.colorSpread );
  82769. particle.color = new Color().setHSL( color.x, color.y, color.z );
  82770. particle.opacity = this.randomValue( this.opacityBase, this.opacitySpread );
  82771. particle.age = 0;
  82772. particle.alive = 0; // particles initialize as inactive
  82773. return particle;
  82774. }
  82775. getPointsForBound(){
  82776. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82777. }
  82778. getBound(points){ // points为生成点(圆心)
  82779. this.boundPoints = [];
  82780. let boundingBox = new Box3();
  82781. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  82782. let margin0 = maxSize * 0.11;
  82783. let margin1 = margin0 + 0.5 ;//保守估计还会飘出这么多距离吧: size + 飘动
  82784. points.forEach(bottom=>{
  82785. let top = bottom.clone();
  82786. top.z += this.height;
  82787. boundingBox.expandByPoint(bottom);
  82788. boundingBox.expandByPoint(top);
  82789. this.boundPoints.push(bottom,top);
  82790. });
  82791. let xyExpand = this.radius+margin1;
  82792. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,0));
  82793. boundingBox.min.z -= margin0;
  82794. boundingBox.max.z += margin1;
  82795. this.boundingBox = boundingBox;
  82796. /* if(!this.debugBox){
  82797. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82798. this.add(this.debugBox)
  82799. }
  82800. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82801. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82802. }
  82803. createGeometry(){
  82804. this.particleArray = [];
  82805. const positions = [];
  82806. const colors = [];
  82807. const alives = [];
  82808. const opacitys = [];
  82809. const sizes = [];
  82810. const angles = [];
  82811. let count, points;
  82812. if(this.positions.length>1){
  82813. const spaceDis = 0.6;//间隔距离
  82814. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82815. points = this.curve.getSpacedPoints( count );
  82816. count = points.length;
  82817. /* points.forEach(e=> {
  82818. var sphere = debugSphere.clone();
  82819. sphere.position.copy(e)
  82820. viewer.scene.scene.add(sphere)
  82821. }) */
  82822. let haventGetPoints = points.slice();
  82823. var getRanPoints = function(i){
  82824. var a = Math.random();
  82825. let choseIndex = Math.floor(haventGetPoints.length * a);
  82826. var point = haventGetPoints[choseIndex];
  82827. if(haventGetPoints.length == 1){
  82828. haventGetPoints = points.slice();
  82829. }else {
  82830. haventGetPoints.splice(choseIndex, 1);
  82831. }
  82832. return point
  82833. };
  82834. this.getBound(points);
  82835. }else {
  82836. this.getBound(this.positions);
  82837. }
  82838. for (var i = 0; i < this.particleCount; i++)
  82839. {
  82840. var center = new Vector3().copy(this.positions.length>1 ? getRanPoints(i) : this.positions[0]);
  82841. //var center = new THREE.Vector3().copy(this.positions.length>1 ? points[Math.floor(i/this.particleCount * count)] : this.positions[0])
  82842. // remove duplicate code somehow, here and in update function below.
  82843. this.particleArray[i] = this.createParticle(center);
  82844. positions[3*i] = this.particleArray[i].position.x;
  82845. positions[3*i+1] = this.particleArray[i].position.y;
  82846. positions[3*i+2] = this.particleArray[i].position.z;
  82847. colors[3*i] = this.particleArray[i].color.r;
  82848. colors[3*i+1] = this.particleArray[i].color.g;
  82849. colors[3*i+2] = this.particleArray[i].color.b;
  82850. alives[i] = this.particleArray[i].alive;
  82851. opacitys[i] = this.particleArray[i].opacity;
  82852. sizes[i] = this.particleArray[i].size;
  82853. angles[i] = this.particleArray[i].angle;
  82854. }
  82855. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ));
  82856. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82857. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82858. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82859. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82860. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82861. }
  82862. createMaterial(){
  82863. this.material = new ShaderMaterial(
  82864. {
  82865. uniforms:
  82866. {
  82867. u_sampler: { type: "t", value: getTexture$1() },
  82868. heightOfNearPlane: { type: "f", value:0} //相对far ,以确保画面缩放时点的大小也会缩放
  82869. },
  82870. vertexShader: vertexShader$1,vertexShader: vertexShader$1,
  82871. fragmentShader: fragmentShader$1,
  82872. transparent: true,
  82873. alphaTest: 0.5, // if having transparency issues, try including: alphaTest: 0.5,
  82874. blending: this.blendStyle,
  82875. depthTest: this.blendStyle != NormalBlending
  82876. });
  82877. this.setPerspective(this.fov, this.screenHeight);
  82878. }
  82879. update(dt){
  82880. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82881. return
  82882. }
  82883. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82884. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82885. //console.log('unvi')
  82886. return
  82887. }else {
  82888. viewer.updateVisible(this,'isInsideFrustum', true );
  82889. }
  82890. if(dt > 1){
  82891. console.log('update dt>1', dt);
  82892. }
  82893. //dt *= 0.5;
  82894. const recycleIndices = [];
  82895. const recycleAges = [];
  82896. const positions = [];
  82897. const colors = [];
  82898. const alives = [];
  82899. const opacitys = [];
  82900. const sizes = [];
  82901. const angles = [];
  82902. for (var i = 0; i < this.particleCount; i++)
  82903. {
  82904. if ( this.particleArray[i].alive )
  82905. {
  82906. if ( this.velocityStyle == 'cube' )
  82907. { //一定几率改变下方向
  82908. let ratio = Math.random();
  82909. if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*ratio ){
  82910. this.particleArray[i].velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82911. this.particleArray[i].lastChangeVage = this.particleArray[i].age;
  82912. }
  82913. }else {
  82914. /* if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*0.3 ){
  82915. if( Math.random()>0.1){//一定几率改变下方向
  82916. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82917. this.particleArray[i].velocity = this.randomVector3( new THREE.Vector3, new THREE.Vector3(1,1,1) );
  82918. this.particleArray[i].velocity.normalize().multiplyScalar( speed );
  82919. }
  82920. this.particleArray[i].lastChangeVage = this.particleArray[i].age
  82921. } */
  82922. }
  82923. this.particleArray[i].update(dt);
  82924. // check if particle should expire
  82925. // could also use: death by size<0 or alpha<0.
  82926. if ( this.particleArray[i].age > this.particleDeathAge )
  82927. {
  82928. this.particleArray[i].alive = 0.0;
  82929. recycleIndices.push(i);
  82930. recycleAges.push((this.particleArray[i].age - this.particleDeathAge)%(this.particleDeathAge ));
  82931. }
  82932. // update particle properties in shader
  82933. positions[3*i] = this.particleArray[i].position.x;
  82934. positions[3*i+1] = this.particleArray[i].position.y;
  82935. positions[3*i+2] = this.particleArray[i].position.z;
  82936. colors[3*i] = this.particleArray[i].color.r;
  82937. colors[3*i+1] = this.particleArray[i].color.g;
  82938. colors[3*i+2] = this.particleArray[i].color.b;
  82939. alives[i] = this.particleArray[i].alive;
  82940. opacitys[i] = this.particleArray[i].opacity;
  82941. sizes[i] = this.particleArray[i].size;
  82942. angles[i] = this.particleArray[i].angle;
  82943. }
  82944. }
  82945. // check if particle emitter is still running
  82946. //if ( !this.emitterAlive ) return;
  82947. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  82948. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82949. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82950. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82951. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82952. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82953. this.geometry.attributes.customColor.needsUpdate = true;
  82954. this.geometry.attributes.customVisible.needsUpdate = true;
  82955. this.geometry.attributes.customOpacity.needsUpdate = true;
  82956. this.geometry.attributes.customSize.needsUpdate = true;
  82957. this.geometry.attributes.customAngle.needsUpdate = true;
  82958. // if no particles have died yet, then there are still particles to activate
  82959. if ( this.emitterAge < this.particleDeathAge ) //开始时一个个放出来
  82960. {
  82961. let particlesPerSecond = this.particleCount / this.particleDeathAge;
  82962. // determine indices of particles to activate
  82963. var startIndex = Math.round( particlesPerSecond * (this.emitterAge + 0) );
  82964. var endIndex = Math.round( particlesPerSecond * (this.emitterAge + dt) );
  82965. if ( endIndex > this.particleCount )
  82966. endIndex = this.particleCount;
  82967. for (var i = startIndex; i < endIndex; i++)
  82968. this.particleArray[i].alive = 1.0;
  82969. }
  82970. // if any particles have died while the emitter is still running, we imediately recycle them
  82971. for (var j = 0; j < recycleIndices.length; j++)
  82972. {
  82973. var i = recycleIndices[j];
  82974. this.particleArray[i] = this.createParticle(this.particleArray[i].center);
  82975. this.particleArray[i].alive = 1.0; // activate right away
  82976. this.particleArray[i].age = recycleAges[j];
  82977. positions[3*i] = this.particleArray[i].position.x;
  82978. positions[3*i+1] = this.particleArray[i].position.y;
  82979. positions[3*i+2] = this.particleArray[i].position.z;
  82980. }
  82981. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  82982. this.geometry.attributes.position.needsUpdate = true;
  82983. // stop emitter?
  82984. this.emitterAge += dt;
  82985. //if ( this.emitterAge > this.emitterDeathAge ) this.emitterAlive = false;
  82986. }
  82987. randomValue(base, spread)
  82988. {
  82989. //return base + spread * (Math.random() - 0.5);
  82990. let p = Math.random();
  82991. return base * p + spread * (1-p)
  82992. }
  82993. randomVector3(base, spread)
  82994. {
  82995. var rand3 = new Vector3( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 );
  82996. return new Vector3().addVectors( base, new Vector3().multiplyVectors( spread, rand3 ) );
  82997. }
  82998. setSize(e){
  82999. let viewport = e.viewport;
  83000. this.screenHeight = viewport.resolution.y;
  83001. this.setPerspective(this.fov, this.screenHeight);
  83002. }
  83003. setFov(fov){
  83004. this.fov = fov;
  83005. this.setPerspective(this.fov, this.screenHeight);
  83006. }
  83007. setPerspective(fov, height){
  83008. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  83009. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  83010. this.material.uniforms.heightOfNearPlane.value = far;
  83011. }
  83012. dispose(){
  83013. this.geometry.dispose();
  83014. this.material.dispose();
  83015. this.dispatchEvent('dispose');
  83016. }
  83017. }
  83018. /*
  83019. 改进:如果有必要
  83020. 根据curve中分成的点,分成多个簇,每个簇掌管该部分的可见性和particle的数量。
  83021. 在camera_changed时根据远近修改每个簇的particle的数量,当然不会大于初始创建的个数。多出的随机隐藏。
  83022. */
  83023. const vertexShader$2 = `
  83024. attribute vec3 color;
  83025. attribute float size;
  83026. attribute float angle;
  83027. attribute float opacity;
  83028. attribute float visible;
  83029. varying vec4 vColor;
  83030. varying float vAngle;
  83031. uniform float heightOfNearPlane;
  83032. void main() {
  83033. if(visible > 0.5) {
  83034. vColor = vec4(color, opacity);
  83035. } else {
  83036. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  83037. }
  83038. vAngle = angle;
  83039. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
  83040. gl_Position = projectionMatrix * mvPosition;
  83041. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  83042. }
  83043. `;
  83044. const fragmentShader$2 = `
  83045. uniform sampler2D u_sampler;
  83046. varying vec4 vColor;
  83047. varying float vAngle;
  83048. void main() {
  83049. gl_FragColor = vColor;
  83050. float u = cos(vAngle);
  83051. float v = sin(vAngle);
  83052. vec2 uv = vec2(
  83053. u * (gl_PointCoord.x - 0.5) + v * (gl_PointCoord.y - 0.5) + 0.5,
  83054. u * (gl_PointCoord.y - 0.5) - v * (gl_PointCoord.x - 0.5) + 0.5
  83055. );
  83056. vec4 texture = texture2D(u_sampler, uv);
  83057. gl_FragColor = gl_FragColor * texture;
  83058. }
  83059. `;
  83060. // import { vertexShader, fragmentShader } from './shader'
  83061. const DEG2RAD = Math.PI / 180;
  83062. class Particle$2 {
  83063. constructor() {
  83064. this.position = new Vector3();
  83065. this.velocity = new Vector3();
  83066. this.angle = 0;
  83067. this.angleVelocity = 0;
  83068. this.angleAcceleration = 0;
  83069. this.size = 16;
  83070. this.color = new Color();
  83071. this.opacity = 1;
  83072. this.rebornCount = 0;//重生次数
  83073. this.age = 0;
  83074. this.alive = 0; //注意,一开始时是未出生的
  83075. this.deadAge = 0;//已死亡时间
  83076. this.sizeTween = null;
  83077. this.colorTween = null;
  83078. this.opacityTween = null;
  83079. }
  83080. update(dt) {
  83081. //s = s0 + (v0 + at) * t 或 lastS + delta(vt)
  83082. this.position.add(this.velocity.clone().multiplyScalar(dt));
  83083. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  83084. this.angle += this.angleVelocity * DEG2RAD * dt;
  83085. this.angleVelocity += this.angleAcceleration * DEG2RAD * dt;
  83086. this.age += dt;
  83087. if(this.sizeTween.times.length > 0) {
  83088. this.size = this.sizeTween.lerp(this.age/this.deathAge);
  83089. }
  83090. if(this.colorTween.times.length > 0) {
  83091. const colorHSL = this.colorTween.lerp(this.age/this.deathAge);
  83092. this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z);
  83093. }
  83094. if(this.opacityTween.times.length > 0) {
  83095. this.opacity = this.opacityTween.lerp(this.age/this.deathAge);
  83096. }
  83097. }
  83098. }
  83099. class Util {
  83100. constructor() {}
  83101. randomValue(min, max) {
  83102. //return min + max * (Math.random() - 0.5)
  83103. let p = Math.random();
  83104. return min * p + max * (1-p)
  83105. }
  83106. randomVector3(min, max) {
  83107. const rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
  83108. return new Vector3().addVectors(min, new Vector3().multiplyVectors(max, rand3))
  83109. }
  83110. }
  83111. const util$1 = new Util();
  83112. const Shape$1 = {
  83113. CUBE: 1,
  83114. SPHERE: 2
  83115. };
  83116. let particleTexture$1;
  83117. const getTexture$2 = ()=>{
  83118. if (!particleTexture$1) {
  83119. particleTexture$1 = new TextureLoader().load(Potree.resourcePath + '/textures/explode.png');
  83120. }
  83121. return particleTexture$1
  83122. };
  83123. const sphereGeo$1 = new SphereBufferGeometry(1, 10,4);
  83124. const sphereMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  83125. const defaults$1 = {
  83126. position: new Vector3(0,0,1),
  83127. positionShape: Shape$1.SPHERE,
  83128. positionRange: new Vector3(1,1,1),
  83129. //cube
  83130. radius: 1.3,
  83131. //sphere
  83132. velocityShape: Shape$1.SPHERE,
  83133. velocity: new Vector3(0,0,2),
  83134. //cube
  83135. velocityRange: new Vector3(0,0,3),
  83136. //sphere
  83137. speed: 0.4,
  83138. speedRange: 1,
  83139. size: 0.4,
  83140. sizeRange: 2,
  83141. //sizeTween: new Tween( [0, 0.05, 0.3, 0.45], [0, 1, 3, 0.1] ),
  83142. sizeTween: [[0, 0.04, 0.2, 1],[0.1, 1, 6, 8]] ,
  83143. color: new Vector3(1.0,1.0,1.0),
  83144. colorRange: new Vector3(0,0,0),
  83145. colorTween: new Tween(),
  83146. opacity: 1.0,
  83147. opacityRange: 0.0,
  83148. opacityTween: new Tween([0, 0.06, 0.3, 0.8, 1],[0, 1, 0.3, 0.05, 0]),
  83149. blendMode: AdditiveBlending,
  83150. acceleration: 0.5,
  83151. accelerationRange: 0,
  83152. angle: 0,
  83153. angleRange: 0,
  83154. angleVelocity: 0,
  83155. angleVelocityRange: 0,
  83156. angleAcceleration: 0,
  83157. angleAccelerationRange: 0,
  83158. strength:1,
  83159. //particlesPerSecond: 8,
  83160. particleDeathAge: 0.7 ,
  83161. recycleTimes : 3 , //每个粒子在一次爆炸后循环次数,循环完毕进入particleSpaceTime,等待下一次爆炸.
  83162. //爆炸时长: particleDeathAge * (recycleTimes+1)
  83163. particleSpaceTime: 3, //间隔
  83164. };
  83165. class ExplodeParticle extends Points {
  83166. constructor(params) {
  83167. super();
  83168. this.age = 0;
  83169. this.alive = true;
  83170. //this.deathAge = 60
  83171. this.loop = true;
  83172. this.blendMode = NormalBlending;
  83173. this.setParameters(params);
  83174. this.createParticles();
  83175. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  83176. //------------------------------------
  83177. this.setSize({viewport:viewer.mainViewport});
  83178. this.setFov(viewer.fov);
  83179. let setSize = (e)=>{
  83180. if(e.viewport.name != "MainView")return
  83181. this.setSize(e);
  83182. };
  83183. let setFov = (e)=>{
  83184. this.setFov(e.fov);
  83185. };
  83186. /* let reStart = (e)=>{
  83187. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  83188. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  83189. //console.log('归零')
  83190. //this.reStart()
  83191. },1)
  83192. }
  83193. } */
  83194. viewer.addEventListener('resize',setSize);
  83195. viewer.addEventListener('fov_changed',setFov);
  83196. //viewer.addEventListener('pageVisible', reStart)
  83197. this.addEventListener('dispose',()=>{
  83198. viewer.removeEventListener('resize',setSize);
  83199. viewer.removeEventListener('fov_changed',setFov);
  83200. //viewer.removeEventListener('pageVisible', reStart)
  83201. });
  83202. }
  83203. computeParams(){
  83204. if(this.curve){
  83205. this.position.copy(this.curve.points[0]);
  83206. }
  83207. const minSize = 0.8, maxSize = 10, minRadiusBound = 0.2, maxRadiusBound = 20;
  83208. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius*this.strength , minRadiusBound, maxRadiusBound);
  83209. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  83210. this.particleCount = Math.ceil( this.strength * this.radius * 5 /* * this.radius * this.radius */ );
  83211. this.speed = defaults$1.speed * this.radius;
  83212. this.speedRange = defaults$1.speedRange * this.radius;
  83213. console.log(this.particleCount);
  83214. {
  83215. this.boundPoints = [];
  83216. this.boundPoints.push(this.position.clone());
  83217. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  83218. let margin = maxSize * 0.35 + 0.5;
  83219. let scale = this.radius+margin;
  83220. let sphere = new Sphere(this.position, scale);//加上防止剪裁
  83221. this.boundingSphere = sphere; //虽然还是会有一些后续移动的会超出
  83222. this.boundingBox = new Box3().setFromCenterAndSize(this.position, new Vector3(scale*2,scale*2,scale*2));
  83223. /* if(!this.debugSphere){
  83224. this.debugSphere = new THREE.Mesh(sphereGeo, sphereMat)
  83225. this.add(this.debugSphere)
  83226. }
  83227. this.debugSphere.scale.set(scale,scale,scale) */
  83228. }
  83229. }
  83230. getPointsForBound(){
  83231. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  83232. }
  83233. reStart(){
  83234. this.age = 0;
  83235. this.createParticles();
  83236. }
  83237. setParameters(params) {
  83238. params = $.extend({}, defaults$1, params);
  83239. for (var key in params) {
  83240. let value = params[key];
  83241. if (key == 'position')
  83242. this.position.copy(value);
  83243. else if (value instanceof Array && value[0]instanceof Array){
  83244. this[key] = new Tween(...value);
  83245. }else if(value instanceof Vector3 || value instanceof Color){
  83246. this[ key ] = value.clone();
  83247. }else {
  83248. this[key] = value;
  83249. }
  83250. }
  83251. this.defaultSizeTween = this.sizeTween.clone();
  83252. //Object.assign(this, params)
  83253. this.particles = [];
  83254. this.age = 0.0;
  83255. this.alive = true;
  83256. this.geometry = new BufferGeometry();
  83257. this.computeParams();
  83258. this.material = new ShaderMaterial({
  83259. uniforms: {
  83260. u_sampler: {
  83261. value: this.texture || getTexture$2()
  83262. },
  83263. heightOfNearPlane: {
  83264. type: "f",
  83265. value: 0
  83266. }//相对far ,以确保画面缩放时点的大小也会缩放
  83267. },
  83268. vertexShader: vertexShader$2,
  83269. fragmentShader: fragmentShader$2,
  83270. transparent: true,
  83271. alphaTest: 0.5,
  83272. depthTest: this.blendMode == NormalBlending,
  83273. blending: this.blendMode
  83274. });
  83275. }
  83276. createParticles() {
  83277. this.particles = [];
  83278. const count = this.particleCount;
  83279. const positionArray = new Float32Array(count * 3);
  83280. const colorArray = new Float32Array(count * 3);
  83281. const sizeArray = new Float32Array(count);
  83282. const angleArray = new Float32Array(count);
  83283. const opacityArray = new Float32Array(count);
  83284. const visibleArray = new Float32Array(count);
  83285. for (let i = 0; i < count; i++) {
  83286. const particle = this.createParticle();
  83287. /* positionArray[i * 3] = particle.position.x
  83288. positionArray[i * 3 + 1] = particle.position.y
  83289. positionArray[i * 3 + 2] = particle.position.z
  83290. colorArray[i * 3] = particle.color.r
  83291. colorArray[i * 3 + 1] = particle.color.g
  83292. colorArray[i * 3 + 2] = particle.color.b
  83293. sizeArray[i] = particle.size
  83294. angleArray[i] = particle.angel
  83295. opacityArray[i] = particle.opacity
  83296. visibleArray[i] = particle.alive */
  83297. this.particles[i] = particle;
  83298. }
  83299. this.geometry.setAttribute('position', new BufferAttribute(positionArray,3));
  83300. this.geometry.setAttribute('color', new BufferAttribute(colorArray,3));
  83301. this.geometry.setAttribute('angle', new BufferAttribute(angleArray,1));
  83302. this.geometry.setAttribute('size', new BufferAttribute(sizeArray,1));
  83303. this.geometry.setAttribute('visible', new BufferAttribute(visibleArray,1));
  83304. this.geometry.setAttribute('opacity', new BufferAttribute(opacityArray,1));
  83305. }
  83306. createParticle() {
  83307. const particle = new Particle$2();
  83308. particle.sizeTween = this.sizeTween;
  83309. particle.colorTween = this.colorTween;
  83310. particle.opacityTween = this.opacityTween;
  83311. particle.deathAge = this.particleDeathAge;
  83312. if (this.positionShape == Shape$1.CUBE) {
  83313. particle.position = util$1.randomVector3(new Vector3, this.positionRange);
  83314. }
  83315. if (this.positionShape == Shape$1.SPHERE) {
  83316. /* const z = 2 * Math.random() - 1
  83317. const t = Math.PI * 2 * Math.random()
  83318. const r = Math.sqrt(1 - z*z)
  83319. const vec3 = new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), z)
  83320. particle.position = vec3.multiplyScalar(this.radius) */
  83321. const y = 2 * Math.random() - 1;
  83322. const t = Math.PI * 2 * Math.random();
  83323. const r = Math.sqrt(1 - y * y);
  83324. const vec3 = new Vector3(r * Math.cos(t),y,r * Math.sin(t));
  83325. particle.position = vec3.multiplyScalar(this.radius);
  83326. }
  83327. if (this.velocityShape == Shape$1.CUBE) {
  83328. particle.velocity = util$1.randomVector3(this.velocity, this.velocityRange);
  83329. }
  83330. if (this.velocityShape == Shape$1.SPHERE) {
  83331. const direction = new Vector3().addVectors(particle.position, new Vector3(0,0,this.radius*2));//向上升?
  83332. const speed = util$1.randomValue(this.speed, this.speedRange);
  83333. particle.velocity = direction.normalize().multiplyScalar(speed);
  83334. }
  83335. particle.acceleration = util$1.randomValue(this.acceleration, this.accelerationRange);
  83336. particle.angle = util$1.randomValue(this.angle, this.angleRange);
  83337. particle.angleVelocity = util$1.randomValue(this.angleVelocity, this.angleVelocityRange);
  83338. particle.angleAcceleration = util$1.randomValue(this.angleAcceleration, this.angleAccelerationRange);
  83339. particle.size = util$1.randomValue(this.size, this.sizeRange);
  83340. const color = util$1.randomVector3(this.color, this.colorRange);
  83341. particle.color = new Color().setHSL(color.x, color.y, color.z);
  83342. particle.opacity = util$1.randomValue(this.opacity, this.opacityRange);
  83343. return particle
  83344. }
  83345. update(dt) {
  83346. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  83347. return
  83348. }
  83349. if(this.delayStartTime>0){ // 爆炸延迟
  83350. return this.delayStartTime -= dt
  83351. }
  83352. if(!Potree.Utils.isInsideFrustum(this.boundingSphere, viewer.scene.getActiveCamera())){
  83353. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  83354. return
  83355. }else {
  83356. viewer.updateVisible(this,'isInsideFrustum', true );
  83357. }
  83358. //const timeRatio = 0.5
  83359. if(dt > 1){
  83360. console.log('update dt>1', dt);
  83361. }
  83362. //dt *= timeRatio
  83363. let particleDeathAge = this.particleDeathAge;/* * timeRatio */
  83364. let particleSpaceTime = this.particleSpaceTime; /* * timeRatio */
  83365. const recycleIndices = [];
  83366. const recycleAges = [];
  83367. const recycleRebornCount = [];
  83368. const positionArray = this.geometry.attributes.position.array;
  83369. const opacityArray = this.geometry.attributes.opacity.array;
  83370. const visibleArray = this.geometry.attributes.visible.array;
  83371. const colorArray = this.geometry.attributes.color.array;
  83372. const angleArray = this.geometry.attributes.angle.array;
  83373. const sizeArray = this.geometry.attributes.size.array;
  83374. for (let i = 0; i < this.particleCount; i++) {
  83375. const particle = this.particles[i];
  83376. if (particle.alive) {
  83377. particle.update(dt);
  83378. if (particle.age > particleDeathAge) {
  83379. particle.alive = 0.0;
  83380. if(particle.rebornCount >= this.recycleTimes){
  83381. particle.deadAge = particle.age - particleDeathAge; //已死亡时间
  83382. }else {//直接循环
  83383. recycleIndices.push(i);
  83384. recycleAges.push(/* ( */particle.age - particleDeathAge/* )%(this.particleDeathAge ) */);
  83385. recycleRebornCount.push(particle.rebornCount+1);
  83386. }
  83387. }
  83388. positionArray[i * 3] = particle.position.x;
  83389. positionArray[i * 3 + 1] = particle.position.y;
  83390. positionArray[i * 3 + 2] = particle.position.z;
  83391. colorArray[i * 3] = particle.color.r;
  83392. colorArray[i * 3 + 1] = particle.color.g;
  83393. colorArray[i * 3 + 2] = particle.color.b;
  83394. visibleArray[i] = particle.alive;
  83395. opacityArray[i] = particle.opacity;
  83396. angleArray[i] = particle.angle;
  83397. sizeArray[i] = particle.size;
  83398. }else {
  83399. if(particle.rebornCount >= this.recycleTimes){
  83400. if(particle.age > particleDeathAge) {//其他已经死亡的粒子的时间继续增加
  83401. particle.deadAge += dt;
  83402. }
  83403. }
  83404. }
  83405. if (particle.rebornCount >= this.recycleTimes && particle.age > particleDeathAge) {//已经死亡
  83406. if(particle.deadAge >= particleSpaceTime){//死亡时间超过设定的间隔时间后重启
  83407. recycleIndices.push(i);
  83408. let wholeTime = particleDeathAge * (this.recycleTimes+1) + particleSpaceTime;
  83409. recycleAges.push((particle.deadAge - particleSpaceTime)% wholeTime ); //剩余时间就是重生后的age
  83410. recycleRebornCount.push(0);
  83411. }
  83412. }
  83413. }
  83414. this.geometry.attributes.size.needsUpdate = true;
  83415. this.geometry.attributes.color.needsUpdate = true;
  83416. this.geometry.attributes.angle.needsUpdate = true;
  83417. this.geometry.attributes.visible.needsUpdate = true;
  83418. this.geometry.attributes.opacity.needsUpdate = true;
  83419. this.geometry.attributes.position.needsUpdate = true;
  83420. if (!this.alive)
  83421. return
  83422. if (this.age < particleDeathAge) {
  83423. let startIndex = Math.round(this.particleCount * (this.age + 0)/ particleDeathAge);
  83424. let endIndex = Math.round(this.particleCount * (this.age + dt)/ particleDeathAge);
  83425. if (endIndex > this.particleCount) {
  83426. endIndex = this.particleCount;
  83427. }
  83428. for (let i = startIndex; i < endIndex; i++) {
  83429. this.particles[i].alive = 1.0;
  83430. }
  83431. }
  83432. for (let j = 0; j < recycleIndices.length; j++) {
  83433. let i = recycleIndices[j];
  83434. this.particles[i] = this.createParticle();
  83435. this.particles[i].alive = 1.0; //出生
  83436. this.particles[i].age = recycleAges[j];
  83437. this.particles[i].rebornCount= recycleRebornCount[j];
  83438. /* if(this.particles[i].age < particleDeathAge){
  83439. positionArray[i * 3] = this.particles[i].position.x
  83440. positionArray[i * 3 + 1] = this.particles[i].position.y
  83441. positionArray[i * 3 + 2] = this.particles[i].position.z
  83442. visibleArray[i] = particle.alive?
  83443. } */
  83444. }
  83445. this.geometry.attributes.position.needsUpdate = true;
  83446. this.age += dt;
  83447. if (this.age > this.deathAge && !this.loop) {
  83448. this.alive = false;
  83449. }
  83450. }
  83451. setSize(e) {
  83452. let viewport = e.viewport;
  83453. this.screenHeight = viewport.resolution.y;
  83454. this.setPerspective(this.fov, this.screenHeight);
  83455. }
  83456. setFov(fov) {
  83457. this.fov = fov;
  83458. this.setPerspective(this.fov, this.screenHeight);
  83459. }
  83460. setPerspective(fov, height) {
  83461. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  83462. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  83463. this.material.uniforms.heightOfNearPlane.value = far;
  83464. }
  83465. updateGeometry(){
  83466. this.computeParams();
  83467. this.reStart();
  83468. }
  83469. dispose(){
  83470. this.geometry.dispose();
  83471. this.material.dispose();
  83472. this.dispatchEvent('dispose');
  83473. }
  83474. }
  83475. const colors$1 = {
  83476. 'fire+smoke':0xffffff,
  83477. 'smoke': 0xffffff,
  83478. 'explode':0xffffff,
  83479. };
  83480. let depthMatPrefix = {
  83481. clipDistance : 100, occlusionDistance:60, /* 变为backColor距离 */
  83482. maxClipFactor:0.5, backColor:"#777" ,
  83483. useDepth:true, transparent: !0,
  83484. };
  83485. let lineMats$2;
  83486. let getLineMat$1 = function(type){
  83487. if(!lineMats$2){
  83488. lineMats$2 = {
  83489. 'fire+smoke':LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83490. color: colors$1['fire+smoke'],
  83491. lineWidth: 2
  83492. })),
  83493. 'smoke' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83494. color: colors$1['smoke'],
  83495. lineWidth: 2
  83496. })),
  83497. 'explode' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83498. color: colors$1['explode'],
  83499. lineWidth: 2
  83500. })),
  83501. };
  83502. }
  83503. return lineMats$2[type]
  83504. };
  83505. let handleMats;
  83506. let getHandleMat = function(type){
  83507. if(!handleMats){
  83508. let texLoader = new TextureLoader();
  83509. handleMats = {
  83510. "fire+smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83511. map: texLoader.load(Potree.resourcePath+'/textures/icon-fire.png' ),
  83512. color: colors$1['fire+smoke'],
  83513. })),
  83514. "smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83515. map: texLoader.load(Potree.resourcePath+'/textures/icon-smoke.png' ),
  83516. color: colors$1['smoke'],
  83517. })),
  83518. "explode" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83519. map: texLoader.load(Potree.resourcePath+'/textures/icon-explode.png' ),
  83520. color: colors$1['explode'],
  83521. })),
  83522. };
  83523. }
  83524. return handleMats[type]
  83525. };
  83526. let ParticleEditor = {
  83527. bus: new EventDispatcher$1,
  83528. particleGroup : new Object3D ,
  83529. curveGroup:new Object3D ,
  83530. init:function(){
  83531. this.particleGroup.name = 'particles';
  83532. viewer.scene.scene.add( this.particleGroup );
  83533. this.curveGroup.name = 'particles-curves';
  83534. viewer.scene.scene.add( this.curveGroup );
  83535. },
  83536. addParticle : function(prop={}){
  83537. let particle;
  83538. if(prop.type == 'fire'){
  83539. particle = new FireParticle(prop);
  83540. }else if(prop.type == 'smoke'){
  83541. particle = new SmokeParticle(prop);
  83542. }else if(prop.type == 'explode'){
  83543. particle = new ExplodeParticle(prop);
  83544. }
  83545. this.particleGroup.add(particle);
  83546. return particle
  83547. }
  83548. ,
  83549. removeParticle(particle){
  83550. //particle.dispatchEvent('delete')
  83551. particle.dispose();
  83552. this.particleGroup.remove(particle);
  83553. particle.curve.dispose();
  83554. }
  83555. ,
  83556. update(delta){
  83557. this.particleGroup.children.forEach(e=>e.update(delta));
  83558. }
  83559. ,
  83560. startInsertion(type = 'fire', prop={}){ //viewer.modules.ParticleEditor.startInsertion()
  83561. let deferred = $.Deferred();
  83562. let particles = [];
  83563. let finish = (ifDone)=>{
  83564. if(ifDone){
  83565. deferred.resolve(particles);
  83566. }
  83567. viewer.dispatchEvent({
  83568. type : "CursorChange", action : "remove", name:"addSth"
  83569. });
  83570. viewer.removeEventListener('global_click', click);
  83571. this.bus.removeEventListener('cancel_insertions',cancel);
  83572. };
  83573. let curve = new CurveCtrl([], getLineMat$1(type), colors$1[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83574. this.curveGroup.add(curve);
  83575. prop.curve = curve;
  83576. prop.type = type;
  83577. //console.log('创建curve',type,curve.uuid)
  83578. let cancel = ()=>{
  83579. console.log('cancel_insertions', curve.uuid );
  83580. curve.dispose();
  83581. finish(false);
  83582. };
  83583. this.bus.dispatchEvent('cancel_insertions');//删除旧的
  83584. this.bus.addEventListener('cancel_insertions',cancel);
  83585. var click = (e)=>{
  83586. if(e.button === MOUSE.RIGHT){
  83587. if(curve.points.length>=1){ //if(type.includes('fire') || type.includes('smoke') ){
  83588. particles = this.createFromData(prop);
  83589. finish(true);
  83590. }
  83591. return
  83592. }
  83593. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  83594. if(!I)return
  83595. curve.addPoint(I, null, true);
  83596. if(type == 'explode'){
  83597. particles = this.createFromData(prop);
  83598. finish(true);
  83599. }
  83600. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  83601. };
  83602. viewer.addEventListener('global_click', click, 10);//add importance:10
  83603. viewer.dispatchEvent({
  83604. type : "CursorChange", action : "add", name:"addSth"
  83605. });
  83606. return deferred.promise()
  83607. },
  83608. createFromData(prop){
  83609. const type = prop.type;
  83610. var particles = [];
  83611. let curve = prop.curve;
  83612. if(!curve){
  83613. curve = new CurveCtrl(prop.points, getLineMat$1(type), colors$1[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83614. this.curveGroup.add(curve);
  83615. }
  83616. if(type.includes('fire') || type.includes('smoke') ){
  83617. if(type.includes('fire')){
  83618. var fire = this.addParticle({
  83619. type : 'fire',
  83620. positions : curve.points,
  83621. curve,
  83622. radius : prop.radius,
  83623. height: prop.height,
  83624. strength : prop.strength,
  83625. });
  83626. particles.push(fire);
  83627. }
  83628. if(type.includes('smoke')){
  83629. var smoke = this.addParticle({
  83630. type : 'smoke',
  83631. positions : curve.points,
  83632. curve,
  83633. positionStyle : 'sphere' ,
  83634. strength : prop.smokeStrength,
  83635. radius: prop.smokeRadius,
  83636. height: prop.smokeHeight,
  83637. });
  83638. particles.push(smoke);
  83639. }
  83640. }else if(type == 'explode'){
  83641. var explode = this.addParticle({
  83642. type : 'explode',
  83643. position : curve.points[0],
  83644. strength: prop.strength,
  83645. radius : prop.radius,
  83646. particleSpaceTime: prop.particleSpaceTime,
  83647. curve,
  83648. delayStartTime:prop.delayStartTime,
  83649. });
  83650. particles.push(explode);
  83651. }
  83652. var geoNeedsUpdate;
  83653. curve.addEventListener('dragCurvePoint',()=>{
  83654. geoNeedsUpdate = true;
  83655. Common.intervalTool.isWaiting('particlePointChange', ()=>{ //延时update,防止卡顿
  83656. if(geoNeedsUpdate){
  83657. particles.forEach(e=>e.updateGeometry());
  83658. geoNeedsUpdate = false;
  83659. curve.dispatchEvent('sendUpdatePoints');
  83660. return true
  83661. }
  83662. }, 400);
  83663. });
  83664. return particles
  83665. }
  83666. };
  83667. let CamAniEditor = {
  83668. createAnimation(data){
  83669. let animation = new CameraAnimation(viewer);
  83670. if(data) {
  83671. animation.name = data.name;
  83672. animation.duration = data.duration;
  83673. animation.useDurSlice = data.useDurSlice;
  83674. for(const cpdata of data.points){
  83675. /* const position = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.position, datasetId: Potree.settings.originDatasetId })
  83676. const target = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.target, datasetId: Potree.settings.originDatasetId })
  83677. */
  83678. const position = new Vector3().copy(cpdata.position);
  83679. const target = new Vector3().copy(cpdata.target);
  83680. const duration = cpdata.time;
  83681. const cp = animation.createControlPoint(null, {position, target, duration});
  83682. }
  83683. }
  83684. animation.changeCallback();
  83685. viewer.scene.addCameraAnimation(animation);
  83686. return animation
  83687. },
  83688. removeAnimation(animation){
  83689. animation.dispatchEvent('dispose');
  83690. viewer.scene.removeCameraAnimation(animation);
  83691. }
  83692. };
  83693. let images360, Alignment$1, SiteModel$1;
  83694. const texLoader$c = new TextureLoader();
  83695. texLoader$c.crossOrigin = "anonymous";
  83696. const lineMats$3 = {};
  83697. const circleMats = {};
  83698. const renderOrders$1 = {
  83699. circleSelected:3,
  83700. circle:2,
  83701. line:1,
  83702. };
  83703. const pointColor = {
  83704. /* selected:"#c80",
  83705. default:'#1ac' */
  83706. selected:"#c60",
  83707. default:'#17c'
  83708. };
  83709. const opacitys = {
  83710. default:1.3,
  83711. selected: 2.0
  83712. };
  83713. const cameraProps = [
  83714. {
  83715. name : 'top',
  83716. axis:["x","y"],
  83717. direction : new Vector3(0,0,-1), //镜头朝向
  83718. openCount:0,
  83719. },
  83720. {
  83721. name : 'right',
  83722. axis:["y","z"],
  83723. direction : new Vector3(1,0,0),
  83724. openCount:0,
  83725. }
  83726. ];
  83727. class PanoEditor extends EventDispatcher{
  83728. constructor(){
  83729. super();
  83730. this.panoGroup = [], //分组
  83731. this.viewports = {},
  83732. this.panoLink = {},
  83733. this.panoMeshs = new Object3D,
  83734. this.lineMeshes = new Object3D;
  83735. this.views = {};
  83736. this.cameras = {};
  83737. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  83738. this.selectedPano;
  83739. this.selectedGroup;
  83740. this.operation;
  83741. this.visiblePanos = [];
  83742. }
  83743. init(){
  83744. {//init lineMats
  83745. lineMats$3.default = LineDraw.createFatLineMat({
  83746. color: '#eeeeee',
  83747. lineWidth: 2,
  83748. depthTest:false
  83749. });
  83750. lineMats$3.hovered = LineDraw.createFatLineMat({
  83751. color: '#00c8af',
  83752. lineWidth: 2,
  83753. depthTest:false
  83754. });
  83755. lineMats$3.selected = LineDraw.createFatLineMat({
  83756. color: '#00c8af',
  83757. lineWidth: 3,
  83758. depthTest:false
  83759. });
  83760. }
  83761. this.initViews();
  83762. viewer.addEventListener('allLoaded',()=>{
  83763. images360 = viewer.images360;
  83764. Alignment$1 = viewer.modules.Alignment;
  83765. SiteModel$1 = viewer.modules.SiteModel;
  83766. this.panoMeshs.name = 'panoMeshs';
  83767. viewer.scene.scene.add(this.panoMeshs);
  83768. this.lineMeshes.name = 'lineMeshes';
  83769. viewer.scene.scene.add(this.lineMeshes);
  83770. this.initPanoLink();
  83771. this.addPanoMesh();
  83772. viewer.scene.pointclouds.forEach(e=>{
  83773. e.material.color = pointColor.default;
  83774. });
  83775. this.switchView('top');
  83776. SiteModel$1.bus.addEventListener('initDataDone',()=>{
  83777. let floor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.length); //选择有漫游点的一层
  83778. if(!floor){
  83779. floor = 'all'; //SiteModel.entities.find(e=>e.buildType == 'floor')
  83780. console.log('没有一层有漫游点?!');
  83781. }
  83782. this.gotoFloor(floor);
  83783. });
  83784. Alignment$1.bus.addEventListener('switchHandle', this.updateCursor.bind(this));
  83785. viewer.addEventListener('global_click',(e)=>{
  83786. if(e.button === MOUSE.RIGHT){//取消旋转和平移
  83787. console.log('right click',e);
  83788. this.setLinkOperateState('addLink',false);
  83789. this.setLinkOperateState('removeLink',false);
  83790. }else if(this.clickToZoomInEnabled){
  83791. this.zoomIn(e.intersect.orthoIntersect, e.pointer);
  83792. this.setZoomInState(false);
  83793. }
  83794. });
  83795. {//旋转时的辅助线
  83796. this.rotGuideLine = LineDraw.createLine([], {color:'#aaffee'});
  83797. this.rotGuideLine.visible = false;
  83798. this.rotGuideLine.name = 'rotGuideLine';
  83799. this.rotGuideLine.renderOrder = renderOrders$1.line;
  83800. viewer.scene.scene.add(this.rotGuideLine);
  83801. let startPoint;
  83802. Alignment$1.bus.addEventListener('rotateStart', (e)=>{
  83803. startPoint = e.startPoint;
  83804. });
  83805. Alignment$1.bus.addEventListener('rotate', (e)=>{
  83806. LineDraw.updateLine(this.rotGuideLine, [startPoint, e.endPoint] );
  83807. this.rotGuideLine.visible = true;
  83808. });
  83809. viewer.fpControls.addEventListener("end",(e)=>{
  83810. startPoint = null;
  83811. this.rotGuideLine.visible = false;
  83812. });
  83813. }
  83814. {//连接时的辅助线
  83815. this.linkGuideLine = LineDraw.createLine([], {color:'#aaa', deshed:true, dashSize:0.1,gapSize:0.1,});
  83816. this.linkGuideLine.visible = false;
  83817. this.linkGuideLine.name = 'linkGuideLine';
  83818. viewer.scene.scene.add(this.linkGuideLine);
  83819. this.linkGuideLine.renderOrder = renderOrders$1.line;
  83820. let update = (e)=>{
  83821. if(this.operation != 'addLink' || this.activeViewName != 'top' || !this.selectedPano){
  83822. return this.linkGuideLine.visible = false
  83823. }
  83824. LineDraw.updateLine(this.linkGuideLine, [this.selectedPano.position, e.intersect.orthoIntersect.clone().setZ(this.selectedPano.position.z)] );
  83825. this.linkGuideLine.visible = true;
  83826. };
  83827. viewer.addEventListener('global_mousemove', (e)=>{
  83828. update(e);
  83829. });
  83830. this.addEventListener('updateLinkGuideLine', update);
  83831. //为何打开调试时移动很卡
  83832. }
  83833. });
  83834. }
  83835. //////////////////////////////////
  83836. initViews(){
  83837. this.splitScreenTool = new SplitScreen;
  83838. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  83839. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  83840. for(let i=0;i<2;i++){
  83841. let prop = cameraProps[i];
  83842. let view = new View();
  83843. this.views[prop.name] = view;
  83844. this.cameras[prop.name] = this.orthoCamera;
  83845. view.direction = prop.direction;
  83846. }
  83847. this.views.mainView = viewer.mainViewport.view;
  83848. this.cameras.mainView = viewer.mainViewport.camera;
  83849. }
  83850. switchView(name){//替换view和camera到mainViewport
  83851. let view = this.views[name];
  83852. let camera = this.cameras[name];
  83853. let prop = cameraProps.find(e=>e.name == name);
  83854. let {boundSize, center} = viewer.bound;
  83855. this.lastViewName = this.activeViewName;
  83856. this.activeViewName = name;
  83857. let lastView = this.views[this.lastViewName];
  83858. let lastCamera = this.cameras[this.lastViewName];
  83859. viewer.mainViewport.view = view;
  83860. viewer.mainViewport.camera = camera;
  83861. if(lastCamera)lastView.zoom = lastCamera.zoom;
  83862. this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center );
  83863. this.targetPlane.projectPoint(view.position, this.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  83864. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  83865. if(view.zoom)camera.zoom = view.zoom;//恢复上次的zoom
  83866. viewer.updateScreenSize({forceUpdateSize:true});//更新camera aspect left等
  83867. this.updateCursor();
  83868. if(name == 'mainView'){
  83869. viewer.mainViewport.alignment = null;
  83870. viewer.scene.pointclouds.forEach(e=>{
  83871. e.material.activeAttributeName = 'rgba';
  83872. e.material.useFilterByNormal = false;
  83873. e.changePointOpacity(1,true);
  83874. });
  83875. viewer.updateVisible(viewer.reticule, 'force', true);
  83876. if(lastView){
  83877. view.copy(lastView);
  83878. //view.position.
  83879. let direction = view.direction;
  83880. let panos = images360.panos.filter(e=>e.circle.visible);
  83881. let nearestPano = Common.sortByScore(panos , [], [(pano)=>{
  83882. let vec = new Vector3().subVectors(pano.position, view.position);
  83883. return -vec.dot(direction);
  83884. }], true);
  83885. console.log('最近',nearestPano );
  83886. if(nearestPano && nearestPano[0] ){ //尽量不变画面范围,使pano点保持原位,转换到mainView
  83887. let halfHeight = lastCamera.top/lastCamera.zoom;
  83888. let dis = halfHeight / Math.tan( MathUtils.degToRad(camera.fov/2));
  83889. view.position.add(direction.clone().multiplyScalar(-nearestPano[0].score - dis));
  83890. //console.log('getCloser', -nearestPano[0].score - dis)
  83891. this.lastDisToPano = dis; //记录一下
  83892. }
  83893. }
  83894. viewer.fpControls.lockKey = false;
  83895. }else {
  83896. if(prop.openCount == 0){//只需执行一次
  83897. this.viewportFitBound(name, boundSize, center);
  83898. }
  83899. prop.openCount ++;
  83900. viewer.scene.pointclouds.forEach(e=>{
  83901. e.material.activeAttributeName = 'color';
  83902. e.material.useFilterByNormal = true; //defines : use_filter_by_normal attenuated_opacity
  83903. if(this.selectedPano && this.selectedClouds.includes(e) /* this.selectedPano.pointcloud == e */){
  83904. e.changePointOpacity(opacitys.selected,true);
  83905. }else {
  83906. e.changePointOpacity(opacitys.default,true);
  83907. }
  83908. });
  83909. viewer.updateVisible(viewer.reticule, 'force', false);
  83910. if(name == 'top') viewer.mainViewport.alignment = {rotate:true,translate:true};
  83911. if(name == 'right'){
  83912. viewer.mainViewport.alignment = {translate:true, rotateSide:true};
  83913. viewer.mainViewport.rotateSide = true;
  83914. }else {
  83915. viewer.mainViewport.rotateSide = false;
  83916. }
  83917. viewer.fpControls.lockKey = true;
  83918. }
  83919. this.setZoomInState(false); //取消放大模式
  83920. }
  83921. //new THREE.Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] )
  83922. viewportFitBound(/* name, boundSize_, target */){ //使一个viewport聚焦在某个范围
  83923. /* let viewport = viewer.mainViewport
  83924. let {boundSize, center} = viewer.bound
  83925. var prop = cameraProps.find(v => name == v.name )
  83926. let expand = 10;
  83927. targetPlane.setFromNormalAndCoplanarPoint( prop.direction.clone(), center )
  83928. let shiftTarget = targetPlane.projectPoint(target, new THREE.Vector3() ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  83929. this.setCameraPose(shiftTarget, prop.direction)
  83930. if(name == 'top'){
  83931. let axis = prop.axis
  83932. var width = Math.max(boundSize_[axis[0]], boundSize_[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  83933. }else{//因为侧面可能旋转
  83934. let vec1 = new THREE.Vector3(boundSize_.x, 0,0);
  83935. let vec2 = new THREE.Vector3(0,boundSize_.y,0);
  83936. let v1 = vec1.projectOnPlane( prop.direction.clone() )
  83937. let v2 = vec2.projectOnPlane( prop.direction.clone() )
  83938. var width = Math.max(v1.length()+v2.length(), boundSize_.z * viewport.camera.aspect)//视口宽度(米)
  83939. }
  83940. var margin = 50 //px
  83941. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  83942. viewport.camera.updateProjectionMatrix() */
  83943. if(viewer.mainViewport.resolution.x == 0 || viewer.mainViewport.resolution.y == 0){
  83944. return setTimeout(()=>{
  83945. this.viewportFitBound(/* name, boundSize_, target */);
  83946. },10)
  83947. }
  83948. this.gotoFloor(this.currentFloor, true, 0, null, true);
  83949. }
  83950. rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  83951. this.splitScreenTool.rotateSideCamera(viewer.mainViewport, angle);
  83952. }
  83953. /* rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  83954. var prop = cameraProps.find(v => v.name == 'right' )
  83955. let {boundSize, center} = viewer.bound
  83956. //找到平移向量
  83957. targetPlane.setFromNormalAndCoplanarPoint(viewer.mainViewport.view.direction , center )
  83958. targetPlane.projectPoint(viewer.mainViewport.view.position, this.shiftTarget ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  83959. let vec = new THREE.Vector3().subVectors(center, this.shiftTarget)//相对于中心的偏移值,旋转后偏移值也旋转
  83960. //旋转
  83961. var rotMatrix = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0,0,1), angle)
  83962. //prop.direction.applyMatrix4(rotMatrix)
  83963. viewer.mainViewport.view.direction = viewer.mainViewport.view.direction.applyMatrix4(rotMatrix)
  83964. vec.applyMatrix4(rotMatrix)
  83965. this.shiftTarget.subVectors(center,vec) //新的
  83966. viewer.mainViewport.view.position = this.splitScreenTool.getPosOutOfModel(viewer.mainViewport) // this.getPosOutOfModel()
  83967. } */
  83968. /* getPosOutOfModel(){//已知shiftTarget和currentDir后
  83969. let {boundSize, center} = viewer.bound
  83970. let expand = 10;
  83971. let view = viewer.mainViewport.view
  83972. let radius = boundSize.length() / 2
  83973. let position = this.shiftTarget.clone().sub(view.direction.clone().multiplyScalar(radius + expand))
  83974. return position
  83975. } */
  83976. zoomIn(intersect, pointer){
  83977. let camera = viewer.mainViewport.camera;
  83978. let endZoom = 700;
  83979. //this.moveFit(intersect, {endZoom:viewer.mainViewport.camera.zoom < aimZoom ? aimZoom : null} , 300)
  83980. let startZoom = camera.zoom;
  83981. if(startZoom >= endZoom){return}
  83982. viewer.mainViewport.view.zoomOrthoCamera(camera, endZoom, pointer, 300);
  83983. }
  83984. /* getRadius(){
  83985. let {boundSize, center} = viewer.bound
  83986. let expand = 10;
  83987. let radius = boundSize.length() / 2
  83988. return radius + expand
  83989. } */
  83990. moveFit(pos, info, duration){
  83991. var margin = {x:200, y:230};
  83992. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin );
  83993. /* targetPlane.projectPoint(pos, this.shiftTarget) //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  83994. info.endPosition = this.getPosOutOfModel()
  83995. info
  83996. let view = viewer.mainViewport.view
  83997. view.moveOrthoCamera(viewer.mainViewport, info , duration ) */
  83998. }
  83999. setZoomInState(state, informinformBy2d){//是否点击后可放大
  84000. if(state && this.activeViewName == 'mainView')return console.log('3D不可放大')
  84001. this.clickToZoomInEnabled = !!state;
  84002. if(state){
  84003. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"zoomInCloud"} );
  84004. }else {
  84005. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"zoomInCloud" });
  84006. }
  84007. if(!state && !informinformBy2d){
  84008. this.dispatchEvent({type:'operationCancel', operation: 'zoomIn'});
  84009. }
  84010. }
  84011. gotoFloor(floor, force, duration = 600, informBy2d, fitBound){// 选择不同楼层, 切换点位显示。 'all'为全部显示
  84012. floor = floor || 'all';
  84013. if(this.currentFloor == floor && !force)return
  84014. //let pointclouds = viewer.findPointcloudsAtFloor(floor)
  84015. let panos = floor == 'all' ? viewer.images360.panos : floor.panos;
  84016. viewer.images360.panos.forEach(pano=>{
  84017. let v = panos.includes(pano);
  84018. this.switchPanoVisible(pano,v);
  84019. });
  84020. this.updateLinesVisible();
  84021. //切换楼层时清空选择状态
  84022. if(this.selectedPano && floor != 'all' && !floor.panos.includes(this.selectedPano)){
  84023. this.selectedPano.circle.dispatchEvent('click');
  84024. }
  84025. if(this.selectedLine){
  84026. this.selectedLine.dispatchEvent('click');
  84027. }
  84028. let bound, center;
  84029. if(floor == 'all'){
  84030. bound = viewer.images360.bound.bounding;
  84031. center = viewer.images360.bound.center;
  84032. }else {
  84033. bound = this.getPanosBound(floor);
  84034. center = bound.getCenter(new Vector3());
  84035. if(floor.panos.length == 0)console.log(floor.name, 'floor无漫游点' );
  84036. }
  84037. if(this.activeViewName != 'mainView' ){
  84038. fitBound && this.moveFit(center, {bound}, duration);
  84039. }else if(this.activeViewName == 'mainView'){
  84040. if(floor != 'all'){ //切换一下位置,因为原处点云会消失
  84041. viewer.scene.view.setView({position:center, duration });
  84042. }
  84043. }
  84044. this.currentFloor = floor;
  84045. if(!informBy2d){
  84046. this.dispatchEvent({type:'changeFloor', floor});
  84047. }
  84048. }
  84049. getPanosBound(floor){
  84050. if(!floor.panosBound){
  84051. if(floor.panos.length == 0){
  84052. floor.panosBound = viewer.images360.bound.bounding.clone();
  84053. }else {
  84054. /* floor.panosBound = new THREE.Box3
  84055. floor.panos.forEach(pano=>{
  84056. floor.panosBound.expandByPoint(pano.position)
  84057. })
  84058. let center = floor.panosBound.getCenter(new THREE.Vector3)
  84059. let minBound = (new THREE.Box3()).setFromCenterAndSize(center, new THREE.Vector3(5,5,5))
  84060. floor.panosBound.union(minBound) */
  84061. let minSize = new Vector3(5,5,5);
  84062. let bound = math.getBoundByPoints(floor.panos.map(e=>e.position), minSize);
  84063. floor.panosBound = bound.bounding;
  84064. }
  84065. }
  84066. return floor.panosBound
  84067. }
  84068. switchPanoVisible(pano, v, informBy2d){
  84069. pano.circle.visible = v;
  84070. viewer.updateVisible(pano, 'panoEditor', v);
  84071. viewer.updateVisible(pano.pointcloud, 'panoEditor', v);
  84072. if(v){
  84073. this.visiblePanos.includes(pano) || this.visiblePanos.push(pano);
  84074. }else {
  84075. let index = this.visiblePanos.indexOf(pano);
  84076. index>-1 && this.visiblePanos.splice(index,1);
  84077. }
  84078. if(informBy2d){
  84079. this.updateLinesVisible();
  84080. }
  84081. informBy2d || this.dispatchEvent({type:"switchPanoVisible", pano, v});
  84082. }
  84083. updateLinesVisible(){
  84084. this.lineMeshes.children.forEach(line=>{
  84085. let names = line.name.split('-');
  84086. var pano0 = images360.getPano(names[0]);
  84087. var pano1 = images360.getPano(names[1]);
  84088. line.visible = this.visiblePanos.includes(pano0) || this.visiblePanos.includes(pano1);
  84089. });
  84090. }
  84091. updateCursor(){
  84092. let cursor;
  84093. if(this.activeViewName == 'mainView' || !this.selectedPano){
  84094. cursor = null;
  84095. }else {
  84096. cursor = Alignment$1.handleState;
  84097. }
  84098. if(cursor == 'rotate'){
  84099. viewer.dispatchEvent({
  84100. type : "CursorChange", action : "add", name:"rotatePointcloud"
  84101. });
  84102. viewer.dispatchEvent({
  84103. type : "CursorChange", action : "remove", name:"movePointcloud"
  84104. });
  84105. }else if(cursor == 'translate'){
  84106. viewer.dispatchEvent({
  84107. type : "CursorChange", action : "add", name:"movePointcloud"
  84108. });
  84109. viewer.dispatchEvent({
  84110. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  84111. });
  84112. }else {
  84113. viewer.dispatchEvent({
  84114. type : "CursorChange", action : "remove", name:"movePointcloud"
  84115. });
  84116. viewer.dispatchEvent({
  84117. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  84118. });
  84119. }
  84120. //this.cursorState = cursor
  84121. }
  84122. setLinkOperateState(name, state, informinformBy2d){
  84123. if(state && name == this.operation || !state && name != this.operation)return
  84124. let old = this.operation;
  84125. this.operation = state ? name : null;
  84126. if(this.operation == 'removeLink'){
  84127. if(this.selectedLine){
  84128. this.selectedLine.dispatchEvent('click');//删除
  84129. }
  84130. if(this.selectedPano){
  84131. this.selectedPano.circle.dispatchEvent('click');//删除
  84132. }
  84133. }
  84134. if(this.operation != 'addLink'){
  84135. this.linkGuideLine.visible = false;
  84136. }
  84137. if(!state && !informinformBy2d){
  84138. this.dispatchEvent({type: "operationCancel", operation: old});
  84139. }
  84140. if(this.operation == 'addLink'){
  84141. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"connectPano"} );
  84142. }else {
  84143. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"connectPano"} );
  84144. }
  84145. if(this.operation == 'removeLink'){
  84146. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"disconnectPano"} );
  84147. }else {
  84148. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"disconnectPano"} );
  84149. }
  84150. }
  84151. /////////////////////////////////
  84152. initPanoLink(){
  84153. images360.panos.forEach((pano)=>{
  84154. this.panoLink[pano.id] = {};
  84155. });
  84156. images360.panos.forEach((pano)=>{
  84157. pano.visibles.forEach(index=>{//visibles中存的是下标!
  84158. this.linkChange(pano, images360.getPano(index,'index'), 'add');
  84159. });
  84160. });
  84161. console.log('panoLink',this.panoLink);
  84162. }
  84163. groupChange(pano0, pano1, type){//修改group (type == 'remove'时,pano1可以为空)
  84164. if(type == 'add'){
  84165. Common.pushToGroupAuto([pano0, pano1], this.panoGroup );
  84166. }else {
  84167. let atGroup = this.panoGroup.find(e=>e.includes(pano0) && (e.includes(pano1) || !pano1));//所在组
  84168. if(!atGroup){
  84169. if(pano1){
  84170. console.log('这两个pano原本就不在一个组', pano0.id, pano1.id);
  84171. }else {
  84172. console.log('pano0不在任何组', pano0);
  84173. }
  84174. return
  84175. }
  84176. //断开连接时,因为组内没有其他成员的连接信息,所以需要清除整组,并将剩余的一个个重新连接
  84177. this.panoGroup.splice(this.panoGroup.indexOf(atGroup),1); //删除
  84178. atGroup.forEach(pano=>{//然后再重新生成这两个和组的关系,各自分组
  84179. if(pano == pano0 || pano == pano1)return
  84180. for(let id in this.panoLink[pano.id]){
  84181. if(this.panoLink[pano.id][id]){
  84182. let pano_ = images360.getPano(id);
  84183. Common.pushToGroupAuto([pano, pano_], this.panoGroup );
  84184. }
  84185. }
  84186. });
  84187. }
  84188. }
  84189. linkChange(pano0, pano1, type){//修改link (type == 'remove'时,pano1可以为空)
  84190. let temp = [];
  84191. if(type == 'add'){
  84192. if(!pano1)return console.error('不支持add时pano1为空')
  84193. this.panoLink[pano0.id][pano1.id] = this.panoLink[pano0.id][pano1.id] || {};
  84194. this.panoLink[pano1.id][pano0.id] = this.panoLink[pano1.id][pano0.id] || {};
  84195. }else {
  84196. if(!pano1){
  84197. for(let id in this.panoLink[pano0.id]){
  84198. if(this.panoLink[pano0.id][id]){
  84199. this.panoLink[id][pano0.id] = false;
  84200. temp.push(id);
  84201. }
  84202. }
  84203. this.panoLink[pano0.id] = {}; //全部断连
  84204. }else {
  84205. this.panoLink[pano0.id][pano1.id] = false;
  84206. this.panoLink[pano1.id][pano0.id] = false;
  84207. }
  84208. }
  84209. if(!pano1){ //全部断连
  84210. temp.forEach(id=>{
  84211. this.lineChange(pano0, images360.getPano(id) , type);
  84212. });
  84213. }else {
  84214. this.lineChange(pano0, pano1, type);
  84215. }
  84216. this.groupChange(pano0, pano1, type);
  84217. //this.updateSelectGroup()
  84218. this.selectPano(this.selectedPano, false,true); //更新选中点云显示
  84219. }
  84220. lineChange(pano0, pano1, type){//修改line
  84221. if(type == 'add'){
  84222. if(this.panoLink[pano0.id][pano1.id].line) return
  84223. let line = LineDraw.createFatLine([pano0.position, pano1.position], {material:lineMats$3.default});
  84224. line.name = `${pano0.id}-${pano1.id}`;
  84225. line.renderOrder = line.pickOrder = renderOrders$1.line;
  84226. this.lineMeshes.add(line);
  84227. this.panoLink[pano0.id][pano1.id].line = this.panoLink[pano1.id][pano0.id].line = line;
  84228. line.addEventListener('mouseover', ()=>{
  84229. if(this.clickToZoomInEnabled)return
  84230. if(this.activeViewName == 'mainView')return
  84231. if(this.selectedLine != line)line.material = lineMats$3.hovered;
  84232. viewer.dispatchEvent({
  84233. type : "CursorChange", action : "add", name:"hoverLine"
  84234. });
  84235. });
  84236. line.addEventListener('mouseleave', ()=>{
  84237. if(this.clickToZoomInEnabled)return
  84238. //if(this.activeViewName == 'mainView')return
  84239. if(this.selectedLine != line)line.material = lineMats$3.default;
  84240. viewer.dispatchEvent({
  84241. type : "CursorChange", action : "remove", name:"hoverLine"
  84242. });
  84243. });
  84244. line.addEventListener('click', (e)=>{
  84245. if(this.clickToZoomInEnabled)return
  84246. if(this.activeViewName == 'mainView')return
  84247. if(this.operation == 'removeLink'){
  84248. if(this.selectedLine == line) this.selectLine(null);
  84249. return this.linkChange(pano0, pano1, 'remove')
  84250. }
  84251. this.selectLine(line);
  84252. });
  84253. }else {
  84254. let line = this.lineMeshes.children.find(e=>e.name == `${pano0.id}-${pano1.id}` || e.name == `${pano1.id}-${pano0.id}` );
  84255. if(line){
  84256. this.lineMeshes.remove(line);
  84257. line.geometry.dispose();
  84258. }
  84259. }
  84260. }
  84261. selectLine(line){
  84262. if(this.selectedLine == line)return
  84263. if(this.selectedLine){
  84264. this.selectedLine.material = lineMats$3.default;
  84265. }
  84266. if(line){
  84267. line.material = lineMats$3.selected;
  84268. }
  84269. this.selectedLine = line;
  84270. }
  84271. addPanoMesh(){
  84272. let map = texLoader$c.load(Potree.resourcePath+'/textures/correct_n.png' );
  84273. circleMats.default = new MeshBasicMaterial({
  84274. map,
  84275. color: 0xffffff,
  84276. transparent: true,
  84277. depthTest: false,
  84278. depthWrite: false,
  84279. });
  84280. circleMats.hovered = new MeshBasicMaterial({
  84281. map,
  84282. color: 0xffff00,
  84283. transparent: true,
  84284. depthTest: false,
  84285. depthWrite: false,
  84286. });
  84287. circleMats.selected = new MeshBasicMaterial({
  84288. map: texLoader$c.load(Potree.resourcePath+'/textures/correct_s.png' ) ,
  84289. color: 0xffffff,
  84290. transparent: true,
  84291. depthTest: false,
  84292. depthWrite: false,
  84293. });
  84294. let setPos = (circle)=>{
  84295. circle.position.copy(circle.pano.position);
  84296. for(let id in this.panoLink[circle.pano.id]){
  84297. let linkInfo = this.panoLink[circle.pano.id][id];
  84298. if(linkInfo){
  84299. LineDraw.updateLine(linkInfo.line, [circle.pano.position, images360.getPano(id).position] );
  84300. }
  84301. }
  84302. circle.update(); //update sprite Matrix
  84303. };
  84304. images360.panos.forEach(pano=>{
  84305. var circle = new Sprite$1({mat: circleMats.default, sizeInfo:{
  84306. minSize : 50 , maxSize : 120, nearBound : 2, farBound : 10,
  84307. },
  84308. renderOrder : renderOrders$1.circle,
  84309. pickOrder: renderOrders$1.circle
  84310. }); //new THREE.Sprite(circleMats.default)
  84311. circle.name = 'panoCircle';
  84312. circle.sid = pano.id;
  84313. circle.pano = pano;
  84314. pano.circle = circle;
  84315. this.panoMeshs.add(circle);
  84316. setPos(circle);
  84317. pano.addEventListener('rePos', setPos.bind(this,circle));
  84318. let drag = ()=>{
  84319. if(this.activeViewName == 'mainView')return
  84320. this.selectPano(circle.pano); //为了方便拖拽点云,拖动circle就直接选中
  84321. viewer.inputHandler.drag.object = null; //取消拖拽状态,否则不触发点云拖动
  84322. };
  84323. circle.addEventListener('drag', drag);
  84324. /* circle.addEventListener('drop', ()=>{
  84325. }) */
  84326. circle.addEventListener('mouseover', ()=>{
  84327. this.hoverPano(pano,true);
  84328. });
  84329. circle.addEventListener('mouseleave', ()=>{
  84330. this.hoverPano(pano,false);
  84331. });
  84332. circle.addEventListener('click', ()=>{
  84333. //if(this.activeViewName == 'mainView')return
  84334. if(this.clickToZoomInEnabled)return
  84335. if(this.operation == 'removeLink'){
  84336. this.linkChange(pano, null, 'remove'); //删除所有连接
  84337. }
  84338. if(this.selectedPano == circle.pano) return this.selectPano(null)
  84339. if(this.operation == 'addLink' && this.selectedPano){
  84340. this.linkChange(this.selectedPano, circle.pano, 'add');
  84341. //this.setLinkOperateState('addLink',false)
  84342. return
  84343. }
  84344. //if(this.operation == 'removeLink' && this.selectedPano){ //和选择中心点冲突
  84345. // this.linkChange(this.selectedPano, circle.pano, 'remove')
  84346. // //this.setLinkOperateState('removeLink',false)
  84347. // return
  84348. // }
  84349. this.selectPano(circle.pano);
  84350. });
  84351. });
  84352. }
  84353. hoverPano(pano, state){
  84354. if(this.clickToZoomInEnabled)return
  84355. if(pano && state){ //在hover一个pano之前,一定会先取消已经hover的pano, 最多存在一个hovered的pano
  84356. if(this.hoveredPano == pano)return
  84357. if(this.hoveredPano){
  84358. this.hoverPano(this.hoveredPano,false);
  84359. }
  84360. this.hoveredPano = pano;
  84361. pano.hovered = true;
  84362. if(/* this.activeViewName == 'mainView' || */Alignment$1.handleState && this.selectedPano && this.selectedPano == pano)return
  84363. if(this.operation != 'addLink' || !this.selectedPano || this.selectedPano == pano){ // this.selectedPano == pano?
  84364. viewer.dispatchEvent({
  84365. type : "CursorChange", action : "add", name:"hoverPano"
  84366. });
  84367. }
  84368. if(this.selectedPano != pano) pano.circle.material = circleMats.hovered;
  84369. }else if(pano && !state){//unhover
  84370. if(this.hoveredPano != pano)return
  84371. pano.hovered = false;
  84372. viewer.dispatchEvent({
  84373. type : "CursorChange", action : "remove", name:"hoverPano"
  84374. });
  84375. if(this.selectedPano != pano) pano.circle.material = circleMats.default;
  84376. this.hoveredPano = null;
  84377. }else {//unhover any
  84378. if(this.hoveredPano){
  84379. this.hoverPano(this.hoveredPano, false);
  84380. }
  84381. }
  84382. }
  84383. selectPano(pano, informinformBy2d, force){
  84384. if(this.selectedPano == pano && !force)return
  84385. let lastSeletedPano = this.selectedPano;
  84386. if(this.selectedPano){
  84387. this.selectedPano.circle.material = circleMats.default;
  84388. this.selectedPano.circle.renderOrder = renderOrders$1.circle;
  84389. if(this.activeViewName != 'mainView'){
  84390. this.selectedClouds.forEach(e=>{
  84391. e.changePointOpacity(opacitys.default,true);
  84392. e.material.color = pointColor.default;
  84393. });
  84394. //this.selectedPano.pointcloud.changePointOpacity(opacitys.default,true)
  84395. //this.selectedPano.pointcloud.material.color = Potree.config.material.pointColor
  84396. }
  84397. }
  84398. this.selectedPano = pano || null;
  84399. this.updateSelectGroup();
  84400. if(pano){
  84401. this.selectedPano.circle.material = circleMats.selected;
  84402. this.selectedPano.circle.renderOrder = this.selectedPano.circle.pickOrder = renderOrders$1.circleSelected; //侧视图能显示在最前
  84403. //this.selectedPano.pointcloud.material.color = '#ff0000'
  84404. //this.selectedPano.pointcloud.changePointOpacity(opacitys.selected,true)
  84405. if(this.activeViewName != 'mainView'){
  84406. this.selectedClouds.forEach(e=>{
  84407. e.changePointOpacity(opacitys.selected,true);
  84408. e.material.color = pointColor.selected;
  84409. });
  84410. }
  84411. {//自动切换楼层
  84412. let atFloor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.includes(pano));
  84413. if(!atFloor){
  84414. atFloor = 'all';
  84415. }else {
  84416. }
  84417. this.gotoFloor(atFloor, false, 600 );
  84418. }
  84419. }
  84420. this.updateCursor();
  84421. if(informinformBy2d){
  84422. if(this.selectedPano){
  84423. if(this.activeViewName == 'mainView'){ //平移,focus选中的pano
  84424. let distance = this.lastDisToPano || 5;
  84425. if(lastSeletedPano){
  84426. distance = viewer.mainViewport.camera.position.distanceTo(lastSeletedPano.position);
  84427. }
  84428. viewer.focusOnObject({ position:this.selectedPano.position}, 'point', null, {distance });
  84429. }else {
  84430. this.moveFit(this.selectedPano.position, {}, 500);
  84431. }
  84432. }
  84433. }else {
  84434. this.dispatchEvent({type:'panoSelect', pano });
  84435. }
  84436. }
  84437. updateSelectGroup(){//更新选中的组
  84438. this.selectedGroup = this.panoGroup.find(e=>e.includes(this.selectedPano));
  84439. this.selectedClouds = this.selectedPano ? (this.selectedGroup || [this.selectedPano]).map(e=>e.pointcloud) : [];
  84440. }
  84441. checkIfCanSave(){//如果未全部相连,不能保存
  84442. for(let datasetId in Potree.settings.datasetsPanos ) {
  84443. if(!this.checkIfAllLinked({datasetId})){
  84444. console.log('没有全部连通,不能保存。其中一个:', datasetId);
  84445. return
  84446. }
  84447. }
  84448. return true
  84449. }
  84450. checkIfAllLinked(o){//某个(or组所在的)数据集是否全部连通
  84451. let datasetId, group;
  84452. if(o.group){
  84453. group = o.group;
  84454. let pano = o.group[0];
  84455. if(!pano)return //会有没有漫游点的点云来编辑吗
  84456. datasetId = pano.pointcloud.dataset_id;
  84457. }else if(o.datasetId){
  84458. datasetId = o.datasetId;
  84459. group = this.panoGroup.find(panos=>panos[0].pointcloud.dataset_id == datasetId );
  84460. if(!group)return //要找的数据集的pano全部都孤立了
  84461. }
  84462. let panos = Potree.settings.datasetsPanos[datasetId].panos;
  84463. return panos.length == group.length
  84464. }
  84465. exportSavingData(){//输出漫游点新的坐标和朝向、以及连接信息
  84466. let sweepLocations = {};
  84467. let rotQua = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI);
  84468. for(let datasetId in Potree.settings.datasetsPanos ) {
  84469. let {panos} = Potree.settings.datasetsPanos[datasetId];
  84470. let data = panos.map(pano=>{
  84471. let visibles = [];
  84472. for(let id in this.panoLink[pano.id]){
  84473. if(this.panoLink[pano.id][id]){
  84474. visibles.push(viewer.images360.getPano(id).index);
  84475. }
  84476. }
  84477. return Object.assign({}, pano.panosData, {
  84478. uuid: pano.uuid,
  84479. pose:{
  84480. translation: dealData(pano.position.clone()/* .negate() */),
  84481. rotation: dealData(new Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ),
  84482. },
  84483. visibles,
  84484. //subgroup: 0,group: 1, "id_view":..
  84485. })
  84486. });
  84487. sweepLocations[datasetId] = {sweepLocations:data};
  84488. }
  84489. /* this.lineMeshes.children.forEach(e=>{//从line中搜集连接信息,而不从linkInfo,这样visibles不会重复一次
  84490. let names = e.name.split('-') //是不是该转成数字
  84491. var pano0 = names[0]
  84492. var pano1 = names[1]
  84493. sweepLocations.find(s=>s.uuid == pano0).visibles.push(pano1)
  84494. }) */
  84495. function dealData(value){
  84496. let v = math.toPrecision(value, 6);
  84497. if(v instanceof Quaternion){
  84498. return {x:v.x, y:v.y, z:v.z, w:v.w}
  84499. }else if(v instanceof Vector3){
  84500. return {x:v.x, y:v.y, z:v.z}
  84501. }
  84502. }
  84503. console.log(sweepLocations);
  84504. return sweepLocations
  84505. }
  84506. }
  84507. /*
  84508. 不同数据集之间不能连线
  84509. 不同楼层可能也不能
  84510. 如果楼层在不同建筑物怎么办? 楼层切换按钮只能在一个建筑内切换。
  84511. 全部相连时不能移动和旋转
  84512. 如果未全部相连,不能保存
  84513. */
  84514. var PanoEditor$1 = new PanoEditor();
  84515. var OBJLoader = ( function () {
  84516. // o object_name | g group_name
  84517. var object_pattern = /^[og]\s*(.+)?/;
  84518. // mtllib file_reference
  84519. var material_library_pattern = /^mtllib /;
  84520. // usemtl material_name
  84521. var material_use_pattern = /^usemtl /;
  84522. // usemap map_name
  84523. var map_use_pattern = /^usemap /;
  84524. var vA = new Vector3();
  84525. var vB = new Vector3();
  84526. var vC = new Vector3();
  84527. var ab = new Vector3();
  84528. var cb = new Vector3();
  84529. function ParserState() {
  84530. var state = {
  84531. objects: [],
  84532. object: {},
  84533. vertices: [],
  84534. normals: [],
  84535. colors: [],
  84536. uvs: [],
  84537. materials: {},
  84538. materialLibraries: [],
  84539. startObject: function ( name, fromDeclaration ) {
  84540. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  84541. // file. We need to use it for the first parsed g/o to keep things in sync.
  84542. if ( this.object && this.object.fromDeclaration === false ) {
  84543. this.object.name = name;
  84544. this.object.fromDeclaration = ( fromDeclaration !== false );
  84545. return;
  84546. }
  84547. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  84548. if ( this.object && typeof this.object._finalize === 'function' ) {
  84549. this.object._finalize( true );
  84550. }
  84551. this.object = {
  84552. name: name || '',
  84553. fromDeclaration: ( fromDeclaration !== false ),
  84554. geometry: {
  84555. vertices: [],
  84556. normals: [],
  84557. colors: [],
  84558. uvs: [],
  84559. hasUVIndices: false
  84560. },
  84561. materials: [],
  84562. smooth: true,
  84563. startMaterial: function ( name, libraries ) {
  84564. var previous = this._finalize( false );
  84565. // New usemtl declaration overwrites an inherited material, except if faces were declared
  84566. // after the material, then it must be preserved for proper MultiMaterial continuation.
  84567. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  84568. this.materials.splice( previous.index, 1 );
  84569. }
  84570. var material = {
  84571. index: this.materials.length,
  84572. name: name || '',
  84573. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  84574. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  84575. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  84576. groupEnd: - 1,
  84577. groupCount: - 1,
  84578. inherited: false,
  84579. clone: function ( index ) {
  84580. var cloned = {
  84581. index: ( typeof index === 'number' ? index : this.index ),
  84582. name: this.name,
  84583. mtllib: this.mtllib,
  84584. smooth: this.smooth,
  84585. groupStart: 0,
  84586. groupEnd: - 1,
  84587. groupCount: - 1,
  84588. inherited: false
  84589. };
  84590. cloned.clone = this.clone.bind( cloned );
  84591. return cloned;
  84592. }
  84593. };
  84594. this.materials.push( material );
  84595. return material;
  84596. },
  84597. currentMaterial: function () {
  84598. if ( this.materials.length > 0 ) {
  84599. return this.materials[ this.materials.length - 1 ];
  84600. }
  84601. return undefined;
  84602. },
  84603. _finalize: function ( end ) {
  84604. var lastMultiMaterial = this.currentMaterial();
  84605. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  84606. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  84607. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  84608. lastMultiMaterial.inherited = false;
  84609. }
  84610. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  84611. if ( end && this.materials.length > 1 ) {
  84612. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  84613. if ( this.materials[ mi ].groupCount <= 0 ) {
  84614. this.materials.splice( mi, 1 );
  84615. }
  84616. }
  84617. }
  84618. // Guarantee at least one empty material, this makes the creation later more straight forward.
  84619. if ( end && this.materials.length === 0 ) {
  84620. this.materials.push( {
  84621. name: '',
  84622. smooth: this.smooth
  84623. } );
  84624. }
  84625. return lastMultiMaterial;
  84626. }
  84627. };
  84628. // Inherit previous objects material.
  84629. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  84630. // If a usemtl declaration is encountered while this new object is being parsed, it will
  84631. // overwrite the inherited material. Exception being that there was already face declarations
  84632. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  84633. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  84634. var declared = previousMaterial.clone( 0 );
  84635. declared.inherited = true;
  84636. this.object.materials.push( declared );
  84637. }
  84638. this.objects.push( this.object );
  84639. },
  84640. finalize: function () {
  84641. if ( this.object && typeof this.object._finalize === 'function' ) {
  84642. this.object._finalize( true );
  84643. }
  84644. },
  84645. parseVertexIndex: function ( value, len ) {
  84646. var index = parseInt( value, 10 );
  84647. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84648. },
  84649. parseNormalIndex: function ( value, len ) {
  84650. var index = parseInt( value, 10 );
  84651. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84652. },
  84653. parseUVIndex: function ( value, len ) {
  84654. var index = parseInt( value, 10 );
  84655. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  84656. },
  84657. addVertex: function ( a, b, c ) {
  84658. var src = this.vertices;
  84659. var dst = this.object.geometry.vertices;
  84660. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84661. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84662. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84663. },
  84664. addVertexPoint: function ( a ) {
  84665. var src = this.vertices;
  84666. var dst = this.object.geometry.vertices;
  84667. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84668. },
  84669. addVertexLine: function ( a ) {
  84670. var src = this.vertices;
  84671. var dst = this.object.geometry.vertices;
  84672. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84673. },
  84674. addNormal: function ( a, b, c ) {
  84675. var src = this.normals;
  84676. var dst = this.object.geometry.normals;
  84677. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84678. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84679. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84680. },
  84681. addFaceNormal: function ( a, b, c ) {
  84682. var src = this.vertices;
  84683. var dst = this.object.geometry.normals;
  84684. vA.fromArray( src, a );
  84685. vB.fromArray( src, b );
  84686. vC.fromArray( src, c );
  84687. cb.subVectors( vC, vB );
  84688. ab.subVectors( vA, vB );
  84689. cb.cross( ab );
  84690. cb.normalize();
  84691. dst.push( cb.x, cb.y, cb.z );
  84692. dst.push( cb.x, cb.y, cb.z );
  84693. dst.push( cb.x, cb.y, cb.z );
  84694. },
  84695. addColor: function ( a, b, c ) {
  84696. var src = this.colors;
  84697. var dst = this.object.geometry.colors;
  84698. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84699. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84700. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84701. },
  84702. addUV: function ( a, b, c ) {
  84703. var src = this.uvs;
  84704. var dst = this.object.geometry.uvs;
  84705. dst.push( src[ a + 0 ], src[ a + 1 ] );
  84706. dst.push( src[ b + 0 ], src[ b + 1 ] );
  84707. dst.push( src[ c + 0 ], src[ c + 1 ] );
  84708. },
  84709. addDefaultUV: function () {
  84710. var dst = this.object.geometry.uvs;
  84711. dst.push( 0, 0 );
  84712. dst.push( 0, 0 );
  84713. dst.push( 0, 0 );
  84714. },
  84715. addUVLine: function ( a ) {
  84716. var src = this.uvs;
  84717. var dst = this.object.geometry.uvs;
  84718. dst.push( src[ a + 0 ], src[ a + 1 ] );
  84719. },
  84720. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  84721. var vLen = this.vertices.length;
  84722. var ia = this.parseVertexIndex( a, vLen );
  84723. var ib = this.parseVertexIndex( b, vLen );
  84724. var ic = this.parseVertexIndex( c, vLen );
  84725. this.addVertex( ia, ib, ic );
  84726. this.addColor( ia, ib, ic );
  84727. // normals
  84728. if ( na !== undefined && na !== '' ) {
  84729. var nLen = this.normals.length;
  84730. ia = this.parseNormalIndex( na, nLen );
  84731. ib = this.parseNormalIndex( nb, nLen );
  84732. ic = this.parseNormalIndex( nc, nLen );
  84733. this.addNormal( ia, ib, ic );
  84734. } else {
  84735. this.addFaceNormal( ia, ib, ic );
  84736. }
  84737. // uvs
  84738. if ( ua !== undefined && ua !== '' ) {
  84739. var uvLen = this.uvs.length;
  84740. ia = this.parseUVIndex( ua, uvLen );
  84741. ib = this.parseUVIndex( ub, uvLen );
  84742. ic = this.parseUVIndex( uc, uvLen );
  84743. this.addUV( ia, ib, ic );
  84744. this.object.geometry.hasUVIndices = true;
  84745. } else {
  84746. // add placeholder values (for inconsistent face definitions)
  84747. this.addDefaultUV();
  84748. }
  84749. },
  84750. addPointGeometry: function ( vertices ) {
  84751. this.object.geometry.type = 'Points';
  84752. var vLen = this.vertices.length;
  84753. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  84754. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  84755. this.addVertexPoint( index );
  84756. this.addColor( index );
  84757. }
  84758. },
  84759. addLineGeometry: function ( vertices, uvs ) {
  84760. this.object.geometry.type = 'Line';
  84761. var vLen = this.vertices.length;
  84762. var uvLen = this.uvs.length;
  84763. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  84764. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  84765. }
  84766. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  84767. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  84768. }
  84769. }
  84770. };
  84771. state.startObject( '', false );
  84772. return state;
  84773. }
  84774. //
  84775. function OBJLoader( manager ) {
  84776. Loader.call( this, manager );
  84777. this.materials = null;
  84778. }
  84779. OBJLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  84780. constructor: OBJLoader,
  84781. load: function ( url, onLoad, onProgress, onError ) {
  84782. var scope = this;
  84783. var loader = new FileLoader( this.manager );
  84784. loader.setPath( this.path );
  84785. loader.setRequestHeader( this.requestHeader );
  84786. loader.setWithCredentials( this.withCredentials );
  84787. loader.load( url, function ( text , total ) {// xzw add total
  84788. try {
  84789. onLoad( scope.parse( text ) , total );
  84790. } catch ( e ) {
  84791. if ( onError ) {
  84792. onError( e );
  84793. } else {
  84794. console.error( e );
  84795. }
  84796. scope.manager.itemError( url );
  84797. }
  84798. }, onProgress, onError );
  84799. },
  84800. setMaterials: function ( materials ) {
  84801. this.materials = materials;
  84802. return this;
  84803. },
  84804. parse: function ( text ) {
  84805. var state = new ParserState();
  84806. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  84807. // This is faster than String.split with regex that splits on both
  84808. text = text.replace( /\r\n/g, '\n' );
  84809. }
  84810. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  84811. // join lines separated by a line continuation character (\)
  84812. text = text.replace( /\\\n/g, '' );
  84813. }
  84814. var lines = text.split( '\n' );
  84815. var line = '', lineFirstChar = '';
  84816. var lineLength = 0;
  84817. var result = [];
  84818. // Faster to just trim left side of the line. Use if available.
  84819. var trimLeft = ( typeof ''.trimLeft === 'function' );
  84820. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  84821. line = lines[ i ];
  84822. line = trimLeft ? line.trimLeft() : line.trim();
  84823. lineLength = line.length;
  84824. if ( lineLength === 0 ) continue;
  84825. lineFirstChar = line.charAt( 0 );
  84826. // @todo invoke passed in handler if any
  84827. if ( lineFirstChar === '#' ) continue;
  84828. if ( lineFirstChar === 'v' ) {
  84829. var data = line.split( /\s+/ );
  84830. switch ( data[ 0 ] ) {
  84831. case 'v':
  84832. state.vertices.push(
  84833. parseFloat( data[ 1 ] ),
  84834. parseFloat( data[ 2 ] ),
  84835. parseFloat( data[ 3 ] )
  84836. );
  84837. if ( data.length >= 7 ) {
  84838. state.colors.push(
  84839. parseFloat( data[ 4 ] ),
  84840. parseFloat( data[ 5 ] ),
  84841. parseFloat( data[ 6 ] )
  84842. );
  84843. } else {
  84844. // if no colors are defined, add placeholders so color and vertex indices match
  84845. state.colors.push( undefined, undefined, undefined );
  84846. }
  84847. break;
  84848. case 'vn':
  84849. state.normals.push(
  84850. parseFloat( data[ 1 ] ),
  84851. parseFloat( data[ 2 ] ),
  84852. parseFloat( data[ 3 ] )
  84853. );
  84854. break;
  84855. case 'vt':
  84856. state.uvs.push(
  84857. parseFloat( data[ 1 ] ),
  84858. parseFloat( data[ 2 ] )
  84859. );
  84860. break;
  84861. }
  84862. } else if ( lineFirstChar === 'f' ) {
  84863. var lineData = line.substr( 1 ).trim();
  84864. var vertexData = lineData.split( /\s+/ );
  84865. var faceVertices = [];
  84866. // Parse the face vertex data into an easy to work with format
  84867. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  84868. var vertex = vertexData[ j ];
  84869. if ( vertex.length > 0 ) {
  84870. var vertexParts = vertex.split( '/' );
  84871. faceVertices.push( vertexParts );
  84872. }
  84873. }
  84874. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  84875. var v1 = faceVertices[ 0 ];
  84876. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  84877. var v2 = faceVertices[ j ];
  84878. var v3 = faceVertices[ j + 1 ];
  84879. state.addFace(
  84880. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  84881. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  84882. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  84883. );
  84884. }
  84885. } else if ( lineFirstChar === 'l' ) {
  84886. var lineParts = line.substring( 1 ).trim().split( ' ' );
  84887. var lineVertices = [], lineUVs = [];
  84888. if ( line.indexOf( '/' ) === - 1 ) {
  84889. lineVertices = lineParts;
  84890. } else {
  84891. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  84892. var parts = lineParts[ li ].split( '/' );
  84893. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  84894. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  84895. }
  84896. }
  84897. state.addLineGeometry( lineVertices, lineUVs );
  84898. } else if ( lineFirstChar === 'p' ) {
  84899. var lineData = line.substr( 1 ).trim();
  84900. var pointData = lineData.split( ' ' );
  84901. state.addPointGeometry( pointData );
  84902. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  84903. // o object_name
  84904. // or
  84905. // g group_name
  84906. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  84907. // var name = result[ 0 ].substr( 1 ).trim();
  84908. var name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  84909. state.startObject( name );
  84910. } else if ( material_use_pattern.test( line ) ) {
  84911. // material
  84912. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  84913. } else if ( material_library_pattern.test( line ) ) {
  84914. // mtl file
  84915. state.materialLibraries.push( line.substring( 7 ).trim() );
  84916. } else if ( map_use_pattern.test( line ) ) {
  84917. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  84918. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  84919. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  84920. } else if ( lineFirstChar === 's' ) {
  84921. result = line.split( ' ' );
  84922. // smooth shading
  84923. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  84924. // but does not define a usemtl for each face set.
  84925. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  84926. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  84927. // where explicit usemtl defines geometry groups.
  84928. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  84929. /*
  84930. * http://paulbourke.net/dataformats/obj/
  84931. * or
  84932. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  84933. *
  84934. * From chapter "Grouping" Syntax explanation "s group_number":
  84935. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  84936. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  84937. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  84938. * than 0."
  84939. */
  84940. if ( result.length > 1 ) {
  84941. var value = result[ 1 ].trim().toLowerCase();
  84942. state.object.smooth = ( value !== '0' && value !== 'off' );
  84943. } else {
  84944. // ZBrush can produce "s" lines #11707
  84945. state.object.smooth = true;
  84946. }
  84947. var material = state.object.currentMaterial();
  84948. if ( material ) material.smooth = state.object.smooth;
  84949. } else {
  84950. // Handle null terminated files without exception
  84951. if ( line === '\0' ) continue;
  84952. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  84953. }
  84954. }
  84955. state.finalize();
  84956. var container = new Group();
  84957. container.materialLibraries = [].concat( state.materialLibraries );
  84958. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  84959. if ( hasPrimitives === true ) {
  84960. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  84961. var object = state.objects[ i ];
  84962. var geometry = object.geometry;
  84963. var materials = object.materials;
  84964. var isLine = ( geometry.type === 'Line' );
  84965. var isPoints = ( geometry.type === 'Points' );
  84966. var hasVertexColors = false;
  84967. // Skip o/g line declarations that did not follow with any faces
  84968. if ( geometry.vertices.length === 0 ) continue;
  84969. var buffergeometry = new BufferGeometry();
  84970. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  84971. if ( geometry.normals.length > 0 ) {
  84972. buffergeometry.setAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  84973. }
  84974. if ( geometry.colors.length > 0 ) {
  84975. hasVertexColors = true;
  84976. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  84977. }
  84978. if ( geometry.hasUVIndices === true ) {
  84979. buffergeometry.setAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  84980. }
  84981. // Create materials
  84982. var createdMaterials = [];
  84983. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  84984. var sourceMaterial = materials[ mi ];
  84985. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  84986. var material = state.materials[ materialHash ];
  84987. if ( this.materials !== null ) {
  84988. material = this.materials.create( sourceMaterial.name );
  84989. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  84990. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  84991. var materialLine = new LineBasicMaterial();
  84992. Material.prototype.copy.call( materialLine, material );
  84993. materialLine.color.copy( material.color );
  84994. material = materialLine;
  84995. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  84996. var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  84997. Material.prototype.copy.call( materialPoints, material );
  84998. materialPoints.color.copy( material.color );
  84999. materialPoints.map = material.map;
  85000. material = materialPoints;
  85001. }
  85002. }
  85003. if ( material === undefined ) {
  85004. if ( isLine ) {
  85005. material = new LineBasicMaterial();
  85006. } else if ( isPoints ) {
  85007. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  85008. } else {
  85009. material = new MeshPhongMaterial();
  85010. }
  85011. material.name = sourceMaterial.name;
  85012. material.flatShading = sourceMaterial.smooth ? false : true;
  85013. material.vertexColors = hasVertexColors;
  85014. state.materials[ materialHash ] = material;
  85015. }
  85016. createdMaterials.push( material );
  85017. }
  85018. // Create mesh
  85019. var mesh;
  85020. if ( createdMaterials.length > 1 ) {
  85021. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  85022. var sourceMaterial = materials[ mi ];
  85023. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  85024. }
  85025. if ( isLine ) {
  85026. mesh = new LineSegments( buffergeometry, createdMaterials );
  85027. } else if ( isPoints ) {
  85028. mesh = new Points( buffergeometry, createdMaterials );
  85029. } else {
  85030. mesh = new Mesh( buffergeometry, createdMaterials );
  85031. }
  85032. } else {
  85033. if ( isLine ) {
  85034. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  85035. } else if ( isPoints ) {
  85036. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  85037. } else {
  85038. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  85039. }
  85040. }
  85041. mesh.name = object.name;
  85042. container.add( mesh );
  85043. }
  85044. } else {
  85045. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  85046. if ( state.vertices.length > 0 ) {
  85047. var material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  85048. var buffergeometry = new BufferGeometry();
  85049. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( state.vertices, 3 ) );
  85050. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  85051. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( state.colors, 3 ) );
  85052. material.vertexColors = true;
  85053. }
  85054. var points = new Points( buffergeometry, material );
  85055. container.add( points );
  85056. }
  85057. }
  85058. return container;
  85059. }
  85060. } );
  85061. return OBJLoader;
  85062. } )();
  85063. /**
  85064. * Loads a Wavefront .mtl file specifying materials
  85065. */
  85066. var MTLLoader = function ( manager ) {
  85067. Loader.call( this, manager );
  85068. };
  85069. MTLLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  85070. constructor: MTLLoader,
  85071. /**
  85072. * Loads and parses a MTL asset from a URL.
  85073. *
  85074. * @param {String} url - URL to the MTL file.
  85075. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  85076. * @param {Function} [onProgress] - Callback for download progress.
  85077. * @param {Function} [onError] - Callback for download errors.
  85078. *
  85079. * @see setPath setResourcePath
  85080. *
  85081. * @note In order for relative texture references to resolve correctly
  85082. * you must call setResourcePath() explicitly prior to load.
  85083. */
  85084. load: function ( url, onLoad, onProgress, onError ) {
  85085. var scope = this;
  85086. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  85087. var loader = new FileLoader( this.manager );
  85088. loader.setPath( this.path );
  85089. loader.setRequestHeader( this.requestHeader );
  85090. loader.setWithCredentials( this.withCredentials );
  85091. loader.load( url, function ( text ) {
  85092. try {
  85093. onLoad( scope.parse( text, path ) );
  85094. } catch ( e ) {
  85095. if ( onError ) {
  85096. onError( e );
  85097. } else {
  85098. console.error( e );
  85099. }
  85100. scope.manager.itemError( url );
  85101. }
  85102. }, onProgress, onError );
  85103. },
  85104. setMaterialOptions: function ( value ) {
  85105. this.materialOptions = value;
  85106. return this;
  85107. },
  85108. /**
  85109. * Parses a MTL file.
  85110. *
  85111. * @param {String} text - Content of MTL file
  85112. * @return {MTLLoader.MaterialCreator}
  85113. *
  85114. * @see setPath setResourcePath
  85115. *
  85116. * @note In order for relative texture references to resolve correctly
  85117. * you must call setResourcePath() explicitly prior to parse.
  85118. */
  85119. parse: function ( text, path ) {
  85120. var lines = text.split( '\n' );
  85121. var info = {};
  85122. var delimiter_pattern = /\s+/;
  85123. var materialsInfo = {};
  85124. for ( var i = 0; i < lines.length; i ++ ) {
  85125. var line = lines[ i ];
  85126. line = line.trim();
  85127. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  85128. // Blank line or comment ignore
  85129. continue;
  85130. }
  85131. var pos = line.indexOf( ' ' );
  85132. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  85133. key = key.toLowerCase();
  85134. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  85135. value = value.trim();
  85136. if ( key === 'newmtl' ) {
  85137. // New material
  85138. info = { name: value };
  85139. materialsInfo[ value ] = info;
  85140. } else {
  85141. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  85142. var ss = value.split( delimiter_pattern, 3 );
  85143. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  85144. } else {
  85145. info[ key ] = value;
  85146. }
  85147. }
  85148. }
  85149. var materialCreator = new MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  85150. materialCreator.setCrossOrigin( this.crossOrigin );
  85151. materialCreator.setManager( this.manager );
  85152. materialCreator.setMaterials( materialsInfo );
  85153. return materialCreator;
  85154. }
  85155. } );
  85156. /**
  85157. * Create a new MTLLoader.MaterialCreator
  85158. * @param baseUrl - Url relative to which textures are loaded
  85159. * @param options - Set of options on how to construct the materials
  85160. * side: Which side to apply the material
  85161. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  85162. * wrap: What type of wrapping to apply for textures
  85163. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  85164. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  85165. * Default: false, assumed to be already normalized
  85166. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  85167. * Default: false
  85168. * @constructor
  85169. */
  85170. MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  85171. this.baseUrl = baseUrl || '';
  85172. this.options = options;
  85173. this.materialsInfo = {};
  85174. this.materials = {};
  85175. this.materialsArray = [];
  85176. this.nameLookup = {};
  85177. this.side = ( this.options && this.options.side ) ? this.options.side : FrontSide;
  85178. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : RepeatWrapping;
  85179. };
  85180. MTLLoader.MaterialCreator.prototype = {
  85181. constructor: MTLLoader.MaterialCreator,
  85182. crossOrigin: 'anonymous',
  85183. setCrossOrigin: function ( value ) {
  85184. this.crossOrigin = value;
  85185. return this;
  85186. },
  85187. setManager: function ( value ) {
  85188. this.manager = value;
  85189. },
  85190. setMaterials: function ( materialsInfo ) {
  85191. this.materialsInfo = this.convert( materialsInfo );
  85192. this.materials = {};
  85193. this.materialsArray = [];
  85194. this.nameLookup = {};
  85195. },
  85196. convert: function ( materialsInfo ) {
  85197. if ( ! this.options ) return materialsInfo;
  85198. var converted = {};
  85199. for ( var mn in materialsInfo ) {
  85200. // Convert materials info into normalized form based on options
  85201. var mat = materialsInfo[ mn ];
  85202. var covmat = {};
  85203. converted[ mn ] = covmat;
  85204. for ( var prop in mat ) {
  85205. var save = true;
  85206. var value = mat[ prop ];
  85207. var lprop = prop.toLowerCase();
  85208. switch ( lprop ) {
  85209. case 'kd':
  85210. case 'ka':
  85211. case 'ks':
  85212. // Diffuse color (color under white light) using RGB values
  85213. if ( this.options && this.options.normalizeRGB ) {
  85214. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  85215. }
  85216. if ( this.options && this.options.ignoreZeroRGBs ) {
  85217. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  85218. // ignore
  85219. save = false;
  85220. }
  85221. }
  85222. break;
  85223. default:
  85224. break;
  85225. }
  85226. if ( save ) {
  85227. covmat[ lprop ] = value;
  85228. }
  85229. }
  85230. }
  85231. return converted;
  85232. },
  85233. preload: function () {
  85234. for ( var mn in this.materialsInfo ) {
  85235. this.create( mn );
  85236. }
  85237. },
  85238. getIndex: function ( materialName ) {
  85239. return this.nameLookup[ materialName ];
  85240. },
  85241. getAsArray: function () {
  85242. var index = 0;
  85243. for ( var mn in this.materialsInfo ) {
  85244. this.materialsArray[ index ] = this.create( mn );
  85245. this.nameLookup[ mn ] = index;
  85246. index ++;
  85247. }
  85248. return this.materialsArray;
  85249. },
  85250. create: function ( materialName ) {
  85251. if ( this.materials[ materialName ] === undefined ) {
  85252. this.createMaterial_( materialName );
  85253. }
  85254. return this.materials[ materialName ];
  85255. },
  85256. createMaterial_: function ( materialName ) {
  85257. // Create material
  85258. var scope = this;
  85259. var mat = this.materialsInfo[ materialName ];
  85260. var params = {
  85261. name: materialName,
  85262. side: this.side
  85263. };
  85264. function resolveURL( baseUrl, url ) {
  85265. if ( typeof url !== 'string' || url === '' )
  85266. return '';
  85267. // Absolute URL
  85268. if ( /^https?:\/\//i.test( url ) ) return url;
  85269. return baseUrl + url;
  85270. }
  85271. function setMapForType( mapType, value ) {
  85272. if ( params[ mapType ] ) return; // Keep the first encountered texture
  85273. var texParams = scope.getTextureParams( value, params );
  85274. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  85275. map.repeat.copy( texParams.scale );
  85276. map.offset.copy( texParams.offset );
  85277. map.wrapS = scope.wrap;
  85278. map.wrapT = scope.wrap;
  85279. params[ mapType ] = map;
  85280. }
  85281. for ( var prop in mat ) {
  85282. var value = mat[ prop ];
  85283. var n;
  85284. if ( value === '' ) continue;
  85285. switch ( prop.toLowerCase() ) {
  85286. // Ns is material specular exponent
  85287. case 'kd':
  85288. // Diffuse color (color under white light) using RGB values
  85289. params.color = new Color().fromArray( value );
  85290. break;
  85291. case 'ks':
  85292. // Specular color (color when light is reflected from shiny surface) using RGB values
  85293. //params.specular = new Color().fromArray( value );
  85294. //console.log('specular',value)
  85295. break;
  85296. case 'ke':
  85297. // Emissive using RGB values
  85298. params.emissive = new Color().fromArray( value );
  85299. break;
  85300. case 'map_kd':
  85301. // Diffuse texture map
  85302. setMapForType( 'map', value );
  85303. break;
  85304. case 'map_ks':
  85305. // Specular map
  85306. setMapForType( 'specularMap', value );
  85307. break;
  85308. case 'map_ke':
  85309. // Emissive map
  85310. setMapForType( 'emissiveMap', value );
  85311. break;
  85312. case 'norm':
  85313. setMapForType( 'normalMap', value );
  85314. break;
  85315. case 'map_bump':
  85316. case 'bump':
  85317. // Bump texture map
  85318. setMapForType( 'bumpMap', value );
  85319. break;
  85320. case 'map_d':
  85321. // Alpha map
  85322. setMapForType( 'alphaMap', value );
  85323. params.transparent = true;
  85324. break;
  85325. case 'ns':
  85326. // The specular exponent (defines the focus of the specular highlight)
  85327. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  85328. //params.shininess = parseFloat( value );
  85329. //console.log('shininess',value)
  85330. break;
  85331. case 'd':
  85332. n = parseFloat( value );
  85333. if ( n < 1 ) {
  85334. params.opacity = n;
  85335. params.transparent = true;
  85336. }
  85337. break;
  85338. case 'tr':
  85339. n = parseFloat( value );
  85340. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  85341. if ( n > 0 ) {
  85342. params.opacity = 1 - n;
  85343. params.transparent = true;
  85344. }
  85345. break;
  85346. default:
  85347. break;
  85348. }
  85349. }
  85350. this.materials[ materialName ] = new MeshStandardMaterial( params );//MeshPhongMaterial( params );
  85351. return this.materials[ materialName ];
  85352. },
  85353. getTextureParams: function ( value, matParams ) {
  85354. var texParams = {
  85355. scale: new Vector2$1( 1, 1 ),
  85356. offset: new Vector2$1( 0, 0 )
  85357. };
  85358. var items = value.split( /\s+/ );
  85359. var pos;
  85360. pos = items.indexOf( '-bm' );
  85361. if ( pos >= 0 ) {
  85362. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  85363. items.splice( pos, 2 );
  85364. }
  85365. pos = items.indexOf( '-s' );
  85366. if ( pos >= 0 ) {
  85367. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85368. items.splice( pos, 4 ); // we expect 3 parameters here!
  85369. }
  85370. pos = items.indexOf( '-o' );
  85371. if ( pos >= 0 ) {
  85372. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85373. items.splice( pos, 4 ); // we expect 3 parameters here!
  85374. }
  85375. texParams.url = items.join( ' ' ).trim();
  85376. return texParams;
  85377. },
  85378. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  85379. var texture;
  85380. var manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  85381. var loader = manager.getHandler( url );
  85382. if ( loader === null ) {
  85383. loader = new TextureLoader( manager );
  85384. }
  85385. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  85386. texture = loader.load( url, onLoad, onProgress, onError );
  85387. if ( mapping !== undefined ) texture.mapping = mapping;
  85388. return texture;
  85389. }
  85390. };
  85391. /**
  85392. * @author alteredq / http://alteredqualia.com/
  85393. */
  85394. let Pass = function () {
  85395. // if set to true, the pass is processed by the composer
  85396. this.enabled = true;
  85397. // if set to true, the pass indicates to swap read and write buffer after rendering
  85398. this.needsSwap = true;
  85399. // if set to true, the pass clears its buffer before rendering
  85400. this.clear = false;
  85401. // if set to true, the result of the pass is rendered to screen
  85402. this.renderToScreen = false;
  85403. };
  85404. Object.assign( Pass.prototype, {
  85405. setSize: function ( width, height ) {},
  85406. render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
  85407. console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
  85408. }
  85409. } );
  85410. let ShaderPass = function ( shader, textureID ) {
  85411. Pass.call( this );
  85412. this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse";
  85413. if ( shader instanceof ShaderMaterial ) {
  85414. this.uniforms = shader.uniforms;
  85415. this.material = shader;
  85416. } else if ( shader ) {
  85417. this.uniforms = UniformsUtils.clone( shader.uniforms );
  85418. this.material = new ShaderMaterial( {
  85419. defines: Object.assign( {}, shader.defines ),
  85420. uniforms: this.uniforms,
  85421. vertexShader: shader.vertexShader,
  85422. fragmentShader: shader.fragmentShader,
  85423. transparent:true,//add
  85424. } );
  85425. }
  85426. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85427. this.scene = new Scene();
  85428. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  85429. this.quad.frustumCulled = false; // Avoid getting clipped
  85430. this.scene.add( this.quad );
  85431. };
  85432. ShaderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85433. constructor: ShaderPass,
  85434. render: function(scene,camera, renderer, writeBuffer, readBuffer, delta, maskActive ) {
  85435. let oldTarget = renderer.getRenderTarget();
  85436. /* if(this.readTarget){ //add
  85437. readBuffer = oldTarget
  85438. } */
  85439. if ( this.uniforms[ this.textureID ] ) {
  85440. this.uniforms[ this.textureID ].value = readBuffer.texture;
  85441. }
  85442. this.quad.material = this.material;
  85443. if ( this.renderToScreen ) {
  85444. renderer.render( this.scene, this.camera );
  85445. } else {
  85446. renderer.setRenderTarget(writeBuffer);
  85447. if(this.clear) renderer.clear();
  85448. renderer.render( this.scene, this.camera );
  85449. renderer.setRenderTarget(oldTarget);
  85450. }
  85451. }
  85452. } );
  85453. /**
  85454. * @author alteredq / http://alteredqualia.com/
  85455. *
  85456. * Full-screen textured quad shader
  85457. */
  85458. let CopyShader = {
  85459. uniforms: {
  85460. "tDiffuse": { value: null },
  85461. "opacity": { value: 1.0 }
  85462. },
  85463. vertexShader: [
  85464. "varying vec2 vUv;",
  85465. "void main() {",
  85466. "vUv = uv;",
  85467. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  85468. "}"
  85469. ].join( "\n" ),
  85470. fragmentShader: [
  85471. "uniform float opacity;",
  85472. "uniform sampler2D tDiffuse;",
  85473. "varying vec2 vUv;",
  85474. "void main() {",
  85475. "vec4 texel = texture2D( tDiffuse, vUv );", //如果开启premultipliedAlpha用这个,否则用注释的
  85476. "gl_FragColor = opacity * texel;",
  85477. //"gl_FragColor = texture2D( tDiffuse, vUv );",
  85478. //"gl_FragColor.a *= opacity;",
  85479. "}"
  85480. ].join( "\n" )
  85481. };
  85482. /**
  85483. *
  85484. * Supersample Anti-Aliasing Render Pass
  85485. *
  85486. * @author bhouston / http://clara.io/
  85487. *
  85488. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  85489. *
  85490. * References: https://en.wikipedia.org/wiki/Supersampling
  85491. *
  85492. */
  85493. //较为原始的一种抗锯齿 (超级采样抗锯齿)
  85494. let SSAARenderPass = function ( clearColor, clearAlpha ) {
  85495. Pass.call( this );
  85496. //this.scene //= scene;
  85497. //this.camera = camera;
  85498. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  85499. this.unbiased = true;
  85500. // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
  85501. this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
  85502. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  85503. this.renderUniforms = {
  85504. bgTex : {value:null},
  85505. outlineTex : {value:null},
  85506. opacity : {value:1},
  85507. };
  85508. this.renderMat = new ShaderMaterial({
  85509. uniforms: this.renderUniforms,
  85510. vertexShader: CopyShader.vertexShader,
  85511. /* fragmentShader: CopyShader.fragmentShader, */
  85512. fragmentShader: `
  85513. uniform sampler2D bgTex;
  85514. uniform sampler2D outlineTex;
  85515. uniform float opacity;
  85516. varying vec2 vUv;
  85517. void main() {
  85518. vec4 color1 = texture2D( bgTex, vUv );
  85519. vec4 color2 = texture2D( outlineTex, vUv );
  85520. gl_FragColor = opacity * mix(color1, color2, color2.a) ;
  85521. }
  85522. `,
  85523. premultipliedAlpha: true,
  85524. blending: AdditiveBlending,
  85525. depthTest: false,
  85526. depthWrite: false,
  85527. transparent: true
  85528. });
  85529. this.renderMat2 = new ShaderMaterial({
  85530. uniforms: UniformsUtils.clone(CopyShader.uniforms) ,
  85531. vertexShader: CopyShader.vertexShader,
  85532. fragmentShader:`uniform float opacity;
  85533. uniform sampler2D tDiffuse;
  85534. varying vec2 vUv;
  85535. void main() {
  85536. vec4 texel = texture2D( tDiffuse, vUv );
  85537. if(texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0){
  85538. discard;
  85539. }else{
  85540. gl_FragColor = opacity * texel;
  85541. }
  85542. }
  85543. ` ,
  85544. depthTest: false,
  85545. depthWrite: false,
  85546. transparent: true
  85547. });
  85548. ////////////////////
  85549. /* this.renderMat.blendSrc = THREE.OneFactor //即将写入缓冲区的颜色。
  85550. this.renderMat.blendDst = THREE.OneFactor //缓冲区已经存在的颜色
  85551. this.renderMat.blendEquation = THREE.AddEquation;
  85552. this.renderMat.blendEquationAlpha = THREE.AddEquation;
  85553. this.renderMat.blendDstAlpha = THREE.SrcAlphaFactor
  85554. this.renderMat.blendSrcAlpha = THREE.SrcAlphaFactor */
  85555. this.camera2 = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85556. this.scene2 = new Scene();
  85557. this.quad2 = new Mesh( new PlaneBufferGeometry( 2, 2 ), this.renderMat/* this.copyMaterial */ );
  85558. this.quad2.frustumCulled = false; // Avoid getting clipped
  85559. this.scene2.add( this.quad2 );
  85560. this.copyPass = new ShaderPass( CopyShader );
  85561. this.copyPass.renderToScreen = true;
  85562. };
  85563. SSAARenderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85564. constructor: SSAARenderPass,
  85565. dispose: function () {
  85566. if ( this.sampleRenderTarget ) {
  85567. this.sampleRenderTarget.dispose();
  85568. this.sampleRenderTarget = null;
  85569. }
  85570. },
  85571. setSize: function ( width, height ) {
  85572. if ( this.sampleRenderTarget ) this.sampleRenderTarget.setSize( width, height );
  85573. this.childPass && this.childPass.setSize(width, height);
  85574. },
  85575. addPass: function (pass){
  85576. this.childPass = pass;
  85577. },
  85578. render: function (scene, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  85579. if(this.useCopy ){
  85580. scene = this.copyPass.scene; camera = this.copyPass.camera;
  85581. }
  85582. if ( ! this.sampleRenderTarget ) {
  85583. this.sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat } );
  85584. this.sampleRenderTarget.texture.name = "SSAARenderPass.sample";
  85585. }
  85586. var jitterOffsets = SSAARenderPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  85587. var autoClear = renderer.autoClear;
  85588. renderer.autoClear = false;
  85589. var oldClearColor = renderer.getClearColor(new Color).getHex();
  85590. var oldClearAlpha = renderer.getClearAlpha();
  85591. renderer.setClearColor( this.clearColor, this.clearAlpha );
  85592. var baseSampleWeight = 1.0 / jitterOffsets.length;
  85593. var roundingRange = 1 / 32;
  85594. //this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
  85595. let oldTarget = renderer.getRenderTarget();
  85596. if(oldTarget){
  85597. if(oldTarget.scissorTest){
  85598. var width = oldTarget.scissor.w, height = oldTarget.scissor.z;
  85599. }else {
  85600. var width = oldTarget.width, height = oldTarget.height;
  85601. }
  85602. }else {
  85603. var width = readBuffer.width, height = readBuffer.height;
  85604. }
  85605. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  85606. let opa = 0;
  85607. for ( var i = 0; i < jitterOffsets.length; i ++ ) {
  85608. var jitterOffset = jitterOffsets[ i ];
  85609. if ( camera.setViewOffset ) {
  85610. camera.setViewOffset( width, height,
  85611. jitterOffset[ 0 ] * 0.0625 , jitterOffset[ 1 ] * 0.0625 , // 0.0625 = 1 / 16
  85612. width, height );
  85613. }
  85614. var sampleWeight = baseSampleWeight;
  85615. if ( this.unbiased ) {//更柔和
  85616. var uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  85617. sampleWeight += roundingRange * uniformCenteredDistribution;
  85618. }
  85619. renderer.setRenderTarget(this.sampleRenderTarget);
  85620. renderer.clear();
  85621. if(this.useCopy){
  85622. this.copyPass.render(scene,camera, renderer, writeBuffer, readBuffer );
  85623. }else {
  85624. if(renderFun){
  85625. renderFun({target : this.sampleRenderTarget});
  85626. }else {
  85627. renderer.render( scene, camera );
  85628. }
  85629. }
  85630. renderer.setRenderTarget(oldTarget);
  85631. //---------------------
  85632. //获取outline tex
  85633. let hasOutline = this.childPass && this.childPass.render(scene, camera, renderer, writeBuffer, readBuffer, null, renderFun );
  85634. //合成到该材质
  85635. this.renderUniforms[ "bgTex" ].value = this.sampleRenderTarget.texture;
  85636. this.renderUniforms[ "outlineTex" ].value = hasOutline ? readBuffer.texture : null;
  85637. this.renderUniforms[ "opacity" ].value = sampleWeight;
  85638. /* console.log('sampleWeight', sampleWeight)
  85639. opa += sampleWeight */
  85640. if(!this.renderToScreen){
  85641. renderer.setRenderTarget(writeBuffer);
  85642. }
  85643. if(i === 0 ){
  85644. renderer.setClearColor( 0x000000, 0 ); //叠加前颜色必须0
  85645. renderer.clear();
  85646. }
  85647. renderer.render( this.scene2, this.camera2); // , this.renderToScreen ? null : writeBuffer, ( i === 0 )
  85648. if(!this.renderToScreen){
  85649. renderer.setRenderTarget(oldTarget);
  85650. }
  85651. //if(i==2)break;
  85652. }
  85653. //console.log('sum:',opa)
  85654. if ( camera.clearViewOffset )camera.clearViewOffset();
  85655. //renderer.setRenderTarget(readBuffer)
  85656. //renderer.setClearColor( 0x000000, 0 );
  85657. //renderer.clear()
  85658. /* this.quad2.material = this.renderMat2
  85659. this.renderMat2.uniforms.tDiffuse.value = writeBuffer.texture;
  85660. renderer.render( this.scene2, this.camera2);
  85661. this.quad2.material = this.renderMat */
  85662. //renderer.setRenderTarget(oldTarget)
  85663. renderer.autoClear = autoClear;
  85664. renderer.setClearColor( oldClearColor, oldClearAlpha );
  85665. /* 试了好几次,测量线的透明度还是还原不了。 clearAlpha十分影响结果。
  85666. 因为绘制测量线需要背景透明。 或许可以先全部绘制完后,再 copyshader中 抗锯齿?
  85667. 另外会有黑边。
  85668. */
  85669. }
  85670. } );
  85671. // These jitter vectors are specified in integers because it is easier.
  85672. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  85673. // before being used, thus these integers need to be scaled by 1/16.
  85674. //
  85675. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  85676. SSAARenderPass.JitterVectors = [
  85677. [
  85678. [ 0, 0 ]
  85679. ],
  85680. [
  85681. [ 4, 4 ], [ - 4, - 4 ]
  85682. ],
  85683. [
  85684. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  85685. ],
  85686. [
  85687. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  85688. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  85689. ],
  85690. [
  85691. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  85692. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  85693. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  85694. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  85695. ],
  85696. [
  85697. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  85698. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  85699. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  85700. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  85701. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  85702. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  85703. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  85704. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  85705. ]
  85706. ];
  85707. class MaskPass extends Pass {
  85708. constructor( scene, camera ) {
  85709. super();
  85710. this.scene = scene;
  85711. this.camera = camera;
  85712. this.clear = true;
  85713. this.needsSwap = false;
  85714. this.inverse = false;
  85715. }
  85716. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  85717. const context = renderer.getContext();
  85718. const state = renderer.state;
  85719. // don't update color or depth
  85720. state.buffers.color.setMask( false );
  85721. state.buffers.depth.setMask( false );
  85722. // lock buffers
  85723. state.buffers.color.setLocked( true );
  85724. state.buffers.depth.setLocked( true );
  85725. // set up stencil
  85726. let writeValue, clearValue;
  85727. if ( this.inverse ) {
  85728. writeValue = 0;
  85729. clearValue = 1;
  85730. } else {
  85731. writeValue = 1;
  85732. clearValue = 0;
  85733. }
  85734. state.buffers.stencil.setTest( true );
  85735. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  85736. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  85737. state.buffers.stencil.setClear( clearValue );
  85738. state.buffers.stencil.setLocked( true );
  85739. // draw into the stencil buffer
  85740. renderer.setRenderTarget( readBuffer );
  85741. if ( this.clear ) renderer.clear();
  85742. renderer.render( this.scene, this.camera );
  85743. renderer.setRenderTarget( writeBuffer );
  85744. if ( this.clear ) renderer.clear();
  85745. renderer.render( this.scene, this.camera );
  85746. // unlock color and depth buffer for subsequent rendering
  85747. state.buffers.color.setLocked( false );
  85748. state.buffers.depth.setLocked( false );
  85749. // only render where stencil is set to 1
  85750. state.buffers.stencil.setLocked( false );
  85751. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  85752. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  85753. state.buffers.stencil.setLocked( true );
  85754. }
  85755. }
  85756. class ClearMaskPass extends Pass {
  85757. constructor() {
  85758. super();
  85759. this.needsSwap = false;
  85760. }
  85761. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  85762. renderer.state.buffers.stencil.setLocked( false );
  85763. renderer.state.buffers.stencil.setTest( false );
  85764. }
  85765. }
  85766. /**
  85767. * @author alteredq / http://alteredqualia.com/
  85768. */
  85769. var EffectComposer = function ( renderer, renderTarget ) {
  85770. this.renderer = renderer;
  85771. if ( renderTarget === undefined ) {
  85772. var parameters = {
  85773. minFilter: LinearFilter,
  85774. magFilter: LinearFilter,
  85775. format: RGBAFormat,
  85776. stencilBuffer: false,
  85777. };
  85778. var size = renderer.getDrawingBufferSize(new Vector2$1);
  85779. renderTarget = new WebGLRenderTarget( size.width, size.height , parameters );
  85780. renderTarget.texture.name = 'EffectComposer.rt1';
  85781. }
  85782. this.renderTarget1 = renderTarget;
  85783. this.renderTarget2 = renderTarget.clone();
  85784. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  85785. this.writeBuffer = this.renderTarget1;
  85786. this.readBuffer = this.renderTarget2;
  85787. this.passes = [];
  85788. // dependencies
  85789. /* if ( THREE.CopyShader === undefined ) {
  85790. console.error( 'THREE.EffectComposer relies on THREE.CopyShader' );
  85791. }
  85792. if ( THREE.ShaderPass === undefined ) {
  85793. console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' );
  85794. } */
  85795. this.copyPass = new ShaderPass( CopyShader );
  85796. };
  85797. Object.assign( EffectComposer.prototype, {
  85798. swapBuffers: function () {
  85799. var tmp = this.readBuffer;
  85800. this.readBuffer = this.writeBuffer;
  85801. this.writeBuffer = tmp;
  85802. },
  85803. addPass: function ( pass ) {
  85804. this.passes.push( pass );
  85805. var size = this.renderer.getDrawingBufferSize(new Vector2$1);
  85806. pass.setSize( size.width, size.height );
  85807. },
  85808. removePass: function(pass){ //add
  85809. let index = this.passes.indexOf(pass);
  85810. index > -1 && this.passes.splice(index,1);
  85811. },
  85812. insertPass: function ( pass, index ) {
  85813. this.passes.splice( index, 0, pass );
  85814. },
  85815. render: function ( scene, camera, viewports, renderFun ) {
  85816. var maskActive = false;
  85817. let passes = this.passes.filter(e=>e.enabled);
  85818. var pass, i, il = passes.length;
  85819. if(this.readTarget){ //add 使用当前renderTarget中的像素
  85820. this.copyPass.render(scene, this.renderer, this.readBuffer, this.renderer.getRenderTarget() );
  85821. }
  85822. for ( i = 0; i < il; i ++ ) {
  85823. pass = passes[ i ];
  85824. //if(i == il-1)pass.renderToScreen = true//
  85825. pass.render( scene, camera, viewports, this.renderer, this.writeBuffer, this.readBuffer, maskActive, renderFun );
  85826. if ( pass.needsSwap ) {
  85827. if ( maskActive ) {
  85828. var context = this.renderer.context;
  85829. context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
  85830. this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer );// delta
  85831. context.stencilFunc( context.EQUAL, 1, 0xffffffff );
  85832. }
  85833. this.swapBuffers();
  85834. }
  85835. if ( MaskPass !== undefined ) {
  85836. if ( pass instanceof MaskPass ) {
  85837. maskActive = true;
  85838. } else if ( pass instanceof ClearMaskPass ) {
  85839. maskActive = false;
  85840. }
  85841. }
  85842. }
  85843. //add
  85844. if(!pass.renderToScreen){ //最后一个如果没有绘制到屏幕or target上
  85845. this.copyPass.renderToScreen = true;
  85846. this.copyPass.render(null,null, this.renderer, this.writeBuffer, this.readBuffer);
  85847. }
  85848. },
  85849. reset: function ( renderTarget ) {
  85850. if ( renderTarget === undefined ) {
  85851. var size = this.renderer.getDrawingBufferSize(new Vector2$1);
  85852. renderTarget = this.renderTarget1.clone();
  85853. renderTarget.setSize( size.width, size.height );
  85854. }
  85855. this.renderTarget1.dispose();
  85856. this.renderTarget2.dispose();
  85857. this.renderTarget1 = renderTarget;
  85858. this.renderTarget2 = renderTarget.clone();
  85859. this.writeBuffer = this.renderTarget1;
  85860. this.readBuffer = this.renderTarget2;
  85861. },
  85862. setSize: function ( width, height, scaleRatio ) {
  85863. scaleRatio = scaleRatio || 1;
  85864. this.renderTarget1.setSize( width * scaleRatio , height * scaleRatio );
  85865. this.renderTarget2.setSize( width * scaleRatio, height * scaleRatio );
  85866. for ( var i = 0; i < this.passes.length; i ++ ) {
  85867. this.passes[ i ].setSize( width * scaleRatio, height * scaleRatio );
  85868. }
  85869. }
  85870. } );
  85871. /**
  85872. * @author alteredq / http://alteredqualia.com/
  85873. */
  85874. class RenderPass extends Pass {
  85875. constructor( overrideMaterial, clearColor, clearAlpha ) {
  85876. super();
  85877. /* this.scene = scene;
  85878. this.camera = camera; */
  85879. this.overrideMaterial = overrideMaterial;
  85880. this.clearColor = clearColor;
  85881. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  85882. this.clear = true;
  85883. this.clearDepth = false;
  85884. this.needsSwap = false;
  85885. this._oldClearColor = new Color();
  85886. }
  85887. render(scene, camera, renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  85888. const oldAutoClear = renderer.autoClear;
  85889. renderer.autoClear = false;
  85890. let oldClearAlpha, oldOverrideMaterial;
  85891. if ( this.overrideMaterial !== undefined ) {
  85892. oldOverrideMaterial = this.scene.overrideMaterial;
  85893. scene.overrideMaterial = this.overrideMaterial;
  85894. }
  85895. if ( this.clearColor ) {
  85896. renderer.getClearColor( this._oldClearColor );
  85897. oldClearAlpha = renderer.getClearAlpha();
  85898. renderer.setClearColor( this.clearColor, this.clearAlpha );
  85899. }
  85900. if ( this.clearDepth ) {
  85901. renderer.clearDepth();
  85902. }
  85903. let oldTarget = renderer.getRenderTarget();
  85904. if(!this.renderToScreen)renderer.setRenderTarget( readBuffer );
  85905. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  85906. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  85907. renderer.render( scene, camera );
  85908. if(!this.renderToScreen)renderer.setRenderTarget( oldTarget );
  85909. if ( this.clearColor ) {
  85910. renderer.setClearColor( this._oldClearColor, oldClearAlpha );
  85911. }
  85912. if ( this.overrideMaterial !== undefined ) {
  85913. scene.overrideMaterial = oldOverrideMaterial;
  85914. }
  85915. renderer.autoClear = oldAutoClear;
  85916. }
  85917. }
  85918. /**
  85919. * NVIDIA FXAA by Timothy Lottes
  85920. * https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf
  85921. * - WebGL port by @supereggbert
  85922. * http://www.glge.org/demos/fxaa/
  85923. * Further improved by Daniel Sturk
  85924. */
  85925. const FXAAShader = {
  85926. uniforms: {
  85927. 'tDiffuse': { value: null },
  85928. 'resolution': { value: new Vector2$1( 1 / 1024, 1 / 512 ) }
  85929. },
  85930. vertexShader: /* glsl */`
  85931. varying vec2 vUv;
  85932. void main() {
  85933. vUv = uv;
  85934. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  85935. }`,
  85936. fragmentShader: `
  85937. precision highp float;
  85938. uniform sampler2D tDiffuse;
  85939. uniform vec2 resolution;
  85940. varying vec2 vUv;
  85941. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  85942. //----------------------------------------------------------------------------------
  85943. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  85944. // SDK Version: v3.00
  85945. // Email: gameworks@nvidia.com
  85946. // Site: http://developer.nvidia.com/
  85947. //
  85948. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  85949. //
  85950. // Redistribution and use in source and binary forms, with or without
  85951. // modification, are permitted provided that the following conditions
  85952. // are met:
  85953. // * Redistributions of source code must retain the above copyright
  85954. // notice, this list of conditions and the following disclaimer.
  85955. // * Redistributions in binary form must reproduce the above copyright
  85956. // notice, this list of conditions and the following disclaimer in the
  85957. // documentation and/or other materials provided with the distribution.
  85958. // * Neither the name of NVIDIA CORPORATION nor the names of its
  85959. // contributors may be used to endorse or promote products derived
  85960. // from this software without specific prior written permission.
  85961. //
  85962. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  85963. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  85964. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  85965. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  85966. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  85967. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  85968. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  85969. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  85970. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  85971. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  85972. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  85973. //
  85974. //----------------------------------------------------------------------------------
  85975. #ifndef FXAA_DISCARD
  85976. //
  85977. // Only valid for PC OpenGL currently.
  85978. // Probably will not work when FXAA_GREEN_AS_LUMA = 1.
  85979. //
  85980. // 1 = Use discard on pixels which don't need AA.
  85981. // For APIs which enable concurrent TEX+ROP from same surface.
  85982. // 0 = Return unchanged color on pixels which don't need AA.
  85983. //
  85984. #define FXAA_DISCARD 0
  85985. #endif
  85986. /*--------------------------------------------------------------------------*/
  85987. #define FxaaTexTop(t, p) texture2D(t, p, -100.0)
  85988. #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), -100.0)
  85989. /*--------------------------------------------------------------------------*/
  85990. #define NUM_SAMPLES 5
  85991. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  85992. float contrast( vec4 a, vec4 b ) {
  85993. vec4 diff = abs( a - b );
  85994. return max( max( max( diff.r, diff.g ), diff.b ), diff.a );
  85995. }
  85996. /*============================================================================
  85997. FXAA3 QUALITY - PC
  85998. ============================================================================*/
  85999. /*--------------------------------------------------------------------------*/
  86000. vec4 FxaaPixelShader(
  86001. vec2 posM,
  86002. sampler2D tex,
  86003. vec2 fxaaQualityRcpFrame,
  86004. float fxaaQualityEdgeThreshold,
  86005. float fxaaQualityinvEdgeThreshold
  86006. ) {
  86007. vec4 rgbaM = FxaaTexTop(tex, posM);
  86008. vec4 rgbaS = FxaaTexOff(tex, posM, vec2( 0.0, 1.0), fxaaQualityRcpFrame.xy);
  86009. vec4 rgbaE = FxaaTexOff(tex, posM, vec2( 1.0, 0.0), fxaaQualityRcpFrame.xy);
  86010. vec4 rgbaN = FxaaTexOff(tex, posM, vec2( 0.0,-1.0), fxaaQualityRcpFrame.xy);
  86011. vec4 rgbaW = FxaaTexOff(tex, posM, vec2(-1.0, 0.0), fxaaQualityRcpFrame.xy);
  86012. // . S .
  86013. // W M E
  86014. // . N .
  86015. bool earlyExit = max( max( max(
  86016. contrast( rgbaM, rgbaN ),
  86017. contrast( rgbaM, rgbaS ) ),
  86018. contrast( rgbaM, rgbaE ) ),
  86019. contrast( rgbaM, rgbaW ) )
  86020. < fxaaQualityEdgeThreshold;
  86021. // . 0 .
  86022. // 0 0 0
  86023. // . 0 .
  86024. #if (FXAA_DISCARD == 1)
  86025. if(earlyExit) FxaaDiscard;
  86026. #else
  86027. if(earlyExit) return rgbaM;
  86028. #endif
  86029. float contrastN = contrast( rgbaM, rgbaN );
  86030. float contrastS = contrast( rgbaM, rgbaS );
  86031. float contrastE = contrast( rgbaM, rgbaE );
  86032. float contrastW = contrast( rgbaM, rgbaW );
  86033. float relativeVContrast = ( contrastN + contrastS ) - ( contrastE + contrastW );
  86034. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  86035. bool horzSpan = relativeVContrast > 0.;
  86036. // . 1 .
  86037. // 0 0 0
  86038. // . 1 .
  86039. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  86040. if( abs( relativeVContrast ) < .3 ) {
  86041. // locate the edge
  86042. vec2 dirToEdge;
  86043. dirToEdge.x = contrastE > contrastW ? 1. : -1.;
  86044. dirToEdge.y = contrastS > contrastN ? 1. : -1.;
  86045. // . 2 . . 1 .
  86046. // 1 0 2 ~= 0 0 1
  86047. // . 1 . . 0 .
  86048. // tap 2 pixels and see which ones are "outside" the edge, to
  86049. // determine if the edge is vertical or horizontal
  86050. vec4 rgbaAlongH = FxaaTexOff(tex, posM, vec2( dirToEdge.x, -dirToEdge.y ), fxaaQualityRcpFrame.xy);
  86051. float matchAlongH = contrast( rgbaM, rgbaAlongH );
  86052. // . 1 .
  86053. // 0 0 1
  86054. // . 0 H
  86055. vec4 rgbaAlongV = FxaaTexOff(tex, posM, vec2( -dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy);
  86056. float matchAlongV = contrast( rgbaM, rgbaAlongV );
  86057. // V 1 .
  86058. // 0 0 1
  86059. // . 0 .
  86060. relativeVContrast = matchAlongV - matchAlongH;
  86061. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  86062. if( abs( relativeVContrast ) < .3 ) { // 45 deg edge
  86063. // 1 1 .
  86064. // 0 0 1
  86065. // . 0 1
  86066. // do a simple blur
  86067. return mix(
  86068. rgbaM,
  86069. (rgbaN + rgbaS + rgbaE + rgbaW) * .25,
  86070. .4
  86071. );
  86072. }
  86073. horzSpan = relativeVContrast > 0.;
  86074. }
  86075. if(!horzSpan) rgbaN = rgbaW;
  86076. if(!horzSpan) rgbaS = rgbaE;
  86077. // . 0 . 1
  86078. // 1 0 1 -> 0
  86079. // . 0 . 1
  86080. bool pairN = contrast( rgbaM, rgbaN ) > contrast( rgbaM, rgbaS );
  86081. if(!pairN) rgbaN = rgbaS;
  86082. vec2 offNP;
  86083. offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;
  86084. offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;
  86085. bool doneN = false;
  86086. bool doneP = false;
  86087. float nDist = 0.;
  86088. float pDist = 0.;
  86089. vec2 posN = posM;
  86090. vec2 posP = posM;
  86091. int iterationsUsed = 0;
  86092. int iterationsUsedN = 0;
  86093. int iterationsUsedP = 0;
  86094. for( int i = 0; i < NUM_SAMPLES; i++ ) {
  86095. iterationsUsed = i;
  86096. float increment = float(i + 1);
  86097. if(!doneN) {
  86098. nDist += increment;
  86099. posN = posM + offNP * nDist;
  86100. vec4 rgbaEndN = FxaaTexTop(tex, posN.xy);
  86101. doneN = contrast( rgbaEndN, rgbaM ) > contrast( rgbaEndN, rgbaN );
  86102. iterationsUsedN = i;
  86103. }
  86104. if(!doneP) {
  86105. pDist += increment;
  86106. posP = posM - offNP * pDist;
  86107. vec4 rgbaEndP = FxaaTexTop(tex, posP.xy);
  86108. doneP = contrast( rgbaEndP, rgbaM ) > contrast( rgbaEndP, rgbaN );
  86109. iterationsUsedP = i;
  86110. }
  86111. if(doneN || doneP) break;
  86112. }
  86113. if ( !doneP && !doneN ) return rgbaM; // failed to find end of edge
  86114. float dist = min(
  86115. doneN ? float( iterationsUsedN ) / float( NUM_SAMPLES - 1 ) : 1.,
  86116. doneP ? float( iterationsUsedP ) / float( NUM_SAMPLES - 1 ) : 1.
  86117. );
  86118. // hacky way of reduces blurriness of mostly diagonal edges
  86119. // but reduces AA quality
  86120. dist = pow(dist, .5);
  86121. dist = 1. - dist;
  86122. return mix(
  86123. rgbaM,
  86124. rgbaN,
  86125. dist * .5
  86126. );
  86127. }
  86128. void main() {
  86129. const float edgeDetectionQuality = .05 ; //越高,越保留细节;越低,越平滑 但模糊
  86130. const float invEdgeDetectionQuality = 1. / edgeDetectionQuality;
  86131. gl_FragColor = FxaaPixelShader(
  86132. vUv,
  86133. tDiffuse,
  86134. resolution,
  86135. edgeDetectionQuality, // [0,1] contrast needed, otherwise early discard
  86136. invEdgeDetectionQuality
  86137. );
  86138. }
  86139. `
  86140. };
  86141. /**
  86142. * @author spidersharma / http://eduperiment.com/
  86143. */
  86144. let OutlinePass = function ( selectedObjects ) {
  86145. /* scene = scene;
  86146. camera = camera; */
  86147. this.selectedObjects = selectedObjects !== undefined ? selectedObjects : [];
  86148. this.visibleEdgeColor = new Color( 1, 1, 1 );
  86149. this.hiddenEdgeColor = new Color( 0.1, 0.04, 0.02 );
  86150. this.edgeGlow = 0.0;
  86151. this.usePatternTexture = false;
  86152. //this.edgeThickness = 1.0;
  86153. this.edgeStrength = 50;
  86154. this.downSampleRatio = 1;//2; // 抗锯齿 值越低renderTarget size越大,抗锯齿越强,线条可越细(或许可以把模糊化去掉?)
  86155. this.pulsePeriod = 0;
  86156. Pass.call( this );
  86157. this.resolution = new Vector2$1( 256, 256 );
  86158. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  86159. var resx = Math.round( this.resolution.x / this.downSampleRatio );
  86160. var resy = Math.round( this.resolution.y / this.downSampleRatio );
  86161. //this.maskBufferMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff } );
  86162. //this.maskBufferMaterial.side = THREE.DoubleSide;
  86163. this.renderTargetMaskBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  86164. this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask";
  86165. this.renderTargetMaskBuffer.texture.generateMipmaps = false;
  86166. this.depthMaterial = new MeshDepthMaterial();
  86167. this.depthMaterial.side = DoubleSide;
  86168. this.depthMaterial.depthPacking = RGBADepthPacking;
  86169. this.depthMaterial.blending = NoBlending;
  86170. this.prepareMaskMaterial = this.getPrepareMaskMaterial();
  86171. this.prepareMaskMaterial.side = DoubleSide;
  86172. //this.replaceDepthToViewZ( viewer.mainViewport.camera /* camera */ );
  86173. this.renderTargetDepthBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  86174. this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth";
  86175. this.renderTargetDepthBuffer.texture.generateMipmaps = false;
  86176. /* this.renderTargetMaskDownSampleBuffer = new THREE.WebGLRenderTarget( resx, resy, pars );
  86177. this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample";
  86178. this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false;
  86179. this.renderTargetBlurBuffer1 = new THREE.WebGLRenderTarget( resx, resy, pars );
  86180. this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1";
  86181. this.renderTargetBlurBuffer1.texture.generateMipmaps = false;
  86182. this.renderTargetBlurBuffer2 = new THREE.WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), pars );
  86183. this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2";
  86184. this.renderTargetBlurBuffer2.texture.generateMipmaps = false; */
  86185. this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(this.edgeStrength);
  86186. this.renderTargetEdgeBuffer1 = new WebGLRenderTarget( resx, resy, pars );
  86187. this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1";
  86188. this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
  86189. /* this.renderTargetEdgeBuffer2 = new THREE.WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), pars );
  86190. this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2";
  86191. this.renderTargetEdgeBuffer2.texture.generateMipmaps = false;
  86192. var MAX_EDGE_THICKNESS = 4;
  86193. var MAX_EDGE_GLOW = 4;
  86194. this.separableBlurMaterial1 = this.getSeperableBlurMaterial( MAX_EDGE_THICKNESS );
  86195. this.separableBlurMaterial1.uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
  86196. this.separableBlurMaterial1.uniforms[ "kernelRadius" ].value = 1;
  86197. this.separableBlurMaterial2 = this.getSeperableBlurMaterial( MAX_EDGE_GLOW );
  86198. this.separableBlurMaterial2.uniforms[ "texSize" ].value = new THREE.Vector2( Math.round( resx / 2 ), Math.round( resy / 2 ) );
  86199. this.separableBlurMaterial2.uniforms[ "kernelRadius" ].value = MAX_EDGE_GLOW;
  86200. */
  86201. // Overlay material
  86202. this.overlayMaterial = this.getOverlayMaterial();
  86203. // copy material
  86204. this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
  86205. this.copyUniforms[ "opacity" ].value = 1.0;
  86206. this.materialCopy = new ShaderMaterial( {
  86207. uniforms: this.copyUniforms,
  86208. vertexShader: CopyShader.vertexShader,
  86209. fragmentShader: CopyShader.fragmentShader,
  86210. blending: NoBlending,
  86211. depthTest: false,
  86212. depthWrite: false,
  86213. transparent: true
  86214. } );
  86215. this.enabled = true;
  86216. this.needsSwap = false;
  86217. this.oldClearColor = new Color();
  86218. this.oldClearAlpha = 1;
  86219. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  86220. this.scene = new Scene();
  86221. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  86222. this.quad.frustumCulled = false; // Avoid getting clipped
  86223. this.scene.add( this.quad );
  86224. /* this.tempPulseColor1 = new THREE.Color();
  86225. this.tempPulseColor2 = new THREE.Color(); */
  86226. this.textureMatrix = new Matrix4();
  86227. };
  86228. OutlinePass.prototype = Object.assign( Object.create( Pass.prototype ), {
  86229. constructor: OutlinePass,
  86230. dispose: function () {
  86231. this.renderTargetMaskBuffer.dispose();
  86232. this.renderTargetEdgeBuffer1.dispose();
  86233. this.renderTargetDepthBuffer.dispose();
  86234. },
  86235. replaceDepthToViewZ( camera ) {
  86236. var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
  86237. if(type == this.lastCameraType )return
  86238. this.lastCameraType = type;
  86239. this.prepareMaskMaterial.fragmentShader = this.prepareMaskMaterial.fragmentShader.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );
  86240. this.prepareMaskMaterial.needsUpdate = true;
  86241. },
  86242. setSize: function ( width, height ) {
  86243. this.renderTargetEdgeBuffer1.setSize( width, height );
  86244. this.renderTargetMaskBuffer.setSize( width, height );
  86245. this.resolution.set(width,height);
  86246. },
  86247. changeVisibilityOfSelectedObjects: function ( bVisible ) {
  86248. function gatherSelectedMeshesCallBack( object ) {
  86249. /* if ( object.isMesh ) { */
  86250. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  86251. /* if ( bVisible ) {
  86252. object.visible = object.userData.oldVisible;
  86253. delete object.userData.oldVisible;
  86254. } else {
  86255. object.userData.oldVisible = object.visible;
  86256. object.visible = bVisible;
  86257. } */
  86258. viewer.updateVisible(object, 'overlinePass', bVisible);
  86259. }
  86260. }
  86261. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  86262. var selectedObject = this.selectedObjects[ i ];
  86263. selectedObject.traverse( gatherSelectedMeshesCallBack );
  86264. }
  86265. },
  86266. changeVisibilityOfNonSelectedObjects: function ( bVisible , scenes) {
  86267. var selectedMeshes = [];
  86268. function gatherSelectedMeshesCallBack( object ) {
  86269. //if ( object.isMesh ) selectedMeshes.push( object );
  86270. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  86271. selectedMeshes.push( object );
  86272. }
  86273. }
  86274. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  86275. var selectedObject = this.selectedObjects[ i ];
  86276. selectedObject.traverse( gatherSelectedMeshesCallBack );
  86277. }
  86278. function VisibilityChangeCallBack( object ) {
  86279. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  86280. var bFound = false;
  86281. for ( var i = 0; i < selectedMeshes.length; i ++ ) {
  86282. var selectedObjectId = selectedMeshes[ i ].id;
  86283. if ( selectedObjectId === object.id ) {
  86284. bFound = true;
  86285. break;
  86286. }
  86287. }
  86288. if ( ! bFound ) {
  86289. var visibility = object.visible;
  86290. viewer.updateVisible(object, 'overlinePass', bVisible); //add
  86291. //但保不齐在设置为false后,渲染时又true了,所以在其他地方update时设置visible 得用updateVisible
  86292. if(!bVisible){
  86293. object.visible = false;
  86294. }else {
  86295. object.visible = !!object.bVisible;
  86296. }
  86297. object.bVisible = visibility;
  86298. //这两种updateVisible 和 visible 设置都不能去掉, 第一块是为了防止有的visible不是通过updateVisible设置的; 第二块是为了防止渲染时updateVisible又修改了visible为true, 另外渲染时
  86299. return {stopContinue:true} //for pointcloud
  86300. }
  86301. }
  86302. }
  86303. scenes.forEach(scene=>scene.traverse( VisibilityChangeCallBack ));
  86304. },
  86305. updateTextureMatrix: function (camera) {
  86306. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  86307. 0.0, 0.5, 0.0, 0.5,
  86308. 0.0, 0.0, 0.5, 0.5,
  86309. 0.0, 0.0, 0.0, 1.0 );
  86310. this.textureMatrix.multiply( camera.projectionMatrix );
  86311. this.textureMatrix.multiply( camera.matrixWorldInverse );
  86312. },
  86313. render: function (scenes, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  86314. if(!(scenes instanceof Array))scenes = [scenes];
  86315. if ( this.selectedObjects.length > 0 && this.edgeStrength > 0) {
  86316. let render2 = (target, dontRenderRtEDL=true)=>{
  86317. if(renderFun){
  86318. renderFun({target , dontRenderRtEDL});
  86319. }else {
  86320. renderer.setRenderTarget(target);
  86321. renderer.clear();
  86322. scenes.forEach(scene=>renderer.render( scene, camera));
  86323. }
  86324. };
  86325. viewports.forEach(e=>{
  86326. e.oldBeforeRender = e.beforeRender;
  86327. e.beforeRender = ()=>{
  86328. e.oldBeforeRender && e.oldBeforeRender();
  86329. this.replaceDepthToViewZ( e.camera );
  86330. };
  86331. });
  86332. this.oldClearColor.copy( renderer.getClearColor(new Color) );
  86333. this.oldClearAlpha = renderer.getClearAlpha();
  86334. let oldAutoClear = renderer.autoClear;
  86335. let oldTarget = renderer.getRenderTarget();
  86336. renderer.autoClear = false;
  86337. if ( maskActive ) renderer.context.disable( renderer.context.STENCIL_TEST );
  86338. renderer.setClearColor( 0xffffff, 1 );
  86339. // Make selected objects invisible
  86340. this.changeVisibilityOfSelectedObjects( false );
  86341. scenes.forEach(scene=>{
  86342. scene.currentBackground = scene.background;
  86343. scene.background = null;
  86344. // 1. Draw Non Selected objects in the depth buffer
  86345. scene.overrideMaterial = this.depthMaterial;
  86346. });
  86347. render2(this.renderTargetDepthBuffer);
  86348. //renderer.setRenderTarget(this.renderTargetDepthBuffer)
  86349. //renderer.clear()
  86350. //renderer.render( scene, camera/* , this.renderTargetDepthBuffer, true */);
  86351. // Make selected objects visible
  86352. this.changeVisibilityOfSelectedObjects( true );
  86353. viewports.forEach(e=>{
  86354. e.beforeRender = ()=>{
  86355. e.oldBeforeRender && e.oldBeforeRender();
  86356. // Update Texture Matrix for Depth compare
  86357. this.updateTextureMatrix(e.camera);
  86358. this.prepareMaskMaterial.uniforms[ "cameraNearFar" ].value = new Vector2$1( e.camera.near, e.camera.far );
  86359. };
  86360. });
  86361. // Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects
  86362. this.changeVisibilityOfNonSelectedObjects( false , scenes);
  86363. scenes.forEach(scene=>{
  86364. scene.overrideMaterial = this.prepareMaskMaterial;
  86365. });
  86366. this.prepareMaskMaterial.uniforms[ "depthTexture" ].value = this.renderTargetDepthBuffer.texture;
  86367. this.prepareMaskMaterial.uniforms[ "textureMatrix" ].value = this.textureMatrix;
  86368. //renderer.setRenderTarget(this.renderTargetMaskBuffer)
  86369. //renderer.clear()
  86370. //renderer.render( scene, camera/* , this.renderTargetMaskBuffer, true */ );
  86371. viewer.scene.pointclouds.forEach(e=>{ //先将点云透明度变为1,因为点云透明度莫名其妙会影响其r值
  86372. e.material._oldOpa = e.material.opacity;
  86373. e.material.opacity = 1;
  86374. });
  86375. render2(this.renderTargetMaskBuffer);
  86376. viewer.scene.pointclouds.forEach(e=>{//恢复
  86377. e.material.opacity = e.material._oldOpa;
  86378. delete e.material._oldOpa;
  86379. });
  86380. viewports.forEach((e)=>{e.beforeRender = e.oldBeforeRender;});
  86381. this.changeVisibilityOfNonSelectedObjects( true , scenes);
  86382. scenes.forEach(scene=>{
  86383. scene.overrideMaterial = null;
  86384. scene.background = scene.currentBackground;
  86385. });
  86386. // 3. Apply Edge Detection Pass
  86387. this.quad.material = this.edgeDetectionMaterial;
  86388. this.edgeDetectionMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;//this.renderTargetMaskDownSampleBuffer.texture;
  86389. this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new Vector2$1(this.resolution.x, this.resolution.y );//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  86390. //this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2(this.renderTargetMaskBuffer.width, this.renderTargetMaskBuffer.height)//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  86391. this.edgeDetectionMaterial.uniforms[ "edgeStrength" ].value = this.edgeStrength;
  86392. this.edgeDetectionMaterial.uniforms[ "visibleEdgeColor" ].value = this.visibleEdgeColor;//this.tempPulseColor1;
  86393. this.edgeDetectionMaterial.uniforms[ "hiddenEdgeColor" ].value = this.hiddenEdgeColor; //this.tempPulseColor2;
  86394. let buffer = readBuffer;
  86395. if ( this.renderToScreen ) {
  86396. this.quad.material.transparent = true;
  86397. buffer = null;
  86398. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  86399. render2(null,false);
  86400. //绘制到全屏
  86401. let renderSize = renderer.getSize(new Vector2$1()); //是client大小
  86402. renderer.setViewport(0, 0, renderSize.x, renderSize.y); //规定视口,影响图形变换(画布的使用范围)
  86403. renderer.setScissorTest( false );
  86404. }else {
  86405. renderer.setClearColor( 0x000000, 0 );
  86406. renderer.clear();
  86407. }
  86408. renderer.setRenderTarget(buffer/* this.renderTargetEdgeBuffer1 */);
  86409. renderer.render( this.scene, this.camera/* , this.renderTargetEdgeBuffer1, true */);
  86410. //这次删掉
  86411. /* // Blend it additively over the input texture
  86412. this.quad.material = this.overlayMaterial;
  86413. //this.overlayMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;
  86414. this.overlayMaterial.uniforms[ "edgeTexture1" ].value = this.renderTargetEdgeBuffer1.texture;
  86415. //this.overlayMaterial.uniforms[ "edgeTexture2" ].value = this.renderTargetEdgeBuffer2.texture;
  86416. //this.overlayMaterial.uniforms[ "patternTexture" ].value = this.patternTexture;
  86417. this.overlayMaterial.uniforms[ "edgeStrength" ].value = this.edgeStrength;
  86418. //this.overlayMaterial.uniforms[ "edgeGlow" ].value = this.edgeGlow;
  86419. //this.overlayMaterial.uniforms[ "usePatternTexture" ].value = this.usePatternTexture;
  86420. if ( maskActive ) renderer.context.enable( renderer.context.STENCIL_TEST );
  86421. //renderer.render( this.scene, camera, readBuffer, false );
  86422. //改:清空readBuffer, 仅绘制出outline的部分
  86423. renderer.setClearColor( 0x000000, 0 );
  86424. renderer.setRenderTarget(readBuffer)
  86425. renderer.clear()
  86426. renderer.render( this.scene, this.camera );
  86427. */
  86428. renderer.setRenderTarget(oldTarget);
  86429. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  86430. renderer.autoClear = oldAutoClear;
  86431. return true
  86432. }
  86433. /* if ( this.renderToScreen ) {
  86434. this.quad.material = this.materialCopy;
  86435. this.copyUniforms[ "tDiffuse" ].value = readBuffer.texture;
  86436. renderer.render( this.scene , this.camera );
  86437. } */
  86438. },
  86439. getPrepareMaskMaterial: function () {
  86440. return new ShaderMaterial( {
  86441. uniforms: {
  86442. "depthTexture": { value: null },
  86443. "cameraNearFar": { value: new Vector2$1( 0.5, 0.5 ) },
  86444. "textureMatrix": { value: new Matrix4() }
  86445. },
  86446. vertexShader: [
  86447. 'varying vec4 projTexCoord;',
  86448. 'varying vec4 vPosition;',
  86449. 'uniform mat4 textureMatrix;',
  86450. 'void main() {',
  86451. ' vPosition = modelViewMatrix * vec4( position, 1.0 );',
  86452. ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
  86453. ' projTexCoord = textureMatrix * worldPosition;',
  86454. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  86455. '}'
  86456. ].join( '\n' ),
  86457. fragmentShader: [
  86458. '#include <packing>',
  86459. 'varying vec4 vPosition;',
  86460. 'varying vec4 projTexCoord;',
  86461. 'uniform sampler2D depthTexture;',
  86462. 'uniform vec2 cameraNearFar;',
  86463. 'void main() {',
  86464. ' float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));',
  86465. ' float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );',
  86466. ' float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;',
  86467. ' gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);',
  86468. '}'
  86469. ].join( '\n' )
  86470. //scene.overrideMaterial
  86471. //为什么画出来红色通道不为0,且depthTest似乎会改变红色通道的值
  86472. } );
  86473. },
  86474. getEdgeDetectionMaterial: function (edgeStrength) {
  86475. return new ShaderMaterial( {
  86476. uniforms: {
  86477. "edgeStrength": { value: edgeStrength },
  86478. "maskTexture": { value: null },
  86479. "texSize": { value: new Vector2$1( 10, 10 ) },
  86480. "visibleEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  86481. "hiddenEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  86482. },
  86483. vertexShader:
  86484. "varying vec2 vUv;\n\
  86485. void main() {\n\
  86486. vUv = uv;\n\
  86487. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86488. }",
  86489. /* fragmentShader:
  86490. "varying vec2 vUv;\
  86491. uniform sampler2D maskTexture;\
  86492. uniform vec2 texSize;\
  86493. uniform vec3 visibleEdgeColor;\
  86494. uniform vec3 hiddenEdgeColor;\
  86495. \
  86496. void main() {\n\
  86497. vec2 invSize = 1.0 / texSize;\
  86498. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\
  86499. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\
  86500. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\
  86501. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\
  86502. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\
  86503. float diff1 = (c1.r - c2.r)*0.5;\
  86504. float diff2 = (c3.r - c4.r)*0.5;\
  86505. float d = length( vec2(diff1, diff2) );\
  86506. float a1 = min(c1.g, c2.g);\
  86507. float a2 = min(c3.g, c4.g);\
  86508. float visibilityFactor = min(a1, a2);\
  86509. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\
  86510. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\
  86511. }" */
  86512. fragmentShader:
  86513. `varying vec2 vUv;
  86514. uniform sampler2D maskTexture;
  86515. uniform float edgeStrength;
  86516. uniform vec2 texSize;
  86517. uniform vec3 visibleEdgeColor;
  86518. uniform vec3 hiddenEdgeColor;
  86519. void main() {
  86520. const float thickness = 1.0;
  86521. vec2 invSize = thickness / texSize;
  86522. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);
  86523. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);
  86524. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);
  86525. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);
  86526. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);
  86527. float diff1 = (c1.r - c2.r)*0.5; //检测边缘,
  86528. float diff2 = (c3.r - c4.r)*0.5;
  86529. float d = length( vec2(diff1, diff2) ) * edgeStrength;
  86530. float a1 = min(c1.g, c2.g);
  86531. float a2 = min(c3.g, c4.g);
  86532. float visibilityFactor = min(a1, a2);
  86533. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;
  86534. //gl_FragColor = vec4(0.0,1.0,0.0,1.0);
  86535. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);
  86536. }`
  86537. } );
  86538. //为什么vec4(0.0,1.0,1.0,1.0); 显示出来的是rgb(109,255,255) ? 几乎只有绿色通道会影响红色通道
  86539. },
  86540. getSeperableBlurMaterial: function ( maxRadius ) {
  86541. return new ShaderMaterial( {
  86542. defines: {
  86543. "MAX_RADIUS": maxRadius,
  86544. },
  86545. uniforms: {
  86546. "colorTexture": { value: null },
  86547. "texSize": { value: new Vector2$1( 0.5, 0.5 ) },
  86548. "direction": { value: new Vector2$1( 0.5, 0.5 ) },
  86549. "kernelRadius": { value: 1.0 }
  86550. },
  86551. vertexShader:
  86552. "varying vec2 vUv;\n\
  86553. void main() {\n\
  86554. vUv = uv;\n\
  86555. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86556. }",
  86557. fragmentShader:
  86558. "#include <common>\
  86559. varying vec2 vUv;\
  86560. uniform sampler2D colorTexture;\
  86561. uniform vec2 texSize;\
  86562. uniform vec2 direction;\
  86563. uniform float kernelRadius;\
  86564. \
  86565. float gaussianPdf(in float x, in float sigma) {\
  86566. return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
  86567. }\
  86568. void main() {\
  86569. vec2 invSize = 1.0 / texSize;\
  86570. float weightSum = gaussianPdf(0.0, kernelRadius);\
  86571. vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
  86572. vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);\
  86573. vec2 uvOffset = delta;\
  86574. for( int i = 1; i <= MAX_RADIUS; i ++ ) {\
  86575. float w = gaussianPdf(uvOffset.x, kernelRadius);\
  86576. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
  86577. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
  86578. diffuseSum += ((sample1 + sample2) * w);\
  86579. weightSum += (2.0 * w);\
  86580. uvOffset += delta;\
  86581. }\
  86582. gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\
  86583. }"
  86584. } );
  86585. },
  86586. getOverlayMaterial: function () {
  86587. return new ShaderMaterial( {
  86588. uniforms: {
  86589. "maskTexture": { value: null },
  86590. "edgeTexture1": { value: null },
  86591. "edgeTexture2": { value: null },
  86592. "patternTexture": { value: null },
  86593. "edgeStrength": { value: 1.0 },
  86594. "edgeGlow": { value: 1.0 },
  86595. "usePatternTexture": { value: 0.0 }
  86596. },
  86597. vertexShader:
  86598. "varying vec2 vUv;\n\
  86599. void main() {\n\
  86600. vUv = uv;\n\
  86601. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86602. }",
  86603. /* fragmentShader:
  86604. "varying vec2 vUv;\
  86605. uniform sampler2D maskTexture;\
  86606. uniform sampler2D edgeTexture1;\
  86607. uniform sampler2D edgeTexture2;\
  86608. uniform sampler2D patternTexture;\
  86609. uniform float edgeStrength;\
  86610. uniform float edgeGlow;\
  86611. uniform bool usePatternTexture;\
  86612. \
  86613. void main() {\
  86614. vec4 edgeValue1 = texture2D(edgeTexture1, vUv);\
  86615. vec4 edgeValue2 = texture2D(edgeTexture2, vUv);\
  86616. vec4 maskColor = texture2D(maskTexture, vUv);\
  86617. vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);\
  86618. float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;\
  86619. vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;\
  86620. vec4 finalColor = edgeStrength * maskColor.r * edgeValue;\ // 删除 * maskColor.r 也就是去掉遮罩,使模型部分也有outline
  86621. if(usePatternTexture)\
  86622. finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);\
  86623. gl_FragColor = finalColor;\
  86624. }", */
  86625. fragmentShader:
  86626. `varying vec2 vUv;
  86627. uniform sampler2D edgeTexture1;
  86628. uniform float edgeStrength;
  86629. void main() {
  86630. gl_FragColor = edgeStrength * texture2D(edgeTexture1, vUv);
  86631. }`,
  86632. blending: AdditiveBlending,
  86633. depthTest: false,
  86634. depthWrite: false,
  86635. transparent: true
  86636. } );
  86637. }
  86638. } );
  86639. OutlinePass.BlurDirectionX = new Vector2$1( 1.0, 0.0 );
  86640. OutlinePass.BlurDirectionY = new Vector2$1( 0.0, 1.0 );
  86641. class BasicMaterial extends ShaderMaterial{
  86642. constructor(o={}){
  86643. super( Object.assign({},{
  86644. uniforms:{
  86645. tDiffuse: { type: 't', value: o.map },
  86646. alpha : {type:'f', value : 1 }
  86647. },
  86648. vertexShader: Shaders['basicTextured.vs'],
  86649. fragmentShader: Shaders['basicTextured.fs']
  86650. },o));
  86651. }
  86652. set opacity(o){
  86653. this.uniforms && (this.uniforms.alpha.value = o);
  86654. }
  86655. get opacity(){
  86656. return this.uniforms.alpha.value
  86657. }
  86658. set map(o){
  86659. this.uniforms.tDiffuse.value = o;
  86660. }
  86661. get map(){
  86662. return this.uniforms.tDiffuse.value
  86663. }
  86664. }
  86665. const manager = new LoadingManager();
  86666. let loaders = {};
  86667. let mapArea;
  86668. let blockedByIntersectHistory = new Map();
  86669. class Viewer extends ViewerBase{
  86670. constructor(domElement, mapArea_, args = {}){
  86671. super(domElement, $.extend(args,{name:'mainViewer'}));
  86672. window.viewer = this;
  86673. if(Potree.settings.editType == "pano" || Potree.settings.editType == "merge"){
  86674. this.modules = {
  86675. Alignment,
  86676. SiteModel
  86677. };
  86678. Potree.settings.useDepthTex = false;
  86679. if(Potree.settings.editType == "pano" ){
  86680. this.modules.PanoEditor = PanoEditor$1;
  86681. }else if(Potree.settings.editType == "merge"){
  86682. this.modules.MergeEditor = MergeEditor;
  86683. this.modules.CamAniEditor = CamAniEditor;
  86684. }
  86685. }else {
  86686. this.modules = {
  86687. Clip,
  86688. Alignment,
  86689. SiteModel,
  86690. RouteGuider : new RouteGuider,
  86691. ParticleEditor,
  86692. CamAniEditor,
  86693. };
  86694. }
  86695. console.log('create viewer');
  86696. this.navigateMode = 'free'; // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点,
  86697. this.isEdit = true;
  86698. this.waitQueue = [];
  86699. this.unitConvert = new UoMService();
  86700. mapArea = mapArea_;
  86701. this.visible = true;
  86702. this.fpVisiDatasets = [];
  86703. this.atDatasets = [];
  86704. this.objs = new Object3D;
  86705. //this.lastPos = new THREE.Vector3(Infinity,Infinity,Infinity)
  86706. //-------------
  86707. var supportExtFragDepth = !!Features.EXT_DEPTH.isSupported() ;//iphoneX居然不支持
  86708. //这意味着边缘增强和测量线遮挡失效
  86709. if(!supportExtFragDepth)console.error('ExtFragDepth unsupported! 边缘增强和测量线遮挡失效');
  86710. this.guiLoaded = false;
  86711. this.guiLoadTasks = [];
  86712. this.onVrListeners = [];
  86713. this.messages = [];
  86714. this.elMessages = $(`
  86715. <div id="message_listing"
  86716. style="position: absolute; z-index: 1000; left: 10px; bottom: 10px">
  86717. </div>`);
  86718. $(domElement).append(this.elMessages);
  86719. this.paused;
  86720. document.addEventListener('visibilitychange',(e)=>{
  86721. //console.log('visibilitychange', !document.hidden )
  86722. this.dispatchEvent({type:'pageVisible', v:!document.hidden} );
  86723. });
  86724. try{
  86725. if(!Potree.settings.isOfficial)
  86726. { // generate missing dom hierarchy
  86727. if ($(domElement).find('#potree_map').length === 0) {
  86728. let potreeMap = $(`
  86729. <div id="potree_map" class="mapBox" style="position: absolute; left: 50px; top: 50px; width: 400px; height: 400px; display: none">
  86730. <div id="potree_map_header" style="position: absolute; width: 100%; height: 25px; top: 0px; background-color: rgba(0,0,0,0.5); z-index: 1000; border-top-left-radius: 3px; border-top-right-radius: 3px;">
  86731. </div>
  86732. <div id="potree_map_content" class="map" style="position: absolute; z-index: 100; top: 25px; width: 100%; height: calc(100% - 25px); border: 2px solid rgba(0,0,0,0.5); box-sizing: border-box;"></div>
  86733. </div>
  86734. `);
  86735. $(domElement).append(potreeMap);
  86736. }
  86737. if ($(domElement).find('#potree_description').length === 0) {
  86738. let potreeDescription = $(`<div id="potree_description" class="potree_info_text"></div>`);
  86739. $(domElement).append(potreeDescription);
  86740. }
  86741. if ($(domElement).find('#potree_annotations').length === 0) {
  86742. let potreeAnnotationContainer = $(`
  86743. <div id="potree_annotation_container"
  86744. style="position: absolute; z-index: 100000; width: 100%; height: 100%; pointer-events: none;"></div>`);
  86745. $(domElement).append(potreeAnnotationContainer);
  86746. }
  86747. if ($(domElement).find('#potree_quick_buttons').length === 0) {
  86748. let potreeMap = $(`
  86749. <div id="potree_quick_buttons" class="quick_buttons_container" style="">
  86750. </div>
  86751. `);
  86752. $(domElement).append(potreeMap);
  86753. }
  86754. //add
  86755. {
  86756. if(!mapArea && Potree.settings.editType != 'merge'){
  86757. $(domElement).append($("<div id='potree_labels'></div>"));
  86758. mapArea = $("<div id='mapGaode'></div>");
  86759. $(domElement).append(mapArea);
  86760. mapArea = mapArea[0];
  86761. }
  86762. }
  86763. /* let domRoot = this.renderer.domElement.parentElement;
  86764. let elAttach = $("<input type='button' value='test'></input>");
  86765. elAttach.css({
  86766. position : "absolute",
  86767. right : '10%',
  86768. bottom: '20px',
  86769. zIndex: "10000",
  86770. fontSize:'1em', color:"black",
  86771. background:'rgba(255,255,255,0.8)',
  86772. })
  86773. let state = false
  86774. elAttach.on("click", () => {
  86775. window.buttonFunction && window.buttonFunction()
  86776. });
  86777. domRoot.appendChild(elAttach[0]); */
  86778. }
  86779. this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {};
  86780. // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  86781. // defaultSettings.navigation = "Orbit";
  86782. // }
  86783. this.server = null;
  86784. this.fov = 60;
  86785. this.isFlipYZ = false;
  86786. this.useDEMCollisions = false;
  86787. this.generateDEM = false;
  86788. this.minNodeSize = 30;
  86789. this.edlStrength = 1.0;
  86790. this.edlRadius = 1.4;
  86791. this.edlOpacity = 1.0;
  86792. this.useEDL = false;
  86793. this.description = "";
  86794. this.classifications = ClassificationScheme.DEFAULT;
  86795. this.moveSpeed = 10;
  86796. this.lengthUnit = LengthUnits.METER;
  86797. this.lengthUnitDisplay = LengthUnits.METER;
  86798. this.showBoundingBox = false;
  86799. this.showAnnotations = true;
  86800. this.freeze = false;
  86801. this.clipTask = ClipTask.HIGHLIGHT;
  86802. this.clipMethod = ClipMethod.INSIDE_ANY;
  86803. this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP;
  86804. this.filterReturnNumberRange = [0, 7];
  86805. this.filterNumberOfReturnsRange = [0, 7];
  86806. this.filterGPSTimeRange = [-Infinity, Infinity];
  86807. this.filterPointSourceIDRange = [0, 65535];
  86808. this.potreeRenderer = null;
  86809. this.edlRenderer = null;
  86810. this.pRenderer = null;
  86811. this.scene = null;
  86812. this.sceneVR = null;
  86813. this.overlay = null;
  86814. this.overlayCamera = null;
  86815. this.inputHandler = null;
  86816. this.controls = null;
  86817. this.clippingTool = null;
  86818. this.transformationTool = null;
  86819. this.navigationCube = null;
  86820. this.compass = null;
  86821. this.skybox = null;
  86822. this.clock = new Clock();
  86823. this.background = null;
  86824. if(args.noDragAndDrop){
  86825. }else {
  86826. this.initDragAndDrop();
  86827. }
  86828. if(typeof Stats !== "undefined"){
  86829. this.stats = new Stats();
  86830. this.stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
  86831. document.body.appendChild( this.stats.dom );
  86832. }
  86833. {
  86834. let canvas = this.renderer.domElement;
  86835. canvas.addEventListener("webglcontextlost", (e) => {
  86836. console.log(e);
  86837. this.postMessage("WebGL context lost. \u2639");
  86838. let gl = this.renderer.getContext();
  86839. let error = gl.getError();
  86840. console.log(error);
  86841. this.dispatchEvent({type:'webglError', msg:'webglcontextlost'});
  86842. }, false);
  86843. }
  86844. {
  86845. this.overlay = new Scene();
  86846. this.overlayCamera = new OrthographicCamera(
  86847. 0, 1,
  86848. 1, 0,
  86849. -1000, 1000
  86850. );
  86851. }
  86852. this.pRenderer = new Renderer(this.renderer);
  86853. {
  86854. let near = 2.5;
  86855. let far = 10.0;
  86856. let fov = 90;
  86857. this.shadowTestCam = new PerspectiveCamera(90, 1, near, far);
  86858. this.shadowTestCam.position.set(3.50, -2.80, 8.561);
  86859. this.shadowTestCam.lookAt(new Vector3(0, 0, 4.87));
  86860. }
  86861. let scene = new Scene$1(this.renderer);
  86862. { // create VR scene
  86863. this.sceneVR = new Scene();
  86864. // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  86865. // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
  86866. // let infoMaterial = new THREE.MeshBasicMaterial({map: texture});
  86867. // let infoNode = new THREE.Mesh(plane, infoMaterial);
  86868. // infoNode.position.set(-0.5, 1, 0);
  86869. // infoNode.scale.set(0.4, 0.3, 1);
  86870. // infoNode.lookAt(0, 1, 0)
  86871. // this.sceneVR.add(infoNode);
  86872. // window.infoNode = infoNode;
  86873. }
  86874. this.setScene(scene);
  86875. //add: for 截图时抗锯齿
  86876. {
  86877. this.composer = new EffectComposer( this.renderer );
  86878. this.ssaaRenderPass = new SSAARenderPass(0x000000, 0);
  86879. this.composer.addPass( this.ssaaRenderPass );
  86880. //this.ssaaRenderPass.useCopy = true
  86881. //this.ssaaRenderPass.renderToScreen = true;
  86882. //this.ssaaRenderPass.needsSwap = false
  86883. //见 https://threejs.org/examples/?q=AA#webgl_postprocessing_fxaa 效果和SSAA差不多,都对透明不太友好。
  86884. /* const renderPass = new RenderPass();
  86885. renderPass.clearColor = new THREE.Color( 0, 0, 0 );
  86886. renderPass.clearAlpha = 0;
  86887. this.composer.addPass( renderPass );
  86888. this.fxaaPass = new ShaderPass( FXAAShader );
  86889. this.composer.addPass( this.fxaaPass );
  86890. this.fxaaPass.setSize = function(width, height){
  86891. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width );
  86892. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height );
  86893. }
  86894. this.fxaaPass.renderToScreen = true; */
  86895. /* this.fxaaPass = new ShaderPass( FXAAShader );
  86896. //this.fxaaPass.readTarget = true //add
  86897. this.composer.addPass( this.fxaaPass );
  86898. this.composer.readTarget = true
  86899. this.fxaaPass.setSize = function(width, height){
  86900. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width );
  86901. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height );
  86902. }
  86903. this.fxaaPass.renderToScreen = true; */
  86904. //for 融合页面
  86905. /* let outlinePass = this.outlinePass = new OutlinePass( );
  86906. //composer.addPass( outlinePass );
  86907. outlinePass.edgeStrength = 10
  86908. outlinePass.edgeGlow = 0
  86909. outlinePass.visibleEdgeColor = new THREE.Color("#09a1b3")
  86910. outlinePass.hiddenEdgeColor = new THREE.Color("#09a1b3")
  86911. this.ssaaRenderPass.addPass(outlinePass)
  86912. */
  86913. let outlinePass = this.outlinePass = new OutlinePass( );
  86914. outlinePass.renderToScreen = true; //这样更流畅,不用ssaa了,缺点是outline有锯齿
  86915. outlinePass.enabled = false;
  86916. this.composer.addPass( outlinePass );
  86917. outlinePass.edgeStrength = 10;
  86918. outlinePass.edgeGlow = 0;
  86919. outlinePass.visibleEdgeColor = new Color("#09a1b3");
  86920. outlinePass.hiddenEdgeColor = new Color("#09a1b3");
  86921. }
  86922. {
  86923. this.mainViewport = new Viewport( this.scene.view, this.scene.cameraP, {
  86924. left:0, bottom:0, width:1, height: 1, name:'MainView'
  86925. });
  86926. this.viewports = [this.mainViewport];
  86927. Potree.settings.showCompass && (this.compass = new Compass(Potree.settings.compassDom, this.mainViewport));
  86928. this.magnifier = new Magnifier(this);
  86929. this.reticule = new Reticule(this);
  86930. this.scene.scene.add(this.magnifier);
  86931. this.scene.scene.add(this.reticule);
  86932. if(Potree.settings.editType != "pano" && Potree.settings.editType != 'merge'){
  86933. this.mapViewer = new MapViewer(mapArea/* $('#mapGaode')[0] */);
  86934. }
  86935. this.inputHandler = new InputHandler(this, this.scene.scene);
  86936. //this.inputHandler.setScene(this.scene);
  86937. //this.inputHandler.addInputListener(this);//add
  86938. this.clippingTool = new ClippingTool(this);
  86939. this.transformationTool = new TransformationTool(this);
  86940. this.navigationCube = new NavigationCube(this);
  86941. this.navigationCube.visible = false;
  86942. this.createControls();
  86943. this.clippingTool.setScene(this.scene);
  86944. let onPointcloudAdded = (e) => {
  86945. if (this.scene.pointclouds.length === 1) {
  86946. let speed = e.pointcloud.boundingBox.getSize(new Vector3()).length();
  86947. speed = speed / 2000;
  86948. this.setMoveSpeed(speed);
  86949. }
  86950. };
  86951. let onVolumeRemoved = (e) => {
  86952. this.inputHandler.deselect(e.volume);
  86953. };
  86954. this.addEventListener('scene_changed', (e) => {
  86955. this.inputHandler.setScene(e.scene);
  86956. this.clippingTool.setScene(this.scene);
  86957. if(!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)){
  86958. e.scene.addEventListener("pointcloud_added", onPointcloudAdded);
  86959. }
  86960. if(!e.scene.hasEventListener("volume_removed", onPointcloudAdded)){
  86961. e.scene.addEventListener("volume_removed", onVolumeRemoved);
  86962. }
  86963. });
  86964. this.scene.addEventListener("volume_removed", onVolumeRemoved);
  86965. this.scene.addEventListener('pointcloud_added', onPointcloudAdded);
  86966. }
  86967. { // set defaults
  86968. this.setFOV(60);
  86969. this.setEDLEnabled(false);
  86970. this.setEDLRadius(1.4);
  86971. this.setEDLStrength(0.4);
  86972. this.setEDLOpacity(1.0);
  86973. this.setClipTask(ClipTask.HIGHLIGHT);
  86974. this.setClipMethod(ClipMethod.INSIDE_ANY);
  86975. this.setPointBudget(1*1000*1000);
  86976. this.setShowBoundingBox(false);
  86977. this.setFreeze(false);
  86978. this.setControls(this.fpControls/* orbitControls */);
  86979. this.setBackground( new Color(Potree.config.background),1 /* 'gradient' */ );
  86980. this.scaleFactor = 1;
  86981. this.loadSettingsFromURL();
  86982. }
  86983. // start rendering!
  86984. //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){
  86985. //requestAnimationFrame(this.loop.bind(this));
  86986. //}
  86987. this.renderer.setAnimationLoop(this.loop.bind(this));
  86988. this.loadGUI = this.loadGUI.bind(this);
  86989. this.annotationTool = new AnnotationTool(this);
  86990. this.measuringTool = new MeasuringTool(this);
  86991. this.profileTool = new ProfileTool(this);
  86992. this.volumeTool = new VolumeTool(this);
  86993. this.tagTool = new TagTool(this);
  86994. //-----------
  86995. CursorDeal.init(this, this.mapViewer ? [this, this.mapViewer] : [this]);//ADD
  86996. if(Potree.settings.editType == "pano"){
  86997. this.modules.PanoEditor.init();
  86998. }else if(Potree.settings.editType == "merge"){
  86999. this.modules.MergeEditor.init();
  87000. }else {
  87001. this.modules.SiteModel.init();
  87002. this.modules.ParticleEditor.init();
  87003. }
  87004. this.modules.Alignment.init();
  87005. this.images360 = new Images360(this);
  87006. this.scene.scene.add(this.objs);
  87007. loaders = {
  87008. objLoader : new OBJLoader( manager ),
  87009. mtlLoader : new MTLLoader( manager ),
  87010. glbLoader : new GLTFLoader(undefined, this.renderer, Potree.settings.libsUrl )
  87011. };
  87012. //add test
  87013. /* const environment = new RoomEnvironment();
  87014. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  87015. this.scene.scene.environment = pmremGenerator.fromScene( environment ).texture;
  87016. */
  87017. //-----------
  87018. }catch(e){
  87019. this.onCrash(e);
  87020. }
  87021. //-----------------------add----------------------------------------------------
  87022. /* {
  87023. let ratio
  87024. this.addEventListener('resize',(e)=>{
  87025. if(ratio != e.deviceRatio){ //因为devicePixelRatio会影响到点云大小,所以改变时计算下点云大小
  87026. viewer.scene.pointclouds.forEach(p => {
  87027. p.changePointSize()
  87028. })
  87029. }
  87030. ratio = e.deviceRatio
  87031. })
  87032. } */
  87033. {
  87034. let pointDensity = '';
  87035. Object.defineProperty(Potree.settings , "pointDensity",{
  87036. get: function() {
  87037. return pointDensity
  87038. },
  87039. set: (density)=>{
  87040. if(density && density != pointDensity){
  87041. let pointBudget;
  87042. var config = Potree.config.pointDensity[density];
  87043. if(this.magnifier.visible){//放大镜打开时不要切换pointBudget,否则点云会闪烁。这时使用最高密度。
  87044. pointBudget = Potree.config.pointDensity['magnifier'].pointBudget;
  87045. }else {
  87046. pointBudget = config.pointBudget;
  87047. }
  87048. viewer.setPointBudget(pointBudget );
  87049. //Potree.maxPointLevel = config.maxLevel
  87050. pointDensity = density;
  87051. this.setPointLevels();
  87052. }
  87053. }
  87054. });
  87055. let UserPointDensity = '';
  87056. Object.defineProperty(Potree.settings , "UserPointDensity",{
  87057. get: function() {
  87058. return UserPointDensity
  87059. },
  87060. set: (density)=>{
  87061. if(UserPointDensity != density){
  87062. if(Potree.settings.displayMode == 'showPointCloud' && this.viewports.length != 4){//漫游模式和四屏时都有自己的pointDensity
  87063. Potree.settings.pointDensity = density;
  87064. }
  87065. UserPointDensity = density;
  87066. }
  87067. }
  87068. });
  87069. }
  87070. {
  87071. let cameraFar = Potree.settings.cameraFar;
  87072. Object.defineProperty(Potree.settings , "cameraFar",{
  87073. get: function() {
  87074. return cameraFar
  87075. },
  87076. set: (far)=>{
  87077. if(far != cameraFar){
  87078. if(Potree.settings.displayMode != 'showPanos'){
  87079. this.mainViewport.camera.far = far;
  87080. this.mainViewport.camera.updateProjectionMatrix();
  87081. }
  87082. cameraFar = far;
  87083. }
  87084. }
  87085. });
  87086. }
  87087. this.addEventListener('allLoaded', ()=>{
  87088. setTimeout(this.testPointcloudsMaxLevel.bind(this), 2000); //延迟一丢丢,等画面出现
  87089. });
  87090. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  87091. this.addEventListener('switchFloorplanSelect',(e)=>{//进入平面图设置后 切换选中的数据集
  87092. this.selectedFloorplan = e.pointcloud; //绝对显示
  87093. this.updateFpVisiDatasets();
  87094. let pointclouds;
  87095. if(e.pointcloud){
  87096. pointclouds = [e.pointcloud];
  87097. }else if(this.fpVisiDatasets.length){
  87098. pointclouds = this.fpVisiDatasets;
  87099. }
  87100. pointclouds && this.mapViewer.fitToDatasets(pointclouds);
  87101. });
  87102. this.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  87103. this.updateFpVisiDatasets();
  87104. });
  87105. this.mapViewer.mapLayer.addEventListener('floorplanLoaded',()=>{
  87106. this.updateCadVisibles(this.fpVisiDatasets, true); //加载完成后重新更新下
  87107. });
  87108. /* this.modules.Clip.bus.addEventListener('updateSelectedDatasets',()=>{
  87109. this.updateFpVisiDatasets()
  87110. }) */
  87111. }
  87112. {
  87113. //更新所在数据集
  87114. this.addEventListener('camera_changed', e => {
  87115. if(e.changeInfo.positionChanged){
  87116. blockedByIntersectHistory.clear(); //清空
  87117. this.updateDatasetAt();
  87118. }
  87119. });
  87120. }
  87121. }
  87122. ifPointBlockedByIntersect(pos3d, object){//点是否被遮挡
  87123. let ifShelter;
  87124. let shelter = blockedByIntersectHistory.get(object || pos3d);
  87125. if(shelter){
  87126. ifShelter = shelter.ifShelter;
  87127. }else {
  87128. ifShelter = viewer.inputHandler.ifBlockedByIntersect(pos3d, 0.3, true);//由于热点都是使用点云得到的位置,所以判断遮挡时也用点云
  87129. blockedByIntersectHistory.set(object || pos3d, {ifShelter});
  87130. }
  87131. return ifShelter
  87132. }
  87133. updateDatasetAt(force){//更新所在数据集
  87134. let fun = ()=>{
  87135. let currPos = viewer.mainViewport.view.position;
  87136. //if(force || !currPos.equals(this.lastPos)){
  87137. //this.lastPos.copy(currPos)
  87138. var at = this.scene.pointclouds.filter(e=>e.ifContainsPoint(currPos));
  87139. if(Common.getDifferenceSet(at, this.atDatasets).length){
  87140. //console.log('atDatasets', at)
  87141. this.atDatasets = at;
  87142. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge')this.updateFpVisiDatasets();
  87143. this.dispatchEvent({type:'pointcloudAtChange',pointclouds:at});
  87144. }
  87145. force = false;
  87146. return true
  87147. //}
  87148. };
  87149. if(force)fun();
  87150. else Common.intervalTool.isWaiting('atWhichDataset', fun , 500);
  87151. }
  87152. updatePanosVisibles(currentFloor){//显示当前楼层的所有panos
  87153. viewer.images360.panos.forEach(pano=>{
  87154. let visible = currentFloor && currentFloor.panos.includes(pano);
  87155. viewer.updateVisible(pano, 'buildingChange', visible, 2);
  87156. });
  87157. }
  87158. updateFpVisiDatasets(){
  87159. let Clip = this.modules.Clip;
  87160. let SiteModel = this.modules.SiteModel;
  87161. let Alignment = this.modules.Alignment;
  87162. var currentFloor = SiteModel.currentFloor;
  87163. /* if(Clip.editing){//下载页面已经改为和普通时一样,根据位置判断
  87164. this.updateCadVisibles(Clip.selectedDatasets)
  87165. }else */if(this.selectedFloorplan){//平面图设置中
  87166. let pointclouds = [this.selectedFloorplan];
  87167. this.updateCadVisibles(pointclouds);
  87168. }else if(SiteModel.editing || Alignment.editing){//只显示勾选的,也就是显示的点云的
  87169. let pointclouds = this.scene.pointclouds.filter(p => this.getObjVisiByReason(p,'datasetSelection') );
  87170. this.updateCadVisibles(pointclouds);
  87171. this.updatePanosVisibles(currentFloor/* , pointclouds */);
  87172. }else {
  87173. let pointclouds = currentFloor ? this.findPointcloudsAtFloor(currentFloor) : [];
  87174. if(pointclouds.length == 0){//如果当前不在任何楼层或楼层中无数据集,就用当前所在数据集
  87175. pointclouds = this.atDatasets;
  87176. }
  87177. this.updateCadVisibles(pointclouds);
  87178. this.updatePanosVisibles(currentFloor/* , pointclouds */);
  87179. }
  87180. }
  87181. findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。
  87182. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  87183. //重叠体积>50% 或 包含>50%的漫游点
  87184. const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95;
  87185. var lowScores = [];
  87186. var pointclouds = viewer.scene.pointclouds.filter(e=>{
  87187. let score = 0;
  87188. if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  87189. return true
  87190. }
  87191. if(e.panos.length){//条件2
  87192. var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position));
  87193. let panoCountRatio = insidePanos.length / e.panos.length;
  87194. if(panoCountRatio > ratio2)return true
  87195. if(panoCountRatio < ratio1){
  87196. score += panoCountRatio;//return false
  87197. }
  87198. }
  87199. //条件3
  87200. let volume = entity.intersectPointcloudVolume(e);
  87201. let volumeRatio = volume / entity.getVolume(true); //注:hole加入计算
  87202. if(volumeRatio > ratio3){ //ratio3要高一些,因为点云bounding可能很大,包含很多无点云的空间。即使整个数据集包含entity都不一定看起来在数据集中。(千万要防止两层楼都显示了)
  87203. return true
  87204. }else {
  87205. score += volumeRatio;
  87206. }
  87207. lowScores.push({score, pointcloud:e});
  87208. });
  87209. if(pointclouds.length == 0){//从低分项挑一个出来。
  87210. lowScores.sort((a,b)=>{return a.score - b.score});
  87211. if(lowScores[0].score > 0.4){
  87212. pointclouds = [lowScores[0].pointcloud];
  87213. }
  87214. }
  87215. return pointclouds
  87216. }
  87217. updateCadVisibles(visiClouds, force){
  87218. let oldVisi = this.fpVisiDatasets;
  87219. var visiClouds = this.fpVisiDatasets = visiClouds;
  87220. if(!force){
  87221. var difference = Common.getDifferenceSet(oldVisi , visiClouds);
  87222. if(difference.length == 0)return
  87223. }
  87224. //console.log('visiClouds',visiClouds.map(e=>e.name))
  87225. viewer.scene.pointclouds.forEach(pointcloud=>{
  87226. var floorplan = viewer.mapViewer.mapLayer.getFloorplan(pointcloud.dataset_id);
  87227. var visi = visiClouds.includes(pointcloud);
  87228. if(floorplan){
  87229. viewer.updateVisible(floorplan.objectGroup, 'buildingChange', visi);
  87230. }/* else if(!visi){
  87231. let changeVisi = (e)=>{
  87232. viewer.updateVisible(e.floorplan.objectGroup, 'buildingChange', this.fpVisiDatasets.includes(pointcloud))
  87233. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', changeVisi)
  87234. console.log('updateCadVisibles加载后更改显示',e)
  87235. }
  87236. viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', changeVisi)
  87237. } */
  87238. //已经添加了全局的 floorplanLoaded后会updateCadVisibles,这段就删了
  87239. });
  87240. viewer.mapViewer.mapLayer.needUpdate = true; //可能需要更新加载的level程度
  87241. viewer.mapViewer.needRender = true; //若上句不触发加载也要立即重新绘制
  87242. }
  87243. //促使点云加载出最高级别
  87244. testPointcloudsMaxLevel(){ //所有点云都无需testMaxNodeLevel 就停止
  87245. let camera_changed, count = 0;
  87246. let test = ()=>{
  87247. camera_changed = true;
  87248. Common.intervalTool.isWaiting('testPointcloudsMaxLevel', ()=>{
  87249. if(!camera_changed && count>20 )return //只有当camera_changed后才继续循环, 除了最开始几次需要连续加载下
  87250. camera_changed = false;
  87251. count ++;
  87252. //console.log('testPointcloudsMaxLevel中')
  87253. var success = true;
  87254. viewer.scene.pointclouds.forEach(e=>{
  87255. var wait = e.testMaxNodeLevel();
  87256. if(wait){
  87257. success = false;
  87258. }
  87259. });
  87260. if(!success)return true //没有全部加载完,继续循环
  87261. else {
  87262. this.removeEventListener('camera_changed',test);
  87263. console.log('testPointcloudsMaxLevel结束');
  87264. }
  87265. }, count<10 ? 150 : 500);
  87266. };
  87267. this.addEventListener('camera_changed',test);
  87268. test();
  87269. /* 检验:
  87270. viewer.scene.pointclouds.sort((a,b)=>a.nodeMaxLevelPredict.min - b.nodeMaxLevelPredict.min).forEach(e=>console.log(e.nodeMaxLevel, e.nodeMaxLevelPredict.min))
  87271. */
  87272. }
  87273. setPointLevels(){
  87274. this.scene.pointclouds.forEach(e=>{
  87275. e.setPointLevel();
  87276. });
  87277. }
  87278. onCrash(error){
  87279. $(this.renderArea).empty();
  87280. if ($(this.renderArea).find('#potree_failpage').length === 0) {
  87281. let elFailPage = $(`
  87282. <div id="#potree_failpage" class="potree_failpage">
  87283. <h1>Potree Encountered An Error </h1>
  87284. <p>
  87285. This may happen if your browser or graphics card is not supported.
  87286. <br>
  87287. We recommend to use
  87288. <a href="https://www.google.com/chrome/browser" target="_blank" style="color:initial">Chrome</a>
  87289. or
  87290. <a href="https://www.mozilla.org/" target="_blank">Firefox</a>.
  87291. </p>
  87292. <p>
  87293. Please also visit <a href="http://webglreport.com/" target="_blank">webglreport.com</a> and
  87294. check whether your system supports WebGL.
  87295. </p>
  87296. <p>
  87297. If you are already using one of the recommended browsers and WebGL is enabled,
  87298. consider filing an issue report at <a href="https://github.com/potree/potree/issues" target="_blank">github</a>,<br>
  87299. including your operating system, graphics card, browser and browser version, as well as the
  87300. error message below.<br>
  87301. Please do not report errors on unsupported browsers.
  87302. </p>
  87303. <pre id="potree_error_console" style="width: 100%; height: 100%"></pre>
  87304. </div>`);
  87305. let elErrorMessage = elFailPage.find('#potree_error_console');
  87306. elErrorMessage.html(error.stack);
  87307. $(this.renderArea).append(elFailPage);
  87308. }
  87309. throw error;
  87310. }
  87311. // ------------------------------------------------------------------------------------
  87312. // Viewer API
  87313. // ------------------------------------------------------------------------------------
  87314. setScene (scene) {
  87315. if (scene === this.scene) {
  87316. return;
  87317. }
  87318. let oldScene = this.scene;
  87319. this.scene = scene;
  87320. this.dispatchEvent({
  87321. type: 'scene_changed',
  87322. oldScene: oldScene,
  87323. scene: scene
  87324. });
  87325. { // Annotations
  87326. $('.annotation').detach();
  87327. // for(let annotation of this.scene.annotations){
  87328. // this.renderArea.appendChild(annotation.domElement[0]);
  87329. // }
  87330. this.scene.annotations.traverse(annotation => {
  87331. this.renderArea.appendChild(annotation.domElement[0]);
  87332. });
  87333. if (!this.onAnnotationAdded) {
  87334. this.onAnnotationAdded = e => {
  87335. // console.log("annotation added: " + e.annotation.title);
  87336. e.annotation.traverse(node => {
  87337. $("#potree_annotation_container").append(node.domElement);
  87338. //this.renderArea.appendChild(node.domElement[0]);
  87339. node.scene = this.scene;
  87340. });
  87341. };
  87342. }
  87343. if (oldScene) {
  87344. oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  87345. }
  87346. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  87347. }
  87348. };
  87349. setControls(controls/* , setSpeed */){
  87350. if (controls !== this.controls) {
  87351. if (this.controls) {
  87352. this.controls.setEnable(false);
  87353. //this.inputHandler.removeInputListener(this.controls);
  87354. this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小)
  87355. }
  87356. this.controls = controls;
  87357. controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed); //add
  87358. this.controls.setEnable(true);
  87359. //this.inputHandler.addInputListener(this.controls);
  87360. }
  87361. }
  87362. getControls () {
  87363. if(this.renderer.xr.isPresenting){
  87364. return this.vrControls;
  87365. }else {
  87366. return this.controls;
  87367. }
  87368. }
  87369. getMinNodeSize () {
  87370. return this.minNodeSize;
  87371. };
  87372. setMinNodeSize (value) {
  87373. if (this.minNodeSize !== value) {
  87374. this.minNodeSize = value;
  87375. this.dispatchEvent({'type': 'minnodesize_changed', 'viewer': this});
  87376. }
  87377. };
  87378. getBackground () {
  87379. return this.background;
  87380. }
  87381. setBackground(bg){
  87382. if (this.background === bg) {
  87383. return;
  87384. }
  87385. if(bg === "skybox"){
  87386. this.skybox = Utils.loadSkybox(new URL(Potree.resourcePath + '/textures/skybox2/').href);
  87387. }
  87388. this.background = bg;
  87389. this.backgroundOpacity = 1;//add
  87390. this.dispatchEvent({'type': 'background_changed', 'viewer': this});
  87391. }
  87392. setDescription (value) {
  87393. this.description = value;
  87394. $('#potree_description').html(value);
  87395. //$('#potree_description').text(value);
  87396. }
  87397. getDescription(){
  87398. return this.description;
  87399. }
  87400. setShowBoundingBox (value) {
  87401. if (this.showBoundingBox !== value) {
  87402. this.showBoundingBox = value;
  87403. this.dispatchEvent({'type': 'show_boundingbox_changed', 'viewer': this});
  87404. }
  87405. };
  87406. getShowBoundingBox () {
  87407. return this.showBoundingBox;
  87408. };
  87409. setMoveSpeed (value) {
  87410. if (this.getMoveSpeed() !== value) {
  87411. this.mainViewport.setMoveSpeed(value);
  87412. this.dispatchEvent({'type': 'move_speed_changed', 'viewer': this, 'speed': value});
  87413. }
  87414. };
  87415. getMoveSpeed () {
  87416. return this.mainViewport.moveSpeed;
  87417. };
  87418. setWeightClassification (w) {
  87419. for (let i = 0; i < this.scene.pointclouds.length; i++) {
  87420. this.scene.pointclouds[i].material.weightClassification = w;
  87421. this.dispatchEvent({'type': 'attribute_weights_changed' + i, 'viewer': this});
  87422. }
  87423. };
  87424. setFreeze (value) {
  87425. value = Boolean(value);
  87426. if (this.freeze !== value) {
  87427. this.freeze = value;
  87428. this.dispatchEvent({'type': 'freeze_changed', 'viewer': this});
  87429. }
  87430. };
  87431. getFreeze () {
  87432. return this.freeze;
  87433. };
  87434. getClipTask(){
  87435. return this.clipTask;
  87436. }
  87437. getClipMethod(){
  87438. return this.clipMethod;
  87439. }
  87440. setClipTask(value){
  87441. if(this.clipTask !== value){
  87442. this.clipTask = value;
  87443. this.dispatchEvent({
  87444. type: "cliptask_changed",
  87445. viewer: this});
  87446. }
  87447. }
  87448. setClipMethod(value){
  87449. if(this.clipMethod !== value){
  87450. this.clipMethod = value;
  87451. this.dispatchEvent({
  87452. type: "clipmethod_changed",
  87453. viewer: this});
  87454. }
  87455. }
  87456. setElevationGradientRepeat(value){
  87457. if(this.elevationGradientRepeat !== value){
  87458. this.elevationGradientRepeat = value;
  87459. this.dispatchEvent({
  87460. type: "elevation_gradient_repeat_changed",
  87461. viewer: this});
  87462. }
  87463. }
  87464. setPointBudget (value) {
  87465. if (Potree.pointBudget !== value) {
  87466. Potree.pointBudget = parseInt(value);
  87467. this.dispatchEvent({'type': 'point_budget_changed', 'viewer': this});
  87468. }
  87469. };
  87470. getPointBudget () {
  87471. return Potree.pointBudget;
  87472. };
  87473. setShowAnnotations (value) {
  87474. if (this.showAnnotations !== value) {
  87475. this.showAnnotations = value;
  87476. this.dispatchEvent({'type': 'show_annotations_changed', 'viewer': this});
  87477. }
  87478. }
  87479. getShowAnnotations () {
  87480. return this.showAnnotations;
  87481. }
  87482. setDEMCollisionsEnabled(value){
  87483. if(this.useDEMCollisions !== value){
  87484. this.useDEMCollisions = value;
  87485. this.dispatchEvent({'type': 'use_demcollisions_changed', 'viewer': this});
  87486. };
  87487. };
  87488. getDEMCollisionsEnabled () {
  87489. return this.useDEMCollisions;
  87490. };
  87491. setEDLEnabled (value) {
  87492. value = Boolean(value) && Features.SHADER_EDL.isSupported();
  87493. if (this.useEDL !== value) {
  87494. this.useEDL = value;
  87495. this.dispatchEvent({'type': 'use_edl_changed', 'viewer': this});
  87496. }
  87497. };
  87498. getEDLEnabled () {
  87499. return this.useEDL;
  87500. };
  87501. setEDLRadius (value) {
  87502. if (this.edlRadius !== value) {
  87503. this.edlRadius = value;
  87504. this.dispatchEvent({'type': 'edl_radius_changed', 'viewer': this});
  87505. }
  87506. };
  87507. getEDLRadius () {
  87508. return this.edlRadius;
  87509. };
  87510. setEDLStrength (value) {
  87511. if (this.edlStrength !== value) {
  87512. this.edlStrength = value;
  87513. this.dispatchEvent({'type': 'edl_strength_changed', 'viewer': this});
  87514. }
  87515. };
  87516. getEDLStrength () {
  87517. return this.edlStrength;
  87518. };
  87519. setEDLOpacity (value) {
  87520. if (this.edlOpacity !== value) {
  87521. this.edlOpacity = value;
  87522. this.dispatchEvent({'type': 'edl_opacity_changed', 'viewer': this});
  87523. }
  87524. };
  87525. getEDLOpacity () {
  87526. return this.edlOpacity;
  87527. };
  87528. setFOV (value) {
  87529. if (this.fov !== value) {
  87530. let oldFov = this.fov;
  87531. this.fov = value;
  87532. this.scene.cameraP.fov = this.fov;
  87533. this.scene.cameraP.updateProjectionMatrix();
  87534. this.dispatchEvent({'type': 'fov_changed', 'viewer': this, oldFov, fov:this.fov});
  87535. }
  87536. };
  87537. getFOV () {
  87538. return this.fov;
  87539. };
  87540. disableAnnotations () {
  87541. this.scene.annotations.traverse(annotation => {
  87542. annotation.domElement.css('pointer-events', 'none');
  87543. // return annotation.visible;
  87544. });
  87545. };
  87546. enableAnnotations () {
  87547. this.scene.annotations.traverse(annotation => {
  87548. annotation.domElement.css('pointer-events', 'auto');
  87549. // return annotation.visible;
  87550. });
  87551. }
  87552. setClassifications(classifications){
  87553. this.classifications = classifications;
  87554. this.dispatchEvent({'type': 'classifications_changed', 'viewer': this});
  87555. }
  87556. setClassificationVisibility (key, value) {
  87557. if (!this.classifications[key]) {
  87558. this.classifications[key] = {visible: value, name: 'no name'};
  87559. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87560. } else if (this.classifications[key].visible !== value) {
  87561. this.classifications[key].visible = value;
  87562. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87563. }
  87564. }
  87565. toggleAllClassificationsVisibility(){
  87566. let numVisible = 0;
  87567. let numItems = 0;
  87568. for(const key of Object.keys(this.classifications)){
  87569. if(this.classifications[key].visible){
  87570. numVisible++;
  87571. }
  87572. numItems++;
  87573. }
  87574. let visible = true;
  87575. if(numVisible === numItems){
  87576. visible = false;
  87577. }
  87578. let somethingChanged = false;
  87579. for(const key of Object.keys(this.classifications)){
  87580. if(this.classifications[key].visible !== visible){
  87581. this.classifications[key].visible = visible;
  87582. somethingChanged = true;
  87583. }
  87584. }
  87585. if(somethingChanged){
  87586. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87587. }
  87588. }
  87589. setFilterReturnNumberRange(from, to){
  87590. this.filterReturnNumberRange = [from, to];
  87591. this.dispatchEvent({'type': 'filter_return_number_range_changed', 'viewer': this});
  87592. }
  87593. setFilterNumberOfReturnsRange(from, to){
  87594. this.filterNumberOfReturnsRange = [from, to];
  87595. this.dispatchEvent({'type': 'filter_number_of_returns_range_changed', 'viewer': this});
  87596. }
  87597. setFilterGPSTimeRange(from, to){
  87598. this.filterGPSTimeRange = [from, to];
  87599. this.dispatchEvent({'type': 'filter_gps_time_range_changed', 'viewer': this});
  87600. }
  87601. setFilterPointSourceIDRange(from, to){
  87602. this.filterPointSourceIDRange = [from, to];
  87603. this.dispatchEvent({'type': 'filter_point_source_id_range_changed', 'viewer': this});
  87604. }
  87605. setLengthUnit (value) {
  87606. switch (value) {
  87607. case 'm':
  87608. this.lengthUnit = LengthUnits.METER;
  87609. this.lengthUnitDisplay = LengthUnits.METER;
  87610. break;
  87611. case 'ft':
  87612. this.lengthUnit = LengthUnits.FEET;
  87613. this.lengthUnitDisplay = LengthUnits.FEET;
  87614. break;
  87615. case 'in':
  87616. this.lengthUnit = LengthUnits.INCH;
  87617. this.lengthUnitDisplay = LengthUnits.INCH;
  87618. break;
  87619. }
  87620. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: value});
  87621. };
  87622. setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) {
  87623. switch (lengthUnitValue) {
  87624. case 'm':
  87625. this.lengthUnit = LengthUnits.METER;
  87626. break;
  87627. case 'ft':
  87628. this.lengthUnit = LengthUnits.FEET;
  87629. break;
  87630. case 'in':
  87631. this.lengthUnit = LengthUnits.INCH;
  87632. break;
  87633. }
  87634. switch (lengthUnitDisplayValue) {
  87635. case 'm':
  87636. this.lengthUnitDisplay = LengthUnits.METER;
  87637. break;
  87638. case 'ft':
  87639. this.lengthUnitDisplay = LengthUnits.FEET;
  87640. break;
  87641. case 'in':
  87642. this.lengthUnitDisplay = LengthUnits.INCH;
  87643. break;
  87644. }
  87645. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: lengthUnitValue });
  87646. };
  87647. zoomTo(node, factor, animationDuration = 0){
  87648. let view = this.scene.view;
  87649. let camera = this.scene.cameraP.clone();
  87650. camera.rotation.copy(this.scene.cameraP.rotation);
  87651. camera.rotation.order = "ZXY";
  87652. camera.rotation.x = Math.PI / 2 + view.pitch;
  87653. camera.rotation.z = view.yaw;
  87654. camera.updateMatrix();
  87655. camera.updateMatrixWorld();
  87656. camera.zoomTo(node, factor);
  87657. let bs;
  87658. if (node.boundingSphere) {
  87659. bs = node.boundingSphere;
  87660. } else if (node.geometry && node.geometry.boundingSphere) {
  87661. bs = node.geometry.boundingSphere;
  87662. } else {
  87663. bs = node.boundingBox.getBoundingSphere(new Sphere());
  87664. }
  87665. bs = bs.clone().applyMatrix4(node.matrixWorld);
  87666. let startPosition = view.position.clone();
  87667. let endPosition = camera.position.clone();
  87668. let startTarget = view.getPivot();
  87669. let endTarget = bs.center;
  87670. let startRadius = view.radius;
  87671. let endRadius = endPosition.distanceTo(endTarget);
  87672. let easing = TWEEN.Easing.Quartic.Out;
  87673. { // animate camera position
  87674. let pos = startPosition.clone();
  87675. let tween = new TWEEN.Tween(pos).to(endPosition, animationDuration);
  87676. tween.easing(easing);
  87677. tween.onUpdate(() => {
  87678. view.position.copy(pos);
  87679. });
  87680. tween.start();
  87681. }
  87682. { // animate camera target
  87683. let target = startTarget.clone();
  87684. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  87685. tween.easing(easing);
  87686. tween.onUpdate(() => {
  87687. view.lookAt(target);
  87688. });
  87689. tween.onComplete(() => {
  87690. view.lookAt(target);
  87691. this.dispatchEvent({type: 'focusing_finished', target: this});
  87692. });
  87693. this.dispatchEvent({type: 'focusing_started', target: this});
  87694. tween.start();
  87695. }
  87696. };
  87697. moveToGpsTimeVicinity(time){
  87698. const result = Potree.Utils.findClosestGpsTime(time, viewer);
  87699. const box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox();
  87700. const diameter = box.min.distanceTo(box.max);
  87701. const camera = this.scene.getActiveCamera();
  87702. const offset = camera.getWorldDirection(new Vector3()).multiplyScalar(diameter);
  87703. const newCamPos = result.position.clone().sub(offset);
  87704. this.scene.view.position.copy(newCamPos);
  87705. this.scene.view.lookAt(result.position);
  87706. }
  87707. showAbout () {
  87708. $(function () {
  87709. $('#about-panel').dialog();
  87710. });
  87711. };
  87712. getGpsTimeExtent(){
  87713. const range = [Infinity, -Infinity];
  87714. for(const pointcloud of this.scene.pointclouds){
  87715. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  87716. const aGpsTime = attributes.find(a => a.name === "gps-time");
  87717. if(aGpsTime){
  87718. range[0] = Math.min(range[0], aGpsTime.range[0]);
  87719. range[1] = Math.max(range[1], aGpsTime.range[1]);
  87720. }
  87721. }
  87722. return range;
  87723. }
  87724. fitToScreen (factor = 1, animationDuration = 0) {
  87725. let box = this.getBoundingBox(this.scene.pointclouds);
  87726. let node = new Object3D();
  87727. node.boundingBox = box;
  87728. this.zoomTo(node, factor, animationDuration);
  87729. this.controls.stop();
  87730. };
  87731. toggleNavigationCube() {
  87732. this.navigationCube.visible = !this.navigationCube.visible;
  87733. }
  87734. /* setView(pos, view) {
  87735. if(!pos) return;
  87736. switch(pos) {
  87737. case "F":
  87738. this.setFrontView(view);
  87739. break;
  87740. case "B":
  87741. this.setBackView(view);
  87742. break;
  87743. case "L":
  87744. this.setLeftView(view);
  87745. break;
  87746. case "R":
  87747. this.setRightView(view);
  87748. break;
  87749. case "U":
  87750. this.setTopView(view);
  87751. break;
  87752. case "D":
  87753. this.setBottomView(view);
  87754. break;
  87755. }
  87756. } */
  87757. setTopView(view){
  87758. view = view || this.scene.view;
  87759. view.setCubeView("top");
  87760. this.fitToScreen();
  87761. };
  87762. setBottomView(){
  87763. this.scene.view.yaw = -Math.PI;
  87764. this.scene.view.pitch = Math.PI / 2;
  87765. this.fitToScreen();
  87766. };
  87767. setFrontView(view){
  87768. view = view || this.scene.view;
  87769. view.yaw = 0;
  87770. view.pitch = 0;
  87771. this.fitToScreen();
  87772. };
  87773. setBackView(view){
  87774. view = view || this.scene.view;
  87775. view.yaw = Math.PI;
  87776. view.pitch = 0;
  87777. this.fitToScreen();
  87778. };
  87779. setLeftView(){
  87780. this.scene.view.yaw = -Math.PI / 2;
  87781. this.scene.view.pitch = 0;
  87782. this.fitToScreen();
  87783. };
  87784. setRightView () {
  87785. this.scene.view.yaw = Math.PI / 2;
  87786. this.scene.view.pitch = 0;
  87787. this.fitToScreen();
  87788. };
  87789. flipYZ () {
  87790. this.isFlipYZ = !this.isFlipYZ;
  87791. // TODO flipyz
  87792. console.log('TODO');
  87793. }
  87794. setCameraMode(mode){
  87795. this.scene.cameraMode = mode;
  87796. for(let pointcloud of this.scene.pointclouds) {
  87797. pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC;
  87798. }
  87799. }
  87800. getProjection(){
  87801. const pointcloud = this.scene.pointclouds[0];
  87802. if(pointcloud){
  87803. return pointcloud.projection;
  87804. }else {
  87805. return null;
  87806. }
  87807. }
  87808. async loadProject(url,done){
  87809. const response = await fetch(url);
  87810. if(response.ok){
  87811. const text = await response.text();
  87812. const json = lib.parse(text);
  87813. // const json = JSON.parse(text);
  87814. if(json.type === "Potree"){
  87815. Potree.loadProject(viewer, json, done);
  87816. }
  87817. }else {
  87818. console.warn("未能加载:"+url );
  87819. }
  87820. }
  87821. saveProject(){
  87822. return Potree.saveProject(this);
  87823. }
  87824. loadSettingsFromURL(){
  87825. if(Utils.getParameterByName("pointSize")){
  87826. this.setPointSize(parseFloat(Utils.getParameterByName("pointSize")));
  87827. }
  87828. if(Utils.getParameterByName("FOV")){
  87829. this.setFOV(parseFloat(Utils.getParameterByName("FOV")));
  87830. }
  87831. if(Utils.getParameterByName("opacity")){
  87832. this.setOpacity(parseFloat(Utils.getParameterByName("opacity")));
  87833. }
  87834. if(Utils.getParameterByName("edlEnabled")){
  87835. let enabled = Utils.getParameterByName("edlEnabled") === "true";
  87836. this.setEDLEnabled(enabled);
  87837. }
  87838. if (Utils.getParameterByName('edlRadius')) {
  87839. this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius')));
  87840. }
  87841. if (Utils.getParameterByName('edlStrength')) {
  87842. this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength')));
  87843. }
  87844. if (Utils.getParameterByName('pointBudget')) {
  87845. this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget')));
  87846. }
  87847. if (Utils.getParameterByName('showBoundingBox')) {
  87848. let enabled = Utils.getParameterByName('showBoundingBox') === 'true';
  87849. if (enabled) {
  87850. this.setShowBoundingBox(true);
  87851. } else {
  87852. this.setShowBoundingBox(false);
  87853. }
  87854. }
  87855. if (Utils.getParameterByName('material')) {
  87856. let material = Utils.getParameterByName('material');
  87857. this.setMaterial(material);
  87858. }
  87859. if (Utils.getParameterByName('pointSizing')) {
  87860. let sizing = Utils.getParameterByName('pointSizing');
  87861. this.setPointSizing(sizing);
  87862. }
  87863. if (Utils.getParameterByName('quality')) {
  87864. let quality = Utils.getParameterByName('quality');
  87865. this.setQuality(quality);
  87866. }
  87867. if (Utils.getParameterByName('position')) {
  87868. let value = Utils.getParameterByName('position');
  87869. value = value.replace('[', '').replace(']', '');
  87870. let tokens = value.split(';');
  87871. let x = parseFloat(tokens[0]);
  87872. let y = parseFloat(tokens[1]);
  87873. let z = parseFloat(tokens[2]);
  87874. this.scene.view.position.set(x, y, z);
  87875. }
  87876. if (Utils.getParameterByName('target')) {
  87877. let value = Utils.getParameterByName('target');
  87878. value = value.replace('[', '').replace(']', '');
  87879. let tokens = value.split(';');
  87880. let x = parseFloat(tokens[0]);
  87881. let y = parseFloat(tokens[1]);
  87882. let z = parseFloat(tokens[2]);
  87883. this.scene.view.lookAt(new Vector3(x, y, z));
  87884. }
  87885. if (Utils.getParameterByName('background')) {
  87886. let value = Utils.getParameterByName('background');
  87887. this.setBackground(value);
  87888. }
  87889. // if(Utils.getParameterByName("elevationRange")){
  87890. // let value = Utils.getParameterByName("elevationRange");
  87891. // value = value.replace("[", "").replace("]", "");
  87892. // let tokens = value.split(";");
  87893. // let x = parseFloat(tokens[0]);
  87894. // let y = parseFloat(tokens[1]);
  87895. //
  87896. // this.setElevationRange(x, y);
  87897. // //this.scene.view.target.set(x, y, z);
  87898. // }
  87899. };
  87900. // ------------------------------------------------------------------------------------
  87901. // Viewer Internals
  87902. // ------------------------------------------------------------------------------------
  87903. createControls () {
  87904. { // create FIRST PERSON CONTROLS
  87905. this.fpControls = new FirstPersonControls(this, this.mainViewport);
  87906. this.fpControls.enabled = false;
  87907. this.fpControls.addEventListener('start', this.disableAnnotations.bind(this));
  87908. this.fpControls.addEventListener('end', this.enableAnnotations.bind(this));
  87909. /* this.addEventListener("loadPointCloudDone", ()=>{
  87910. let boundPlane = new THREE.Box3()
  87911. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  87912. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  87913. FirstPersonControls.boundPlane = boundPlane
  87914. FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  87915. }) */
  87916. }
  87917. // { // create GEO CONTROLS
  87918. // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement);
  87919. // this.geoControls.enabled = false;
  87920. // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this));
  87921. // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this));
  87922. // this.geoControls.addEventListener("move_speed_changed", (event) => {
  87923. // this.setMoveSpeed(this.geoControls.moveSpeed);
  87924. // });
  87925. // }
  87926. { // create ORBIT CONTROLS
  87927. this.orbitControls = new OrbitControls(this);
  87928. this.orbitControls.enabled = false;
  87929. this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this));
  87930. this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this));
  87931. }
  87932. { // create EARTH CONTROLS
  87933. this.earthControls = new EarthControls(this);
  87934. this.earthControls.enabled = false;
  87935. this.earthControls.addEventListener('start', this.disableAnnotations.bind(this));
  87936. this.earthControls.addEventListener('end', this.enableAnnotations.bind(this));
  87937. }
  87938. { // create DEVICE ORIENTATION CONTROLS
  87939. this.deviceControls = new DeviceOrientationControls(this);
  87940. this.deviceControls.enabled = false;
  87941. this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this));
  87942. this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this));
  87943. }
  87944. /* { // create VR CONTROLS
  87945. this.vrControls = new VRControls(this);
  87946. this.vrControls.enabled = false;
  87947. this.vrControls.addEventListener('start', this.disableAnnotations.bind(this));
  87948. this.vrControls.addEventListener('end', this.enableAnnotations.bind(this));
  87949. } */
  87950. };
  87951. toggleSidebar () {
  87952. let renderArea = $('#potree_render_area');
  87953. let isVisible = renderArea.css('left') !== '0px';
  87954. if (isVisible) {
  87955. renderArea.css('left', '0px');
  87956. } else {
  87957. renderArea.css('left', '300px');
  87958. }
  87959. };
  87960. toggleMap () {
  87961. // let map = $('#potree_map');
  87962. // map.toggle(100);
  87963. if (this.mapView) {
  87964. this.mapView.toggle();
  87965. }
  87966. };
  87967. onGUILoaded(callback){
  87968. if(this.guiLoaded){
  87969. callback();
  87970. }else {
  87971. this.guiLoadTasks.push(callback);
  87972. }
  87973. }
  87974. promiseGuiLoaded(){
  87975. return new Promise( resolve => {
  87976. if(this.guiLoaded){
  87977. resolve();
  87978. }else {
  87979. this.guiLoadTasks.push(resolve);
  87980. }
  87981. });
  87982. }
  87983. loadGUI(callback){
  87984. if(callback){
  87985. this.onGUILoaded(callback);
  87986. }
  87987. let viewer = this;
  87988. let sidebarContainer = $('#potree_sidebar_container');
  87989. sidebarContainer.load(new URL(Potree.scriptPath + '/' + (Potree.settings.sidebar || 'sidebar.html')).href, () => {
  87990. sidebarContainer.css('width', '300px');
  87991. sidebarContainer.css('height', '100%');
  87992. let imgMenuToggle = document.createElement('img');
  87993. imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href;
  87994. imgMenuToggle.onclick = this.toggleSidebar;
  87995. imgMenuToggle.classList.add('potree_menu_toggle');
  87996. let imgMapToggle = document.createElement('img');
  87997. imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href;
  87998. imgMapToggle.style.display = 'none';
  87999. imgMapToggle.onclick = e => { this.toggleMap(); };
  88000. imgMapToggle.id = 'potree_map_toggle';
  88001. let elButtons = $("#potree_quick_buttons").get(0);
  88002. elButtons.append(imgMenuToggle);
  88003. elButtons.append(imgMapToggle);
  88004. /*
  88005. VRButton.createButton(this.renderer).then(vrButton => {
  88006. if(vrButton == null){
  88007. console.log("VR not supported or active.");
  88008. return;
  88009. }
  88010. this.renderer.xr.enabled = true;
  88011. let element = vrButton.element;
  88012. element.style.position = "";
  88013. element.style.bottom = "";
  88014. element.style.left = "";
  88015. element.style.margin = "4px";
  88016. element.style.fontSize = "100%";
  88017. element.style.width = "2.5em";
  88018. element.style.height = "2.5em";
  88019. element.style.padding = "0";
  88020. element.style.textShadow = "black 2px 2px 2px";
  88021. element.style.display = "block";
  88022. elButtons.append(element);
  88023. vrButton.onStart(() => {
  88024. this.dispatchEvent({type: "vr_start"});
  88025. });
  88026. vrButton.onEnd(() => {
  88027. this.dispatchEvent({type: "vr_end"});
  88028. });
  88029. });
  88030. this.mapView = new MapView(this);
  88031. this.mapView.init(); */
  88032. i18n.init({
  88033. lng: 'en',
  88034. resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json',
  88035. preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'],
  88036. getAsync: true,
  88037. debug: false
  88038. }, function (t) {
  88039. // Start translation once everything is loaded
  88040. $('body').i18n();
  88041. });
  88042. $(() => {
  88043. //initSidebar(this);
  88044. let sidebar = new Sidebar(this);
  88045. sidebar.init();
  88046. this.sidebar = sidebar;
  88047. //if (callback) {
  88048. // $(callback);
  88049. //}
  88050. let elProfile = $('<div>').load(new URL(Potree.scriptPath + '/profile.html').href, () => {
  88051. $(document.body).append(elProfile.children());
  88052. this.profileWindow = new ProfileWindow(this);
  88053. this.profileWindowController = new ProfileWindowController(this);
  88054. $('#profile_window').draggable({
  88055. handle: $('#profile_titlebar'),
  88056. containment: $(document.body)
  88057. });
  88058. $('#profile_window').resizable({
  88059. containment: $(document.body),
  88060. handles: 'n, e, s, w'
  88061. });
  88062. $(() => {
  88063. this.guiLoaded = true;
  88064. for(let task of this.guiLoadTasks){
  88065. task();
  88066. }
  88067. });
  88068. });
  88069. });
  88070. });
  88071. return this.promiseGuiLoaded();
  88072. }
  88073. setLanguage (lang) {
  88074. i18n.setLng(lang);
  88075. $('body').i18n();
  88076. }
  88077. setServer (server) {
  88078. this.server = server;
  88079. }
  88080. initDragAndDrop(){
  88081. function allowDrag(e) {
  88082. e.dataTransfer.dropEffect = 'copy';
  88083. e.preventDefault();
  88084. }
  88085. let dropHandler = async (event) => {
  88086. console.log(event);
  88087. event.preventDefault();
  88088. for(const item of event.dataTransfer.items){
  88089. console.log(item);
  88090. if(item.kind !== "file"){
  88091. continue;
  88092. }
  88093. const file = item.getAsFile();
  88094. const isJson = file.name.toLowerCase().endsWith(".json");
  88095. const isGeoPackage = file.name.toLowerCase().endsWith(".gpkg");
  88096. if(isJson){
  88097. try{
  88098. const text = await file.text();
  88099. const json = JSON.parse(text);
  88100. if(json.type === "Potree"){
  88101. Potree.loadProject(viewer, json);
  88102. }
  88103. }catch(e){
  88104. console.error("failed to parse the dropped file as JSON");
  88105. console.error(e);
  88106. }
  88107. }else if(isGeoPackage){
  88108. const hasPointcloud = viewer.scene.pointclouds.length > 0;
  88109. if(!hasPointcloud){
  88110. let msg = "At least one point cloud is needed that specifies the ";
  88111. msg += "coordinate reference system before loading vector data.";
  88112. console.error(msg);
  88113. }else {
  88114. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  88115. proj4.defs("pointcloud", this.getProjection());
  88116. let transform = proj4("WGS84", "pointcloud");
  88117. const buffer = await file.arrayBuffer();
  88118. const params = {
  88119. transform: transform,
  88120. source: file.name,
  88121. };
  88122. const geo = await Potree.GeoPackageLoader.loadBuffer(buffer, params);
  88123. viewer.scene.addGeopackage(geo);
  88124. }
  88125. }
  88126. }
  88127. };
  88128. $("body")[0].addEventListener("dragenter", allowDrag);
  88129. $("body")[0].addEventListener("dragover", allowDrag);
  88130. $("body")[0].addEventListener("drop", dropHandler);
  88131. }
  88132. updateAnnotations () {
  88133. if(!this.visibleAnnotations){
  88134. this.visibleAnnotations = new Set();
  88135. }
  88136. this.scene.annotations.updateBounds();
  88137. this.scene.cameraP.updateMatrixWorld();
  88138. this.scene.cameraO.updateMatrixWorld();
  88139. let distances = [];
  88140. let renderAreaSize = this.renderer.getSize(new Vector2$1());
  88141. let viewer = this;
  88142. let visibleNow = [];
  88143. this.scene.annotations.traverse(annotation => {
  88144. if (annotation === this.scene.annotations) {
  88145. return true;
  88146. }
  88147. if (!annotation.visible) {
  88148. return false;
  88149. }
  88150. annotation.scene = this.scene;
  88151. let element = annotation.domElement;
  88152. let position = annotation.position.clone();
  88153. position.add(annotation.offset);
  88154. if (!position) {
  88155. position = annotation.boundingBox.getCenter(new Vector3());
  88156. }
  88157. let distance = viewer.scene.cameraP.position.distanceTo(position);
  88158. let radius = annotation.boundingBox.getBoundingSphere(new Sphere()).radius;
  88159. let screenPos = new Vector3();
  88160. let screenSize = 0;
  88161. {
  88162. // SCREEN POS
  88163. screenPos.copy(position).project(this.scene.getActiveCamera());
  88164. screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2;
  88165. screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2);
  88166. // SCREEN SIZE
  88167. if(viewer.scene.cameraMode == CameraMode.PERSPECTIVE) {
  88168. let fov = Math.PI * viewer.scene.cameraP.fov / 180;
  88169. let slope = Math.tan(fov / 2.0);
  88170. let projFactor = 0.5 * renderAreaSize.y / (slope * distance);
  88171. screenSize = radius * projFactor;
  88172. } else {
  88173. screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y);
  88174. }
  88175. }
  88176. element.css("left", screenPos.x + "px");
  88177. element.css("top", screenPos.y + "px");
  88178. //element.css("display", "block");
  88179. let zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far);
  88180. if(annotation.descriptionVisible){
  88181. zIndex += 10000000;
  88182. }
  88183. element.css("z-index", parseInt(zIndex));
  88184. if(annotation.children.length > 0){
  88185. let expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position);
  88186. annotation.expand = expand;
  88187. if (!expand) {
  88188. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  88189. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  88190. if(inFrustum){
  88191. visibleNow.push(annotation);
  88192. }
  88193. }
  88194. return expand;
  88195. } else {
  88196. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  88197. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  88198. if(inFrustum){
  88199. visibleNow.push(annotation);
  88200. }
  88201. }
  88202. });
  88203. let notVisibleAnymore = new Set(this.visibleAnnotations);
  88204. for(let annotation of visibleNow){
  88205. annotation.display = true;
  88206. notVisibleAnymore.delete(annotation);
  88207. }
  88208. this.visibleAnnotations = visibleNow;
  88209. for(let annotation of notVisibleAnymore){
  88210. annotation.display = false;
  88211. }
  88212. }
  88213. updateMaterialDefaults(pointcloud){
  88214. // PROBLEM STATEMENT:
  88215. // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded
  88216. // * the point cloud material won't know the range it should use until some data is loaded
  88217. // * users can modify the range at runtime, but sensible default ranges should be
  88218. // applied even if no GUI is present
  88219. // * display ranges shouldn't suddenly change even if the actual range changes over time.
  88220. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to
  88221. // [0, 2047]. We should not automatically change to the new range because that would result
  88222. // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider.
  88223. const material = pointcloud.material;
  88224. const attIntensity = pointcloud.getAttribute("intensity");
  88225. if(attIntensity != null && material.intensityRange[0] === Infinity){
  88226. material.intensityRange = [...attIntensity.range];
  88227. }
  88228. // const attIntensity = pointcloud.getAttribute("intensity");
  88229. // if(attIntensity && material.intensityRange[0] === Infinity){
  88230. // material.intensityRange = [...attIntensity.range];
  88231. // }
  88232. // let attributes = pointcloud.getAttributes();
  88233. // for(let attribute of attributes.attributes){
  88234. // if(attribute.range){
  88235. // let range = [...attribute.range];
  88236. // material.computedRange.set(attribute.name, range);
  88237. // //material.setRange(attribute.name, range);
  88238. // }
  88239. // }
  88240. }
  88241. update(delta, timestamp){
  88242. if(Potree.measureTimings) performance.mark("update-start");
  88243. this.dispatchEvent({
  88244. type: 'update_start',
  88245. delta: delta,
  88246. timestamp: timestamp});
  88247. this.updateScreenSize(); //判断是否改变canvas大小
  88248. const scene = this.scene;
  88249. const camera = scene.getActiveCamera();
  88250. const visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible);
  88251. Potree.pointLoadLimit = Potree.pointBudget * 2;
  88252. const lTarget = camera.position.clone().add(camera.getWorldDirection(new Vector3()).multiplyScalar(1000));
  88253. this.scene.directionalLight.position.copy(camera.position);
  88254. this.scene.directionalLight.lookAt(lTarget);
  88255. for (let pointcloud of visiblePointClouds) {
  88256. pointcloud.showBoundingBox = this.showBoundingBox;
  88257. pointcloud.generateDEM = this.generateDEM;
  88258. pointcloud.minimumNodePixelSize = this.minNodeSize;
  88259. let material = pointcloud.material;
  88260. material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange;
  88261. material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange;
  88262. material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange;
  88263. material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange;
  88264. material.classification = this.classifications;
  88265. material.recomputeClassification();
  88266. this.updateMaterialDefaults(pointcloud);
  88267. }
  88268. {
  88269. if(this.showBoundingBox){
  88270. let bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root");
  88271. if(!bbRoot){
  88272. let node = new Object3D();
  88273. node.name = "potree_bounding_box_root";
  88274. this.scene.scene.add(node);
  88275. bbRoot = node;
  88276. }
  88277. let visibleBoxes = [];
  88278. for(let pointcloud of this.scene.pointclouds){
  88279. for(let node of pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)){
  88280. let box = node.boundingBoxNode;
  88281. visibleBoxes.push(box);
  88282. }
  88283. }
  88284. bbRoot.children = visibleBoxes;
  88285. }
  88286. }
  88287. if (!this.freeze) {
  88288. /*let cameraGroup = []
  88289. let size = this.renderer.getSize(new THREE.Vector2())
  88290. if(this.viewports){
  88291. this.viewports.forEach(viewport=>{
  88292. if(!viewport.active)return
  88293. cameraGroup.push({camera:viewport.camera, areaSize:new THREE.Vector2(Math.floor(size.x * viewport.width), Math.floor(size.y * viewport.height))})
  88294. })
  88295. }else{
  88296. cameraGroup.push({camera, areaSize:size})
  88297. }
  88298. let result = Potree.updatePointClouds(scene.pointclouds, cameraGroup );
  88299. */
  88300. // DEBUG - ONLY DISPLAY NODES THAT INTERSECT MOUSE
  88301. //if(false){
  88302. // let renderer = viewer.renderer;
  88303. // let mouse = viewer.inputHandler.mouse;
  88304. // let nmouse = {
  88305. // x: (mouse.x / renderer.domElement.clientWidth) * 2 - 1,
  88306. // y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1
  88307. // };
  88308. // let pickParams = {};
  88309. // //if(params.pickClipped){
  88310. // // pickParams.pickClipped = params.pickClipped;
  88311. // //}
  88312. // pickParams.x = mouse.x;
  88313. // pickParams.y = renderer.domElement.clientHeight - mouse.y;
  88314. // let raycaster = new THREE.Raycaster();
  88315. // raycaster.setFromCamera(nmouse, camera);
  88316. // let ray = raycaster.ray;
  88317. // for(let pointcloud of scene.pointclouds){
  88318. // let nodes = pointcloud.nodesOnRay(pointcloud.visibleNodes, ray);
  88319. // pointcloud.visibleNodes = nodes;
  88320. // }
  88321. //}
  88322. // const tStart = performance.now();
  88323. // const worldPos = new THREE.Vector3();
  88324. // const camPos = viewer.scene.getActiveCamera().getWorldPosition(new THREE.Vector3());
  88325. // let lowestDistance = Infinity;
  88326. // let numNodes = 0;
  88327. // viewer.scene.scene.traverse(node => {
  88328. // node.getWorldPosition(worldPos);
  88329. // const distance = worldPos.distanceTo(camPos);
  88330. // lowestDistance = Math.min(lowestDistance, distance);
  88331. // numNodes++;
  88332. // if(Number.isNaN(distance)){
  88333. // console.error(":(");
  88334. // }
  88335. // });
  88336. // const duration = (performance.now() - tStart).toFixed(2);
  88337. // Potree.debug.computeNearDuration = duration;
  88338. // Potree.debug.numNodes = numNodes;
  88339. //console.log(lowestDistance.toString(2), duration);
  88340. //搬走
  88341. /* const tStart = performance.now();
  88342. const campos = camera.position;
  88343. let closestImage = Infinity;
  88344. for(const images of this.scene.orientedImages){
  88345. for(const image of images.images){
  88346. const distance = image.mesh.position.distanceTo(campos);
  88347. closestImage = Math.min(closestImage, distance);
  88348. }
  88349. }
  88350. const tEnd = performance.now();
  88351. if(result.lowestSpacing !== Infinity){
  88352. let near = result.lowestSpacing * 10.0;
  88353. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  88354. far = Math.max(far * 1.5, 10000);
  88355. near = Math.min(100.0, Math.max(0.01, near));
  88356. near = Math.min(near, closestImage);
  88357. far = Math.max(far, near + 10000);
  88358. if(near === Infinity){
  88359. near = 0.1;
  88360. }
  88361. camera.near = near;
  88362. camera.far = far;
  88363. }else{
  88364. // don't change near and far in this case
  88365. }
  88366. if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {
  88367. camera.near = -camera.far;
  88368. }*/
  88369. }
  88370. this.scene.cameraP.fov = this.fov;
  88371. let controls = this.getControls();
  88372. if (controls === this.deviceControls) {
  88373. this.controls.setScene(scene);
  88374. this.controls.update(delta);
  88375. this.scene.cameraP.position.copy(scene.view.position);
  88376. this.scene.cameraO.position.copy(scene.view.position);
  88377. } else if (controls !== null) {
  88378. controls.setScene(scene);
  88379. controls.update(delta);
  88380. //更新camera
  88381. this.viewports.forEach(viewport=>{
  88382. if(!viewport.active)return
  88383. viewport.view.applyToCamera(viewport.camera);
  88384. });
  88385. }
  88386. /* this.viewports.forEach(e=>{//判断camera画面是否改变
  88387. if(e.cameraChanged()){
  88388. this.dispatchEvent({
  88389. type: "camera_changed",
  88390. camera: e.camera,
  88391. viewport : e
  88392. })
  88393. }
  88394. }) */
  88395. this.cameraChanged();//判断camera画面是否改变
  88396. /* {//判断camera画面是否改变
  88397. if(this._previousCamera === undefined){
  88398. this._previousCamera = this.scene.getActiveCamera().clone();
  88399. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  88400. }
  88401. if(!this._previousCamera.matrixWorld.equals(camera.matrixWorld) ||
  88402. !this._previousCamera.projectionMatrix.equals(camera.projectionMatrix)
  88403. ){
  88404. this.dispatchEvent({
  88405. type: "camera_changed",
  88406. previous: this._previousCamera,
  88407. camera: camera
  88408. });
  88409. }
  88410. this._previousCamera = this.scene.getActiveCamera().clone();
  88411. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  88412. } */
  88413. { // update clip boxes
  88414. let boxes = [];
  88415. // volumes with clipping enabled
  88416. //boxes.push(...this.scene.volumes.filter(v => (v.clip)));
  88417. boxes.push(...this.scene.volumes.filter(v => (v.clip && v instanceof BoxVolume)));
  88418. // profile segments
  88419. for(let profile of this.scene.profiles){
  88420. boxes.push(...profile.boxes);
  88421. }
  88422. // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816
  88423. let degenerate = (box) => box.matrixWorld.determinant() !== 0;
  88424. let clipBoxes = boxes.filter(degenerate).map( box => {
  88425. box.updateMatrixWorld();
  88426. let boxInverse = box.matrixWorld.clone().invert();
  88427. let boxPosition = box.getWorldPosition(new Vector3());
  88428. return {box: box, inverse: boxInverse, position: boxPosition};
  88429. });
  88430. let clipPolygons = this.scene.polygonClipVolumes.filter(vol => vol.initialized);
  88431. // set clip volumes in material
  88432. for(let pointcloud of visiblePointClouds){
  88433. pointcloud.material.setClipBoxes(clipBoxes);
  88434. pointcloud.material.setClipPolygons(clipPolygons, this.clippingTool.maxPolygonVertices);
  88435. pointcloud.material.clipTask = this.clipTask;
  88436. pointcloud.material.clipMethod = this.clipMethod;
  88437. }
  88438. }
  88439. {
  88440. for(let pointcloud of visiblePointClouds){
  88441. pointcloud.material.elevationGradientRepeat = this.elevationGradientRepeat;
  88442. }
  88443. }
  88444. { // update navigation cube
  88445. this.navigationCube.update(camera.rotation);
  88446. }
  88447. this.updateAnnotations();
  88448. if(this.mapView){
  88449. this.mapView.update(delta);
  88450. if(this.mapView.sceneProjection){
  88451. $( "#potree_map_toggle" ).css("display", "block");
  88452. }
  88453. }
  88454. TWEEN.update(timestamp);
  88455. transitions.update(delta);
  88456. this.transformationTool.update();
  88457. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  88458. this.modules.ParticleEditor.update(delta);
  88459. this.mapViewer.update(delta);
  88460. }
  88461. this.dispatchEvent({
  88462. type: 'update',
  88463. delta: delta,
  88464. timestamp: timestamp});
  88465. if(Potree.measureTimings) {
  88466. performance.mark("update-end");
  88467. performance.measure("update", "update-start", "update-end");
  88468. }
  88469. //add ------
  88470. this.reticule.updateVisible();
  88471. }
  88472. updateViewPointcloud(camera, areaSize, isViewport){
  88473. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize );
  88474. //if(isViewport)return
  88475. const tStart = performance.now();
  88476. const campos = camera.position;
  88477. let closestImage = Infinity;
  88478. for(const images of this.scene.orientedImages){
  88479. for(const image of images.images){
  88480. const distance = image.mesh.position.distanceTo(campos);
  88481. closestImage = Math.min(closestImage, distance);
  88482. }
  88483. }
  88484. const tEnd = performance.now();
  88485. //改:不根据点云修改视野near far
  88486. var near = camera.near, far = camera.far;
  88487. if(!camera.limitFar && result.lowestSpacing !== Infinity){
  88488. //let near = result.lowestSpacing * 10.0;
  88489. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  88490. far = Math.max(far * 1.5, 10000);
  88491. //near = Math.min(100.0, Math.max(0.01, near));
  88492. //near = Math.min(near, closestImage);
  88493. far = Math.max(far, near + 10000);
  88494. /* if(near === Infinity){
  88495. near = 0.1;
  88496. } */
  88497. //camera.near = near; //为了其他物体的显示,不修改near
  88498. camera.far = far;
  88499. }
  88500. /* if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//???
  88501. camera.near = -camera.far;
  88502. } */
  88503. if(/* near != camera.near || */far != camera.far){
  88504. camera.updateProjectionMatrix();
  88505. }
  88506. //注:pointcloud.visibleNodes会随着near far自动更新
  88507. }
  88508. getPRenderer(){
  88509. if(this.useHQ){
  88510. if (!this.hqRenderer) {
  88511. this.hqRenderer = new HQSplatRenderer(this);
  88512. }
  88513. this.hqRenderer.useEDL = this.useEDL;
  88514. return this.hqRenderer;
  88515. }else {
  88516. /* if (this.useEDL && Features.SHADER_EDL.isSupported()) {
  88517. if (!this.edlRenderer) {
  88518. this.edlRenderer = new EDLRenderer(this);
  88519. }
  88520. return this.edlRenderer;
  88521. } else {
  88522. if (!this.potreeRenderer) {
  88523. this.potreeRenderer = new PotreeRenderer(this);
  88524. }
  88525. return this.potreeRenderer;
  88526. } */
  88527. if (!this.edlRenderer) {
  88528. this.edlRenderer = new EDLRenderer(this);
  88529. }
  88530. return this.edlRenderer;
  88531. }
  88532. }
  88533. renderVR(){
  88534. let renderer = this.renderer;
  88535. renderer.setClearColor(0x550000, 0);
  88536. renderer.clear();
  88537. let xr = renderer.xr;
  88538. let dbg = new PerspectiveCamera();
  88539. let xrCameras = xr.getCamera(dbg);
  88540. if(xrCameras.cameras.length !== 2){
  88541. return;
  88542. }
  88543. let makeCam = this.vrControls.getCamera.bind(this.vrControls);
  88544. { // clear framebuffer
  88545. if(viewer.background === "skybox"){
  88546. renderer.setClearColor(0xff0000, 1);
  88547. }else if(viewer.background === "gradient"){
  88548. renderer.setClearColor(0x112233, 1);
  88549. }else if(viewer.background === "black"){
  88550. renderer.setClearColor(0x000000, 1);
  88551. }else if(viewer.background === "white"){
  88552. renderer.setClearColor(0xFFFFFF, 1);
  88553. }else {
  88554. renderer.setClearColor(0x000000, 0);
  88555. }
  88556. renderer.clear();
  88557. }
  88558. // render background
  88559. if(this.background === "skybox"){
  88560. let {skybox} = this;
  88561. let cam = makeCam();
  88562. skybox.camera.rotation.copy(cam.rotation);
  88563. skybox.camera.fov = cam.fov;
  88564. skybox.camera.aspect = cam.aspect;
  88565. // let dbg = new THREE.Object3D();
  88566. let dbg = skybox.parent;
  88567. // dbg.up.set(0, 0, 1);
  88568. dbg.rotation.x = Math.PI / 2;
  88569. // skybox.camera.parent = dbg;
  88570. // dbg.children.push(skybox.camera);
  88571. dbg.updateMatrix();
  88572. dbg.updateMatrixWorld();
  88573. skybox.camera.updateMatrix();
  88574. skybox.camera.updateMatrixWorld();
  88575. skybox.camera.updateProjectionMatrix();
  88576. renderer.render(skybox.scene, skybox.camera);
  88577. // renderer.render(skybox.scene, cam);
  88578. }else if(this.background === "gradient"){
  88579. // renderer.render(this.scene.sceneBG, this.scene.cameraBG);
  88580. }
  88581. this.renderer.xr.getSession().updateRenderState({
  88582. depthNear: 0.1,
  88583. depthFar: 10000
  88584. });
  88585. let cam = null;
  88586. let view = null;
  88587. { // render world scene
  88588. cam = makeCam();
  88589. cam.position.z -= 0.8 * cam.scale.x;
  88590. cam.parent = null;
  88591. // cam.near = 0.05;
  88592. cam.near = viewer.scene.getActiveCamera().near;
  88593. cam.far = viewer.scene.getActiveCamera().far;
  88594. cam.updateMatrix();
  88595. cam.updateMatrixWorld();
  88596. this.scene.scene.updateMatrix();
  88597. this.scene.scene.updateMatrixWorld();
  88598. this.scene.scene.matrixAutoUpdate = false;
  88599. let camWorld = cam.matrixWorld.clone();
  88600. view = camWorld.clone().invert();
  88601. this.scene.scene.matrix.copy(view);
  88602. this.scene.scene.matrixWorld.copy(view);
  88603. cam.matrix.identity();
  88604. cam.matrixWorld.identity();
  88605. cam.matrixWorldInverse.identity();
  88606. renderer.render(this.scene.scene, cam);
  88607. this.scene.scene.matrixWorld.identity();
  88608. }
  88609. for(let pointcloud of this.scene.pointclouds){
  88610. let viewport = xrCameras.cameras[0].viewport;
  88611. pointcloud.material.useEDL = false;
  88612. pointcloud.screenHeight = viewport.height;
  88613. pointcloud.screenWidth = viewport.width;
  88614. // automatically switch to paraboloids because they cause far less flickering in VR,
  88615. // when point sizes are larger than around 2 pixels
  88616. // if(Features.SHADER_INTERPOLATION.isSupported()){
  88617. // pointcloud.material.shape = Potree.PointShape.PARABOLOID;
  88618. // }
  88619. }
  88620. // render point clouds
  88621. for(let xrCamera of xrCameras.cameras){
  88622. let v = xrCamera.viewport;
  88623. renderer.setViewport(v.x, v.y, v.width, v.height);
  88624. // xrCamera.fov = 90;
  88625. { // estimate VR fov
  88626. let proj = xrCamera.projectionMatrix;
  88627. let inv = proj.clone().invert();
  88628. let p1 = new Vector4(0, 1, -1, 1).applyMatrix4(inv);
  88629. let rad = p1.y;
  88630. let fov = 180 * (rad / Math.PI);
  88631. xrCamera.fov = fov;
  88632. }
  88633. for(let pointcloud of this.scene.pointclouds){
  88634. const {material} = pointcloud;
  88635. material.useEDL = false;
  88636. }
  88637. let vrWorld = view.clone().invert();
  88638. vrWorld.multiply(xrCamera.matrixWorld);
  88639. let vrView = vrWorld.clone().invert();
  88640. this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, {
  88641. viewOverride: vrView,
  88642. });
  88643. }
  88644. { // render VR scene
  88645. let cam = makeCam();
  88646. cam.parent = null;
  88647. renderer.render(this.sceneVR, cam);
  88648. }
  88649. renderer.resetState();
  88650. }
  88651. clear(params={}){
  88652. let background = params.background || this.background;
  88653. let backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  88654. let renderer = this.renderer;
  88655. //let gl = renderer.getContext()
  88656. if(background instanceof Color){ //add
  88657. renderer.setClearColor(background, backgroundOpacity);
  88658. }else if(background === "skybox"){
  88659. renderer.setClearColor(0x000000, 0);
  88660. } else if (background === 'gradient') {
  88661. renderer.setClearColor(0x000000, 0);
  88662. } else if (background === 'black') {
  88663. renderer.setClearColor(0x000000, 1);
  88664. } else if (background === 'white') {
  88665. renderer.setClearColor(0xFFFFFF, 1);
  88666. } else {
  88667. renderer.setClearColor(background, backgroundOpacity);
  88668. }
  88669. params.target || renderer.clear();
  88670. }
  88671. renderDefault(params_={}){
  88672. if(!this.visible || this.paused )return
  88673. /* if(this.outlinePass.selectedObjects.length){
  88674. this.clear()
  88675. this.composer.render(this.scene.scene, this.mainViewport.camera );
  88676. return;
  88677. } */
  88678. let pRenderer = this.getPRenderer();
  88679. let viewports = params_.viewports || this.viewports;
  88680. let renderSize;
  88681. if(params_.target){
  88682. renderSize = new Vector2$1(params_.target.width, params_.target.height); //是画布大小
  88683. //可能需要viewer.setSize
  88684. }else {
  88685. renderSize = this.renderer.getSize(new Vector2$1()); //是client大小
  88686. }
  88687. let needSResize = viewports.filter(e=>e.active).length > 1 || params_.resize;
  88688. viewports.forEach(view=>{
  88689. let params = $.extend({},params_);
  88690. params.viewport = view;
  88691. //if(!params.target){
  88692. params.camera = params.camera || view.camera;
  88693. params.extraEnableLayers = view.extraEnableLayers;
  88694. params.cameraLayers = view.cameraLayers;
  88695. //}
  88696. if(!view.active)return
  88697. var left,bottom,width,height;
  88698. {
  88699. left = Math.ceil(renderSize.x * view.left);
  88700. bottom = Math.ceil(renderSize.y * view.bottom);
  88701. if(params_.target){//有target时最好viewport是专门建出来的
  88702. width = Math.ceil(renderSize.x * view.width); //target的大小可能和viewport不同,比如截图,这时会更改viewport大小
  88703. height = Math.ceil(renderSize.y * view.height);
  88704. }else {
  88705. width = view.resolution.x; // 用的是client的width和height
  88706. height = view.resolution.y;
  88707. }
  88708. if(width == 0 || height == 0)return
  88709. let scissorTest = view.width<1 || view.height<1;
  88710. if(params_.target){
  88711. params_.target.viewport.set(left, bottom, width, height);
  88712. scissorTest && params_.target.scissor.set(left, bottom, width, height);
  88713. params_.target.scissorTest = scissorTest;
  88714. }else {
  88715. this.renderer.setViewport(left, bottom, width, height); //规定视口,影响图形变换(画布的使用范围)
  88716. scissorTest && this.renderer.setScissor( left, bottom, width, height );//规定渲染范围
  88717. this.renderer.setScissorTest( scissorTest );//开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪
  88718. }
  88719. }
  88720. if(needSResize){
  88721. this.emitResizeMsg( { viewport:view} );
  88722. }
  88723. //needSResize && this.emitResizeMsg({resolution: params_.target ? new THREE.Vector2(width,height) : view.resolution2, left:view.left, bottom:view.bottom })//resize everything such as lines targets
  88724. viewer.dispatchEvent({type: "render.begin", viewer: viewer, viewport:view, params });
  88725. if(view.render){
  88726. view.render($.extend({}, params, {
  88727. renderer:this.renderer, clear:this.clear.bind(this), resize:null,
  88728. renderOverlay: this.renderOverlay.bind(this), force:!view.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好)
  88729. }));
  88730. }
  88731. view.render || this.clear(params);
  88732. pRenderer.clearTargets(params);
  88733. //先渲染不透明的model:
  88734. /* if(this.objs.children.length){
  88735. this.renderer.setRenderTarget(params.target||null)
  88736. this.setCameraLayers(params.camera, ['model'] )//先渲染模型后渲染点云,否则半透明的点云的blend没有混合模型的部分(但模型为何可以混合点云的部分?估计还是PotreeRenderer有问题)
  88737. this.renderer.render(this.scene.scene, params.camera);
  88738. } */
  88739. if(Potree.settings.notAdditiveBlending){
  88740. params.renderBeforeCloud = true;
  88741. this.renderOverlay1(params);
  88742. //view.render || this.renderOverlay(params)
  88743. }
  88744. if(!view.noPointcloud ){
  88745. //if(!params.target){
  88746. //params.width = width; params.height = height;
  88747. //}
  88748. if(view.render){
  88749. params.noBG = true;
  88750. }
  88751. view.beforeRender && view.beforeRender();
  88752. this.updateViewPointcloud(params.camera, view.resolution2, true);
  88753. params.background = view.background;
  88754. params.backgroundColor = view.backgroundColor;
  88755. params.backgroundOpacity = view.backgroundOpacity;
  88756. pRenderer.render(params);
  88757. }
  88758. //view.render || this.renderOverlay(params)
  88759. if(Potree.settings.notAdditiveBlending){
  88760. params.renderBeforeCloud = false;
  88761. this.renderOverlay1(params);
  88762. this.renderOverlay2(params);
  88763. }else {
  88764. view.render || this.renderOverlay(params);
  88765. }
  88766. view.afterRender && view.afterRender();
  88767. this.dispatchEvent({type: "render.end", viewer: this, viewport:view });
  88768. });
  88769. /* if(params_.screenshot){ //抗锯齿
  88770. params_.target.viewport.set(0, 0, params_.target.width, params_.target.height);
  88771. //scissorTest && params_.target.scissor.set(left, bottom, width, height);
  88772. params_.target.scissorTest = false
  88773. this.renderer.setRenderTarget(params_.target)
  88774. this.composer.render();
  88775. this.renderer.setRenderTarget(params_.target) //本想再画一层标签,但是viewport总是出错
  88776. } */
  88777. this.renderer.setRenderTarget(null);
  88778. }
  88779. /*
  88780. 关于透明度:
  88781. 由于点云和mesh是分开渲染的,且材质很不一样,所以透明和blend有冲突
  88782. 1 如果点云的blend是AdditiveBlending,也就是普通的叠加模式。
  88783. 则半透明点云的depthTest和depthWrite都为false
  88784. 这时候mesh要后渲染,且depthWrite不能为false(除非depthTest也为false),否则将被点云遮住。
  88785. 2 如果点云的blend是普通型
  88786. 则半透明点云的depthTest和depthWrite都为true。(为何depthWrite不能像mesh一样为false, 否则点云自身透明会错乱,可能因为太多points了)
  88787. 这时候若mesh全部先渲染,则 透过depthWrite为false的半透明mesh看不透明点云,mesh会完全被点云遮住。但是透明的物体就是depthWrite要为false,否则也会完全遮住点云
  88788. 即使是后渲染半透明的mesh,若透过点云看mesh,mesh会完全被点云遮住(为什么之前遇到过 透过点云看mesh,点云会显示不出)
  88789. 最终选择是先渲染不透明的mesh,然后点云,然后透明的mesh。虽然点云对mesh透明会失效。
  88790. */
  88791. renderOverlay(params){
  88792. this.renderOverlay1(params);
  88793. this.renderOverlay2(params);
  88794. /* let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  88795. this.reticule.updateAtViewports(params.viewport)
  88796. this.renderer.setRenderTarget(params.target||null)
  88797. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  88798. let cameraLayers
  88799. if(params.cameraLayers) cameraLayers = params.cameraLayers
  88800. else{
  88801. if(params.isMap)cameraLayers = ['bothMapAndScene']
  88802. else cameraLayers = ['sceneObjects', 'model', 'bothMapAndScene' ];
  88803. }
  88804. if(cameraLayers.length){
  88805. this.setCameraLayers(camera, cameraLayers, params.extraEnableLayers) //透明贴图层 skybox 、reticule marker 不能遮住测量线
  88806. this.renderer.render(this.scene.scene, camera);
  88807. }
  88808. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  88809. //清除深度 !!!!
  88810. this.renderer.clearDepth();
  88811. //this.transformationTool.update();
  88812. if(!params.magnifier){
  88813. //测量线
  88814. this.dispatchEvent({type: "render.pass.perspective_overlay", camera, screenshot:params.screenshot});
  88815. if(!params.screenshot && !params.isMap){
  88816. this.setCameraLayers(camera, ['magnifier']) //magnifier 遮住测量线
  88817. this.renderer.render(this.scene.scene, camera);
  88818. }
  88819. }
  88820. if(!params.isMap) {
  88821. this.setCameraLayers(camera, ['volume','transformationTool'])
  88822. this.renderer.render(this.clippingTool.sceneVolume, camera);
  88823. this.renderer.render(this.transformationTool.scene, camera);
  88824. } */
  88825. }
  88826. renderOverlay1(params){
  88827. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  88828. this.reticule.updateAtViewports(params.viewport);
  88829. this.renderer.setRenderTarget(params.target||null);
  88830. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  88831. let cameraLayers;
  88832. if(params.cameraLayers) cameraLayers = params.cameraLayers;
  88833. else {
  88834. if(params.isMap)cameraLayers = ['bothMapAndScene'];
  88835. else cameraLayers = ['sceneObjects', 'model', 'bothMapAndScene' ];
  88836. }
  88837. if(cameraLayers.length){
  88838. this.setCameraLayers(camera, cameraLayers, params.extraEnableLayers); //透明贴图层 skybox 、reticule marker 不能遮住测量线
  88839. if('renderBeforeCloud' in params){
  88840. this.scene.scene.traverse((object)=>{
  88841. if(object.material){
  88842. this.updateVisible(object, 'renderOpa',
  88843. (params.renderBeforeCloud && (object.material.opacity<1 || !object.material.depthTest) || (!params.renderBeforeCloud) && (object.material.opacity==1 && object.material.depthTest))? false:true);
  88844. //点云之前渲染的话隐藏半透明的, 点云之后渲染的话隐藏不透明的。 depthTest==false的也最后渲染
  88845. }
  88846. });//ground的材质中opacity为1,所以被当做不透明了
  88847. }
  88848. this.renderer.render(this.scene.scene, camera);
  88849. if('renderBeforeCloud' in params){
  88850. this.scene.scene.traverse((object)=>{
  88851. if(object.material){
  88852. this.updateVisible(object, 'renderOpa', true); //恢复
  88853. }
  88854. });
  88855. }
  88856. }
  88857. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  88858. }
  88859. renderOverlay2(params){
  88860. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  88861. //清除深度 !!!!
  88862. this.renderer.clearDepth();
  88863. //this.transformationTool.update();
  88864. if(!params.magnifier){
  88865. //测量线
  88866. this.dispatchEvent({type: "render.pass.perspective_overlay", camera, screenshot:params.screenshot});
  88867. if(!params.screenshot && !params.isMap){
  88868. this.setCameraLayers(camera, ['magnifier']); //magnifier 遮住测量线
  88869. this.renderer.render(this.scene.scene, camera);
  88870. }
  88871. }
  88872. if(!params.isMap) {
  88873. this.setCameraLayers(camera, ['volume','transformationTool']);
  88874. this.renderer.render(this.clippingTool.sceneVolume, camera);
  88875. this.renderer.render(this.transformationTool.scene, camera);
  88876. }
  88877. }
  88878. /* renderDefault(){//测试 ios15.4.1
  88879. //let pRenderer = this.getPRenderer();
  88880. //this.clear()
  88881. this.renderer.autoClear = false
  88882. this.renderer.setRenderTarget(null)
  88883. let camera = this.scene.getActiveCamera();
  88884. this.setCameraLayers(camera, [ 'sceneObjects', 'marker' , 'reticule' ,'skybox' ])
  88885. this.renderer.render(this.scene.scene, camera);
  88886. // pRenderer.clearTargets( );
  88887. //pRenderer.render( );
  88888. } */
  88889. setLimitFar(state){//切换是否limitFar
  88890. viewer.mainViewport.camera.limitFar = !!state;
  88891. if(state){
  88892. viewer.mainViewport.camera.near = 0.02;
  88893. viewer.mainViewport.camera.far = Potree.settings.displayMode == 'showPanos' ? viewer.farWhenShowPano : Potree.settings.cameraFar;
  88894. viewer.mainViewport.camera.updateProjectionMatrix();
  88895. }
  88896. }
  88897. setCameraLayers(camera, enableLayers, extraEnableLayers=[]){//add
  88898. camera.layers.disableAll();
  88899. enableLayers.concat(extraEnableLayers).forEach(e=>{
  88900. let layer = Potree.config.renderLayers[e];
  88901. if(layer == void 0){
  88902. console.error('setCameraLayer没找到layer!');
  88903. return
  88904. }
  88905. camera.layers.enable(layer);
  88906. });
  88907. }
  88908. setObjectLayers(object, layerName){//add
  88909. let layer = Potree.config.renderLayers[layerName];
  88910. if(layer == void 0){
  88911. console.error('setCameraLayer没找到layer!');
  88912. return
  88913. }
  88914. object.traverse(e=>{
  88915. e.layers.set(layer);
  88916. });
  88917. }
  88918. /* updateVisible(object, reason, ifShow, force){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  88919. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  88920. if(!object.forceVisibleReasons) object.forceVisibleReasons = []; //只要有一项代表一定可见,优先级比unvisibleReasons高
  88921. if(ifShow){
  88922. if(force){
  88923. object.forceVisibleReasons.includes(reason) || object.forceVisibleReasons.push(reason)
  88924. object.visible = true;
  88925. object.dispatchEvent({
  88926. type: 'isVisible',
  88927. visible:true,
  88928. reason
  88929. })
  88930. }
  88931. var index = object.unvisibleReasons.indexOf(reason)
  88932. if(index > -1){
  88933. object.unvisibleReasons.splice(index, 1);
  88934. if(object.unvisibleReasons.length == 0){
  88935. object.visible = true;
  88936. //mapChange()
  88937. object.dispatchEvent({
  88938. type: 'isVisible',
  88939. visible:true,
  88940. reason
  88941. })
  88942. }
  88943. }
  88944. }else{
  88945. var index = object.forceVisibleReasons.indexOf(reason)
  88946. if(index > -1){//如果是forceVisibleReasons里的,就只是单纯取消之前设置的一定可见
  88947. object.forceVisibleReasons.splice(index, 1);
  88948. }else{
  88949. if(!object.unvisibleReasons.includes(reason)) object.unvisibleReasons.push(reason)
  88950. }
  88951. if(object.forceVisibleReasons.length) return
  88952. var visiBefore = object.visible
  88953. if(object.unvisibleReasons.length && visiBefore){
  88954. object.visible = false
  88955. //mapChange()
  88956. object.dispatchEvent({
  88957. type: 'isVisible',
  88958. visible:false,
  88959. reason,
  88960. })
  88961. }else if(object.unvisibleReasons.length ==0 && !visiBefore){
  88962. object.visible = true;
  88963. //mapChange()
  88964. object.dispatchEvent({
  88965. type: 'isVisible',
  88966. visible:true,
  88967. reason
  88968. })
  88969. }
  88970. }
  88971. } */
  88972. updateVisible(object, reason, ifShow, level=0, type){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  88973. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  88974. if(!object.visibleReasons) object.visibleReasons = []; //在同级时,优先可见
  88975. var update = function(){
  88976. //先按从高到低的level排列
  88977. object.unvisibleReasons = object.unvisibleReasons.sort((a,b)=>b.level-a.level);
  88978. object.visibleReasons = object.visibleReasons.sort((a,b)=>b.level-a.level);
  88979. var maxVisiLevel = object.visibleReasons[0] ? object.visibleReasons[0].level : -1;
  88980. var maxunVisiLevel = object.unvisibleReasons[0] ? object.unvisibleReasons[0].level : -1;
  88981. var shouldVisi = maxVisiLevel >= maxunVisiLevel;
  88982. var visiBefore = object.visible;
  88983. if(visiBefore != shouldVisi){
  88984. object.visible = shouldVisi;
  88985. object.dispatchEvent({
  88986. type: 'isVisible',
  88987. visible: shouldVisi,
  88988. reason,
  88989. });
  88990. }
  88991. };
  88992. if(ifShow){
  88993. var index = object.unvisibleReasons.findIndex(e=>e.reason == reason);
  88994. if(index > -1){
  88995. type = 'cancel';
  88996. object.unvisibleReasons.splice(index, 1);
  88997. }
  88998. if(type == 'add' ){
  88999. if(!object.visibleReasons.some(e=>e.reason == reason)){
  89000. object.visibleReasons.push({reason,level});
  89001. }
  89002. }
  89003. }else {
  89004. var index = object.visibleReasons.findIndex(e=>e.reason == reason);
  89005. if(index > -1){
  89006. type = 'cancel';
  89007. object.visibleReasons.splice(index, 1);
  89008. }
  89009. if(type != 'cancel' ){
  89010. if(!object.unvisibleReasons.some(e=>e.reason == reason)){
  89011. object.unvisibleReasons.push({reason,level});
  89012. }
  89013. }
  89014. }
  89015. update();
  89016. }
  89017. getObjVisiByReason(object,reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  89018. if(object.visible)return true
  89019. else {
  89020. return !object.unvisibleReasons || !object.unvisibleReasons.some(e=>e.reason == reason)
  89021. }
  89022. }
  89023. /* 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  89024. https://blog.csdn.net/weixin_30378311/article/details/94846947 */
  89025. render(params={}){//add params
  89026. if(Potree.measureTimings) performance.mark("render-start");
  89027. if(this.outlinePass.selectedObjects.length && this.outlinePass.edgeStrength > 0 && !params.screenshot){
  89028. this.composer.render(this.inputHandler.interactiveScenes.concat(this.scene.scene).concat(viewer.scene.scenePointCloud), null, this.viewports, this.renderDefault.bind(this));
  89029. }else {
  89030. this.renderDefault(params);
  89031. }
  89032. if(Potree.measureTimings){
  89033. performance.mark("render-end");
  89034. performance.measure("render", "render-start", "render-end");
  89035. }
  89036. }
  89037. startScreenshot(info={}, width=800, height=400, compressRatio){//add
  89038. let deferred = info.deferred || $.Deferred();
  89039. let viewerMaster = info.map ? this.mapViewer : this; //截图主体
  89040. let useMap = info.type == 'measure' || info.map;
  89041. if(this.images360.flying){//如果在飞,飞完再截图
  89042. info.deferred = deferred;
  89043. let f = ()=>{
  89044. this.startScreenshot(info, width, height, compressRatio);
  89045. this.images360.removeEventListener('cameraMoveDone', f);
  89046. };
  89047. this.images360.addEventListener('cameraMoveDone', f); //once
  89048. return deferred.promise()
  89049. }
  89050. var sid = Date.now();
  89051. //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小
  89052. console.log('startScreenshot: '+sid);
  89053. let updateCamera = ()=>{
  89054. this.viewports.forEach(e=>{
  89055. e.view.applyToCamera(e.camera); //因为fly时只更新了view所以要强制更新下camera
  89056. this.dispatchEvent({ //update map and sprite
  89057. type: "camera_changed",
  89058. camera: e.camera,
  89059. viewport : e,
  89060. changeInfo:{positionChanged:true,changed:true}
  89061. });
  89062. });
  89063. };
  89064. let screenshot = ()=>{
  89065. useMap && (viewer.mapViewer.needRender = true);
  89066. let { dataUrl } = viewerMaster.makeScreenshot( new Vector2$1(width,height), null, compressRatio );
  89067. if(!Potree.settings.isOfficial){
  89068. Common.downloadFile(dataUrl, 'screenshot.jpg');
  89069. }
  89070. var finish = ()=>{
  89071. oldStates.viewports.forEach(old=>{//恢复相机
  89072. var viewport = viewports.find(v=>v.name == old.name);
  89073. viewport.left = old.left;
  89074. viewport.width = old.width;
  89075. viewport.view.copy(old.view);
  89076. viewport.view.applyToCamera(viewport.camera);
  89077. });
  89078. viewer.updateScreenSize({forceUpdateSize:true});//更新像素
  89079. /* oldStates.viewports.forEach(old=>{//恢复相机
  89080. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  89081. this.dispatchEvent({ //update map
  89082. type: "camera_changed",
  89083. camera: viewport.camera,
  89084. viewport : viewport
  89085. })
  89086. }) */
  89087. updateCamera();
  89088. deferred.resolve(dataUrl);
  89089. console.log('screenshot done: '+sid);
  89090. };
  89091. {//恢复:
  89092. if(info.type == 'measure'){
  89093. this.scene.measurements.forEach(e=>this.updateVisible(e, 'screenshot',true));
  89094. info.measurement.setSelected(false, 'screenshot');
  89095. }
  89096. this.images360.panos.forEach(pano=>{
  89097. viewer.updateVisible(pano, 'screenshot', true);
  89098. });
  89099. viewer.updateVisible(this.reticule, 'screenshot', true);
  89100. if(useMap){
  89101. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', true);
  89102. if(oldStates.attachedToViewer != this.mapViewer.attachedToViewer){
  89103. if(info.type == 'measure'){
  89104. this.mapViewer.attachToMainViewer(false );
  89105. }
  89106. }
  89107. mapViewport.camera.zoom = oldStates.mapZoom;
  89108. mapViewport.camera.updateProjectionMatrix();
  89109. }
  89110. if(Potree.settings.displayMode == 'showPanos') {
  89111. viewer.images360.flyToPano({pano:oldStates.pano, duration:0, callback:()=>{
  89112. finish();
  89113. }});
  89114. }else {
  89115. finish();
  89116. }
  89117. }
  89118. };// screenshot end
  89119. let mapViewport;
  89120. let mainViewport = this.mainViewport;
  89121. let viewports = [mainViewport];
  89122. let oldStates = {
  89123. viewports : [mainViewport.clone()],
  89124. pano: Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : null,
  89125. };
  89126. if(useMap){
  89127. mapViewport = this.mapViewer.viewports[0];
  89128. viewports.push(mapViewport);
  89129. oldStates.viewports.push(mapViewport.clone());
  89130. oldStates.attachedToViewer = this.mapViewer.attachedToViewer;
  89131. oldStates.mapZoom = mapViewport.camera.zoom;
  89132. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', false);//令mapCursor不可见
  89133. }
  89134. if(info.hideMarkers){
  89135. this.images360.panos.forEach(pano=>{//令漫游点不可见
  89136. viewer.updateVisible(pano, 'screenshot', false);
  89137. });
  89138. }
  89139. viewer.updateVisible(this.reticule, 'screenshot', false);//令reticule不可见
  89140. if(info.type == 'measure'){//要截图双屏
  89141. this.scene.measurements.forEach(e=>this.updateVisible(e,'screenshot',e == info.measurement) );
  89142. info.measurement.setSelected(true, 'screenshot');
  89143. //因为分屏后位置才最终确定,才能确定是否显示出floorplan所以先分屏
  89144. if(Potree.settings.floorplanEnable){
  89145. this.mapViewer.attachToMainViewer(true, 'measure', 0.5 );
  89146. }
  89147. viewer.updateScreenSize({forceUpdateSize:true, width, height}); //更新viewports相机透视 使focusOnObject在此窗口大小下
  89148. let begin = ()=>{
  89149. useMap = this.mapViewer.attachedToViewer;
  89150. updateCamera();
  89151. let waitTime = Potree.settings.displayMode == 'showPointCloud' ? 500 : 0; //等点云加载 网速差的话还是加载稀疏 是否要用最高质量点云
  89152. if(useMap){
  89153. let waitMap = ()=>{
  89154. //console.log('waitMap: '+sid)
  89155. this.mapViewer.waitLoadDone(screenshot.bind(this));//等待地图所有加载完
  89156. };
  89157. setTimeout(waitMap.bind(this), waitTime);
  89158. }else {
  89159. setTimeout(screenshot.bind(this), waitTime);
  89160. }
  89161. };
  89162. let {promise}= this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024} );//注意:不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的
  89163. promise.done(()=>{
  89164. //console.log('promise.done')
  89165. //根据当前位置更新floorplan显示
  89166. //console.log('view Pos ', this.mainViewport.view.position.toArray())
  89167. this.updateDatasetAt(true);
  89168. this.modules.SiteModel.updateEntityAt(true);
  89169. //this.updateFpVisiDatasets()
  89170. //console.log('currentFloor', this.modules.SiteModel.currentFloor, 'currentDataset', this.atDatasets )
  89171. let floorplanShowed = this.mapViewer.mapLayer.maps.some(e => e.name.includes('floorplan') && e.objectGroup.visible);
  89172. if(!floorplanShowed && this.mapViewer.attachedToViewer){
  89173. this.mapViewer.attachToMainViewer(false); //取消分屏
  89174. viewer.updateScreenSize({forceUpdateSize:true, width, height}); //更新viewports相机透视
  89175. let {promise} = this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024} );//因画面比例更改,重新focus
  89176. promise.done(()=>{
  89177. begin();
  89178. });
  89179. }else {
  89180. begin();
  89181. }
  89182. });
  89183. }else {
  89184. screenshot();
  89185. }
  89186. /*
  89187. 测量线的截图因为要调用分屏的,会改变画面
  89188. 但是普通截图的话,不会改变画面
  89189. */
  89190. return deferred.promise()
  89191. }
  89192. focusOnObject(object, type, duration, o={} ) {
  89193. //飞向热点、测量线等 。
  89194. //console.log('focusOnObject: ', object, type)
  89195. let deferred = o.deferred || $.Deferred();
  89196. let target = new Vector3, //相机focus的位置
  89197. position = new Vector3, //相机最终位置
  89198. dis; //相机距离目标
  89199. duration = duration == void 0 ? 1000 : duration;
  89200. let camera = viewer.scene.getActiveCamera();
  89201. let cameraPos = camera.position.clone();
  89202. let getPosWithFullBound = (points, boundingBox, target, cameraPos )=>{//使boundingBox差不多占满屏幕时的相机到target的距离
  89203. // points 和 boundingBox 至少有一个
  89204. let scale;
  89205. if(o.dontChangeCamDir){
  89206. var inv = camera.matrixWorldInverse;
  89207. }else {
  89208. var cameraTemp = camera.clone();
  89209. cameraTemp.position.copy(cameraPos);
  89210. cameraTemp.lookAt(target);
  89211. cameraTemp.updateMatrix();
  89212. cameraTemp.updateMatrixWorld();
  89213. //对镜头的bound
  89214. var inv = cameraTemp.matrixWorldInverse;
  89215. }
  89216. var bound = new Box3();
  89217. if(points){//使用points得到的bound更小 //如果points和boundingbox的差别较大,尤其使target和points中心不一致,那么points不一定会刚好在boundingbox内
  89218. points.forEach(e=>{
  89219. var p = e.clone().applyMatrix4(inv);
  89220. bound.expandByPoint(p);
  89221. });
  89222. scale = 1.3;
  89223. }else {
  89224. bound = boundingBox.applyMatrix4(inv);
  89225. scale = 0.9;
  89226. }
  89227. let boundSize = bound.getSize(new Vector3);
  89228. {
  89229. boundSize.x *= scale; //稍微放大一些,不然会靠到屏幕边缘
  89230. boundSize.y *= scale;
  89231. let min = 0.0001;
  89232. boundSize.x = Math.max(min, boundSize.x);
  89233. boundSize.y = Math.max(min, boundSize.y);
  89234. }
  89235. let aspect = boundSize.x / boundSize.y;
  89236. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  89237. dis = boundSize.y/2/ Math.tan(MathUtils.degToRad(camera.fov / 2)) + boundSize.z/2;
  89238. }else {
  89239. let hfov = cameraLight.getHFOVForCamera(camera, true);
  89240. dis = boundSize.x/2 / Math.tan(hfov / 2) + boundSize.z/2;
  89241. }
  89242. dis = Math.max(0.1,dis);
  89243. //三个顶点以上的由于measure的中心不等于bound的中心,所以点会超出bound外。 且由于视椎近大远小,即使是两个点的,bound居中后线看上去仍旧不居中.
  89244. //获得相机最佳位置
  89245. let dir;
  89246. if(o.dontChangeCamDir){
  89247. dir = viewer.mainViewport.view.direction.negate();
  89248. }else {
  89249. dir = new Vector3().subVectors(cameraPos, target).normalize();
  89250. }
  89251. if(o.dontLookUp && dir.z < 0){
  89252. dir.negate();
  89253. }
  89254. position.copy(target).add(dir.multiplyScalar(dis));
  89255. if(false){//打开以检查box
  89256. if(!this.boundBox){//调试
  89257. this.boundBox = new Mesh(new BoxGeometry(1,1,1,1));
  89258. this.boundBox.material.wireframe = true;
  89259. this.boundBox.up.set(0,0,1);
  89260. //viewer.updateVisible(this.boundBox, 'hidden', true)//打开以检查box
  89261. this.setObjectLayers(this.boundBox,'sceneObjects');
  89262. this.scene.scene.add(this.boundBox);
  89263. }
  89264. this.boundBox.position.copy(target);
  89265. this.boundBox.scale.copy(boundSize);
  89266. this.boundBox.lookAt(position);
  89267. }
  89268. return position
  89269. };
  89270. if(this.images360.flying){
  89271. let f = ()=>{
  89272. this.focusOnObject(object, type, duration, $.extend(o,{deferred}));
  89273. this.images360.removeEventListener('cameraMoveDone',f);
  89274. };
  89275. this.images360.addEventListener('cameraMoveDone',f);
  89276. return {promise: deferred.promise() }
  89277. }
  89278. if (type == 'measure') {
  89279. target.copy(object.getCenter());
  89280. //试试改变位置,直视测量线。能避免倾斜角度造成的非常不居中、以及看不到面的情况
  89281. if(object.facePlane/* && window.focusMeasureFaceToIt */){
  89282. let normal;
  89283. if(object.facePlane){
  89284. normal = object.facePlane.normal.clone();
  89285. }
  89286. let angle = this.scene.view.direction.angleTo(normal);
  89287. let minDiff = MathUtils.degToRad(60);
  89288. //console.log('angle',angle)
  89289. if(angle>minDiff && angle<Math.PI-minDiff){//当几乎正对时就不执行
  89290. if(angle<Math.PI/2){ //在背面
  89291. normal.negate();
  89292. }
  89293. let dir = new Vector3().subVectors(camera.position, target).normalize();
  89294. let newDir = new Vector3().addVectors(dir,normal);//两个角度的中间
  89295. cameraPos.copy(target.clone().add(newDir));
  89296. }
  89297. }else if(object.points.length == 2){ //线段
  89298. let lineDir = new Vector3().subVectors(object.points[0],object.points[1]).normalize();
  89299. let angle = this.scene.view.direction.angleTo(lineDir);
  89300. let maxDiff = Math.PI*0.25;// 45度
  89301. if(angle<maxDiff || angle>Math.PI-maxDiff){//当几乎正对时就不执行
  89302. if(angle>Math.PI/2){ //令dir和lineDir成钝角
  89303. lineDir.negate();
  89304. }
  89305. let dir = new Vector3().subVectors(camera.position, target).normalize();
  89306. let mid = new Vector3().addVectors(lineDir, dir).normalize(); //中间法向量(如果刚好dir和lineDir反向,那得到的为零向量,就不移动了,但一般不会酱紫吧)
  89307. let newDir = new Vector3().addVectors(dir, mid);
  89308. cameraPos.copy(target.clone().add(newDir));
  89309. }
  89310. }else {
  89311. console.error('measure 没有facePlane points点数还不为2?');
  89312. }
  89313. position = getPosWithFullBound(object.points, null, target, cameraPos );
  89314. if(this.mapViewer/* .attachedToViewer */){
  89315. //console.log('mapFocusOn: '+target.toArray())
  89316. const minBound = new Vector2$1(4,4);//针对垂直线,在地图上只有一个点
  89317. //原始的bound
  89318. let boundOri = new Box3();
  89319. object.points.forEach(e=>{
  89320. boundOri.expandByPoint(e);
  89321. });
  89322. let boundSizeOri = boundOri.getSize(new Vector3);
  89323. let boundSizeMap = boundSizeOri.clone().multiplyScalar(2);
  89324. boundSizeMap.x = Math.max(minBound.x, boundSizeMap.x );
  89325. boundSizeMap.y = Math.max(minBound.y, boundSizeMap.y );
  89326. this.mapViewer.moveTo(target.clone(), boundSizeMap, duration);
  89327. }
  89328. if(Potree.settings.displayMode == 'showPointCloud'){ //点云
  89329. let minDis = 0.3;
  89330. //if(o.checkIntersect){
  89331. let checkIntersect = ( )=>{
  89332. let intersect = this.inputHandler.ifBlockedByIntersect(position, null , true, target);// 不一定准确
  89333. if(intersect){
  89334. let blockCount = 0, unblockCount = 0, visi;
  89335. for(let i=0;i<object.points.length;i++){ //如果顶点超过一半不可见,就要更改位置
  89336. let p = object.points[i];
  89337. let blocked = this.inputHandler.ifBlockedByIntersect(p, 0.3 , true, position, 4);
  89338. if(blocked){
  89339. blockCount ++;
  89340. if(blockCount / object.points.length >= 0.5){
  89341. visi = false;
  89342. break
  89343. }
  89344. }else {
  89345. unblockCount ++;
  89346. if(unblockCount / object.points.length > 0.5){
  89347. visi = true;
  89348. break
  89349. }
  89350. }
  89351. }
  89352. if(visi == void 0){
  89353. visi = unblockCount / object.points.length > 0.5;
  89354. }
  89355. let shrink = ()=>{
  89356. let dir = new Vector3().subVectors(position, target).normalize().multiplyScalar(intersect.distance);
  89357. position.copy(target).add(dir);
  89358. console.log('checkIntersect newPos', position.clone() );
  89359. };
  89360. if(!visi){//更改位置距离target如果小于最小距离,需要反向。 否则直接缩短距离。
  89361. if(intersect.distance < minDis ){
  89362. console.log('检测到intersect 反向', intersect.distance );
  89363. let position1 = position.clone();
  89364. let dir = new Vector3().subVectors(position, target);
  89365. position.copy(target).sub(dir);
  89366. let intersect2 = this.inputHandler.ifBlockedByIntersect(position, null , true, target);// 不一定准确
  89367. if(intersect2){
  89368. if(intersect2.distance < intersect.distance ){
  89369. position.copy(position1);//恢复
  89370. }
  89371. shrink();
  89372. }
  89373. }else {
  89374. shrink();
  89375. }
  89376. }
  89377. }
  89378. };
  89379. checkIntersect();
  89380. //}
  89381. }else if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  89382. let pano = viewer.images360.fitPanoTowardPoint({
  89383. /*point : target, //不使用目标点来判断是因为缺少measure角度的信息。比如虽然可以靠近线的中心,但是线朝向屏幕,那几乎就是一个点了。
  89384. //bestDistance : dis * 0.5, //乘以小数是为了尽量靠近
  89385. boundSphere: boundOri.getBoundingSphere(new THREE.Sphere), */
  89386. target,
  89387. point : position,
  89388. bestDistance : 0 ,
  89389. checkIntersect: o.checkIntersect
  89390. });
  89391. if(pano){
  89392. viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  89393. }
  89394. if(viewer.images360.currentPano == pano){
  89395. let dis1 = viewer.images360.currentPano.position.distanceTo(target);
  89396. let dis2 = position.distanceTo(target);
  89397. console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2);
  89398. return {mag: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() }
  89399. }else {
  89400. return {promise : deferred.promise()}
  89401. }
  89402. //出现过到达位置后测量线标签闪烁的情况
  89403. }
  89404. } else if (type == 'tag' || type == 'point') {
  89405. //dimension = 1
  89406. target.copy(object.position);
  89407. let bestDistance = o.distance || 3;
  89408. if(!o.dontMoveMap && this.mapViewer){
  89409. //console.log('mapFocusOn: '+target.toArray())
  89410. this.mapViewer.moveTo(target.clone(), null, duration);
  89411. }
  89412. if(Potree.settings.displayMode == 'showPointCloud'){
  89413. if(o.dontChangePos){
  89414. position.copy(cameraPos);
  89415. }else {
  89416. dis = bestDistance;
  89417. let dir = o.direction ? o.direction.clone().negate() : this.mainViewport.view.direction.negate();// */new THREE.Vector3().subVectors(camera.position, target).normalize()
  89418. if(o.dontLookUp && dir.z<0) dir.z *= -1;
  89419. position.copy(target).add(dir.multiplyScalar(dis));
  89420. }
  89421. /* if(o.checkIntersect){//识别被点云遮住的话
  89422. let ifShelter
  89423. while(1){
  89424. ifShelter = this.inputHandler.ifBlockedByIntersect(target, o.checkMargin, true, position)
  89425. if(ifShelter){
  89426. if(dis > 0.5){
  89427. dis --
  89428. dir.dot(ifShelter.normal)>0 ? dir.copy(ifShelter.normal).negate() : dir.copy(ifShelter.normal);
  89429. position.copy(target).add(dir.multiplyScalar(dis))
  89430. }
  89431. }
  89432. }
  89433. } */
  89434. }else if(Potree.settings.displayMode == 'showPanos'){
  89435. let pano = viewer.images360.fitPanoTowardPoint({
  89436. point : target,
  89437. bestDistance //越近越好,但不要太近,bestDistance左右差不多
  89438. });
  89439. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize });
  89440. return {promise:deferred.promise() }
  89441. }
  89442. }else if(object.boundingBox && type == 'boundingBox'){//使屏幕刚好看全boundingBox
  89443. target = object.boundingBox.getCenter(new Vector3);
  89444. position = getPosWithFullBound(object.points, object.boundingBox, target, cameraPos );
  89445. if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  89446. let pano = viewer.images360.fitPanoTowardPoint({
  89447. point : position,
  89448. bestDistance : 0 ,
  89449. });
  89450. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  89451. if(!pano){
  89452. console.error('no pano');
  89453. }
  89454. return {promise:deferred.promise() }
  89455. //出现过到达位置后测量线标签闪烁的情况
  89456. }else {
  89457. /* if(o.dontChangeCamDir){
  89458. target = null
  89459. } */
  89460. }
  89461. }
  89462. /*} else if(dimension == 2){//线
  89463. }else if(dimension == 3){//面
  89464. }else{//立体
  89465. } */
  89466. viewer.scene.view.setView({position, target, duration, callback:()=>{
  89467. //console.log('focusOnObjectSuccess: '+object.name, type)
  89468. deferred.resolve();
  89469. }
  89470. });
  89471. this.dispatchEvent({type:'focusOnObject', CamTarget:target, position}); //给controls发送信息
  89472. return {promise:deferred.promise()}
  89473. }
  89474. flyToDataset(o={}){
  89475. var pointcloud;
  89476. if(o instanceof Object3D) pointcloud = o;
  89477. else if(o.pointcloud) pointcloud = o.pointcloud;
  89478. else pointcloud = this.scene.pointclouds.find(p => p.dataset_id == o.id);
  89479. let duration = o.duration == void 0 ? 1000 : o.duration;
  89480. var center = pointcloud.bound.getCenter(new Vector3);
  89481. let position;
  89482. let getPano = ()=>{//获取离中心最近的pano
  89483. let request = [];
  89484. let rank = [
  89485. Images360.scoreFunctions.distanceSquared({position: center})
  89486. ];
  89487. let r = Common.sortByScore(pointcloud.panos, request, rank);
  89488. if(r && r.length){
  89489. return r[0].item
  89490. }
  89491. };
  89492. if(Potree.settings.displayMode == 'showPanos'){
  89493. let pano = getPano();
  89494. if(pano){
  89495. if(pano == this.images360.currentPano) return 'posNoChange'
  89496. this.images360.flyToPano({
  89497. pano
  89498. });
  89499. }else return false
  89500. }else {
  89501. let target;
  89502. position = center;
  89503. if(pointcloud.panosBound){
  89504. let panosCenter = pointcloud.panosBound.center; //pano集中的地方,也就是真正有点云的地方
  89505. position = panosCenter.clone();
  89506. /* let ratio = 0.2
  89507. position.z = center.z * ratio + panosCenter.z * (1-ratio) //因为panos一般比较低,为了不让相机朝下时看不到点云,加一丢丢中心高度
  89508. */
  89509. let pano = getPano();
  89510. if(pano){
  89511. target = pano.position; //针对像隧道一样的场景, 中心点还是panosCenter都在没有点云的地方,所以还是看向其中一个漫游点好。
  89512. position.z = target.z; //水平, 避免朝上或朝下
  89513. }
  89514. }
  89515. if(this.modules.Clip.editing){
  89516. position.z = center.z; //剪裁时在中心高度,因为以点云为重点
  89517. this.modules.Clip.bus.dispatchEvent({type:'flyToPos', position });
  89518. }else {
  89519. if(math.closeTo(position, this.images360.position)) return 'posNoChange'
  89520. viewer.scene.view.setView({position, target, duration });
  89521. o.dontMoveMap || viewer.mapViewer.moveTo(position.clone(), null , duration);
  89522. }
  89523. }
  89524. return true
  89525. }
  89526. resolveTimings(timestamp){
  89527. if(Potree.measureTimings){
  89528. if(!this.toggle){
  89529. this.toggle = timestamp;
  89530. }
  89531. let duration = timestamp - this.toggle;
  89532. if(duration > 1000.0){
  89533. let measures = performance.getEntriesByType("measure");
  89534. let names = new Set();
  89535. for(let measure of measures){
  89536. names.add(measure.name);
  89537. }
  89538. let groups = new Map();
  89539. for(let name of names){
  89540. groups.set(name, {
  89541. measures: [],
  89542. sum: 0,
  89543. n: 0,
  89544. min: Infinity,
  89545. max: -Infinity
  89546. });
  89547. }
  89548. for(let measure of measures){
  89549. let group = groups.get(measure.name);
  89550. group.measures.push(measure);
  89551. group.sum += measure.duration;
  89552. group.n++;
  89553. group.min = Math.min(group.min, measure.duration);
  89554. group.max = Math.max(group.max, measure.duration);
  89555. }
  89556. let glQueries = Potree.resolveQueries(this.renderer.getContext());
  89557. for(let [key, value] of glQueries){
  89558. let group = {
  89559. measures: value.map(v => {return {duration: v}}),
  89560. sum: value.reduce( (a, i) => a + i, 0),
  89561. n: value.length,
  89562. min: Math.min(...value),
  89563. max: Math.max(...value)
  89564. };
  89565. let groupname = `[tq] ${key}`;
  89566. groups.set(groupname, group);
  89567. names.add(groupname);
  89568. }
  89569. for(let [name, group] of groups){
  89570. group.mean = group.sum / group.n;
  89571. group.measures.sort( (a, b) => a.duration - b.duration );
  89572. if(group.n === 1){
  89573. group.median = group.measures[0].duration;
  89574. }else if(group.n > 1){
  89575. group.median = group.measures[parseInt(group.n / 2)].duration;
  89576. }
  89577. }
  89578. let cn = Array.from(names).reduce( (a, i) => Math.max(a, i.length), 0) + 5;
  89579. let cmin = 10;
  89580. let cmed = 10;
  89581. let cmax = 10;
  89582. let csam = 6;
  89583. let message = ` ${"NAME".padEnd(cn)} |`
  89584. + ` ${"MIN".padStart(cmin)} |`
  89585. + ` ${"MEDIAN".padStart(cmed)} |`
  89586. + ` ${"MAX".padStart(cmax)} |`
  89587. + ` ${"SAMPLES".padStart(csam)} \n`;
  89588. message += ` ${"-".repeat(message.length) }\n`;
  89589. names = Array.from(names).sort();
  89590. for(let name of names){
  89591. let group = groups.get(name);
  89592. let min = group.min.toFixed(3);
  89593. let median = group.median.toFixed(3);
  89594. let max = group.max.toFixed(3);
  89595. let n = group.n;
  89596. message += ` ${name.padEnd(cn)} |`
  89597. + ` ${min.padStart(cmin)} |`
  89598. + ` ${median.padStart(cmed)} |`
  89599. + ` ${max.padStart(cmax)} |`
  89600. + ` ${n.toString().padStart(csam)}\n`;
  89601. }
  89602. message += `\n`;
  89603. console.log(message);
  89604. performance.clearMarks();
  89605. performance.clearMeasures();
  89606. this.toggle = timestamp;
  89607. }
  89608. }
  89609. }
  89610. loop(timestamp){
  89611. if(this.stats){
  89612. this.stats.begin();
  89613. }
  89614. if(Potree.measureTimings){
  89615. performance.mark("loop-start");
  89616. }
  89617. this.update(this.clock.getDelta(), timestamp);
  89618. this.magnifier.render();
  89619. this.render();
  89620. // let vrActive = viewer.renderer.xr.isPresenting;
  89621. // if(vrActive){
  89622. // this.update(this.clock.getDelta(), timestamp);
  89623. // this.render();
  89624. // }else{
  89625. // this.update(this.clock.getDelta(), timestamp);
  89626. // this.render();
  89627. // }
  89628. if(Potree.measureTimings){
  89629. performance.mark("loop-end");
  89630. performance.measure("loop", "loop-start", "loop-end");
  89631. }
  89632. this.resolveTimings(timestamp);
  89633. Potree.framenumber++;
  89634. if(this.stats){
  89635. this.stats.end();
  89636. }
  89637. }
  89638. postError(content, params = {}){
  89639. let message = this.postMessage(content, params);
  89640. message.element.addClass("potree_message_error");
  89641. return message;
  89642. }
  89643. postMessage(content, params = {}){
  89644. let message = new Message(content);
  89645. let animationDuration = 100;
  89646. message.element.css("display", "none");
  89647. message.elClose.click( () => {
  89648. message.element.slideToggle(animationDuration);
  89649. let index = this.messages.indexOf(message);
  89650. if(index >= 0){
  89651. this.messages.splice(index, 1);
  89652. }
  89653. });
  89654. this.elMessages.prepend(message.element);
  89655. message.element.slideToggle(animationDuration);
  89656. this.messages.push(message);
  89657. if(params.duration !== undefined){
  89658. let fadeDuration = 500;
  89659. let slideOutDuration = 200;
  89660. setTimeout(() => {
  89661. message.element.animate({
  89662. opacity: 0
  89663. }, fadeDuration);
  89664. message.element.slideToggle(slideOutDuration);
  89665. }, params.duration);
  89666. }
  89667. return message;
  89668. }
  89669. getBoundingBox (pointclouds) {
  89670. //可以直接返回viewer.bound
  89671. if(!this.bound){
  89672. this.updateModelBound();
  89673. }
  89674. return this.bound.boundingBox.clone()//this.scene.getBoundingBox(pointclouds);
  89675. };
  89676. updateModelBound(){
  89677. this.bound = Utils.computePointcloudsBound(this.scene.pointclouds);
  89678. if(Potree.settings.boundAddObjs){//加上obj的bound
  89679. this.objs.children.forEach(e=>{
  89680. this.bound.boundingBox.union(e.boundingBox.clone().applyMatrix4(e.matrixWorld));
  89681. });
  89682. this.bound.boundingBox.getSize(this.bound.boundSize);
  89683. this.bound.boundingBox.getCenter(this.bound.center);
  89684. }
  89685. viewer.farWhenShowPano = this.bound.boundSize.length() * 10;//全景漫游时要能看到整个skybox 原本*2的但对于距离特远的数据集需要乘大一些否则会黑面
  89686. let boundPlane = new Box3();
  89687. boundPlane.expandByPoint(this.bound.boundingBox.min.clone());//最低高度为bound的最低
  89688. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z));//最高高度为bound的中心高度
  89689. FirstPersonControls.boundPlane = boundPlane;
  89690. FirstPersonControls.standardSpeed = MathUtils.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  89691. viewer.scene.pointclouds.forEach(e=>{//海拔范围
  89692. e.material.heightMin = this.bound.boundingBox.min.z;
  89693. e.material.heightMax = this.bound.boundingBox.max.z;
  89694. });
  89695. this.dispatchEvent({type:'updateModelBound'});
  89696. }
  89697. waitForLoad(object, isLoadedCallback){//等待加载时显示loading。主要是贴图
  89698. this.waitQueue.push({
  89699. object,
  89700. isLoadedCallback,
  89701. });
  89702. 1 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:true});
  89703. }
  89704. ifAllLoaded(object){
  89705. if(this.waitQueue.length>0){
  89706. this.waitQueue = this.waitQueue.filter(function(e) {
  89707. return !e.isLoadedCallback()
  89708. });
  89709. }
  89710. 0 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:false});
  89711. }
  89712. setView(o={}){
  89713. let callback = ()=>{
  89714. if(o.displayMode){
  89715. Potree.settings.displayMode = o.displayMode;
  89716. }
  89717. o.callback && o.callback();
  89718. };
  89719. if(o.pano != void 0){//pano 权重高于 position
  89720. this.images360.flyToPano(o);
  89721. }else {
  89722. this.scene.view.setView($.extend({},o, {callback}));
  89723. }
  89724. }
  89725. //设置点云为标准模式
  89726. setPointStandardMat(state, pointDensity, fitPointsize){
  89727. console.log('setPointStandardMat',state);
  89728. if(state){
  89729. if(this.pointStatesBefore){
  89730. return console.error('已设置过pointStatesBefore!')
  89731. }
  89732. this.pointStatesBefore = {
  89733. opacity : new Map(),
  89734. size: new Map(),
  89735. density:Potree.settings.pointDensity,
  89736. useEDL:this.getEDLEnabled(),
  89737. shape: viewer.scene.pointclouds[0].material.shape
  89738. };
  89739. viewer.scene.pointclouds.forEach(e=>{
  89740. this.pointStatesBefore.opacity.set(e, e.temp.pointOpacity); //因为更改pointDensity时会自动变opacity,所以这项最先获取
  89741. this.pointStatesBefore.colorType = e.material.activeAttributeName;
  89742. fitPointsize && this.pointStatesBefore.size.set(e,e.temp.pointSize); //这项不一定有用,因为会被后期覆盖
  89743. });
  89744. if(pointDensity)Potree.settings.pointDensity = pointDensity; //万一之后切换到全景模式怎么办
  89745. if(fitPointsize)Potree.settings.sizeFitToLevel = true;
  89746. viewer.scene.pointclouds.forEach(e=>{
  89747. e.material.activeAttributeName = 'rgba';
  89748. e.material.shape = Potree.PointShape['SQUARE'];
  89749. fitPointsize && e.changePointSize(Potree.config.material.realPointSize, true);
  89750. e.changePointOpacity(1);
  89751. });
  89752. viewer.setEDLEnabled(false);
  89753. }else {
  89754. if(!this.pointStatesBefore){
  89755. return console.error('未设置过pointStatesBefore!')
  89756. }
  89757. Potree.settings.sizeFitToLevel = false;
  89758. if(pointDensity)Potree.settings.pointDensity = this.pointStatesBefore.pointDensity;
  89759. viewer.scene.pointclouds.forEach(e=>{
  89760. e.material.activeAttributeName = this.pointStatesBefore.colorType;
  89761. e.changePointOpacity(this.pointStatesBefore.opacity.get(e));
  89762. e.material.shape = this.pointStatesBefore.shape;
  89763. let size = this.pointStatesBefore.size.get(e);
  89764. if(size) e.changePointSize(size);
  89765. });
  89766. viewer.setEDLEnabled(this.pointStatesBefore.useEDL);
  89767. this.pointStatesBefore = null;
  89768. }
  89769. }
  89770. //调试时显示transformControl来调节object
  89771. transformObject(object){
  89772. let seleted = viewer.inputHandler.selection[0];
  89773. if(!object){//取消
  89774. seleted && viewer.inputHandler.toggleSelection(seleted);
  89775. return
  89776. }
  89777. if(seleted && seleted != object){//要更换,先取消
  89778. return this.transformObject(null)
  89779. }
  89780. if(!object.boundingBox){
  89781. object.boundingBox = new Box3(); //任意大小 只是为了显示黄色外框
  89782. //??? computeBoundingBox
  89783. }
  89784. if(!viewer.inputHandler.selection.includes(object)){
  89785. viewer.inputHandler.toggleSelection(object);
  89786. }
  89787. }
  89788. pointInWhichPointcloud(pos){//选择最接近中心的那个 使用boundSphere
  89789. let result = Common.sortByScore(this.scene.pointclouds,[],[
  89790. (pointcloud)=>{
  89791. var size = pointcloud.pcoGeometry.tightBoundingBox.getSize(new Vector3);
  89792. var center = pointcloud.bound.getCenter(new Vector3);
  89793. var length = size.length() / 2;
  89794. var dis = pos.distanceTo(center);
  89795. return length / dis //到数据集中心的距离占数据集大小越小越好
  89796. }
  89797. ]);
  89798. //若要求更准确的话,可以使用ifContainsPoint判断一下是否在bound中
  89799. let r = result && result[0];
  89800. return r.score > 1 ? result[0].item : null
  89801. }
  89802. /* addObjectTest1(){//加水管
  89803. if(Potree.settings.number == 't-8KbK1JjubE'){
  89804. let boundingBox = new THREE.Box3()
  89805. boundingBox.min.set(-1,-1,-1); boundingBox.max.set(1,1,1)
  89806. let radius = 0.08;
  89807. let radialSegments = 5
  89808. let radSegments = Math.PI*2 / radialSegments
  89809. var circlePts = [];//横截面
  89810. for(let i=0;i<radialSegments;i++){
  89811. let angle = radSegments * i;
  89812. circlePts.push(new THREE.Vector2(radius * Math.cos(angle), radius * Math.sin(angle) ))
  89813. }
  89814. var count = 0
  89815. var addMesh = (color, path, height)=>{//height:在path之上的高度,负数代表在path之下
  89816. var name = 'cylinder'+count
  89817. var mat = new THREE.MeshStandardMaterial({color, depthTest:false, roughness:0.4,metalness:0.5}) 
  89818. let linePath = path.map(e=>new THREE.Vector3().copy(e).setZ(e.z+height))
  89819. let geo = MeshDraw.getExtrudeGeo( circlePts, null,{ extrudePath:linePath, tension:0.2} )
  89820. var mesh = new THREE.Mesh(geo,mat);
  89821. mesh.name = name
  89822. window[name] = mesh
  89823. mesh.boundingBox = boundingBox
  89824. mesh.matrixAutoUpdate = false
  89825. mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix)
  89826. mesh.matrixWorldNeedsUpdate = true
  89827. this.scene.scene.add(mesh);
  89828. count ++
  89829. }
  89830. let linePath, height
  89831. //地上管子 黄色
  89832. linePath = [{"x":-109.83,"y":-68.33,"z":-7.52},{"x":-95.17,"y":-59.3,"z":-7.38}, {"x":-38.75,"y":-24.01,"z":-6.01},{"x":0.5,"y":0.19,"z":-3.89},{"x":39.29,"y":24.41,"z":-1.31}
  89833. ,{"x":43.58,"y":27.7,"z":-0.97},{"x":40.22,"y":35.37,"z":-0.67}// 拐弯向右
  89834. , {"x":39.18,"y":36.71,"z":0.35},{"x":38.69,"y":36.04,"z":18.04} // 拐弯向上
  89835. ]
  89836. height = radius + 0.05;
  89837. addMesh('#b86', linePath, height)
  89838. //地下管子 藍色
  89839. linePath = [{"x":-108.24,"y":-70.61,"z":-7.52}, {"x":-57.8,"y":-39.31,"z":-6.72},{"x":-18.8,"y":-15.35,"z":-5.01},{"x":55.87,"y":31.67,"z":-0.04},{"x":110.53,"y":66.48,"z":5.14}
  89840. ]
  89841. height = -0.5;
  89842. addMesh('#48a', linePath, height)
  89843. }
  89844. }
  89845. */
  89846. /* createRoomEv(){
  89847. const environment = new RoomEnvironment();
  89848. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  89849. }
  89850. */
  89851. loadModel(fileInfo, done, onProgress_, onError){
  89852. let boundingBox = new Box3();
  89853. if(!Potree.settings.boundAddObjs){
  89854. boundingBox.min.set(-0.5,-0.5,-0.5); boundingBox.max.set(0.5,0.5,0.5);
  89855. }
  89856. let fileType = fileInfo.objurl ? 'obj' : 'glb';
  89857. let loadDone = (object, total, url)=>{
  89858. //object.scale.set(1,1,1);//先获取原始的大小时的boundingBox
  89859. object.opacity = 1; //初始化 记录
  89860. object.updateMatrixWorld();
  89861. let weight = Math.round((total / 1024 / 1024) * 100) / 100;
  89862. if(fileInfo.id != void 0)object.dataset_id = fileInfo.id;
  89863. console.log(url.split('/').pop() ,/* fileInfo.id, */ '加载完毕, 模型数据量:' + weight + 'M');
  89864. this.setObjectLayers(object,'model');
  89865. object.traverse( ( child )=>{
  89866. if ( child instanceof Mesh ) {
  89867. child.renderOrder = Potree.config.renderOrders.model;
  89868. if(Potree.settings.boundAddObjs){
  89869. child.geometry.computeBoundingBox();
  89870. //console.log(child.matrixWorld.clone())
  89871. boundingBox.union(child.geometry.boundingBox.clone().applyMatrix4(child.matrixWorld)); //但感觉如果最外层object大小不为1,要还原下scale再乘
  89872. }//获取在scale为1时,表现出的大小
  89873. Common.makeTexDontResize(child.material.map);
  89874. //console.log(child.name, 'roughness',child.material.roughness,'metalness',child.material.metalness)
  89875. /* child.depthMat = child.material.clone()
  89876. child.standardMat = child.material
  89877. child.depthMat.onBeforeCompile = function ( shader ) {
  89878. console.log('vertexShader',shader.vertexShader)
  89879. console.log('fragmentShader',shader.fragmentShader)
  89880. shader.fragmentShader = `
  89881. ${shader.fragmentShader.replace(
  89882. 'gl_FragColor = vec4( outgoingLight, diffuseColor.a );',
  89883. 'diffuseColor.a = log(vViewPosition.z); gl_FragColor = vec4( outgoingLight, diffuseColor.a );'
  89884. )}
  89885. `;
  89886. console.log('fragmentShader1',shader.fragmentShader)
  89887. }; */
  89888. //暂时用这种材质:
  89889. if(fileInfo.unlit && (!(child.material instanceof MeshBasicMaterial) || fileType == 'glb')){
  89890. //let material = new THREE.MeshBasicMaterial({map:child.material.map})
  89891. let material = new BasicMaterial({map : child.material.map}); //很奇怪glb的图会使原本的MeshBasicMaterial 会偏暗,所以自己重新写
  89892. //child.material.dispose()
  89893. child.material = material;
  89894. }
  89895. if(child.material instanceof MeshStandardMaterial){
  89896. child.material.roughness = 0.6;
  89897. child.material.metalness = 0.3;
  89898. }
  89899. }
  89900. } );
  89901. object.name = fileInfo.name != void 0 ? fileInfo.name : 'obj';
  89902. this.objs.add(object);
  89903. object.boundingBox = boundingBox; //未乘上matrixWorld的本地boundingBox
  89904. if(fileInfo.transform){
  89905. let setTransfrom = (name)=>{
  89906. let value = fileInfo.transform[name];
  89907. if(!value)return
  89908. if(value instanceof Array){
  89909. object[name].fromArray(value);
  89910. }else {
  89911. object[name].copy(value);
  89912. }
  89913. };
  89914. setTransfrom('position');
  89915. setTransfrom('rotation');
  89916. setTransfrom('scale');
  89917. }
  89918. if(fileInfo.moveWithPointcloud){
  89919. object.updateMatrix();
  89920. object.matrixAutoUpdate = false;
  89921. object.matrix.premultiply(viewer.scene.pointclouds[0].transformMatrix); //默认跟随第一个数据集
  89922. object.matrixWorldNeedsUpdate = true;
  89923. }
  89924. done && done(object);
  89925. };
  89926. let onProgress = function ( xhr ) {
  89927. if ( xhr.lengthComputable ) {
  89928. let percentComplete = xhr.loaded / xhr.total * 100;
  89929. //console.log( Math.round(percentComplete, 2) + '% downloaded' );
  89930. onProgress_ && onProgress_(percentComplete);
  89931. }
  89932. };
  89933. if(fileType == 'obj'){
  89934. /* manager.onProgress = function ( item, loaded, total ) {
  89935. console.log( item, loaded, total );
  89936. }; */
  89937. /* let onError = function ( xhr ) {
  89938. }; */
  89939. loaders.mtlLoader.load( fileInfo.mtlurl , (materials)=>{
  89940. materials.preload();
  89941. loaders.objLoader.setMaterials( materials ).load(fileInfo.objurl, (object, total)=>{
  89942. loadDone(object, total, fileInfo.objurl);
  89943. });
  89944. } , onProgress, onError );
  89945. }else if(fileType == 'glb'){
  89946. loaders.glbLoader.unlitMat = true;//!!fileInfo.unlit
  89947. loaders.glbLoader.load(fileInfo.glburl, ( gltf, total )=>{ //.setPath( Potree.resourcePath + '/models/glb/' );
  89948. //console.log('loadGLTF', gltf)
  89949. loadDone(gltf.scene, total, fileInfo.glburl);
  89950. }, onProgress, onError);
  89951. }
  89952. /* viewer.onGUILoaded(() => {
  89953. // Add entries to object list in sidebar
  89954. let tree = $(`#jstree_scene`);
  89955. let parentNode = "other";
  89956. let bunnyID = tree.jstree('create_node', parentNode, {
  89957. text: "Bunny Textured",
  89958. icon: `${Potree.resourcePath}/icons/triangle.svg`,
  89959. data: object
  89960. },
  89961. "last", false, false);
  89962. tree.jstree(object.visible ? "check_node" : "uncheck_node", bunnyID);
  89963. //tree.jstree("open_node", parentNode);
  89964. }); */
  89965. }
  89966. removeObj(object){
  89967. this.objs.remove(object);
  89968. if(Potree.settings.boundAddObjs){
  89969. this.updateModelBound();
  89970. }
  89971. }
  89972. loadGLTF(name='87b3a367bc3e4273832cb4fa398782e5.glb'){
  89973. const loader = new GLTFLoader(undefined, this.renderer).setPath( Potree.resourcePath + '/models/glb/' );
  89974. /*
  89975. coffeemat.glb
  89976. ModernJPHouseSofa44216499.glb
  89977. ModernJPHouseSofa44105209.glb
  89978. 87ecd10fb0374ea6b3e0bf24c6459e3c.glb
  89979. 87b3a367bc3e4273832cb4fa398782e5.glb
  89980. */
  89981. loader.load(name, ( gltf )=>{
  89982. console.log('loadGLTF', gltf);
  89983. this.objs.add(gltf.scene);
  89984. });
  89985. }
  89986. addFire(){
  89987. if(Potree.settings.number == 't-CwfhfqJ'){
  89988. let position = Potree.Utils.datasetPosTransform({
  89989. pointcloud:viewer.scene.pointclouds[0],
  89990. position: new Vector3(4.4318,-0.580291847759, -0.78),
  89991. fromDataset:true
  89992. });
  89993. viewer.modules.ParticleEditor.addParticle( {
  89994. type:'fire',
  89995. positions:[position],
  89996. radius:0.42,
  89997. height:10,
  89998. });
  89999. viewer.modules.ParticleEditor.addParticle( {
  90000. type:'smoke',
  90001. positions: [ new Vector3().addVectors(position,new Vector3(0,0,0.3))],
  90002. positionStyle : 'sphere' ,
  90003. positionRadius : 0.3,
  90004. sizeTween: [[0, 0.3, 0.9, 1], [0.05, 0.1, 1, 0.8]],
  90005. opacityBase : 0.2,
  90006. opacityTween :[ [0, 0.3, 0.7, 0.95, 1], [0, 0.2, 1 , 0.1, 0] ],
  90007. velocityBase : new Vector3( 0, 0, 1),
  90008. velocitySpread : new Vector3( 0.2, 0.2, -0.3),
  90009. accelerationBase : 0.2,
  90010. accelerationSpread : 0.7,
  90011. radius:0,
  90012. //particlesPerSecond : 30,
  90013. particleDeathAge : 3.0,
  90014. });
  90015. viewer.modules.ParticleEditor.addParticle( {
  90016. type:'explode',
  90017. name:'fire splash',
  90018. position: new Vector3().addVectors(position,new Vector3(0,0,0.3)),
  90019. size: 0.1,
  90020. sizeRange: 0.3,
  90021. sizeTween:[[0, 0.05, 0.3, 0.45], [0, 0.02, 0.1, 0.05] ],
  90022. opacityTween: [[0, 0.05, 0.3, 0.45], [1, 1, 0.5, 0]] ,
  90023. speed : 1, //sphere
  90024. speedRange : 4,
  90025. radius: 0.1,
  90026. acceleration : 0.3,
  90027. accelerationRange : 1,
  90028. particleSpaceTime:0,
  90029. strength:4,
  90030. });
  90031. }
  90032. }
  90033. addVideo11(){
  90034. if(Potree.settings.number != 'SS-fckI7CClKC')return
  90035. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  90036. video.setAttribute("crossOrigin", 'Anonymous');
  90037. //video.src = Potree.resourcePath+'/video/SS-fckI7CClKC/19.mp4'
  90038. var map = new VideoTexture(video);
  90039. var plane = this.videoPlane = new Mesh(new PlaneGeometry(1, 1, 1, 1), new MeshBasicMaterial({
  90040. color:"#ffffff",
  90041. transparent: !0,
  90042. depthTest:false,
  90043. opacity:0.7,
  90044. side:2,
  90045. map
  90046. }));
  90047. plane.visible = false;
  90048. plane.geometry.computeBoundingBox();
  90049. plane.boundingBox = plane.geometry.boundingBox.clone();//.applyMatrix4()
  90050. plane.boundingBox.max.z = 1;
  90051. plane.boundingBox.max.y = -0.4;
  90052. plane.boundingBox.max.x = 1;
  90053. /* plane.position.copy(this.images360.panos[19].position);
  90054. plane.lookAt(plane.position.clone().setX(0))
  90055. 9:
  90056. viewer.videoPlane.rotation.set(-1.432978005954197, 1.2296264545169697, 3.0098547630197667)
  90057. viewer.videoPlane.position.set( 6.532456676287381, -9.806373049095631, -0.024205281024294284)
  90058. //viewer.transformObject(viewer.videoPlane)
  90059. //19:
  90060. viewer.videoPlane.rotation.set( 1.627167773445286, -1.172425902600188, 0.04682299709711613)
  90061. viewer.videoPlane.position.set( -9.558613948539932,-1.042301166581578, 0.08159683876743667) */
  90062. video.addEventListener('loadeddata', function(e) {
  90063. video.play();
  90064. //plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1) // 1080 * 1920
  90065. console.log('video loadeddata');
  90066. });
  90067. plane.scale.set(1080/1000,1920/1000,1); // 1080 * 1920
  90068. var startPlay = ()=>{
  90069. video.play();
  90070. //video.pause()
  90071. //video.currentTime = 0.1;
  90072. this.removeEventListener('global_mousedown', startPlay);
  90073. };
  90074. this.addEventListener('global_mousedown', startPlay);
  90075. var videoInfo = {
  90076. 9:{
  90077. rotation:[-1.432978005954197, 1.2296264545169697, 3.0098547630197667],
  90078. position:[6.532456676287381, -9.806373049095631, -0.024205281024294284]
  90079. },
  90080. 19:{
  90081. rotation:[1.627167773445286, -1.172425902600188, 0.04682299709711613],
  90082. position:[-9.558613948539932,-1.042301166581578, 0.08159683876743667]
  90083. },
  90084. };
  90085. /* this.images360.addEventListener('cameraMoveDone',(e)=>{
  90086. let info = videoInfo[this.images360.currentPano.id]
  90087. if(info ){
  90088. plane.visible = true;
  90089. plane.material.opacity = 1;
  90090. plane.position.fromArray(info.position)
  90091. plane.rotation.fromArray(info.rotation)
  90092. }
  90093. }) */
  90094. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  90095. if(Potree.settings.displayMode != 'showPanos') return
  90096. let info = videoInfo[e.toPano.pano.id];
  90097. if(info ){ //出现
  90098. setTimeout(()=>{
  90099. plane.visible = true;
  90100. plane.position.fromArray(info.position);
  90101. plane.rotation.fromArray(info.rotation);
  90102. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`;
  90103. video.play();
  90104. video.currentTime = 0;
  90105. Potree.settings.zoom.enabled = false;
  90106. transitions.start(lerp.property(plane.material, "opacity", 1/* , (e)=>{console.log('fadeIn',e)} */) , e.toPano.duration*0.4 , ()=>{
  90107. }, 0, easing['easeInOutQuad']);
  90108. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  90109. }
  90110. //消失
  90111. transitions.start(lerp.property(plane.material, "opacity", 0, /* (e)=>{console.log('fadeOut',e)} */) , e.toPano.duration*0.4, ()=>{
  90112. if(!info){
  90113. plane.visible = false;
  90114. video.pause();
  90115. Potree.settings.zoom.enabled = true;
  90116. }
  90117. }, 0, easing['easeInOutQuad']);
  90118. });
  90119. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  90120. if(e.mode == 'showPanos'){
  90121. let info = videoInfo[this.images360.currentPano.id];
  90122. if(info ){ //出现
  90123. plane.visible = true;
  90124. plane.position.fromArray(info.position);
  90125. plane.rotation.fromArray(info.rotation);
  90126. plane.material.opacity = 0;
  90127. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`;
  90128. video.play();
  90129. video.currentTime = 0;
  90130. Potree.settings.zoom.enabled = false;
  90131. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e);}) , 300 , ()=>{
  90132. }, 0, easing['easeInOutQuad']);
  90133. }
  90134. }else {
  90135. plane.visible = false;
  90136. Potree.settings.zoom.enabled = true;
  90137. }
  90138. });
  90139. this.scene.scene.add(plane);
  90140. }
  90141. ////////////////////////
  90142. addVideo(){
  90143. if(Potree.settings.number != 'SS-t-P6zBR73Gke')return
  90144. var geo = new PlaneGeometry(1, 1, 1, 1);
  90145. var videoInfo = this.videoInfo = [
  90146. /* {
  90147. id: 45,
  90148. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/c02a2c1e-8420-4f34-b951-5f7a07abe932.mp4',
  90149. rotation:[-1.629007730553656, 0.042029565584517974, -3.1345506775116627],
  90150. position:[ 9.467649296794061, -0.7596961214872837, -0.12477576310191862],
  90151. scale:[4.52209111454416,3.3888400031207984,1],
  90152. }, */
  90153. {
  90154. id: '40-2',
  90155. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/10/0aabafee-36b8-455d-9c11-0780bf694786.mp4',
  90156. rotation:[-1.494468618954883, -1.4987317433158989, -3.061254983446741],
  90157. position:[ 19.801820617361624, 2.884673619844108, -0.03362305858221648],
  90158. scale:[3.5741423153151763, 2.8738725275578703, 1],
  90159. },
  90160. {
  90161. id: 40,
  90162. /* rotation:[-1.534692822378723, 0.01083403560862361, 3.141535283661569],
  90163. position:[17.2934294239949861, 2.413510747928117, -0.008057029580231356], */
  90164. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/7896d6ef-a2d6-4fd7-949c-768782a5b484.mp4',
  90165. rotation:[-1.5487684197910518, 0.021848470169552752, -3.1387534893955236],
  90166. position:[17.277316608096, 2.0840432922115846, -0.0931149415437065],
  90167. scale:[2.0821757723834047, 0.6129478480765236, 1],
  90168. visibles: [40]
  90169. },
  90170. ];
  90171. let add = (info)=>{
  90172. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  90173. video.setAttribute("crossOrigin", 'Anonymous');
  90174. video.src = info.url || Potree.resourcePath+`/video/${Potree.settings.number}/${info.id}.mp4`;
  90175. var map = new VideoTexture(video);
  90176. var plane = this.videoPlane = new Mesh(geo, new MeshBasicMaterial({
  90177. color:"#ffffff",
  90178. transparent: !0,
  90179. depthTest:false,
  90180. opacity:0 ,
  90181. //side:2,
  90182. map
  90183. }));
  90184. plane.position.fromArray(info.position);
  90185. plane.rotation.fromArray(info.rotation);
  90186. info.scale && plane.scale.fromArray(info.scale);
  90187. this.scene.scene.add(plane);
  90188. info.plane = plane;
  90189. plane.boundingBox = new Box3(new Vector3(0,-0.5,0),new Vector3(1,-0.4,0.2));
  90190. video.addEventListener('loadeddata', function(e) {
  90191. video.play();
  90192. if(!info.visibles/* ||!viewer.images360.currentPano || info.visibles.includes(viewer.images360.currentPano.id) */){
  90193. plane.material.opacity = 1;
  90194. }
  90195. info.scale || plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1); // 1080 * 1920
  90196. console.log('video loadeddata', info.id);
  90197. });
  90198. if(info.visibles){
  90199. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  90200. if(info.visibles.includes(e.toPano.pano.id)){ //出现
  90201. setTimeout(()=>{
  90202. plane.visible = true;
  90203. video.currentTime = 0;
  90204. video.play();
  90205. if(video.paused){
  90206. var startPlay = ()=>{
  90207. plane.visible && video.play();
  90208. this.removeEventListener('global_mousedown', startPlay);
  90209. };
  90210. this.addEventListener('global_mousedown', startPlay);
  90211. }
  90212. Potree.settings.zoom.enabled = false;
  90213. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  90214. }, 0, easing['easeInOutQuad']);
  90215. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  90216. }else {
  90217. //消失
  90218. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  90219. if(!info){
  90220. plane.visible = false;
  90221. video.pause();
  90222. Potree.settings.zoom.enabled = true;
  90223. }
  90224. }, 0, easing['easeInOutQuad']);
  90225. }
  90226. });
  90227. }
  90228. var startPlay = ()=>{
  90229. video.play();
  90230. //video.pause()
  90231. //video.currentTime = 0.1;
  90232. this.removeEventListener('global_mousedown', startPlay);
  90233. };
  90234. this.addEventListener('global_mousedown', startPlay);
  90235. Potree.settings.isTest && plane.addEventListener('select',(e)=>{console.log(e);});
  90236. };
  90237. videoInfo.forEach(info=>{
  90238. add(info);
  90239. });
  90240. /* var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0]
  90241. video.setAttribute("crossOrigin", 'Anonymous')
  90242. video.src = Potree.resourcePath+'/video/SS-t-P6zBR73Gke/40.mp4'
  90243. var map = new THREE.VideoTexture(video);
  90244. var plane = this.videoPlane = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
  90245. color:"#ffffff",
  90246. transparent: !0,
  90247. depthTest:false,
  90248. opacity:0.7,
  90249. side:2,
  90250. map
  90251. }))
  90252. //plane.visible = false
  90253. this.scene.scene.add(plane)
  90254. plane.geometry.computeBoundingBox();
  90255. plane.boundingBox = plane.geometry.boundingBox.clone()//.applyMatrix4()
  90256. plane.boundingBox.max.z = 0.3
  90257. plane.boundingBox.max.y = -0.4
  90258. plane.boundingBox.max.x = 1
  90259. plane.position.copy(this.images360.panos[40].position);
  90260. plane.lookAt(plane.position.clone().setX(0))
  90261. plane.rotation.set(-1.534692822378723, 0.01083403560862361, 3.141535283661569)
  90262. plane.position.set( 17.2934294239949861, 2.413510747928117, -0.008057029580231356)
  90263. //viewer.transformObject(viewer.videoPlane)
  90264. //19:
  90265. video.addEventListener('loadeddata', function(e) {
  90266. video.play()
  90267. plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1) // 1080 * 1920
  90268. console.log('video loadeddata')
  90269. })
  90270. //plane.scale.set(1080/1000,1920/1000,1) // 1080 * 1920
  90271. var startPlay = ()=>{
  90272. video.play()
  90273. //video.pause()
  90274. //video.currentTime = 0.1;
  90275. this.removeEventListener('global_mousedown', startPlay)
  90276. }
  90277. this.addEventListener('global_mousedown', startPlay)
  90278. */
  90279. /* this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  90280. if(Potree.settings.displayMode != 'showPanos') return
  90281. let info = videoInfo[e.toPano.pano.id]
  90282. if(info ){ //出现
  90283. setTimeout(()=>{
  90284. plane.visible = true;
  90285. plane.position.fromArray(info.position)
  90286. plane.rotation.fromArray(info.rotation)
  90287. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`
  90288. video.play();
  90289. video.currentTime = 0
  90290. Potree.settings.zoom.enabled = false
  90291. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  90292. }, 0, easing['easeInOutQuad'])
  90293. }, e.toPano.duration*0.6) //时间上不能和消失的重叠 延迟
  90294. }
  90295. //消失
  90296. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  90297. if(!info){
  90298. plane.visible = false
  90299. video.pause()
  90300. Potree.settings.zoom.enabled = true
  90301. }
  90302. }, 0, easing['easeInOutQuad'])
  90303. })
  90304. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  90305. if(e.mode == 'showPanos'){
  90306. let info = videoInfo[this.images360.currentPano.id]
  90307. if(info ){ //出现
  90308. plane.visible = true;
  90309. plane.position.fromArray(info.position)
  90310. plane.rotation.fromArray(info.rotation)
  90311. plane.material.opacity = 0
  90312. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`
  90313. video.play();
  90314. video.currentTime = 0
  90315. Potree.settings.zoom.enabled = false
  90316. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e)}) , 300 , ()=>{
  90317. }, 0, easing['easeInOutQuad'])
  90318. }
  90319. }else{
  90320. plane.visible = false;
  90321. Potree.settings.zoom.enabled = true
  90322. }
  90323. })
  90324. */
  90325. }
  90326. };
  90327. //------ CLIP 默认clipTask都是clipInside ----------------------
  90328. /*
  90329. 并集相当于加法,交集相当于加法。 所有结果都能展开成多个乘积相加。
  90330. 假设有4个clipBoxes,ABCD, 如果是 A*B + C*D ,那么这是最终结果。 如果是 (A+B)*(C+D) = A*C+A*D+B*C+B*D
  90331. */
  90332. let Clips = {
  90333. boxes : [],
  90334. unionGroups : [], //二维数组。最外层要求并集,里层要求交集(如果只有一个元素就是本身)。总结起来就是要求一堆交集的并集
  90335. shaderParams:{},
  90336. needsUpdate : true,
  90337. addClip(box, clipMethod){
  90338. //不允许重复
  90339. if(this.boxes.includes(box)){
  90340. return console.warn('addClip重复添加了box',box)
  90341. }
  90342. boxes.push(box);
  90343. if(clipMethod == 'any'){//并
  90344. this.unionGroups.push([box]);
  90345. }else if(clipMethod == 'all'){//交
  90346. this.unionGroups.forEach(mixGroup=>mixGroup.push(box));
  90347. }
  90348. this.needsUpdate = true;
  90349. },
  90350. removeClip(box){
  90351. if(!this.boxes.includes(box)){
  90352. return console.warn('removeClip没有找到该box',box)
  90353. }
  90354. var newGroups = [];
  90355. this.unionGroups.forEach(mixGroup=>{
  90356. if(mixGroup.length == 1 && mixGroup[0] == box)return;//直接删除
  90357. newGroups.push(mixGroup.filter(e=>e!=box));
  90358. });
  90359. this.unionGroups = newGroups;
  90360. this.needsUpdate = true;
  90361. }
  90362. ,
  90363. clearClip(){
  90364. this.boxes = [];
  90365. this.unionGroups = [];
  90366. this.needsUpdate = true;
  90367. }
  90368. ,
  90369. updateShaderParams(){//没写完 - - 见 pointcloud clip.vs
  90370. /*
  90371. uniform mat4 clipBoxes[num_clipboxes];
  90372. uniform int clipBoxGroupCount;
  90373. uniform int mixClipIndices[clipboxGroupItemCount]; //把所有的要求都直接放到数组内
  90374. */
  90375. //这里需要转为Float32Array..? 参考material.setClipBoxes
  90376. let everyClipGroupCount = this.unionGroups.map(e=>e.length);
  90377. let mixClipIndices = [];
  90378. this.unionGroups.forEach(e=>{
  90379. mixClipIndices.push(...e);
  90380. });
  90381. this.shaderParams = {
  90382. num_clipboxes : this.boxes.length,
  90383. clipBoxGroupCount : this.unionGroups.length,
  90384. everyClipGroupCount,
  90385. clipBoxIndexCount: mixClipIndices.length,
  90386. mixClipIndices
  90387. };
  90388. }
  90389. ,
  90390. getShaderParams(){//每次要传递参数到shader中,执行这个就好
  90391. if(this.needsUpdate){
  90392. this.updateShaderParams();
  90393. }
  90394. return this.shaderParams
  90395. }
  90396. };
  90397. /* setTimeout(()=>{
  90398. if( Potree.settings.number == 't-YLZ5XAALl7' || 't-e2Kb2iU' ){
  90399. let transform = {
  90400. 't-YLZ5XAALl7' : {
  90401. rotation : [0, 0, 0.002326740152215126],
  90402. position : [0.421017820930033, -0.22730084679456727, 0.0068952417582]
  90403. },
  90404. 't-e2Kb2iU' : {
  90405. rotation : [0.06595546058095993, -0.026986798620029413, 0.8429662590573239],
  90406. position : [ -502.6216232179794, 1051.5690392495885, 15.48490744053752]
  90407. },
  90408. }
  90409. var path = `${Potree.resourcePath}/models/${Potree.settings.number}/`
  90410. viewer.loadObj({
  90411. objurl: path+'pipe.obj',
  90412. mtlurl: path+'pipe.mtl',
  90413. transform : transform[Potree.settings.number]
  90414. })
  90415. }
  90416. },1000)
  90417. //if(!Potree.settings.isOfficial){
  90418. if(number == 't-e2Kb2iU') {
  90419. setTimeout(//暂时延迟,等focus第一个点之后
  90420. ()=>{
  90421. viewer.loadProject(Potree.scriptPath + "/data/"+ number +"/potree.json5", ()=>{
  90422. viewer.scene.cameraAnimations[0].play()
  90423. })
  90424. },
  90425. 3000)
  90426. }
  90427. */
  90428. OrthographicCamera.prototype.zoomTo = function( node, factor = 1){
  90429. if ( !node.geometry && !node.boundingBox) {
  90430. return;
  90431. }
  90432. // TODO
  90433. //let minWS = new THREE.Vector4(node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z, 1);
  90434. //let minVS = minWS.applyMatrix4(this.matrixWorldInverse);
  90435. //let right = node.boundingBox.max.x;
  90436. //let bottom = node.boundingBox.min.y;
  90437. //let top = node.boundingBox.max.y;
  90438. this.updateProjectionMatrix();
  90439. };
  90440. PerspectiveCamera.prototype.zoomTo = function (node, factor) {
  90441. if (!node.geometry && !node.boundingSphere && !node.boundingBox) {
  90442. return;
  90443. }
  90444. if (node.geometry && node.geometry.boundingSphere === null) {
  90445. node.geometry.computeBoundingSphere();
  90446. }
  90447. node.updateMatrixWorld();
  90448. let bs;
  90449. if (node.boundingSphere) {
  90450. bs = node.boundingSphere;
  90451. } else if (node.geometry && node.geometry.boundingSphere) {
  90452. bs = node.geometry.boundingSphere;
  90453. } else {
  90454. bs = node.boundingBox.getBoundingSphere(new Sphere());
  90455. }
  90456. let _factor = factor || 1;
  90457. bs = bs.clone().applyMatrix4(node.matrixWorld);
  90458. let radius = bs.radius;
  90459. let fovr = this.fov * Math.PI / 180;
  90460. if (this.aspect < 1) {
  90461. fovr = fovr * this.aspect;
  90462. }
  90463. let distanceFactor = Math.abs(radius / Math.sin(fovr / 2)) * _factor;
  90464. let offset = this.getWorldDirection(new Vector3()).multiplyScalar(-distanceFactor);
  90465. this.position.copy(bs.center.clone().add(offset));
  90466. };
  90467. Ray.prototype.distanceToPlaneWithNegative = function (plane) {
  90468. let denominator = plane.normal.dot(this.direction);
  90469. if (denominator === 0) {
  90470. // line is coplanar, return origin
  90471. if (plane.distanceToPoint(this.origin) === 0) {
  90472. return 0;
  90473. }
  90474. // Null is preferable to undefined since undefined means.... it is undefined
  90475. return null;
  90476. }
  90477. let t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  90478. return t;
  90479. };
  90480. const workerPool = new WorkerPool();
  90481. const version = {
  90482. major: 1,
  90483. minor: 8,
  90484. suffix: '.0'
  90485. };
  90486. let lru = new LRU();
  90487. //console.log('Potree ' + version.major + '.' + version.minor + version.suffix);
  90488. let pointBudget = 1 * 1000 * 1000;
  90489. let framenumber = 0;
  90490. let numNodesLoading = 0;
  90491. let maxNodesLoading = 4;
  90492. const debug = {};
  90493. exports.scriptPath = "";
  90494. if (document.currentScript && document.currentScript.src) {
  90495. exports.scriptPath = new URL(document.currentScript.src + '/..').href;
  90496. if (exports.scriptPath.slice(-1) === '/') {
  90497. exports.scriptPath = exports.scriptPath.slice(0, -1);
  90498. }
  90499. } else if(({ url: (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('potree.js', document.baseURI).href)) })){
  90500. exports.scriptPath = new URL((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('potree.js', document.baseURI).href)) + "/..").href;
  90501. if (exports.scriptPath.slice(-1) === '/') {
  90502. exports.scriptPath = exports.scriptPath.slice(0, -1);
  90503. }
  90504. }else {
  90505. console.error('Potree was unable to find its script path using document.currentScript. Is Potree included with a script tag? Does your browser support this function?');
  90506. }
  90507. let resourcePath = exports.scriptPath + '/resources';
  90508. //add:
  90509. async function loadFile(path, callback, onError){
  90510. if(Potree.fileServer){
  90511. Potree.fileServer.get(path).then(data=>{
  90512. callback && callback(data);
  90513. }).catch(onError);
  90514. }else {
  90515. try{
  90516. let response = await fetch(path);
  90517. let text = await response.text();
  90518. var data = JSON.parse(text);
  90519. if(data.data) data = data.data;
  90520. callback && callback(data);
  90521. return data
  90522. }catch(e){
  90523. onError && onError(e);
  90524. }
  90525. }
  90526. //查询: http://192.168.0.26:8080/doc.html#/default/filter-%E6%BC%AB%E6%B8%B8%E7%82%B9/filterUsingGET
  90527. }
  90528. async function loadDatasets(callback,sceneCode,onError){//之后直接把path写进来
  90529. let path;
  90530. sceneCode = sceneCode || Potree.settings.number;
  90531. if(Potree.fileServer){
  90532. path = `/laser/dataset/${sceneCode}/getDataSet`;
  90533. }else {
  90534. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/datasets`
  90535. //现在只能加载得了本地的了
  90536. path = `${Potree.settings.urls.prefix4}laser/dataset/${sceneCode}/getDataSet`;
  90537. //path = `${Potree.scriptPath}/data/${sceneCode}/getDataSet.json`
  90538. }
  90539. return loadFile(path, callback,onError)
  90540. }
  90541. //目前上传平面图后如果不点击保存按钮,数据还是旧的不生效
  90542. async function loadMapEntity(datasetId, force){
  90543. if(!Potree.settings.floorplanEnable && !force && Potree.fileServer )return /* 等待平面图类型定义好会加载 */
  90544. let loaded = 0;
  90545. let needLoads = datasetId == 'all' ? viewer.scene.pointclouds.map(e=>e.dataset_id) : [datasetId];
  90546. let callback = (dataset_id, floorplanType, data )=>{
  90547. //要防止旧的比新的先获取到导致覆盖新的,因为两种type随时可能切换
  90548. if(floorplanType != Potree.settings.floorplanType[dataset_id]) return //如果请求的floorplanType不是当前最新的floorplanType就返回
  90549. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'floorplan_'+ dataset_id);
  90550. if(map){
  90551. viewer.mapViewer.mapLayer.removeMap(map);
  90552. }
  90553. var mapNew = viewer.mapViewer.mapLayer.addMapEntity(data.data || data, dataset_id);
  90554. if(map){
  90555. mapNew.visibleReasons = map.visibleReasons;
  90556. mapNew.unvisibleReasons = map.unvisibleReasons;
  90557. }
  90558. loaded ++;
  90559. };
  90560. needLoads.forEach(dataset_id=>{
  90561. let floorplanType = Potree.settings.floorplanType[dataset_id];
  90562. if(!floorplanType)return
  90563. var path;
  90564. if(Potree.fileServer){
  90565. path = `/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`;
  90566. }else {
  90567. path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/tiled_maps`;
  90568. }
  90569. Potree.settings.floorplanRequests[dataset_id] = true; //开始加载了
  90570. return loadFile(path, callback.bind(this, dataset_id, floorplanType) )
  90571. });
  90572. }
  90573. async function loadPanos(datasetId, callback){
  90574. var path;
  90575. let query = `?datasetId=${datasetId}`; //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  90576. if(Potree.fileServer){
  90577. path = `/laser/filter/${Potree.settings.number}/query` + query;
  90578. }else {
  90579. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/images/filter` + query
  90580. //path = `${Potree.scriptPath}/data/${Potree.settings.number}/panos-${datasetId}.json`
  90581. path = `${Potree.settings.urls.prefix4}laser/filter/${Potree.settings.number}/query` + query;
  90582. }
  90583. return loadFile(path, callback)
  90584. }
  90585. async function loadPanosInfo(callback){
  90586. var path;
  90587. if(Potree.fileServer){
  90588. }else {
  90589. path = `${Potree.scriptPath}/data/panoEdit/vision_edit.txt`;
  90590. }
  90591. return loadFile(path, callback)
  90592. }
  90593. //site_model
  90594. /* {
  90595. "area": 2503.30551910935,
  90596. "attributes": {},
  90597. "center": [
  90598. 113.59568277455075,
  90599. 22.366566635195288,
  90600. 12.78751625
  90601. ],
  90602. "children": [],
  90603. "geometry_hash": 1891071345,
  90604. "id": 10,
  90605. "name": "港湾一号",
  90606. "parentId": null,
  90607. "polygon": {
  90608. "coordinates": [
  90609. [
  90610. [
  90611. 113.59590810534583,
  90612. 22.36679132753878
  90613. ],
  90614. [
  90615. 113.59590810534583,
  90616. 22.366807172528629
  90617. ],
  90618. [
  90619. 113.59545610274934,
  90620. 22.366807172528629
  90621. ],
  90622. [
  90623. 113.59545610274934,
  90624. 22.36679132753878
  90625. ]
  90626. ]
  90627. ],
  90628. "type": "Polygon"
  90629. },
  90630. "type": "BUILDING",
  90631. "volume": null,
  90632. "z_max": null,
  90633. "z_min": null
  90634. }
  90635. */
  90636. function Log(value, color, fontSize){
  90637. color = color || '#13f';
  90638. fontSize = fontSize || 14;
  90639. console.warn(`%c${value}`, `color:${color};font-size:${fontSize}px`);
  90640. }
  90641. function loadPointCloud$1(path, name, sceneCode, timeStamp, callback, onError){
  90642. let loaded = function(e){
  90643. e.pointcloud.name = name;
  90644. e.pointcloud.sceneCode = sceneCode; //对应4dkk的场景码
  90645. callback(e);
  90646. };
  90647. let promise = new Promise( resolve => {
  90648. // load pointcloud
  90649. if (!path){
  90650. // TODO: callback? comment? Hello? Bueller? Anyone?
  90651. } else if (path.indexOf('ept.json') > 0) {
  90652. EptLoader.load(path, function(geometry) {
  90653. if (!geometry) {
  90654. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90655. }
  90656. else {
  90657. let pointcloud = new PointCloudOctree(geometry);
  90658. //loaded(pointcloud);
  90659. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90660. }
  90661. });
  90662. } else if (path.indexOf('cloud.js') > 0) {
  90663. POCLoader.load(path, timeStamp, function (geometry) {
  90664. if (!geometry) {
  90665. //callback({type: 'loading_failed'});
  90666. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90667. onError && onError();
  90668. } else {
  90669. let pointcloud = new PointCloudOctree(geometry);
  90670. // loaded(pointcloud);
  90671. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90672. }
  90673. });
  90674. }/* else if (path.indexOf('metadata.json') > 0) { //部分浏览器(如uc)不支持NodeLoader中的1n的大数据写法
  90675. Potree.OctreeLoader.load(path).then(e => {
  90676. let geometry = e.geometry;
  90677. if(!geometry){
  90678. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90679. }else{
  90680. let pointcloud = new PointCloudOctree(geometry);
  90681. let aPosition = pointcloud.getAttribute("position");
  90682. let material = pointcloud.material;
  90683. material.elevationRange = [
  90684. aPosition.range[0][2],
  90685. aPosition.range[1][2],
  90686. ];
  90687. // loaded(pointcloud);
  90688. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90689. }
  90690. });
  90691. OctreeLoader.load(path, function (geometry) {
  90692. if (!geometry) {
  90693. //callback({type: 'loading_failed'});
  90694. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90695. } else {
  90696. let pointcloud = new PointCloudOctree(geometry);
  90697. // loaded(pointcloud);
  90698. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90699. }
  90700. });
  90701. } */else if (path.indexOf('.vpc') > 0) {
  90702. PointCloudArena4DGeometry.load(path, function (geometry) {
  90703. if (!geometry) {
  90704. //callback({type: 'loading_failed'});
  90705. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90706. } else {
  90707. let pointcloud = new PointCloudArena4D(geometry);
  90708. // loaded(pointcloud);
  90709. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90710. }
  90711. });
  90712. } else {
  90713. //callback({'type': 'loading_failed'});
  90714. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90715. }
  90716. });
  90717. if(callback){
  90718. promise.then(pointcloud => {
  90719. loaded(pointcloud);
  90720. });
  90721. }else {
  90722. return promise;
  90723. }
  90724. };
  90725. // add selectgroup
  90726. (function($){
  90727. $.fn.extend({
  90728. selectgroup: function(args = {}){
  90729. let elGroup = $(this);
  90730. let rootID = elGroup.prop("id");
  90731. let groupID = `${rootID}`;
  90732. let groupTitle = (args.title !== undefined) ? args.title : "";
  90733. let elButtons = [];
  90734. elGroup.find("option").each((index, value) => {
  90735. let buttonID = $(value).prop("id");
  90736. let label = $(value).html();
  90737. let optionValue = $(value).prop("value");
  90738. let elButton = $(`
  90739. <span style="flex-grow: 1; display: inherit">
  90740. <label for="${buttonID}" class="ui-button" style="width: 100%; padding: .4em .1em">${label}</label>
  90741. <input type="radio" name="${groupID}" id="${buttonID}" value="${optionValue}" style="display: none"/>
  90742. </span>
  90743. `);
  90744. let elLabel = elButton.find("label");
  90745. let elInput = elButton.find("input");
  90746. elInput.change( () => {
  90747. elGroup.find("label").removeClass("ui-state-active");
  90748. elGroup.find("label").addClass("ui-state-default");
  90749. if(elInput.is(":checked")){
  90750. elLabel.addClass("ui-state-active");
  90751. }else {
  90752. //elLabel.addClass("ui-state-default");
  90753. }
  90754. });
  90755. elButtons.push(elButton);
  90756. });
  90757. let elFieldset = $(`
  90758. <fieldset style="border: none; margin: 0px; padding: 0px">
  90759. <legend>${groupTitle}</legend>
  90760. <span style="display: flex">
  90761. </span>
  90762. </fieldset>
  90763. `);
  90764. let elButtonContainer = elFieldset.find("span");
  90765. for(let elButton of elButtons){
  90766. elButtonContainer.append(elButton);
  90767. }
  90768. elButtonContainer.find("label").each( (index, value) => {
  90769. $(value).css("margin", "0px");
  90770. $(value).css("border-radius", "0px");
  90771. $(value).css("border", "1px solid black");
  90772. $(value).css("border-left", "none");
  90773. });
  90774. elButtonContainer.find("label:first").each( (index, value) => {
  90775. $(value).css("border-radius", "4px 0px 0px 4px");
  90776. });
  90777. elButtonContainer.find("label:last").each( (index, value) => {
  90778. $(value).css("border-radius", "0px 4px 4px 0px");
  90779. $(value).css("border-left", "none");
  90780. });
  90781. elGroup.empty();
  90782. elGroup.append(elFieldset);
  90783. }
  90784. });
  90785. })(jQuery);
  90786. exports.Action = Action;
  90787. exports.Alignment = Alignment;
  90788. exports.AnimationPath = AnimationPath;
  90789. exports.Annotation = Annotation;
  90790. exports.Box3Helper = Box3Helper$1;
  90791. exports.BoxVolume = BoxVolume;
  90792. exports.Buttons = Buttons;
  90793. exports.CameraAnimation = CameraAnimation;
  90794. exports.CameraMode = CameraMode;
  90795. exports.ClassificationScheme = ClassificationScheme;
  90796. exports.ClipMethod = ClipMethod;
  90797. exports.ClipTask = ClipTask;
  90798. exports.ClipVolume = ClipVolume;
  90799. exports.ClippingTool = ClippingTool;
  90800. exports.DeviceOrientationControls = DeviceOrientationControls;
  90801. exports.DownloadStatus = DownloadStatus;
  90802. exports.EarthControls = EarthControls;
  90803. exports.ElevationGradientRepeat = ElevationGradientRepeat;
  90804. exports.Enum = Enum;
  90805. exports.EnumItem = EnumItem;
  90806. exports.EptBinaryLoader = EptBinaryLoader;
  90807. exports.EptKey = EptKey;
  90808. exports.EptLaszipLoader = EptLaszipLoader;
  90809. exports.EptLazBatcher = EptLazBatcher;
  90810. exports.EptLoader = EptLoader;
  90811. exports.EptZstandardLoader = EptZstandardLoader;
  90812. exports.EventDispatcher = EventDispatcher$1;
  90813. exports.EyeDomeLightingMaterial = EyeDomeLightingMaterial;
  90814. exports.Features = Features;
  90815. exports.FirstPersonControls = FirstPersonControls;
  90816. exports.GLCubeFaces = GLCubeFaces$1;
  90817. exports.GeoPackageLoader = GeoPackageLoader;
  90818. exports.Geopackage = Geopackage$1;
  90819. exports.Gradients = Gradients;
  90820. exports.HierarchicalSlider = HierarchicalSlider;
  90821. exports.Images360 = Images360;
  90822. exports.KeyCodes = KeyCodes;
  90823. exports.LRU = LRU;
  90824. exports.LRUItem = LRUItem;
  90825. exports.LengthUnits = LengthUnits;
  90826. exports.Log = Log;
  90827. exports.Measure = Measure;
  90828. exports.MeasuringTool = MeasuringTool;
  90829. exports.Message = Message;
  90830. exports.ModelManagerEvents = ModelManagerEvents;
  90831. exports.NormalizationEDLMaterial = NormalizationEDLMaterial;
  90832. exports.NormalizationMaterial = NormalizationMaterial;
  90833. exports.OrbitControls = OrbitControls;
  90834. exports.OrientedImage = OrientedImage;
  90835. exports.OrientedImageLoader = OrientedImageLoader;
  90836. exports.OrientedImages = OrientedImages;
  90837. exports.POCLoader = POCLoader;
  90838. exports.PanoRendererEvents = PanoRendererEvents;
  90839. exports.PanoSizeClass = PanoSizeClass;
  90840. exports.PanoramaEvents = PanoramaEvents;
  90841. exports.PathAnimation = PathAnimation;
  90842. exports.PointAttribute = PointAttribute;
  90843. exports.PointAttributeTypes = PointAttributeTypes;
  90844. exports.PointAttributes = PointAttributes;
  90845. exports.PointCloudEptGeometry = PointCloudEptGeometry;
  90846. exports.PointCloudEptGeometryNode = PointCloudEptGeometryNode;
  90847. exports.PointCloudMaterial = PointCloudMaterial$1;
  90848. exports.PointCloudOctree = PointCloudOctree;
  90849. exports.PointCloudOctreeGeometry = PointCloudOctreeGeometry;
  90850. exports.PointCloudOctreeGeometryNode = PointCloudOctreeGeometryNode;
  90851. exports.PointCloudOctreeNode = PointCloudOctreeNode;
  90852. exports.PointCloudSM = PointCloudSM;
  90853. exports.PointCloudTree = PointCloudTree;
  90854. exports.PointCloudTreeNode = PointCloudTreeNode;
  90855. exports.PointShape = PointShape;
  90856. exports.PointSizeType = PointSizeType;
  90857. exports.Points = Points$1;
  90858. exports.PolygonClipVolume = PolygonClipVolume;
  90859. exports.Profile = Profile;
  90860. exports.ProfileData = ProfileData;
  90861. exports.ProfileRequest = ProfileRequest;
  90862. exports.ProfileTool = ProfileTool;
  90863. exports.Renderer = Renderer;
  90864. exports.Scene = Scene$1;
  90865. exports.SceneRendererEvents = SceneRendererEvents;
  90866. exports.ScreenBoxSelectTool = ScreenBoxSelectTool;
  90867. exports.ShapefileLoader = ShapefileLoader;
  90868. exports.SphereVolume = SphereVolume;
  90869. exports.SpotLightHelper = SpotLightHelper$1;
  90870. exports.TileDownloaderEvents = TileDownloaderEvents;
  90871. exports.TransformationTool = TransformationTool;
  90872. exports.TreeType = TreeType;
  90873. exports.Utils = Utils;
  90874. exports.VRControls = VRControls;
  90875. exports.Vectors = Vectors;
  90876. exports.Vectors2 = Vectors2;
  90877. exports.Version = Version;
  90878. exports.Viewer = Viewer;
  90879. exports.Volume = Volume;
  90880. exports.VolumeTool = VolumeTool;
  90881. exports.WorkerPool = WorkerPool;
  90882. exports.XHRFactory = XHRFactory;
  90883. exports.config = config$1;
  90884. exports.debug = debug;
  90885. exports.framenumber = framenumber;
  90886. exports.loadDatasets = loadDatasets;
  90887. exports.loadFile = loadFile;
  90888. exports.loadMapEntity = loadMapEntity;
  90889. exports.loadPanos = loadPanos;
  90890. exports.loadPanosInfo = loadPanosInfo;
  90891. exports.loadPointCloud = loadPointCloud$1;
  90892. exports.loadProject = loadProject;
  90893. exports.lru = lru;
  90894. exports.maxNodesLoading = maxNodesLoading;
  90895. exports.mergeEditStart = mergeEditStart;
  90896. exports.numNodesLoading = numNodesLoading;
  90897. exports.panoEditStart = panoEditStart;
  90898. exports.pointBudget = pointBudget;
  90899. exports.resourcePath = resourcePath;
  90900. exports.saveProject = saveProject;
  90901. exports.settings = settings;
  90902. exports.start = start;
  90903. exports.updatePointClouds = updatePointClouds;
  90904. exports.updateVisibility = updateVisibility;
  90905. exports.updateVisibilityStructures = updateVisibilityStructures;
  90906. exports.version = version;
  90907. exports.workerPool = workerPool;
  90908. Object.defineProperty(exports, '__esModule', { value: true });
  90909. })));
  90910. //# sourceMappingURL=potree.js.map