potree.js 3.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349
  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. prefix1: '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. prefix5: 'https://laser.4dkankan.com',
  423. prefix6: 'https://mix3d.4dkankan.com/backend',
  424. },
  425. /* transitionsTime:{
  426. flyTime : 1000 // 毫秒/米
  427. panoToPano: 1000,
  428. flyIn:1000,
  429. flyOut:1000,
  430. } */
  431. transitionsTime:{
  432. flyMinTime : 500 /* * 3 */, // 毫秒/米
  433. flytimeDistanceMultiplier: 150/* * 3 */,
  434. panoToPanoMax: 2000/* * 3 */,
  435. flyIn:1000,
  436. flyOut:1000
  437. }
  438. ,
  439. moveSpeedAdujust : 0.5 //越小越慢
  440. ,
  441. view:{
  442. fov:70, //navvis:50
  443. near:0.1,
  444. far: 10000,
  445. },
  446. map:{//mapViewer
  447. mapHeight : -1000,//要比点云低。最低
  448. cameraHeight : 1000, //最高 ,注意(如sitemodel)其他的物体不能超过这个高度
  449. },
  450. pointDensity:{
  451. magnifier:{
  452. maxLevelPercent: 1,
  453. pointBudget : 8*1000*1000,
  454. },
  455. panorama:{//显示全景时的漫游。因为点只能显示1个像素的大小,所以必须很密集,但又要限制点的数量
  456. maxLevelPercent: 0.6,
  457. pointBudget : /* 4*1000*1000// */browser.isMobile() ? 0.1*1000*1000 : 0.4*1000*1000, //点云总最大数
  458. },
  459. fourViewports:{//分四屏时防止卡顿
  460. maxLevelPercent: 0.4,
  461. pointBudget :1*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  462. },
  463. fourViewportsMain:{//分四屏时防止卡顿
  464. maxLevelPercent: 0.8,
  465. pointBudget :1*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  466. }
  467. ,
  468. panoEdit:{
  469. maxLevelPercent: 1, //在远处时由于pointBudget限制而展示稀疏,凑近时就变为最高质量了
  470. pointBudget :1*1000*1000, //避免卡顿
  471. },
  472. low:{//highPerformance
  473. maxLevelPercent: 0.4, //最小为0
  474. percentByUser:true, //如果用户定义了percent,使用用户的
  475. pointBudget : 1*1000*1000,
  476. },
  477. middle:{//balanced //不同场景相同级别所产生的numVisibleNodes和numVisiblePoints不同,如果分层比较细,可能要到level8才能看清,那么level5看到的点就很大且很少,如隧道t-e2Kb2iU
  478. maxLevelPercent: 0.7,
  479. percentByUser:true,
  480. pointBudget:browser.isMobile() ? 4*1000*1000 : 2*1000*1000,
  481. },
  482. high:{//highQuality
  483. maxLevelPercent: 1,
  484. percentByUser:true,
  485. pointBudget:browser.isMobile() ? 8*1000*1000 : 4*1000*1000,
  486. }
  487. //browser.isMobile() 时要不要限制下pointBudget,还是让用户自己调低质量?
  488. //minNodeSize?
  489. //数值由testLevelSteps得来,其中nodeMaxLevel为2时,low和middle的都是1,如果真有这么低的点云就单独处理下。
  490. //多个viewport尽量保证pointBudget一样,或者pointBudget不能太低于所需,否则会反复加载了又清除
  491. },
  492. clip:{
  493. color: '#FFC266', //map
  494. },
  495. panoFieldRadius : 10, //当前位置多远范围内可以切全景模式
  496. measure:{
  497. color:'#00C8AF',
  498. default:{
  499. color:"#64C8BB",//"#00c7b2",
  500. opacity:0.7
  501. },
  502. highlight:{
  503. color:'#00C8AF',//"#00c7b2",
  504. opacity:1
  505. },
  506. guide:{
  507. color:'#FFFFFF',
  508. opacity:1
  509. }
  510. ,
  511. backColor:'#333333',
  512. lineWidth: 4,
  513. textColor: "#FFFFFF"
  514. },
  515. material:{//初始化
  516. pointSize: 0.1,
  517. realPointSize : 0.1,//实际上的ui滑动条默认大小(兼容旧的版本)
  518. minSize: 0.1,
  519. maxSize: 10000,
  520. pointSizeType: 'ATTENUATED', //'ADAPTIVE'//'ADAPTIVE' \ FIXED //ADAPTIVE的在小房间里大小会不太匹配,但在远景似乎更好
  521. /*
  522. ATTENUATED : 衰减 真实大小,靠近时感觉是点云一点点变多,缝隙变小
  523. ADAPTIVE: 自适应 大小根据level变化,越高越小。靠近时感觉点云由大慢慢细分成小份。这个感觉更佳但是navvis为何不用这个
  524. */
  525. absolutePanoramaSize: 1.3 ,//全景漫游时的size 是fixed的模式
  526. //sizeAtPanoRtEDL : 2000,
  527. pointColor:'#ffffff',
  528. //sizeAddAtPanoRtEDL : 0.5, //全景模式静止时的size
  529. //ADAPTIVE : 字会失真扭曲
  530. //'ATTENUATED' 往旁边看有缝隙、点在浮动
  531. //navvis的shader在哪里 为什么不会抖动
  532. }
  533. ,
  534. renderLayers:{//渲染层,方便分批渲染管理,替代scene的创建。数字不代表顺序。(数字不能太大)
  535. bg: 20,
  536. bg2: 21,
  537. skybox: 1,
  538. pointcloud: 11,
  539. sceneObjects:0,//default
  540. model : 2,
  541. measure:4,
  542. magnifier:5,
  543. magnifierContent:16,
  544. volume:6,
  545. transformationTool:7,
  546. map:8,
  547. mapObjects:9,//default
  548. bothMapAndScene: 3,
  549. siteModeOnlyMapVisi:12,//只能mapViewer可见
  550. siteModelMapUnvisi:13,//只有mapViewer不可见
  551. siteModeSideVisi:14,//只有侧面可见
  552. layer1: 10,// 备用1
  553. layer2: 15,// 备用2
  554. },
  555. renderOrders:{ //会影响到绘制、pick时的顺序。
  556. model:10
  557. },
  558. siteModel:{
  559. names:{
  560. 'building': '建筑',
  561. 'floor':'楼层',
  562. 'room':'房间'
  563. },
  564. floorHeightDefault: 5,//一层楼的高度
  565. },
  566. panosEdit:{
  567. },
  568. tiling: {
  569. panoPreRenderRepeatDelay: 2500,
  570. panoPreRenderDelay: 500,
  571. preRenderTourPanos: browser.valueFromHash("tileprerender", 0),
  572. tilingFlagNames: ["usetiles", "tiles"],
  573. maxNavPanoQuality: browser.valueFromHash("maxtileq", null),
  574. maxZoomPanoQuality: browser.valueFromHash("maxztileq", null),
  575. overlayStyle: browser.valueFromHash("tileoverlay", 0),
  576. uploadIntervalDelay: browser.valueFromHash("tileupdelay", 10),
  577. initialIntervalDelay: browser.valueFromHash("itiledelay", 0),
  578. maxNonBaseUploadsPerFrame: browser.valueFromHash("maxnbtpf", 2),
  579. maxBaseUploadsPerFrame: browser.valueFromHash("maxbtpf", 6),
  580. customCompression: browser.valueFromHash("tilecustcomp", 0),
  581. mobileHighQualityOverride: !1,
  582. allowUltraHighResolution: !0
  583. },
  584. navigation: {
  585. panoScores: !1,
  586. mouseDirection: !0,
  587. filterStrictness: .75,
  588. angleFactor: -30,
  589. directionFactor: 10,
  590. distanceFactor: -1,
  591. optionalityFactor: 3
  592. }
  593. ,
  594. axis : { 'x':{color:'#d0021b'/* 'red' */}, 'y':{ color:'#86c542' /* 'green' */}, 'z': {color:'#3399c8' /* 'blue' */}},
  595. highQualityMaxZoom: 2,
  596. ultraHighQualityMaxZoom: 3,
  597. clickMaxDragDis:5,
  598. clickMaxPressTime:500, //ms
  599. doubleClickTime:200,//双击间隔时间
  600. background: '#232323',
  601. mapBG:'#F5F5F5', //地图的clearColor
  602. colors: { //from navvis
  603. red: [213,0,0],
  604. pink: [197,17,98],
  605. purple: [170,0,255],
  606. "deep purple": [98,0,234],
  607. blue: [ 41,98,255],
  608. "light blue": [ 0,145,234],
  609. cyan: [ 0,184,212],
  610. teal: [ 0,191,165],
  611. green: [0,200,83],
  612. "light green": [ 100,221,23],
  613. lime: [ 174,234,0],
  614. yellow: [ 255,214,0],
  615. amber: [ 255,171,0],
  616. orange: [ 255,109,0],
  617. "deep orange": [ 255,61,0],
  618. },
  619. };
  620. config$1.OrthoCameraLimit = {
  621. standard:{
  622. zoom:{min:0.001, max:500}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  623. posBound:{
  624. min: {x:-1e5, y:-1e5,z: config$1.map.cameraHeight},
  625. max: {x:1e5, y:1e5, z:1 / 0 }
  626. }
  627. },
  628. expand:{ //范围再大些,用于编辑空间模型等(但是万一中心点靠近地图边缘的话,就很容易扭曲了)
  629. zoom:{min:0.0004, max:100}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  630. posBound:{
  631. min: {x:-5000000, y:-1000000,z:config$1.map.cameraHeight},
  632. max: {x:5000000, y:1000000, z:1 / 0 }
  633. }//40075017
  634. }
  635. };
  636. /* 显示模式:
  637. 1只显示点云: 滚轮为前进后退,方向键可以行走。进入漫游点时自动变为混合(这样全景可以弥补缝隙),过渡时只显示点云。
  638. 2只显示全景: 不能任意行走。 过渡时显示贴图材质非edl的点云(否则有折痕不贴合)。
  639. 3混合:都显示。 不能任意行走。过渡时显示贴图材质非edl的点云(因为只显示点云的话不太美,点云很碎,不细腻)
  640. */
  641. window.testLevelSteps = function(steps){//[0.4,0.7,1]
  642. if(!steps){
  643. let s = Potree.config.pointDensity;
  644. steps = [s.low.maxLevelPercent, s.middle.maxLevelPercent, s.high.maxLevelPercent, ];
  645. }
  646. let max = 1;
  647. while(++max<=12){
  648. let r1 = steps.map(e=>e * max);
  649. let r2 = steps.map(e=>Math.round(e * max));
  650. console.log(`当nodeMaxLevel为${max}时,每一级的level分别为${r2}, (小数:${r1})`);
  651. }
  652. console.log('请检查每一层的三个level是否有重复');
  653. };
  654. function getPrefix(){
  655. let u = window.location.href.split('//');
  656. let v = u[1].split('/');
  657. return v[0]
  658. }
  659. let settings = {//设置 可修改
  660. editType : '',
  661. number: '', //场景序号
  662. originDatasetId:'',//场景原本的数据集id,应该就是数据集第一个吧
  663. isOfficial:false,
  664. webSite:'testdata',//正式:'datav1', //不同环境对应的静态文件的地址不同
  665. isLocal:false, //是否本地 局域网版本
  666. libsUrl:'../libs/',
  667. displayMode:'',
  668. isTest :browser.urlHasValue('test'),
  669. prefix: getPrefix(),
  670. pointDensity: '', UserPointDensity:'',//pointDensity会随着进入不同的模块而自动改变,UserPointDensity记录了用户的设置
  671. UserDensityPercent:null,//点云密度百分比
  672. ifShowMarker:true,//显示漫游点
  673. floorplanType:{},//平面图类型 'default' | 'diy' 不同数据集不同{datasetId:...}
  674. floorplanEnable:false,
  675. floorplanEnables:{},
  676. floorplanRequests:{},//开始加载了的
  677. mapEnable:true,//地图区域是否加载地图
  678. cameraFar : config$1.view.far, //相机最远范围 1-300
  679. //limitFar: true, //是否使用setting的cameraFar来限制(如在点云裁剪时为false)
  680. showPanoMesh:false, //显示小球,
  681. dblToFocusPoint:false,//调试时如果需要双击飞向某个点云的点,就打开。此时不在漫游点的话单击将无法漫游。//因和单击漫游冲突
  682. unableNavigate : false,//进入如裁剪界面时 禁止漫游
  683. sizeFitToLevel: false,//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  684. zoom:{
  685. enabled : true,
  686. min:1,
  687. max: config$1.highQualityMaxZoom,
  688. activationThreshold: 1.1,
  689. },
  690. navConstantly:true,
  691. navTileClass: browser.isMobile() ? '1k' : '2k', //默认加载到
  692. tileClass:'4k', //最高可达
  693. /* loadTilesWhenUnfocus:false, //页面unfocus时也仍在加载tiles
  694. loadPointsWhenUnfocus:true, //页面unfocus时也仍在加载点云 */
  695. //initialShowPano:true
  696. drawEntityData: false,
  697. zoomFromPointert:{//定点缩放(包括点云模式、全景模式、地图)
  698. whenPanos:true,
  699. whenPointCloud:true,
  700. map:true,
  701. },
  702. rotAroundPoint:true,//点云模式是否能绕intersectPoint旋转
  703. tourTestCameraMove:false, //测试镜头时,不移动真实的镜头, 只移动frustum
  704. cameraAniSmoothRatio : 20, //镜头动画平滑系数,越高越平滑
  705. urls : $.extend({}, config$1.urls, {
  706. prefix : config$1.urls.prefix4 //主要使用的 是测试环境,根据不同工程更改
  707. }),
  708. useDepthTex: true,//使用深度贴图,但不代表一定有(得到的intersect更快速准确和稳定) SS-t-7DUfWAUZ3V
  709. //matUseDepth:false,
  710. //panoEdit:
  711. datasetsPanos:{},
  712. //mergeModel:
  713. boundAddObjs:false,
  714. intersectOnObjs:false,
  715. intersectWhenHover:true,
  716. notAdditiveBlending:false, //点云是否使用普通的blend, 否则会曝光过渡
  717. precision:2 // 两位小数
  718. };
  719. //JSON.parse(localStorage.getItem('setting'))
  720. settings.isLocalhost = settings.prefix.includes('localhost');
  721. // threejs.org/license
  722. const REVISION = '124';
  723. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  724. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  725. const CullFaceNone = 0;
  726. const CullFaceBack = 1;
  727. const CullFaceFront = 2;
  728. const CullFaceFrontBack = 3;
  729. const BasicShadowMap = 0;
  730. const PCFShadowMap = 1;
  731. const PCFSoftShadowMap = 2;
  732. const VSMShadowMap = 3;
  733. const FrontSide = 0;
  734. const BackSide = 1;
  735. const DoubleSide = 2;
  736. const FlatShading = 1;
  737. const SmoothShading = 2;
  738. const NoBlending = 0;
  739. const NormalBlending = 1;
  740. const AdditiveBlending = 2;
  741. const SubtractiveBlending = 3;
  742. const MultiplyBlending = 4;
  743. const CustomBlending = 5;
  744. const AddEquation = 100;
  745. const SubtractEquation = 101;
  746. const ReverseSubtractEquation = 102;
  747. const MinEquation = 103;
  748. const MaxEquation = 104;
  749. const ZeroFactor = 200;
  750. const OneFactor = 201;
  751. const SrcColorFactor = 202;
  752. const OneMinusSrcColorFactor = 203;
  753. const SrcAlphaFactor = 204;
  754. const OneMinusSrcAlphaFactor = 205;
  755. const DstAlphaFactor = 206;
  756. const OneMinusDstAlphaFactor = 207;
  757. const DstColorFactor = 208;
  758. const OneMinusDstColorFactor = 209;
  759. const SrcAlphaSaturateFactor = 210;
  760. const NeverDepth = 0;
  761. const AlwaysDepth = 1;
  762. const LessDepth = 2;
  763. const LessEqualDepth = 3;
  764. const EqualDepth = 4;
  765. const GreaterEqualDepth = 5;
  766. const GreaterDepth = 6;
  767. const NotEqualDepth = 7;
  768. const MultiplyOperation = 0;
  769. const MixOperation = 1;
  770. const AddOperation = 2;
  771. const NoToneMapping = 0;
  772. const LinearToneMapping = 1;
  773. const ReinhardToneMapping = 2;
  774. const CineonToneMapping = 3;
  775. const ACESFilmicToneMapping = 4;
  776. const CustomToneMapping = 5;
  777. const UVMapping = 300;
  778. const CubeReflectionMapping = 301;
  779. const CubeRefractionMapping = 302;
  780. const EquirectangularReflectionMapping = 303;
  781. const EquirectangularRefractionMapping = 304;
  782. const CubeUVReflectionMapping = 306;
  783. const CubeUVRefractionMapping = 307;
  784. const RepeatWrapping = 1000;
  785. const ClampToEdgeWrapping = 1001;
  786. const MirroredRepeatWrapping = 1002;
  787. const NearestFilter = 1003;
  788. const NearestMipmapNearestFilter = 1004;
  789. const NearestMipMapNearestFilter = 1004;
  790. const NearestMipmapLinearFilter = 1005;
  791. const NearestMipMapLinearFilter = 1005;
  792. const LinearFilter = 1006;
  793. const LinearMipmapNearestFilter = 1007;
  794. const LinearMipMapNearestFilter = 1007;
  795. const LinearMipmapLinearFilter = 1008;
  796. const LinearMipMapLinearFilter = 1008;
  797. const UnsignedByteType = 1009;
  798. const ByteType = 1010;
  799. const ShortType = 1011;
  800. const UnsignedShortType = 1012;
  801. const IntType = 1013;
  802. const UnsignedIntType = 1014;
  803. const FloatType = 1015;
  804. const HalfFloatType = 1016;
  805. const UnsignedShort4444Type = 1017;
  806. const UnsignedShort5551Type = 1018;
  807. const UnsignedShort565Type = 1019;
  808. const UnsignedInt248Type$1 = 1020;
  809. const AlphaFormat = 1021;
  810. const RGBFormat = 1022;
  811. const RGBAFormat = 1023;
  812. const LuminanceFormat = 1024;
  813. const LuminanceAlphaFormat = 1025;
  814. const RGBEFormat = RGBAFormat;
  815. const DepthFormat = 1026;
  816. const DepthStencilFormat = 1027;
  817. const RedFormat = 1028;
  818. const RedIntegerFormat = 1029;
  819. const RGFormat = 1030;
  820. const RGIntegerFormat = 1031;
  821. const RGBIntegerFormat = 1032;
  822. const RGBAIntegerFormat = 1033;
  823. const RGB_S3TC_DXT1_Format = 33776;
  824. const RGBA_S3TC_DXT1_Format$1 = 33777;
  825. const RGBA_S3TC_DXT3_Format = 33778;
  826. const RGBA_S3TC_DXT5_Format$1 = 33779;
  827. const RGB_PVRTC_4BPPV1_Format = 35840;
  828. const RGB_PVRTC_2BPPV1_Format = 35841;
  829. const RGBA_PVRTC_4BPPV1_Format = 35842;
  830. const RGBA_PVRTC_2BPPV1_Format = 35843;
  831. const RGB_ETC1_Format = 36196;
  832. const RGB_ETC2_Format = 37492;
  833. const RGBA_ETC2_EAC_Format = 37496;
  834. const RGBA_ASTC_4x4_Format = 37808;
  835. const RGBA_ASTC_5x4_Format = 37809;
  836. const RGBA_ASTC_5x5_Format = 37810;
  837. const RGBA_ASTC_6x5_Format = 37811;
  838. const RGBA_ASTC_6x6_Format = 37812;
  839. const RGBA_ASTC_8x5_Format = 37813;
  840. const RGBA_ASTC_8x6_Format = 37814;
  841. const RGBA_ASTC_8x8_Format = 37815;
  842. const RGBA_ASTC_10x5_Format = 37816;
  843. const RGBA_ASTC_10x6_Format = 37817;
  844. const RGBA_ASTC_10x8_Format = 37818;
  845. const RGBA_ASTC_10x10_Format = 37819;
  846. const RGBA_ASTC_12x10_Format = 37820;
  847. const RGBA_ASTC_12x12_Format = 37821;
  848. const RGBA_BPTC_Format = 36492;
  849. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  850. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  851. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  852. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  853. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  854. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  855. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  856. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  857. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  858. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  859. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  860. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  861. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  862. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  863. const LoopOnce = 2200;
  864. const LoopRepeat = 2201;
  865. const LoopPingPong = 2202;
  866. const InterpolateDiscrete = 2300;
  867. const InterpolateLinear = 2301;
  868. const InterpolateSmooth = 2302;
  869. const ZeroCurvatureEnding = 2400;
  870. const ZeroSlopeEnding = 2401;
  871. const WrapAroundEnding = 2402;
  872. const NormalAnimationBlendMode = 2500;
  873. const AdditiveAnimationBlendMode = 2501;
  874. const TrianglesDrawMode = 0;
  875. const TriangleStripDrawMode = 1;
  876. const TriangleFanDrawMode = 2;
  877. const LinearEncoding = 3000;
  878. const sRGBEncoding = 3001;
  879. const GammaEncoding = 3007;
  880. const RGBEEncoding = 3002;
  881. const LogLuvEncoding = 3003;
  882. const RGBM7Encoding = 3004;
  883. const RGBM16Encoding = 3005;
  884. const RGBDEncoding = 3006;
  885. const BasicDepthPacking = 3200;
  886. const RGBADepthPacking = 3201;
  887. const TangentSpaceNormalMap = 0;
  888. const ObjectSpaceNormalMap = 1;
  889. const ZeroStencilOp = 0;
  890. const KeepStencilOp = 7680;
  891. const ReplaceStencilOp = 7681;
  892. const IncrementStencilOp = 7682;
  893. const DecrementStencilOp = 7683;
  894. const IncrementWrapStencilOp = 34055;
  895. const DecrementWrapStencilOp = 34056;
  896. const InvertStencilOp = 5386;
  897. const NeverStencilFunc = 512;
  898. const LessStencilFunc = 513;
  899. const EqualStencilFunc = 514;
  900. const LessEqualStencilFunc = 515;
  901. const GreaterStencilFunc = 516;
  902. const NotEqualStencilFunc = 517;
  903. const GreaterEqualStencilFunc = 518;
  904. const AlwaysStencilFunc = 519;
  905. const StaticDrawUsage = 35044;
  906. const DynamicDrawUsage = 35048;
  907. const StreamDrawUsage = 35040;
  908. const StaticReadUsage = 35045;
  909. const DynamicReadUsage = 35049;
  910. const StreamReadUsage = 35041;
  911. const StaticCopyUsage = 35046;
  912. const DynamicCopyUsage = 35050;
  913. const StreamCopyUsage = 35042;
  914. const GLSL1 = '100';
  915. const GLSL3 = '300 es';
  916. /**
  917. * https://github.com/mrdoob/eventdispatcher.js/
  918. */
  919. function EventDispatcher() {}
  920. Object.assign( EventDispatcher.prototype, {
  921. addEventListener: function ( type, listener, importance=0 ) {//add importance
  922. if ( this._listeners === undefined ) this._listeners = {};
  923. const listeners = this._listeners;
  924. if ( listeners[ type ] === undefined ) {
  925. listeners[ type ] = [];
  926. }
  927. if ( !listeners[ type ].some(e=>e.listener == listener ) ) {
  928. //listeners[ type ].push( listener );
  929. listeners[type].push({ listener, importance});
  930. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  931. }
  932. },
  933. hasEventListener: function ( type, listener ) {
  934. if ( this._listeners === undefined ) return false;
  935. const listeners = this._listeners;
  936. return listeners[ type ] !== undefined && listeners[ type ].some(e=>e.listener == listener )
  937. },
  938. removeEventListener: function ( type, listener ) {
  939. if ( this._listeners === undefined ) return;
  940. const listeners = this._listeners;
  941. const listenerArray = listeners[ type ];
  942. if ( listenerArray !== undefined ) {
  943. /* const index = listenerArray.indexOf( listener );
  944. if ( index !== - 1 ) {
  945. listenerArray.splice( index, 1 );
  946. } */
  947. let item = listenerArray.find(e=>e.listener == listener);
  948. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  949. }
  950. },
  951. removeEventListeners(type){//add
  952. if(this._listeners && this._listeners[type] !== undefined){
  953. delete this._listeners[type];
  954. }
  955. } ,
  956. removeAllListeners(){ //add
  957. this._listeners = {};
  958. },
  959. dispatchEvent: function ( event ) {
  960. if(typeof event == 'string'){//add
  961. event = {type:event};
  962. }
  963. if ( this._listeners === undefined ) return;
  964. const listeners = this._listeners;
  965. const listenerArray = listeners[ event.type ];
  966. if ( listenerArray !== undefined ) {
  967. event.target = this;
  968. // Make a copy, in case listeners are removed while iterating.
  969. for(let {listener} of listenerArray.slice(0)){
  970. let result = listener.call(this, event); //add stopContinue
  971. if(result && result.stopContinue){
  972. break
  973. }
  974. }
  975. }
  976. }
  977. } );
  978. const _lut = [];
  979. for ( let i = 0; i < 256; i ++ ) {
  980. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  981. }
  982. let _seed = 1234567;
  983. const MathUtils = {
  984. DEG2RAD: Math.PI / 180,
  985. RAD2DEG: 180 / Math.PI,
  986. generateUUID: function () {
  987. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  988. const d0 = Math.random() * 0xffffffff | 0;
  989. const d1 = Math.random() * 0xffffffff | 0;
  990. const d2 = Math.random() * 0xffffffff | 0;
  991. const d3 = Math.random() * 0xffffffff | 0;
  992. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  993. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  994. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  995. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  996. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  997. return uuid.toUpperCase();
  998. },
  999. clamp: function ( value, min, max ) {
  1000. return Math.max( min, Math.min( max, value ) );
  1001. },
  1002. // compute euclidian modulo of m % n
  1003. // https://en.wikipedia.org/wiki/Modulo_operation
  1004. euclideanModulo: function ( n, m ) {
  1005. return ( ( n % m ) + m ) % m;
  1006. },
  1007. // Linear mapping from range <a1, a2> to range <b1, b2>
  1008. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1009. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1010. },
  1011. // https://en.wikipedia.org/wiki/Linear_interpolation
  1012. lerp: function ( x, y, t ) {
  1013. return ( 1 - t ) * x + t * y;
  1014. },
  1015. // http://en.wikipedia.org/wiki/Smoothstep
  1016. smoothstep: function ( x, min, max ) {
  1017. if ( x <= min ) return 0;
  1018. if ( x >= max ) return 1;
  1019. x = ( x - min ) / ( max - min );
  1020. return x * x * ( 3 - 2 * x );
  1021. },
  1022. smootherstep: function ( x, min, max ) {
  1023. if ( x <= min ) return 0;
  1024. if ( x >= max ) return 1;
  1025. x = ( x - min ) / ( max - min );
  1026. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1027. },
  1028. // Random integer from <low, high> interval
  1029. randInt: function ( low, high ) {
  1030. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1031. },
  1032. // Random float from <low, high> interval
  1033. randFloat: function ( low, high ) {
  1034. return low + Math.random() * ( high - low );
  1035. },
  1036. // Random float from <-range/2, range/2> interval
  1037. randFloatSpread: function ( range ) {
  1038. return range * ( 0.5 - Math.random() );
  1039. },
  1040. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  1041. seededRandom: function ( s ) {
  1042. if ( s !== undefined ) _seed = s % 2147483647;
  1043. // Park-Miller algorithm
  1044. _seed = _seed * 16807 % 2147483647;
  1045. return ( _seed - 1 ) / 2147483646;
  1046. },
  1047. degToRad: function ( degrees ) {
  1048. return degrees * MathUtils.DEG2RAD;
  1049. },
  1050. radToDeg: function ( radians ) {
  1051. return radians * MathUtils.RAD2DEG;
  1052. },
  1053. isPowerOfTwo: function ( value ) {
  1054. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1055. },
  1056. ceilPowerOfTwo: function ( value ) {
  1057. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1058. },
  1059. floorPowerOfTwo: function ( value ) {
  1060. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1061. },
  1062. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  1063. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  1064. // rotations are applied to the axes in the order specified by 'order'
  1065. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  1066. // angles are in radians
  1067. const cos = Math.cos;
  1068. const sin = Math.sin;
  1069. const c2 = cos( b / 2 );
  1070. const s2 = sin( b / 2 );
  1071. const c13 = cos( ( a + c ) / 2 );
  1072. const s13 = sin( ( a + c ) / 2 );
  1073. const c1_3 = cos( ( a - c ) / 2 );
  1074. const s1_3 = sin( ( a - c ) / 2 );
  1075. const c3_1 = cos( ( c - a ) / 2 );
  1076. const s3_1 = sin( ( c - a ) / 2 );
  1077. switch ( order ) {
  1078. case 'XYX':
  1079. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1080. break;
  1081. case 'YZY':
  1082. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1083. break;
  1084. case 'ZXZ':
  1085. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1086. break;
  1087. case 'XZX':
  1088. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1089. break;
  1090. case 'YXY':
  1091. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1092. break;
  1093. case 'ZYZ':
  1094. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1095. break;
  1096. default:
  1097. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1098. }
  1099. }
  1100. };
  1101. class Vector2$1 {
  1102. constructor( x = 0, y = 0 ) {
  1103. Object.defineProperty( this, 'isVector2', { value: true } );
  1104. this.x = x;
  1105. this.y = y;
  1106. }
  1107. get width() {
  1108. return this.x;
  1109. }
  1110. set width( value ) {
  1111. this.x = value;
  1112. }
  1113. get height() {
  1114. return this.y;
  1115. }
  1116. set height( value ) {
  1117. this.y = value;
  1118. }
  1119. set( x, y ) {
  1120. this.x = x;
  1121. this.y = y;
  1122. return this;
  1123. }
  1124. setScalar( scalar ) {
  1125. this.x = scalar;
  1126. this.y = scalar;
  1127. return this;
  1128. }
  1129. setX( x ) {
  1130. this.x = x;
  1131. return this;
  1132. }
  1133. setY( y ) {
  1134. this.y = y;
  1135. return this;
  1136. }
  1137. setComponent( index, value ) {
  1138. switch ( index ) {
  1139. case 0: this.x = value; break;
  1140. case 1: this.y = value; break;
  1141. default: throw new Error( 'index is out of range: ' + index );
  1142. }
  1143. return this;
  1144. }
  1145. getComponent( index ) {
  1146. switch ( index ) {
  1147. case 0: return this.x;
  1148. case 1: return this.y;
  1149. default: throw new Error( 'index is out of range: ' + index );
  1150. }
  1151. }
  1152. clone() {
  1153. return new this.constructor( this.x, this.y );
  1154. }
  1155. copy( v ) {
  1156. this.x = v.x;
  1157. this.y = v.y;
  1158. return this;
  1159. }
  1160. add( v, w ) {
  1161. if ( w !== undefined ) {
  1162. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1163. return this.addVectors( v, w );
  1164. }
  1165. this.x += v.x;
  1166. this.y += v.y;
  1167. return this;
  1168. }
  1169. addScalar( s ) {
  1170. this.x += s;
  1171. this.y += s;
  1172. return this;
  1173. }
  1174. addVectors( a, b ) {
  1175. this.x = a.x + b.x;
  1176. this.y = a.y + b.y;
  1177. return this;
  1178. }
  1179. addScaledVector( v, s ) {
  1180. this.x += v.x * s;
  1181. this.y += v.y * s;
  1182. return this;
  1183. }
  1184. sub( v, w ) {
  1185. if ( w !== undefined ) {
  1186. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1187. return this.subVectors( v, w );
  1188. }
  1189. this.x -= v.x;
  1190. this.y -= v.y;
  1191. return this;
  1192. }
  1193. subScalar( s ) {
  1194. this.x -= s;
  1195. this.y -= s;
  1196. return this;
  1197. }
  1198. subVectors( a, b ) {
  1199. this.x = a.x - b.x;
  1200. this.y = a.y - b.y;
  1201. return this;
  1202. }
  1203. multiply( v ) {
  1204. this.x *= v.x;
  1205. this.y *= v.y;
  1206. return this;
  1207. }
  1208. multiplyScalar( scalar ) {
  1209. this.x *= scalar;
  1210. this.y *= scalar;
  1211. return this;
  1212. }
  1213. divide( v ) {
  1214. this.x /= v.x;
  1215. this.y /= v.y;
  1216. return this;
  1217. }
  1218. divideScalar( scalar ) {
  1219. return this.multiplyScalar( 1 / scalar );
  1220. }
  1221. applyMatrix3( m ) {
  1222. const x = this.x, y = this.y;
  1223. const e = m.elements;
  1224. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  1225. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  1226. return this;
  1227. }
  1228. min( v ) {
  1229. this.x = Math.min( this.x, v.x );
  1230. this.y = Math.min( this.y, v.y );
  1231. return this;
  1232. }
  1233. max( v ) {
  1234. this.x = Math.max( this.x, v.x );
  1235. this.y = Math.max( this.y, v.y );
  1236. return this;
  1237. }
  1238. clamp( min, max ) {
  1239. // assumes min < max, componentwise
  1240. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1241. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1242. return this;
  1243. }
  1244. clampScalar( minVal, maxVal ) {
  1245. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1246. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1247. return this;
  1248. }
  1249. clampLength( min, max ) {
  1250. const length = this.length();
  1251. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1252. }
  1253. floor() {
  1254. this.x = Math.floor( this.x );
  1255. this.y = Math.floor( this.y );
  1256. return this;
  1257. }
  1258. ceil() {
  1259. this.x = Math.ceil( this.x );
  1260. this.y = Math.ceil( this.y );
  1261. return this;
  1262. }
  1263. round() {
  1264. this.x = Math.round( this.x );
  1265. this.y = Math.round( this.y );
  1266. return this;
  1267. }
  1268. roundToZero() {
  1269. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1270. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1271. return this;
  1272. }
  1273. negate() {
  1274. this.x = - this.x;
  1275. this.y = - this.y;
  1276. return this;
  1277. }
  1278. dot( v ) {
  1279. return this.x * v.x + this.y * v.y;
  1280. }
  1281. cross( v ) {
  1282. return this.x * v.y - this.y * v.x;
  1283. }
  1284. lengthSq() {
  1285. return this.x * this.x + this.y * this.y;
  1286. }
  1287. length() {
  1288. return Math.sqrt( this.x * this.x + this.y * this.y );
  1289. }
  1290. manhattanLength() {
  1291. return Math.abs( this.x ) + Math.abs( this.y );
  1292. }
  1293. normalize() {
  1294. return this.divideScalar( this.length() || 1 );
  1295. }
  1296. angle() {
  1297. // computes the angle in radians with respect to the positive x-axis
  1298. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1299. return angle;
  1300. }
  1301. distanceTo( v ) {
  1302. return Math.sqrt( this.distanceToSquared( v ) );
  1303. }
  1304. distanceToSquared( v ) {
  1305. const dx = this.x - v.x, dy = this.y - v.y;
  1306. return dx * dx + dy * dy;
  1307. }
  1308. manhattanDistanceTo( v ) {
  1309. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1310. }
  1311. setLength( length ) {
  1312. return this.normalize().multiplyScalar( length );
  1313. }
  1314. lerp( v, alpha ) {
  1315. this.x += ( v.x - this.x ) * alpha;
  1316. this.y += ( v.y - this.y ) * alpha;
  1317. return this;
  1318. }
  1319. lerpVectors( v1, v2, alpha ) {
  1320. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1321. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1322. return this;
  1323. }
  1324. equals( v ) {
  1325. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1326. }
  1327. fromArray( array, offset = 0 ) {
  1328. this.x = array[ offset ];
  1329. this.y = array[ offset + 1 ];
  1330. return this;
  1331. }
  1332. toArray( array = [], offset = 0 ) {
  1333. array[ offset ] = this.x;
  1334. array[ offset + 1 ] = this.y;
  1335. return array;
  1336. }
  1337. fromBufferAttribute( attribute, index, offset ) {
  1338. if ( offset !== undefined ) {
  1339. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  1340. }
  1341. this.x = attribute.getX( index );
  1342. this.y = attribute.getY( index );
  1343. return this;
  1344. }
  1345. rotateAround( center, angle ) {
  1346. const c = Math.cos( angle ), s = Math.sin( angle );
  1347. const x = this.x - center.x;
  1348. const y = this.y - center.y;
  1349. this.x = x * c - y * s + center.x;
  1350. this.y = x * s + y * c + center.y;
  1351. return this;
  1352. }
  1353. random() {
  1354. this.x = Math.random();
  1355. this.y = Math.random();
  1356. return this;
  1357. }
  1358. }
  1359. class Matrix3 {
  1360. constructor() {
  1361. Object.defineProperty( this, 'isMatrix3', { value: true } );
  1362. this.elements = [
  1363. 1, 0, 0,
  1364. 0, 1, 0,
  1365. 0, 0, 1
  1366. ];
  1367. if ( arguments.length > 0 ) {
  1368. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  1369. }
  1370. }
  1371. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1372. const te = this.elements;
  1373. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1374. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1375. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1376. return this;
  1377. }
  1378. identity() {
  1379. this.set(
  1380. 1, 0, 0,
  1381. 0, 1, 0,
  1382. 0, 0, 1
  1383. );
  1384. return this;
  1385. }
  1386. clone() {
  1387. return new this.constructor().fromArray( this.elements );
  1388. }
  1389. copy( m ) {
  1390. const te = this.elements;
  1391. const me = m.elements;
  1392. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1393. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1394. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1395. return this;
  1396. }
  1397. extractBasis( xAxis, yAxis, zAxis ) {
  1398. xAxis.setFromMatrix3Column( this, 0 );
  1399. yAxis.setFromMatrix3Column( this, 1 );
  1400. zAxis.setFromMatrix3Column( this, 2 );
  1401. return this;
  1402. }
  1403. setFromMatrix4( m ) {
  1404. const me = m.elements;
  1405. this.set(
  1406. me[ 0 ], me[ 4 ], me[ 8 ],
  1407. me[ 1 ], me[ 5 ], me[ 9 ],
  1408. me[ 2 ], me[ 6 ], me[ 10 ]
  1409. );
  1410. return this;
  1411. }
  1412. multiply( m ) {
  1413. return this.multiplyMatrices( this, m );
  1414. }
  1415. premultiply( m ) {
  1416. return this.multiplyMatrices( m, this );
  1417. }
  1418. multiplyMatrices( a, b ) {
  1419. const ae = a.elements;
  1420. const be = b.elements;
  1421. const te = this.elements;
  1422. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1423. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1424. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1425. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1426. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1427. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1428. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1429. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1430. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1431. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1432. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1433. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1434. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1435. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1436. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1437. return this;
  1438. }
  1439. multiplyScalar( s ) {
  1440. const te = this.elements;
  1441. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1442. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1443. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1444. return this;
  1445. }
  1446. determinant() {
  1447. const te = this.elements;
  1448. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1449. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1450. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1451. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1452. }
  1453. invert() {
  1454. const te = this.elements,
  1455. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1456. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1457. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1458. t11 = n33 * n22 - n32 * n23,
  1459. t12 = n32 * n13 - n33 * n12,
  1460. t13 = n23 * n12 - n22 * n13,
  1461. det = n11 * t11 + n21 * t12 + n31 * t13;
  1462. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1463. const detInv = 1 / det;
  1464. te[ 0 ] = t11 * detInv;
  1465. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1466. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1467. te[ 3 ] = t12 * detInv;
  1468. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1469. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1470. te[ 6 ] = t13 * detInv;
  1471. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1472. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1473. return this;
  1474. }
  1475. transpose() {
  1476. let tmp;
  1477. const m = this.elements;
  1478. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1479. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1480. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1481. return this;
  1482. }
  1483. getNormalMatrix( matrix4 ) {
  1484. return this.setFromMatrix4( matrix4 ).copy( this ).invert().transpose();
  1485. }
  1486. transposeIntoArray( r ) {
  1487. const m = this.elements;
  1488. r[ 0 ] = m[ 0 ];
  1489. r[ 1 ] = m[ 3 ];
  1490. r[ 2 ] = m[ 6 ];
  1491. r[ 3 ] = m[ 1 ];
  1492. r[ 4 ] = m[ 4 ];
  1493. r[ 5 ] = m[ 7 ];
  1494. r[ 6 ] = m[ 2 ];
  1495. r[ 7 ] = m[ 5 ];
  1496. r[ 8 ] = m[ 8 ];
  1497. return this;
  1498. }
  1499. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1500. const c = Math.cos( rotation );
  1501. const s = Math.sin( rotation );
  1502. this.set(
  1503. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1504. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1505. 0, 0, 1
  1506. );
  1507. return this;
  1508. }
  1509. scale( sx, sy ) {
  1510. const te = this.elements;
  1511. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  1512. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  1513. return this;
  1514. }
  1515. rotate( theta ) {
  1516. const c = Math.cos( theta );
  1517. const s = Math.sin( theta );
  1518. const te = this.elements;
  1519. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  1520. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  1521. te[ 0 ] = c * a11 + s * a21;
  1522. te[ 3 ] = c * a12 + s * a22;
  1523. te[ 6 ] = c * a13 + s * a23;
  1524. te[ 1 ] = - s * a11 + c * a21;
  1525. te[ 4 ] = - s * a12 + c * a22;
  1526. te[ 7 ] = - s * a13 + c * a23;
  1527. return this;
  1528. }
  1529. translate( tx, ty ) {
  1530. const te = this.elements;
  1531. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  1532. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  1533. return this;
  1534. }
  1535. equals( matrix ) {
  1536. const te = this.elements;
  1537. const me = matrix.elements;
  1538. for ( let i = 0; i < 9; i ++ ) {
  1539. if ( te[ i ] !== me[ i ] ) return false;
  1540. }
  1541. return true;
  1542. }
  1543. fromArray( array, offset = 0 ) {
  1544. for ( let i = 0; i < 9; i ++ ) {
  1545. this.elements[ i ] = array[ i + offset ];
  1546. }
  1547. return this;
  1548. }
  1549. toArray( array = [], offset = 0 ) {
  1550. const te = this.elements;
  1551. array[ offset ] = te[ 0 ];
  1552. array[ offset + 1 ] = te[ 1 ];
  1553. array[ offset + 2 ] = te[ 2 ];
  1554. array[ offset + 3 ] = te[ 3 ];
  1555. array[ offset + 4 ] = te[ 4 ];
  1556. array[ offset + 5 ] = te[ 5 ];
  1557. array[ offset + 6 ] = te[ 6 ];
  1558. array[ offset + 7 ] = te[ 7 ];
  1559. array[ offset + 8 ] = te[ 8 ];
  1560. return array;
  1561. }
  1562. }
  1563. let _canvas;
  1564. const ImageUtils = {
  1565. getDataURL: function ( image ) {
  1566. if ( /^data:/i.test( image.src ) ) {
  1567. return image.src;
  1568. }
  1569. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1570. return image.src;
  1571. }
  1572. let canvas;
  1573. if ( image instanceof HTMLCanvasElement ) {
  1574. canvas = image;
  1575. } else {
  1576. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  1577. _canvas.width = image.width;
  1578. _canvas.height = image.height;
  1579. const context = _canvas.getContext( '2d' );
  1580. if ( image instanceof ImageData ) {
  1581. context.putImageData( image, 0, 0 );
  1582. } else {
  1583. context.drawImage( image, 0, 0, image.width, image.height );
  1584. }
  1585. canvas = _canvas;
  1586. }
  1587. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1588. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1589. } else {
  1590. return canvas.toDataURL( 'image/png' );
  1591. }
  1592. }
  1593. };
  1594. let textureId = 0;
  1595. 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 ) {
  1596. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1597. this.uuid = MathUtils.generateUUID();
  1598. this.name = '';
  1599. this.image = image;
  1600. this.mipmaps = [];
  1601. this.mapping = mapping;
  1602. this.wrapS = wrapS;
  1603. this.wrapT = wrapT;
  1604. this.magFilter = magFilter;
  1605. this.minFilter = minFilter;
  1606. this.anisotropy = anisotropy;
  1607. this.format = format;
  1608. this.internalFormat = null;
  1609. this.type = type;
  1610. this.offset = new Vector2$1( 0, 0 );
  1611. this.repeat = new Vector2$1( 1, 1 );
  1612. this.center = new Vector2$1( 0, 0 );
  1613. this.rotation = 0;
  1614. this.matrixAutoUpdate = true;
  1615. this.matrix = new Matrix3();
  1616. this.generateMipmaps = true;
  1617. this.premultiplyAlpha = false;
  1618. this.flipY = true;
  1619. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1620. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1621. //
  1622. // Also changing the encoding after already used by a Material will not automatically make the Material
  1623. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1624. this.encoding = encoding;
  1625. this.version = 0;
  1626. this.onUpdate = null;
  1627. }
  1628. Texture.DEFAULT_IMAGE = undefined;
  1629. Texture.DEFAULT_MAPPING = UVMapping;
  1630. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  1631. constructor: Texture,
  1632. isTexture: true,
  1633. updateMatrix: function () {
  1634. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1635. },
  1636. clone: function () {
  1637. return new this.constructor().copy( this );
  1638. },
  1639. copy: function ( source ) {
  1640. this.name = source.name;
  1641. this.image = source.image;
  1642. this.mipmaps = source.mipmaps.slice( 0 );
  1643. this.mapping = source.mapping;
  1644. this.wrapS = source.wrapS;
  1645. this.wrapT = source.wrapT;
  1646. this.magFilter = source.magFilter;
  1647. this.minFilter = source.minFilter;
  1648. this.anisotropy = source.anisotropy;
  1649. this.format = source.format;
  1650. this.internalFormat = source.internalFormat;
  1651. this.type = source.type;
  1652. this.offset.copy( source.offset );
  1653. this.repeat.copy( source.repeat );
  1654. this.center.copy( source.center );
  1655. this.rotation = source.rotation;
  1656. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1657. this.matrix.copy( source.matrix );
  1658. this.generateMipmaps = source.generateMipmaps;
  1659. this.premultiplyAlpha = source.premultiplyAlpha;
  1660. this.flipY = source.flipY;
  1661. this.unpackAlignment = source.unpackAlignment;
  1662. this.encoding = source.encoding;
  1663. return this;
  1664. },
  1665. toJSON: function ( meta ) {
  1666. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1667. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1668. return meta.textures[ this.uuid ];
  1669. }
  1670. const output = {
  1671. metadata: {
  1672. version: 4.5,
  1673. type: 'Texture',
  1674. generator: 'Texture.toJSON'
  1675. },
  1676. uuid: this.uuid,
  1677. name: this.name,
  1678. mapping: this.mapping,
  1679. repeat: [ this.repeat.x, this.repeat.y ],
  1680. offset: [ this.offset.x, this.offset.y ],
  1681. center: [ this.center.x, this.center.y ],
  1682. rotation: this.rotation,
  1683. wrap: [ this.wrapS, this.wrapT ],
  1684. format: this.format,
  1685. type: this.type,
  1686. encoding: this.encoding,
  1687. minFilter: this.minFilter,
  1688. magFilter: this.magFilter,
  1689. anisotropy: this.anisotropy,
  1690. flipY: this.flipY,
  1691. premultiplyAlpha: this.premultiplyAlpha,
  1692. unpackAlignment: this.unpackAlignment
  1693. };
  1694. if ( this.image !== undefined ) {
  1695. // TODO: Move to THREE.Image
  1696. const image = this.image;
  1697. if ( image.uuid === undefined ) {
  1698. image.uuid = MathUtils.generateUUID(); // UGH
  1699. }
  1700. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1701. let url;
  1702. if ( Array.isArray( image ) ) {
  1703. // process array of images e.g. CubeTexture
  1704. url = [];
  1705. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1706. // check cube texture with data textures
  1707. if ( image[ i ].isDataTexture ) {
  1708. url.push( serializeImage( image[ i ].image ) );
  1709. } else {
  1710. url.push( serializeImage( image[ i ] ) );
  1711. }
  1712. }
  1713. } else {
  1714. // process single image
  1715. url = serializeImage( image );
  1716. }
  1717. meta.images[ image.uuid ] = {
  1718. uuid: image.uuid,
  1719. url: url
  1720. };
  1721. }
  1722. output.image = image.uuid;
  1723. }
  1724. if ( ! isRootObject ) {
  1725. meta.textures[ this.uuid ] = output;
  1726. }
  1727. return output;
  1728. },
  1729. dispose: function () {
  1730. this.dispatchEvent( { type: 'dispose' } );
  1731. },
  1732. transformUv: function ( uv ) {
  1733. if ( this.mapping !== UVMapping ) return uv;
  1734. uv.applyMatrix3( this.matrix );
  1735. if ( uv.x < 0 || uv.x > 1 ) {
  1736. switch ( this.wrapS ) {
  1737. case RepeatWrapping:
  1738. uv.x = uv.x - Math.floor( uv.x );
  1739. break;
  1740. case ClampToEdgeWrapping:
  1741. uv.x = uv.x < 0 ? 0 : 1;
  1742. break;
  1743. case MirroredRepeatWrapping:
  1744. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1745. uv.x = Math.ceil( uv.x ) - uv.x;
  1746. } else {
  1747. uv.x = uv.x - Math.floor( uv.x );
  1748. }
  1749. break;
  1750. }
  1751. }
  1752. if ( uv.y < 0 || uv.y > 1 ) {
  1753. switch ( this.wrapT ) {
  1754. case RepeatWrapping:
  1755. uv.y = uv.y - Math.floor( uv.y );
  1756. break;
  1757. case ClampToEdgeWrapping:
  1758. uv.y = uv.y < 0 ? 0 : 1;
  1759. break;
  1760. case MirroredRepeatWrapping:
  1761. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1762. uv.y = Math.ceil( uv.y ) - uv.y;
  1763. } else {
  1764. uv.y = uv.y - Math.floor( uv.y );
  1765. }
  1766. break;
  1767. }
  1768. }
  1769. if ( this.flipY ) {
  1770. uv.y = 1 - uv.y;
  1771. }
  1772. return uv;
  1773. }
  1774. } );
  1775. Object.defineProperty( Texture.prototype, 'needsUpdate', {
  1776. set: function ( value ) {
  1777. if ( value === true ) this.version ++;
  1778. }
  1779. } );
  1780. function serializeImage( image ) {
  1781. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1782. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1783. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1784. // default images
  1785. return ImageUtils.getDataURL( image );
  1786. } else {
  1787. if ( image.data ) {
  1788. // images of DataTexture
  1789. return {
  1790. data: Array.prototype.slice.call( image.data ),
  1791. width: image.width,
  1792. height: image.height,
  1793. type: image.data.constructor.name
  1794. };
  1795. } else {
  1796. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1797. return {};
  1798. }
  1799. }
  1800. }
  1801. class Vector4 {
  1802. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1803. Object.defineProperty( this, 'isVector4', { value: true } );
  1804. this.x = x;
  1805. this.y = y;
  1806. this.z = z;
  1807. this.w = w;
  1808. }
  1809. get width() {
  1810. return this.z;
  1811. }
  1812. set width( value ) {
  1813. this.z = value;
  1814. }
  1815. get height() {
  1816. return this.w;
  1817. }
  1818. set height( value ) {
  1819. this.w = value;
  1820. }
  1821. set( x, y, z, w ) {
  1822. this.x = x;
  1823. this.y = y;
  1824. this.z = z;
  1825. this.w = w;
  1826. return this;
  1827. }
  1828. setScalar( scalar ) {
  1829. this.x = scalar;
  1830. this.y = scalar;
  1831. this.z = scalar;
  1832. this.w = scalar;
  1833. return this;
  1834. }
  1835. setX( x ) {
  1836. this.x = x;
  1837. return this;
  1838. }
  1839. setY( y ) {
  1840. this.y = y;
  1841. return this;
  1842. }
  1843. setZ( z ) {
  1844. this.z = z;
  1845. return this;
  1846. }
  1847. setW( w ) {
  1848. this.w = w;
  1849. return this;
  1850. }
  1851. setComponent( index, value ) {
  1852. switch ( index ) {
  1853. case 0: this.x = value; break;
  1854. case 1: this.y = value; break;
  1855. case 2: this.z = value; break;
  1856. case 3: this.w = value; break;
  1857. default: throw new Error( 'index is out of range: ' + index );
  1858. }
  1859. return this;
  1860. }
  1861. getComponent( index ) {
  1862. switch ( index ) {
  1863. case 0: return this.x;
  1864. case 1: return this.y;
  1865. case 2: return this.z;
  1866. case 3: return this.w;
  1867. default: throw new Error( 'index is out of range: ' + index );
  1868. }
  1869. }
  1870. clone() {
  1871. return new this.constructor( this.x, this.y, this.z, this.w );
  1872. }
  1873. copy( v ) {
  1874. this.x = v.x;
  1875. this.y = v.y;
  1876. this.z = v.z;
  1877. this.w = ( v.w !== undefined ) ? v.w : 1;
  1878. return this;
  1879. }
  1880. add( v, w ) {
  1881. if ( w !== undefined ) {
  1882. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1883. return this.addVectors( v, w );
  1884. }
  1885. this.x += v.x;
  1886. this.y += v.y;
  1887. this.z += v.z;
  1888. this.w += v.w;
  1889. return this;
  1890. }
  1891. addScalar( s ) {
  1892. this.x += s;
  1893. this.y += s;
  1894. this.z += s;
  1895. this.w += s;
  1896. return this;
  1897. }
  1898. addVectors( a, b ) {
  1899. this.x = a.x + b.x;
  1900. this.y = a.y + b.y;
  1901. this.z = a.z + b.z;
  1902. this.w = a.w + b.w;
  1903. return this;
  1904. }
  1905. addScaledVector( v, s ) {
  1906. this.x += v.x * s;
  1907. this.y += v.y * s;
  1908. this.z += v.z * s;
  1909. this.w += v.w * s;
  1910. return this;
  1911. }
  1912. sub( v, w ) {
  1913. if ( w !== undefined ) {
  1914. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1915. return this.subVectors( v, w );
  1916. }
  1917. this.x -= v.x;
  1918. this.y -= v.y;
  1919. this.z -= v.z;
  1920. this.w -= v.w;
  1921. return this;
  1922. }
  1923. subScalar( s ) {
  1924. this.x -= s;
  1925. this.y -= s;
  1926. this.z -= s;
  1927. this.w -= s;
  1928. return this;
  1929. }
  1930. subVectors( a, b ) {
  1931. this.x = a.x - b.x;
  1932. this.y = a.y - b.y;
  1933. this.z = a.z - b.z;
  1934. this.w = a.w - b.w;
  1935. return this;
  1936. }
  1937. multiplyScalar( scalar ) {
  1938. this.x *= scalar;
  1939. this.y *= scalar;
  1940. this.z *= scalar;
  1941. this.w *= scalar;
  1942. return this;
  1943. }
  1944. applyMatrix4( m ) {
  1945. const x = this.x, y = this.y, z = this.z, w = this.w;
  1946. const e = m.elements;
  1947. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1948. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1949. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1950. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1951. return this;
  1952. }
  1953. divideScalar( scalar ) {
  1954. return this.multiplyScalar( 1 / scalar );
  1955. }
  1956. setAxisAngleFromQuaternion( q ) {
  1957. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1958. // q is assumed to be normalized
  1959. this.w = 2 * Math.acos( q.w );
  1960. const s = Math.sqrt( 1 - q.w * q.w );
  1961. if ( s < 0.0001 ) {
  1962. this.x = 1;
  1963. this.y = 0;
  1964. this.z = 0;
  1965. } else {
  1966. this.x = q.x / s;
  1967. this.y = q.y / s;
  1968. this.z = q.z / s;
  1969. }
  1970. return this;
  1971. }
  1972. setAxisAngleFromRotationMatrix( m ) {
  1973. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1974. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1975. let angle, x, y, z; // variables for result
  1976. const epsilon = 0.01, // margin to allow for rounding errors
  1977. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1978. te = m.elements,
  1979. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1980. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1981. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1982. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1983. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1984. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1985. // singularity found
  1986. // first check for identity matrix which must have +1 for all terms
  1987. // in leading diagonal and zero in other terms
  1988. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1989. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1990. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1991. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1992. // this singularity is identity matrix so angle = 0
  1993. this.set( 1, 0, 0, 0 );
  1994. return this; // zero angle, arbitrary axis
  1995. }
  1996. // otherwise this singularity is angle = 180
  1997. angle = Math.PI;
  1998. const xx = ( m11 + 1 ) / 2;
  1999. const yy = ( m22 + 1 ) / 2;
  2000. const zz = ( m33 + 1 ) / 2;
  2001. const xy = ( m12 + m21 ) / 4;
  2002. const xz = ( m13 + m31 ) / 4;
  2003. const yz = ( m23 + m32 ) / 4;
  2004. if ( ( xx > yy ) && ( xx > zz ) ) {
  2005. // m11 is the largest diagonal term
  2006. if ( xx < epsilon ) {
  2007. x = 0;
  2008. y = 0.707106781;
  2009. z = 0.707106781;
  2010. } else {
  2011. x = Math.sqrt( xx );
  2012. y = xy / x;
  2013. z = xz / x;
  2014. }
  2015. } else if ( yy > zz ) {
  2016. // m22 is the largest diagonal term
  2017. if ( yy < epsilon ) {
  2018. x = 0.707106781;
  2019. y = 0;
  2020. z = 0.707106781;
  2021. } else {
  2022. y = Math.sqrt( yy );
  2023. x = xy / y;
  2024. z = yz / y;
  2025. }
  2026. } else {
  2027. // m33 is the largest diagonal term so base result on this
  2028. if ( zz < epsilon ) {
  2029. x = 0.707106781;
  2030. y = 0.707106781;
  2031. z = 0;
  2032. } else {
  2033. z = Math.sqrt( zz );
  2034. x = xz / z;
  2035. y = yz / z;
  2036. }
  2037. }
  2038. this.set( x, y, z, angle );
  2039. return this; // return 180 deg rotation
  2040. }
  2041. // as we have reached here there are no singularities so we can handle normally
  2042. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2043. ( m13 - m31 ) * ( m13 - m31 ) +
  2044. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2045. if ( Math.abs( s ) < 0.001 ) s = 1;
  2046. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2047. // caught by singularity test above, but I've left it in just in case
  2048. this.x = ( m32 - m23 ) / s;
  2049. this.y = ( m13 - m31 ) / s;
  2050. this.z = ( m21 - m12 ) / s;
  2051. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2052. return this;
  2053. }
  2054. min( v ) {
  2055. this.x = Math.min( this.x, v.x );
  2056. this.y = Math.min( this.y, v.y );
  2057. this.z = Math.min( this.z, v.z );
  2058. this.w = Math.min( this.w, v.w );
  2059. return this;
  2060. }
  2061. max( v ) {
  2062. this.x = Math.max( this.x, v.x );
  2063. this.y = Math.max( this.y, v.y );
  2064. this.z = Math.max( this.z, v.z );
  2065. this.w = Math.max( this.w, v.w );
  2066. return this;
  2067. }
  2068. clamp( min, max ) {
  2069. // assumes min < max, componentwise
  2070. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2071. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2072. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2073. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2074. return this;
  2075. }
  2076. clampScalar( minVal, maxVal ) {
  2077. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2078. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2079. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2080. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2081. return this;
  2082. }
  2083. clampLength( min, max ) {
  2084. const length = this.length();
  2085. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2086. }
  2087. floor() {
  2088. this.x = Math.floor( this.x );
  2089. this.y = Math.floor( this.y );
  2090. this.z = Math.floor( this.z );
  2091. this.w = Math.floor( this.w );
  2092. return this;
  2093. }
  2094. ceil() {
  2095. this.x = Math.ceil( this.x );
  2096. this.y = Math.ceil( this.y );
  2097. this.z = Math.ceil( this.z );
  2098. this.w = Math.ceil( this.w );
  2099. return this;
  2100. }
  2101. round() {
  2102. this.x = Math.round( this.x );
  2103. this.y = Math.round( this.y );
  2104. this.z = Math.round( this.z );
  2105. this.w = Math.round( this.w );
  2106. return this;
  2107. }
  2108. roundToZero() {
  2109. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2110. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2111. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2112. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2113. return this;
  2114. }
  2115. negate() {
  2116. this.x = - this.x;
  2117. this.y = - this.y;
  2118. this.z = - this.z;
  2119. this.w = - this.w;
  2120. return this;
  2121. }
  2122. dot( v ) {
  2123. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2124. }
  2125. lengthSq() {
  2126. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2127. }
  2128. length() {
  2129. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2130. }
  2131. manhattanLength() {
  2132. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2133. }
  2134. normalize() {
  2135. return this.divideScalar( this.length() || 1 );
  2136. }
  2137. setLength( length ) {
  2138. return this.normalize().multiplyScalar( length );
  2139. }
  2140. lerp( v, alpha ) {
  2141. this.x += ( v.x - this.x ) * alpha;
  2142. this.y += ( v.y - this.y ) * alpha;
  2143. this.z += ( v.z - this.z ) * alpha;
  2144. this.w += ( v.w - this.w ) * alpha;
  2145. return this;
  2146. }
  2147. lerpVectors( v1, v2, alpha ) {
  2148. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2149. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2150. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2151. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2152. return this;
  2153. }
  2154. equals( v ) {
  2155. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2156. }
  2157. fromArray( array, offset = 0 ) {
  2158. this.x = array[ offset ];
  2159. this.y = array[ offset + 1 ];
  2160. this.z = array[ offset + 2 ];
  2161. this.w = array[ offset + 3 ];
  2162. return this;
  2163. }
  2164. toArray( array = [], offset = 0 ) {
  2165. array[ offset ] = this.x;
  2166. array[ offset + 1 ] = this.y;
  2167. array[ offset + 2 ] = this.z;
  2168. array[ offset + 3 ] = this.w;
  2169. return array;
  2170. }
  2171. fromBufferAttribute( attribute, index, offset ) {
  2172. if ( offset !== undefined ) {
  2173. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  2174. }
  2175. this.x = attribute.getX( index );
  2176. this.y = attribute.getY( index );
  2177. this.z = attribute.getZ( index );
  2178. this.w = attribute.getW( index );
  2179. return this;
  2180. }
  2181. random() {
  2182. this.x = Math.random();
  2183. this.y = Math.random();
  2184. this.z = Math.random();
  2185. this.w = Math.random();
  2186. return this;
  2187. }
  2188. }
  2189. /*
  2190. In options, we can specify:
  2191. * Texture parameters for an auto-generated target texture
  2192. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2193. */
  2194. function WebGLRenderTarget( width, height, options ) {
  2195. this.width = width;
  2196. this.height = height;
  2197. this.scissor = new Vector4( 0, 0, width, height );
  2198. this.scissorTest = false;
  2199. this.viewport = new Vector4( 0, 0, width, height );
  2200. options = options || {};
  2201. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2202. this.texture.image = {};
  2203. this.texture.image.width = width;
  2204. this.texture.image.height = height;
  2205. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2206. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2207. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2208. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2209. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2210. }
  2211. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  2212. constructor: WebGLRenderTarget,
  2213. isWebGLRenderTarget: true,
  2214. setSize: function ( width, height ) {
  2215. if ( this.width !== width || this.height !== height ) {
  2216. this.width = width;
  2217. this.height = height;
  2218. this.texture.image.width = width;
  2219. this.texture.image.height = height;
  2220. this.dispose();
  2221. }
  2222. this.viewport.set( 0, 0, width, height );
  2223. this.scissor.set( 0, 0, width, height );
  2224. },
  2225. clone: function () {
  2226. return new this.constructor().copy( this );
  2227. },
  2228. copy: function ( source ) {
  2229. this.width = source.width;
  2230. this.height = source.height;
  2231. this.viewport.copy( source.viewport );
  2232. this.texture = source.texture.clone();
  2233. this.depthBuffer = source.depthBuffer;
  2234. this.stencilBuffer = source.stencilBuffer;
  2235. this.depthTexture = source.depthTexture;
  2236. return this;
  2237. },
  2238. dispose: function () {
  2239. this.dispatchEvent( { type: 'dispose' } );
  2240. }
  2241. } );
  2242. function WebGLMultisampleRenderTarget( width, height, options ) {
  2243. WebGLRenderTarget.call( this, width, height, options );
  2244. this.samples = 4;
  2245. }
  2246. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  2247. constructor: WebGLMultisampleRenderTarget,
  2248. isWebGLMultisampleRenderTarget: true,
  2249. copy: function ( source ) {
  2250. WebGLRenderTarget.prototype.copy.call( this, source );
  2251. this.samples = source.samples;
  2252. return this;
  2253. }
  2254. } );
  2255. class Quaternion {
  2256. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2257. Object.defineProperty( this, 'isQuaternion', { value: true } );
  2258. this._x = x;
  2259. this._y = y;
  2260. this._z = z;
  2261. this._w = w;
  2262. }
  2263. static slerp( qa, qb, qm, t ) {
  2264. return qm.copy( qa ).slerp( qb, t );
  2265. }
  2266. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2267. // fuzz-free, array-based Quaternion SLERP operation
  2268. let x0 = src0[ srcOffset0 + 0 ],
  2269. y0 = src0[ srcOffset0 + 1 ],
  2270. z0 = src0[ srcOffset0 + 2 ],
  2271. w0 = src0[ srcOffset0 + 3 ];
  2272. const x1 = src1[ srcOffset1 + 0 ],
  2273. y1 = src1[ srcOffset1 + 1 ],
  2274. z1 = src1[ srcOffset1 + 2 ],
  2275. w1 = src1[ srcOffset1 + 3 ];
  2276. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2277. let s = 1 - t;
  2278. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2279. dir = ( cos >= 0 ? 1 : - 1 ),
  2280. sqrSin = 1 - cos * cos;
  2281. // Skip the Slerp for tiny steps to avoid numeric problems:
  2282. if ( sqrSin > Number.EPSILON ) {
  2283. const sin = Math.sqrt( sqrSin ),
  2284. len = Math.atan2( sin, cos * dir );
  2285. s = Math.sin( s * len ) / sin;
  2286. t = Math.sin( t * len ) / sin;
  2287. }
  2288. const tDir = t * dir;
  2289. x0 = x0 * s + x1 * tDir;
  2290. y0 = y0 * s + y1 * tDir;
  2291. z0 = z0 * s + z1 * tDir;
  2292. w0 = w0 * s + w1 * tDir;
  2293. // Normalize in case we just did a lerp:
  2294. if ( s === 1 - t ) {
  2295. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2296. x0 *= f;
  2297. y0 *= f;
  2298. z0 *= f;
  2299. w0 *= f;
  2300. }
  2301. }
  2302. dst[ dstOffset ] = x0;
  2303. dst[ dstOffset + 1 ] = y0;
  2304. dst[ dstOffset + 2 ] = z0;
  2305. dst[ dstOffset + 3 ] = w0;
  2306. }
  2307. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2308. const x0 = src0[ srcOffset0 ];
  2309. const y0 = src0[ srcOffset0 + 1 ];
  2310. const z0 = src0[ srcOffset0 + 2 ];
  2311. const w0 = src0[ srcOffset0 + 3 ];
  2312. const x1 = src1[ srcOffset1 ];
  2313. const y1 = src1[ srcOffset1 + 1 ];
  2314. const z1 = src1[ srcOffset1 + 2 ];
  2315. const w1 = src1[ srcOffset1 + 3 ];
  2316. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2317. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2318. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2319. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2320. return dst;
  2321. }
  2322. get x() {
  2323. return this._x;
  2324. }
  2325. set x( value ) {
  2326. this._x = value;
  2327. this._onChangeCallback();
  2328. }
  2329. get y() {
  2330. return this._y;
  2331. }
  2332. set y( value ) {
  2333. this._y = value;
  2334. this._onChangeCallback();
  2335. }
  2336. get z() {
  2337. return this._z;
  2338. }
  2339. set z( value ) {
  2340. this._z = value;
  2341. this._onChangeCallback();
  2342. }
  2343. get w() {
  2344. return this._w;
  2345. }
  2346. set w( value ) {
  2347. this._w = value;
  2348. this._onChangeCallback();
  2349. }
  2350. set( x, y, z, w ) {
  2351. this._x = x;
  2352. this._y = y;
  2353. this._z = z;
  2354. this._w = w;
  2355. this._onChangeCallback();
  2356. return this;
  2357. }
  2358. clone() {
  2359. return new this.constructor( this._x, this._y, this._z, this._w );
  2360. }
  2361. copy( quaternion ) {
  2362. this._x = quaternion.x;
  2363. this._y = quaternion.y;
  2364. this._z = quaternion.z;
  2365. this._w = quaternion.w;
  2366. this._onChangeCallback();
  2367. return this;
  2368. }
  2369. setFromEuler( euler, update ) {
  2370. if ( ! ( euler && euler.isEuler ) ) {
  2371. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2372. }
  2373. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2374. // http://www.mathworks.com/matlabcentral/fileexchange/
  2375. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2376. // content/SpinCalc.m
  2377. const cos = Math.cos;
  2378. const sin = Math.sin;
  2379. const c1 = cos( x / 2 );
  2380. const c2 = cos( y / 2 );
  2381. const c3 = cos( z / 2 );
  2382. const s1 = sin( x / 2 );
  2383. const s2 = sin( y / 2 );
  2384. const s3 = sin( z / 2 );
  2385. switch ( order ) {
  2386. case 'XYZ':
  2387. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2388. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2389. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2390. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2391. break;
  2392. case 'YXZ':
  2393. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2394. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2395. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2396. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2397. break;
  2398. case 'ZXY':
  2399. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2400. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2401. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2402. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2403. break;
  2404. case 'ZYX':
  2405. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2406. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2407. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2408. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2409. break;
  2410. case 'YZX':
  2411. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2412. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2413. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2414. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2415. break;
  2416. case 'XZY':
  2417. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2418. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2419. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2420. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2421. break;
  2422. default:
  2423. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2424. }
  2425. if ( update !== false ) this._onChangeCallback();
  2426. return this;
  2427. }
  2428. setFromAxisAngle( axis, angle ) {
  2429. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2430. // assumes axis is normalized
  2431. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2432. this._x = axis.x * s;
  2433. this._y = axis.y * s;
  2434. this._z = axis.z * s;
  2435. this._w = Math.cos( halfAngle );
  2436. this._onChangeCallback();
  2437. return this;
  2438. }
  2439. setFromRotationMatrix( m ) {
  2440. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2441. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2442. const te = m.elements,
  2443. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2444. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2445. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2446. trace = m11 + m22 + m33;
  2447. if ( trace > 0 ) {
  2448. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2449. this._w = 0.25 / s;
  2450. this._x = ( m32 - m23 ) * s;
  2451. this._y = ( m13 - m31 ) * s;
  2452. this._z = ( m21 - m12 ) * s;
  2453. } else if ( m11 > m22 && m11 > m33 ) {
  2454. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2455. this._w = ( m32 - m23 ) / s;
  2456. this._x = 0.25 * s;
  2457. this._y = ( m12 + m21 ) / s;
  2458. this._z = ( m13 + m31 ) / s;
  2459. } else if ( m22 > m33 ) {
  2460. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2461. this._w = ( m13 - m31 ) / s;
  2462. this._x = ( m12 + m21 ) / s;
  2463. this._y = 0.25 * s;
  2464. this._z = ( m23 + m32 ) / s;
  2465. } else {
  2466. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2467. this._w = ( m21 - m12 ) / s;
  2468. this._x = ( m13 + m31 ) / s;
  2469. this._y = ( m23 + m32 ) / s;
  2470. this._z = 0.25 * s;
  2471. }
  2472. this._onChangeCallback();
  2473. return this;
  2474. }
  2475. setFromUnitVectors( vFrom, vTo ) {
  2476. // assumes direction vectors vFrom and vTo are normalized
  2477. const EPS = 0.000001;
  2478. let r = vFrom.dot( vTo ) + 1;
  2479. if ( r < EPS ) {
  2480. r = 0;
  2481. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2482. this._x = - vFrom.y;
  2483. this._y = vFrom.x;
  2484. this._z = 0;
  2485. this._w = r;
  2486. } else {
  2487. this._x = 0;
  2488. this._y = - vFrom.z;
  2489. this._z = vFrom.y;
  2490. this._w = r;
  2491. }
  2492. } else {
  2493. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2494. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2495. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2496. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2497. this._w = r;
  2498. }
  2499. return this.normalize();
  2500. }
  2501. angleTo( q ) {
  2502. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  2503. }
  2504. rotateTowards( q, step ) {
  2505. const angle = this.angleTo( q );
  2506. if ( angle === 0 ) return this;
  2507. const t = Math.min( 1, step / angle );
  2508. this.slerp( q, t );
  2509. return this;
  2510. }
  2511. identity() {
  2512. return this.set( 0, 0, 0, 1 );
  2513. }
  2514. invert() {
  2515. // quaternion is assumed to have unit length
  2516. return this.conjugate();
  2517. }
  2518. conjugate() {
  2519. this._x *= - 1;
  2520. this._y *= - 1;
  2521. this._z *= - 1;
  2522. this._onChangeCallback();
  2523. return this;
  2524. }
  2525. dot( v ) {
  2526. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2527. }
  2528. lengthSq() {
  2529. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2530. }
  2531. length() {
  2532. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2533. }
  2534. normalize() {
  2535. let l = this.length();
  2536. if ( l === 0 ) {
  2537. this._x = 0;
  2538. this._y = 0;
  2539. this._z = 0;
  2540. this._w = 1;
  2541. } else {
  2542. l = 1 / l;
  2543. this._x = this._x * l;
  2544. this._y = this._y * l;
  2545. this._z = this._z * l;
  2546. this._w = this._w * l;
  2547. }
  2548. this._onChangeCallback();
  2549. return this;
  2550. }
  2551. multiply( q, p ) {
  2552. if ( p !== undefined ) {
  2553. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2554. return this.multiplyQuaternions( q, p );
  2555. }
  2556. return this.multiplyQuaternions( this, q );
  2557. }
  2558. premultiply( q ) {
  2559. return this.multiplyQuaternions( q, this );
  2560. }
  2561. multiplyQuaternions( a, b ) {
  2562. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2563. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2564. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2565. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2566. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2567. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2568. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2569. this._onChangeCallback();
  2570. return this;
  2571. }
  2572. slerp( qb, t ) {
  2573. if ( t === 0 ) return this;
  2574. if ( t === 1 ) return this.copy( qb );
  2575. const x = this._x, y = this._y, z = this._z, w = this._w;
  2576. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2577. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2578. if ( cosHalfTheta < 0 ) {
  2579. this._w = - qb._w;
  2580. this._x = - qb._x;
  2581. this._y = - qb._y;
  2582. this._z = - qb._z;
  2583. cosHalfTheta = - cosHalfTheta;
  2584. } else {
  2585. this.copy( qb );
  2586. }
  2587. if ( cosHalfTheta >= 1.0 ) {
  2588. this._w = w;
  2589. this._x = x;
  2590. this._y = y;
  2591. this._z = z;
  2592. return this;
  2593. }
  2594. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2595. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2596. const s = 1 - t;
  2597. this._w = s * w + t * this._w;
  2598. this._x = s * x + t * this._x;
  2599. this._y = s * y + t * this._y;
  2600. this._z = s * z + t * this._z;
  2601. this.normalize();
  2602. this._onChangeCallback();
  2603. return this;
  2604. }
  2605. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2606. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2607. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2608. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2609. this._w = ( w * ratioA + this._w * ratioB );
  2610. this._x = ( x * ratioA + this._x * ratioB );
  2611. this._y = ( y * ratioA + this._y * ratioB );
  2612. this._z = ( z * ratioA + this._z * ratioB );
  2613. this._onChangeCallback();
  2614. return this;
  2615. }
  2616. equals( quaternion ) {
  2617. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2618. }
  2619. fromArray( array, offset = 0 ) {
  2620. this._x = array[ offset ];
  2621. this._y = array[ offset + 1 ];
  2622. this._z = array[ offset + 2 ];
  2623. this._w = array[ offset + 3 ];
  2624. this._onChangeCallback();
  2625. return this;
  2626. }
  2627. toArray( array = [], offset = 0 ) {
  2628. array[ offset ] = this._x;
  2629. array[ offset + 1 ] = this._y;
  2630. array[ offset + 2 ] = this._z;
  2631. array[ offset + 3 ] = this._w;
  2632. return array;
  2633. }
  2634. fromBufferAttribute( attribute, index ) {
  2635. this._x = attribute.getX( index );
  2636. this._y = attribute.getY( index );
  2637. this._z = attribute.getZ( index );
  2638. this._w = attribute.getW( index );
  2639. return this;
  2640. }
  2641. _onChange( callback ) {
  2642. this._onChangeCallback = callback;
  2643. return this;
  2644. }
  2645. _onChangeCallback() {}
  2646. }
  2647. class Vector3 {
  2648. constructor( x = 0, y = 0, z = 0 ) {
  2649. Object.defineProperty( this, 'isVector3', { value: true } );
  2650. this.x = x;
  2651. this.y = y;
  2652. this.z = z;
  2653. }
  2654. set( x, y, z ) {
  2655. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2656. this.x = x;
  2657. this.y = y;
  2658. this.z = z;
  2659. return this;
  2660. }
  2661. setScalar( scalar ) {
  2662. this.x = scalar;
  2663. this.y = scalar;
  2664. this.z = scalar;
  2665. return this;
  2666. }
  2667. setX( x ) {
  2668. this.x = x;
  2669. return this;
  2670. }
  2671. setY( y ) {
  2672. this.y = y;
  2673. return this;
  2674. }
  2675. setZ( z ) {
  2676. this.z = z;
  2677. return this;
  2678. }
  2679. setComponent( index, value ) {
  2680. switch ( index ) {
  2681. case 0: this.x = value; break;
  2682. case 1: this.y = value; break;
  2683. case 2: this.z = value; break;
  2684. default: throw new Error( 'index is out of range: ' + index );
  2685. }
  2686. return this;
  2687. }
  2688. getComponent( index ) {
  2689. switch ( index ) {
  2690. case 0: return this.x;
  2691. case 1: return this.y;
  2692. case 2: return this.z;
  2693. default: throw new Error( 'index is out of range: ' + index );
  2694. }
  2695. }
  2696. clone() {
  2697. return new this.constructor( this.x, this.y, this.z );
  2698. }
  2699. copy( v ) {
  2700. this.x = v.x;
  2701. this.y = v.y;
  2702. this.z = v.z;
  2703. return this;
  2704. }
  2705. add( v, w ) {
  2706. if ( w !== undefined ) {
  2707. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2708. return this.addVectors( v, w );
  2709. }
  2710. this.x += v.x;
  2711. this.y += v.y;
  2712. this.z += v.z;
  2713. return this;
  2714. }
  2715. addScalar( s ) {
  2716. this.x += s;
  2717. this.y += s;
  2718. this.z += s;
  2719. return this;
  2720. }
  2721. addVectors( a, b ) {
  2722. this.x = a.x + b.x;
  2723. this.y = a.y + b.y;
  2724. this.z = a.z + b.z;
  2725. return this;
  2726. }
  2727. addScaledVector( v, s ) {
  2728. this.x += v.x * s;
  2729. this.y += v.y * s;
  2730. this.z += v.z * s;
  2731. return this;
  2732. }
  2733. sub( v, w ) {
  2734. if ( w !== undefined ) {
  2735. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2736. return this.subVectors( v, w );
  2737. }
  2738. this.x -= v.x;
  2739. this.y -= v.y;
  2740. this.z -= v.z;
  2741. return this;
  2742. }
  2743. subScalar( s ) {
  2744. this.x -= s;
  2745. this.y -= s;
  2746. this.z -= s;
  2747. return this;
  2748. }
  2749. subVectors( a, b ) {
  2750. this.x = a.x - b.x;
  2751. this.y = a.y - b.y;
  2752. this.z = a.z - b.z;
  2753. return this;
  2754. }
  2755. multiply( v, w ) {
  2756. if ( w !== undefined ) {
  2757. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2758. return this.multiplyVectors( v, w );
  2759. }
  2760. this.x *= v.x;
  2761. this.y *= v.y;
  2762. this.z *= v.z;
  2763. return this;
  2764. }
  2765. multiplyScalar( scalar ) {
  2766. this.x *= scalar;
  2767. this.y *= scalar;
  2768. this.z *= scalar;
  2769. return this;
  2770. }
  2771. multiplyVectors( a, b ) {
  2772. this.x = a.x * b.x;
  2773. this.y = a.y * b.y;
  2774. this.z = a.z * b.z;
  2775. return this;
  2776. }
  2777. applyEuler( euler ) {
  2778. if ( ! ( euler && euler.isEuler ) ) {
  2779. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2780. }
  2781. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  2782. }
  2783. applyAxisAngle( axis, angle ) {
  2784. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  2785. }
  2786. applyMatrix3( m ) {
  2787. const x = this.x, y = this.y, z = this.z;
  2788. const e = m.elements;
  2789. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2790. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2791. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2792. return this;
  2793. }
  2794. applyNormalMatrix( m ) {
  2795. return this.applyMatrix3( m ).normalize();
  2796. }
  2797. applyMatrix4( m ) {
  2798. const x = this.x, y = this.y, z = this.z;
  2799. const e = m.elements;
  2800. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2801. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2802. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2803. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2804. return this;
  2805. }
  2806. applyQuaternion( q ) {
  2807. const x = this.x, y = this.y, z = this.z;
  2808. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2809. // calculate quat * vector
  2810. const ix = qw * x + qy * z - qz * y;
  2811. const iy = qw * y + qz * x - qx * z;
  2812. const iz = qw * z + qx * y - qy * x;
  2813. const iw = - qx * x - qy * y - qz * z;
  2814. // calculate result * inverse quat
  2815. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2816. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2817. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2818. return this;
  2819. }
  2820. project( camera ) {
  2821. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2822. }
  2823. unproject( camera ) {
  2824. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2825. }
  2826. transformDirection( m ) {
  2827. // input: THREE.Matrix4 affine matrix
  2828. // vector interpreted as a direction
  2829. const x = this.x, y = this.y, z = this.z;
  2830. const e = m.elements;
  2831. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2832. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2833. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2834. return this.normalize();
  2835. }
  2836. divide( v ) {
  2837. this.x /= v.x;
  2838. this.y /= v.y;
  2839. this.z /= v.z;
  2840. return this;
  2841. }
  2842. divideScalar( scalar ) {
  2843. return this.multiplyScalar( 1 / scalar );
  2844. }
  2845. min( v ) {
  2846. this.x = Math.min( this.x, v.x );
  2847. this.y = Math.min( this.y, v.y );
  2848. this.z = Math.min( this.z, v.z );
  2849. return this;
  2850. }
  2851. max( v ) {
  2852. this.x = Math.max( this.x, v.x );
  2853. this.y = Math.max( this.y, v.y );
  2854. this.z = Math.max( this.z, v.z );
  2855. return this;
  2856. }
  2857. clamp( min, max ) {
  2858. // assumes min < max, componentwise
  2859. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2860. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2861. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2862. return this;
  2863. }
  2864. clampScalar( minVal, maxVal ) {
  2865. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2866. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2867. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2868. return this;
  2869. }
  2870. clampLength( min, max ) {
  2871. const length = this.length();
  2872. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2873. }
  2874. floor() {
  2875. this.x = Math.floor( this.x );
  2876. this.y = Math.floor( this.y );
  2877. this.z = Math.floor( this.z );
  2878. return this;
  2879. }
  2880. ceil() {
  2881. this.x = Math.ceil( this.x );
  2882. this.y = Math.ceil( this.y );
  2883. this.z = Math.ceil( this.z );
  2884. return this;
  2885. }
  2886. round() {
  2887. this.x = Math.round( this.x );
  2888. this.y = Math.round( this.y );
  2889. this.z = Math.round( this.z );
  2890. return this;
  2891. }
  2892. roundToZero() {
  2893. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2894. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2895. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2896. return this;
  2897. }
  2898. negate() {
  2899. this.x = - this.x;
  2900. this.y = - this.y;
  2901. this.z = - this.z;
  2902. return this;
  2903. }
  2904. dot( v ) {
  2905. return this.x * v.x + this.y * v.y + this.z * v.z;
  2906. }
  2907. // TODO lengthSquared?
  2908. lengthSq() {
  2909. return this.x * this.x + this.y * this.y + this.z * this.z;
  2910. }
  2911. length() {
  2912. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2913. }
  2914. manhattanLength() {
  2915. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2916. }
  2917. normalize() {
  2918. return this.divideScalar( this.length() || 1 );
  2919. }
  2920. setLength( length ) {
  2921. return this.normalize().multiplyScalar( length );
  2922. }
  2923. lerp( v, alpha ) {
  2924. this.x += ( v.x - this.x ) * alpha;
  2925. this.y += ( v.y - this.y ) * alpha;
  2926. this.z += ( v.z - this.z ) * alpha;
  2927. return this;
  2928. }
  2929. lerpVectors( v1, v2, alpha ) {
  2930. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2931. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2932. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2933. return this;
  2934. }
  2935. cross( v, w ) {
  2936. if ( w !== undefined ) {
  2937. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2938. return this.crossVectors( v, w );
  2939. }
  2940. return this.crossVectors( this, v );
  2941. }
  2942. crossVectors( a, b ) {
  2943. const ax = a.x, ay = a.y, az = a.z;
  2944. const bx = b.x, by = b.y, bz = b.z;
  2945. this.x = ay * bz - az * by;
  2946. this.y = az * bx - ax * bz;
  2947. this.z = ax * by - ay * bx;
  2948. return this;
  2949. }
  2950. projectOnVector( v ) {
  2951. const denominator = v.lengthSq();
  2952. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2953. const scalar = v.dot( this ) / denominator;
  2954. return this.copy( v ).multiplyScalar( scalar );
  2955. }
  2956. projectOnPlane( planeNormal ) {
  2957. _vector.copy( this ).projectOnVector( planeNormal );
  2958. return this.sub( _vector );
  2959. }
  2960. reflect( normal ) {
  2961. // reflect incident vector off plane orthogonal to normal
  2962. // normal is assumed to have unit length
  2963. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2964. }
  2965. angleTo( v ) {
  2966. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2967. if ( denominator === 0 ) return Math.PI / 2;
  2968. const theta = this.dot( v ) / denominator;
  2969. // clamp, to handle numerical problems
  2970. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  2971. }
  2972. distanceTo( v ) {
  2973. return Math.sqrt( this.distanceToSquared( v ) );
  2974. }
  2975. distanceToSquared( v ) {
  2976. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2977. return dx * dx + dy * dy + dz * dz;
  2978. }
  2979. manhattanDistanceTo( v ) {
  2980. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2981. }
  2982. setFromSpherical( s ) {
  2983. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2984. }
  2985. setFromSphericalCoords( radius, phi, theta ) {
  2986. const sinPhiRadius = Math.sin( phi ) * radius;
  2987. this.x = sinPhiRadius * Math.sin( theta );
  2988. this.y = Math.cos( phi ) * radius;
  2989. this.z = sinPhiRadius * Math.cos( theta );
  2990. return this;
  2991. }
  2992. setFromCylindrical( c ) {
  2993. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2994. }
  2995. setFromCylindricalCoords( radius, theta, y ) {
  2996. this.x = radius * Math.sin( theta );
  2997. this.y = y;
  2998. this.z = radius * Math.cos( theta );
  2999. return this;
  3000. }
  3001. setFromMatrixPosition( m ) {
  3002. const e = m.elements;
  3003. this.x = e[ 12 ];
  3004. this.y = e[ 13 ];
  3005. this.z = e[ 14 ];
  3006. return this;
  3007. }
  3008. setFromMatrixScale( m ) {
  3009. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3010. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3011. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3012. this.x = sx;
  3013. this.y = sy;
  3014. this.z = sz;
  3015. return this;
  3016. }
  3017. setFromMatrixColumn( m, index ) {
  3018. return this.fromArray( m.elements, index * 4 );
  3019. }
  3020. setFromMatrix3Column( m, index ) {
  3021. return this.fromArray( m.elements, index * 3 );
  3022. }
  3023. equals( v ) {
  3024. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3025. }
  3026. fromArray( array, offset = 0 ) {
  3027. this.x = array[ offset ];
  3028. this.y = array[ offset + 1 ];
  3029. this.z = array[ offset + 2 ];
  3030. return this;
  3031. }
  3032. toArray( array = [], offset = 0 ) {
  3033. array[ offset ] = this.x;
  3034. array[ offset + 1 ] = this.y;
  3035. array[ offset + 2 ] = this.z;
  3036. return array;
  3037. }
  3038. fromBufferAttribute( attribute, index, offset ) {
  3039. if ( offset !== undefined ) {
  3040. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  3041. }
  3042. this.x = attribute.getX( index );
  3043. this.y = attribute.getY( index );
  3044. this.z = attribute.getZ( index );
  3045. return this;
  3046. }
  3047. random() {
  3048. this.x = Math.random();
  3049. this.y = Math.random();
  3050. this.z = Math.random();
  3051. return this;
  3052. }
  3053. }
  3054. const _vector = /*@__PURE__*/ new Vector3();
  3055. const _quaternion = /*@__PURE__*/ new Quaternion();
  3056. class Box3 {
  3057. constructor( min, max ) {
  3058. Object.defineProperty( this, 'isBox3', { value: true } );
  3059. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  3060. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  3061. }
  3062. set( min, max ) {
  3063. this.min.copy( min );
  3064. this.max.copy( max );
  3065. return this;
  3066. }
  3067. setFromArray( array ) {
  3068. let minX = + Infinity;
  3069. let minY = + Infinity;
  3070. let minZ = + Infinity;
  3071. let maxX = - Infinity;
  3072. let maxY = - Infinity;
  3073. let maxZ = - Infinity;
  3074. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3075. const x = array[ i ];
  3076. const y = array[ i + 1 ];
  3077. const z = array[ i + 2 ];
  3078. if ( x < minX ) minX = x;
  3079. if ( y < minY ) minY = y;
  3080. if ( z < minZ ) minZ = z;
  3081. if ( x > maxX ) maxX = x;
  3082. if ( y > maxY ) maxY = y;
  3083. if ( z > maxZ ) maxZ = z;
  3084. }
  3085. this.min.set( minX, minY, minZ );
  3086. this.max.set( maxX, maxY, maxZ );
  3087. return this;
  3088. }
  3089. setFromBufferAttribute( attribute ) {
  3090. let minX = + Infinity;
  3091. let minY = + Infinity;
  3092. let minZ = + Infinity;
  3093. let maxX = - Infinity;
  3094. let maxY = - Infinity;
  3095. let maxZ = - Infinity;
  3096. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3097. const x = attribute.getX( i );
  3098. const y = attribute.getY( i );
  3099. const z = attribute.getZ( i );
  3100. if ( x < minX ) minX = x;
  3101. if ( y < minY ) minY = y;
  3102. if ( z < minZ ) minZ = z;
  3103. if ( x > maxX ) maxX = x;
  3104. if ( y > maxY ) maxY = y;
  3105. if ( z > maxZ ) maxZ = z;
  3106. }
  3107. this.min.set( minX, minY, minZ );
  3108. this.max.set( maxX, maxY, maxZ );
  3109. return this;
  3110. }
  3111. setFromPoints( points ) {
  3112. this.makeEmpty();
  3113. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3114. this.expandByPoint( points[ i ] );
  3115. }
  3116. return this;
  3117. }
  3118. setFromCenterAndSize( center, size ) {
  3119. const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  3120. this.min.copy( center ).sub( halfSize );
  3121. this.max.copy( center ).add( halfSize );
  3122. return this;
  3123. }
  3124. setFromObject( object ) {
  3125. this.makeEmpty();
  3126. return this.expandByObject( object );
  3127. }
  3128. clone() {
  3129. return new this.constructor().copy( this );
  3130. }
  3131. copy( box ) {
  3132. this.min.copy( box.min );
  3133. this.max.copy( box.max );
  3134. return this;
  3135. }
  3136. makeEmpty() {
  3137. this.min.x = this.min.y = this.min.z = + Infinity;
  3138. this.max.x = this.max.y = this.max.z = - Infinity;
  3139. return this;
  3140. }
  3141. isEmpty() {
  3142. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3143. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3144. }
  3145. getCenter( target ) {
  3146. if ( target === undefined ) {
  3147. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  3148. target = new Vector3();
  3149. }
  3150. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3151. }
  3152. getSize( target ) {
  3153. if ( target === undefined ) {
  3154. console.warn( 'THREE.Box3: .getSize() target is now required' );
  3155. target = new Vector3();
  3156. }
  3157. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3158. }
  3159. expandByPoint( point ) {
  3160. this.min.min( point );
  3161. this.max.max( point );
  3162. return this;
  3163. }
  3164. expandByVector( vector ) {
  3165. this.min.sub( vector );
  3166. this.max.add( vector );
  3167. return this;
  3168. }
  3169. expandByScalar( scalar ) {
  3170. this.min.addScalar( - scalar );
  3171. this.max.addScalar( scalar );
  3172. return this;
  3173. }
  3174. expandByObject( object ) {
  3175. // Computes the world-axis-aligned bounding box of an object (including its children),
  3176. // accounting for both the object's, and children's, world transforms
  3177. object.updateWorldMatrix( false, false );
  3178. const geometry = object.geometry;
  3179. if ( geometry !== undefined ) {
  3180. if ( geometry.boundingBox === null ) {
  3181. geometry.computeBoundingBox();
  3182. }
  3183. _box.copy( geometry.boundingBox );
  3184. _box.applyMatrix4( object.matrixWorld );
  3185. this.union( _box );
  3186. }
  3187. const children = object.children;
  3188. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3189. this.expandByObject( children[ i ] );
  3190. }
  3191. return this;
  3192. }
  3193. containsPoint( point ) {
  3194. return point.x < this.min.x || point.x > this.max.x ||
  3195. point.y < this.min.y || point.y > this.max.y ||
  3196. point.z < this.min.z || point.z > this.max.z ? false : true;
  3197. }
  3198. containsBox( box ) {
  3199. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3200. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3201. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3202. }
  3203. getParameter( point, target ) {
  3204. // This can potentially have a divide by zero if the box
  3205. // has a size dimension of 0.
  3206. if ( target === undefined ) {
  3207. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  3208. target = new Vector3();
  3209. }
  3210. return target.set(
  3211. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3212. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3213. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3214. );
  3215. }
  3216. intersectsBox( box ) {
  3217. // using 6 splitting planes to rule out intersections.
  3218. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3219. box.max.y < this.min.y || box.min.y > this.max.y ||
  3220. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3221. }
  3222. intersectsSphere( sphere ) {
  3223. // Find the point on the AABB closest to the sphere center.
  3224. this.clampPoint( sphere.center, _vector$1 );
  3225. // If that point is inside the sphere, the AABB and sphere intersect.
  3226. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3227. }
  3228. intersectsPlane( plane ) {
  3229. // We compute the minimum and maximum dot product values. If those values
  3230. // are on the same side (back or front) of the plane, then there is no intersection.
  3231. let min, max;
  3232. if ( plane.normal.x > 0 ) {
  3233. min = plane.normal.x * this.min.x;
  3234. max = plane.normal.x * this.max.x;
  3235. } else {
  3236. min = plane.normal.x * this.max.x;
  3237. max = plane.normal.x * this.min.x;
  3238. }
  3239. if ( plane.normal.y > 0 ) {
  3240. min += plane.normal.y * this.min.y;
  3241. max += plane.normal.y * this.max.y;
  3242. } else {
  3243. min += plane.normal.y * this.max.y;
  3244. max += plane.normal.y * this.min.y;
  3245. }
  3246. if ( plane.normal.z > 0 ) {
  3247. min += plane.normal.z * this.min.z;
  3248. max += plane.normal.z * this.max.z;
  3249. } else {
  3250. min += plane.normal.z * this.max.z;
  3251. max += plane.normal.z * this.min.z;
  3252. }
  3253. return ( min <= - plane.constant && max >= - plane.constant );
  3254. }
  3255. intersectsTriangle( triangle ) {
  3256. if ( this.isEmpty() ) {
  3257. return false;
  3258. }
  3259. // compute box center and extents
  3260. this.getCenter( _center );
  3261. _extents.subVectors( this.max, _center );
  3262. // translate triangle to aabb origin
  3263. _v0.subVectors( triangle.a, _center );
  3264. _v1.subVectors( triangle.b, _center );
  3265. _v2.subVectors( triangle.c, _center );
  3266. // compute edge vectors for triangle
  3267. _f0.subVectors( _v1, _v0 );
  3268. _f1.subVectors( _v2, _v1 );
  3269. _f2.subVectors( _v0, _v2 );
  3270. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3271. // 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
  3272. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3273. let axes = [
  3274. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3275. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3276. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3277. ];
  3278. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  3279. return false;
  3280. }
  3281. // test 3 face normals from the aabb
  3282. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3283. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  3284. return false;
  3285. }
  3286. // finally testing the face normal of the triangle
  3287. // use already existing triangle edge vectors here
  3288. _triangleNormal.crossVectors( _f0, _f1 );
  3289. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3290. return satForAxes( axes, _v0, _v1, _v2, _extents );
  3291. }
  3292. clampPoint( point, target ) {
  3293. if ( target === undefined ) {
  3294. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  3295. target = new Vector3();
  3296. }
  3297. return target.copy( point ).clamp( this.min, this.max );
  3298. }
  3299. distanceToPoint( point ) {
  3300. const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  3301. return clampedPoint.sub( point ).length();
  3302. }
  3303. getBoundingSphere( target ) {
  3304. if ( target === undefined ) {
  3305. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  3306. //target = new Sphere(); // removed to avoid cyclic dependency
  3307. }
  3308. this.getCenter( target.center );
  3309. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  3310. return target;
  3311. }
  3312. intersect( box ) {
  3313. this.min.max( box.min );
  3314. this.max.min( box.max );
  3315. // 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.
  3316. if ( this.isEmpty() ) this.makeEmpty();
  3317. return this;
  3318. }
  3319. union( box ) {
  3320. this.min.min( box.min );
  3321. this.max.max( box.max );
  3322. return this;
  3323. }
  3324. applyMatrix4( matrix ) {
  3325. // transform of empty box is an empty box.
  3326. if ( this.isEmpty() ) return this;
  3327. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3328. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3329. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3330. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3331. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3332. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3333. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3334. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3335. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3336. this.setFromPoints( _points );
  3337. return this;
  3338. }
  3339. translate( offset ) {
  3340. this.min.add( offset );
  3341. this.max.add( offset );
  3342. return this;
  3343. }
  3344. equals( box ) {
  3345. return box.min.equals( this.min ) && box.max.equals( this.max );
  3346. }
  3347. }
  3348. function satForAxes( axes, v0, v1, v2, extents ) {
  3349. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3350. _testAxis.fromArray( axes, i );
  3351. // project the aabb onto the seperating axis
  3352. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3353. // project all 3 vertices of the triangle onto the seperating axis
  3354. const p0 = v0.dot( _testAxis );
  3355. const p1 = v1.dot( _testAxis );
  3356. const p2 = v2.dot( _testAxis );
  3357. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3358. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3359. // points of the projected triangle are outside the projected half-length of the aabb
  3360. // the axis is seperating and we can exit
  3361. return false;
  3362. }
  3363. }
  3364. return true;
  3365. }
  3366. const _points = [
  3367. /*@__PURE__*/ new Vector3(),
  3368. /*@__PURE__*/ new Vector3(),
  3369. /*@__PURE__*/ new Vector3(),
  3370. /*@__PURE__*/ new Vector3(),
  3371. /*@__PURE__*/ new Vector3(),
  3372. /*@__PURE__*/ new Vector3(),
  3373. /*@__PURE__*/ new Vector3(),
  3374. /*@__PURE__*/ new Vector3()
  3375. ];
  3376. const _vector$1 = /*@__PURE__*/ new Vector3();
  3377. const _box = /*@__PURE__*/ new Box3();
  3378. // triangle centered vertices
  3379. const _v0 = /*@__PURE__*/ new Vector3();
  3380. const _v1 = /*@__PURE__*/ new Vector3();
  3381. const _v2 = /*@__PURE__*/ new Vector3();
  3382. // triangle edge vectors
  3383. const _f0 = /*@__PURE__*/ new Vector3();
  3384. const _f1 = /*@__PURE__*/ new Vector3();
  3385. const _f2 = /*@__PURE__*/ new Vector3();
  3386. const _center = /*@__PURE__*/ new Vector3();
  3387. const _extents = /*@__PURE__*/ new Vector3();
  3388. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3389. const _testAxis = /*@__PURE__*/ new Vector3();
  3390. const _box$1 = /*@__PURE__*/ new Box3();
  3391. class Sphere {
  3392. constructor( center, radius ) {
  3393. this.center = ( center !== undefined ) ? center : new Vector3();
  3394. this.radius = ( radius !== undefined ) ? radius : - 1;
  3395. }
  3396. set( center, radius ) {
  3397. this.center.copy( center );
  3398. this.radius = radius;
  3399. return this;
  3400. }
  3401. setFromPoints( points, optionalCenter ) {
  3402. const center = this.center;
  3403. if ( optionalCenter !== undefined ) {
  3404. center.copy( optionalCenter );
  3405. } else {
  3406. _box$1.setFromPoints( points ).getCenter( center );
  3407. }
  3408. let maxRadiusSq = 0;
  3409. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3410. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3411. }
  3412. this.radius = Math.sqrt( maxRadiusSq );
  3413. return this;
  3414. }
  3415. clone() {
  3416. return new this.constructor().copy( this );
  3417. }
  3418. copy( sphere ) {
  3419. this.center.copy( sphere.center );
  3420. this.radius = sphere.radius;
  3421. return this;
  3422. }
  3423. isEmpty() {
  3424. return ( this.radius < 0 );
  3425. }
  3426. makeEmpty() {
  3427. this.center.set( 0, 0, 0 );
  3428. this.radius = - 1;
  3429. return this;
  3430. }
  3431. containsPoint( point ) {
  3432. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3433. }
  3434. distanceToPoint( point ) {
  3435. return ( point.distanceTo( this.center ) - this.radius );
  3436. }
  3437. intersectsSphere( sphere ) {
  3438. const radiusSum = this.radius + sphere.radius;
  3439. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3440. }
  3441. intersectsBox( box ) {
  3442. return box.intersectsSphere( this );
  3443. }
  3444. intersectsPlane( plane ) {
  3445. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3446. }
  3447. clampPoint( point, target ) {
  3448. const deltaLengthSq = this.center.distanceToSquared( point );
  3449. if ( target === undefined ) {
  3450. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  3451. target = new Vector3();
  3452. }
  3453. target.copy( point );
  3454. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3455. target.sub( this.center ).normalize();
  3456. target.multiplyScalar( this.radius ).add( this.center );
  3457. }
  3458. return target;
  3459. }
  3460. getBoundingBox( target ) {
  3461. if ( target === undefined ) {
  3462. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  3463. target = new Box3();
  3464. }
  3465. if ( this.isEmpty() ) {
  3466. // Empty sphere produces empty bounding box
  3467. target.makeEmpty();
  3468. return target;
  3469. }
  3470. target.set( this.center, this.center );
  3471. target.expandByScalar( this.radius );
  3472. return target;
  3473. }
  3474. applyMatrix4( matrix ) {
  3475. this.center.applyMatrix4( matrix );
  3476. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3477. return this;
  3478. }
  3479. translate( offset ) {
  3480. this.center.add( offset );
  3481. return this;
  3482. }
  3483. equals( sphere ) {
  3484. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3485. }
  3486. }
  3487. const _vector$2 = /*@__PURE__*/ new Vector3();
  3488. const _segCenter = /*@__PURE__*/ new Vector3();
  3489. const _segDir = /*@__PURE__*/ new Vector3();
  3490. const _diff = /*@__PURE__*/ new Vector3();
  3491. const _edge1 = /*@__PURE__*/ new Vector3();
  3492. const _edge2 = /*@__PURE__*/ new Vector3();
  3493. const _normal = /*@__PURE__*/ new Vector3();
  3494. class Ray {
  3495. constructor( origin, direction ) {
  3496. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  3497. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  3498. }
  3499. set( origin, direction ) {
  3500. this.origin.copy( origin );
  3501. this.direction.copy( direction );
  3502. return this;
  3503. }
  3504. clone() {
  3505. return new this.constructor().copy( this );
  3506. }
  3507. copy( ray ) {
  3508. this.origin.copy( ray.origin );
  3509. this.direction.copy( ray.direction );
  3510. return this;
  3511. }
  3512. at( t, target ) {
  3513. if ( target === undefined ) {
  3514. console.warn( 'THREE.Ray: .at() target is now required' );
  3515. target = new Vector3();
  3516. }
  3517. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3518. }
  3519. lookAt( v ) {
  3520. this.direction.copy( v ).sub( this.origin ).normalize();
  3521. return this;
  3522. }
  3523. recast( t ) {
  3524. this.origin.copy( this.at( t, _vector$2 ) );
  3525. return this;
  3526. }
  3527. closestPointToPoint( point, target ) {
  3528. if ( target === undefined ) {
  3529. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  3530. target = new Vector3();
  3531. }
  3532. target.subVectors( point, this.origin );
  3533. const directionDistance = target.dot( this.direction );
  3534. if ( directionDistance < 0 ) {
  3535. return target.copy( this.origin );
  3536. }
  3537. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3538. }
  3539. distanceToPoint( point ) {
  3540. return Math.sqrt( this.distanceSqToPoint( point ) );
  3541. }
  3542. distanceSqToPoint( point ) {
  3543. const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  3544. // point behind the ray
  3545. if ( directionDistance < 0 ) {
  3546. return this.origin.distanceToSquared( point );
  3547. }
  3548. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3549. return _vector$2.distanceToSquared( point );
  3550. }
  3551. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3552. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3553. // It returns the min distance between the ray and the segment
  3554. // defined by v0 and v1
  3555. // It can also set two optional targets :
  3556. // - The closest point on the ray
  3557. // - The closest point on the segment
  3558. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3559. _segDir.copy( v1 ).sub( v0 ).normalize();
  3560. _diff.copy( this.origin ).sub( _segCenter );
  3561. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3562. const a01 = - this.direction.dot( _segDir );
  3563. const b0 = _diff.dot( this.direction );
  3564. const b1 = - _diff.dot( _segDir );
  3565. const c = _diff.lengthSq();
  3566. const det = Math.abs( 1 - a01 * a01 );
  3567. let s0, s1, sqrDist, extDet;
  3568. if ( det > 0 ) {
  3569. // The ray and segment are not parallel.
  3570. s0 = a01 * b1 - b0;
  3571. s1 = a01 * b0 - b1;
  3572. extDet = segExtent * det;
  3573. if ( s0 >= 0 ) {
  3574. if ( s1 >= - extDet ) {
  3575. if ( s1 <= extDet ) {
  3576. // region 0
  3577. // Minimum at interior points of ray and segment.
  3578. const invDet = 1 / det;
  3579. s0 *= invDet;
  3580. s1 *= invDet;
  3581. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3582. } else {
  3583. // region 1
  3584. s1 = segExtent;
  3585. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3586. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3587. }
  3588. } else {
  3589. // region 5
  3590. s1 = - segExtent;
  3591. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3592. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3593. }
  3594. } else {
  3595. if ( s1 <= - extDet ) {
  3596. // region 4
  3597. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3598. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3599. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3600. } else if ( s1 <= extDet ) {
  3601. // region 3
  3602. s0 = 0;
  3603. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3604. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3605. } else {
  3606. // region 2
  3607. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3608. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3609. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3610. }
  3611. }
  3612. } else {
  3613. // Ray and segment are parallel.
  3614. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3615. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3616. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3617. }
  3618. if ( optionalPointOnRay ) {
  3619. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3620. }
  3621. if ( optionalPointOnSegment ) {
  3622. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3623. }
  3624. return sqrDist;
  3625. }
  3626. intersectSphere( sphere, target ) {
  3627. _vector$2.subVectors( sphere.center, this.origin );
  3628. const tca = _vector$2.dot( this.direction );
  3629. const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  3630. const radius2 = sphere.radius * sphere.radius;
  3631. if ( d2 > radius2 ) return null;
  3632. const thc = Math.sqrt( radius2 - d2 );
  3633. // t0 = first intersect point - entrance on front of sphere
  3634. const t0 = tca - thc;
  3635. // t1 = second intersect point - exit point on back of sphere
  3636. const t1 = tca + thc;
  3637. // test to see if both t0 and t1 are behind the ray - if so, return null
  3638. if ( t0 < 0 && t1 < 0 ) return null;
  3639. // test to see if t0 is behind the ray:
  3640. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3641. // in order to always return an intersect point that is in front of the ray.
  3642. if ( t0 < 0 ) return this.at( t1, target );
  3643. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3644. return this.at( t0, target );
  3645. }
  3646. intersectsSphere( sphere ) {
  3647. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3648. }
  3649. distanceToPlane( plane ) {
  3650. const denominator = plane.normal.dot( this.direction );
  3651. if ( denominator === 0 ) {
  3652. // line is coplanar, return origin
  3653. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3654. return 0;
  3655. }
  3656. // Null is preferable to undefined since undefined means.... it is undefined
  3657. return null;
  3658. }
  3659. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3660. // Return if the ray never intersects the plane
  3661. return t >= 0 ? t : null;
  3662. }
  3663. intersectPlane( plane, target ) {
  3664. const t = this.distanceToPlane( plane );
  3665. if ( t === null ) {
  3666. return null;
  3667. }
  3668. return this.at( t, target );
  3669. }
  3670. intersectsPlane( plane ) {
  3671. // check if the ray lies on the plane first
  3672. const distToPoint = plane.distanceToPoint( this.origin );
  3673. if ( distToPoint === 0 ) {
  3674. return true;
  3675. }
  3676. const denominator = plane.normal.dot( this.direction );
  3677. if ( denominator * distToPoint < 0 ) {
  3678. return true;
  3679. }
  3680. // ray origin is behind the plane (and is pointing behind it)
  3681. return false;
  3682. }
  3683. intersectBox( box, target ) {
  3684. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3685. const invdirx = 1 / this.direction.x,
  3686. invdiry = 1 / this.direction.y,
  3687. invdirz = 1 / this.direction.z;
  3688. const origin = this.origin;
  3689. if ( invdirx >= 0 ) {
  3690. tmin = ( box.min.x - origin.x ) * invdirx;
  3691. tmax = ( box.max.x - origin.x ) * invdirx;
  3692. } else {
  3693. tmin = ( box.max.x - origin.x ) * invdirx;
  3694. tmax = ( box.min.x - origin.x ) * invdirx;
  3695. }
  3696. if ( invdiry >= 0 ) {
  3697. tymin = ( box.min.y - origin.y ) * invdiry;
  3698. tymax = ( box.max.y - origin.y ) * invdiry;
  3699. } else {
  3700. tymin = ( box.max.y - origin.y ) * invdiry;
  3701. tymax = ( box.min.y - origin.y ) * invdiry;
  3702. }
  3703. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3704. // These lines also handle the case where tmin or tmax is NaN
  3705. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3706. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3707. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3708. if ( invdirz >= 0 ) {
  3709. tzmin = ( box.min.z - origin.z ) * invdirz;
  3710. tzmax = ( box.max.z - origin.z ) * invdirz;
  3711. } else {
  3712. tzmin = ( box.max.z - origin.z ) * invdirz;
  3713. tzmax = ( box.min.z - origin.z ) * invdirz;
  3714. }
  3715. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3716. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3717. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3718. //return point closest to the ray (positive side)
  3719. if ( tmax < 0 ) return null;
  3720. return this.at( tmin >= 0 ? tmin : tmax, target );
  3721. }
  3722. intersectsBox( box ) {
  3723. return this.intersectBox( box, _vector$2 ) !== null;
  3724. }
  3725. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3726. // Compute the offset origin, edges, and normal.
  3727. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3728. _edge1.subVectors( b, a );
  3729. _edge2.subVectors( c, a );
  3730. _normal.crossVectors( _edge1, _edge2 );
  3731. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3732. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3733. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3734. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3735. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3736. let DdN = this.direction.dot( _normal );
  3737. let sign;
  3738. if ( DdN > 0 ) {
  3739. if ( backfaceCulling ) return null;
  3740. sign = 1;
  3741. } else if ( DdN < 0 ) {
  3742. sign = - 1;
  3743. DdN = - DdN;
  3744. } else {
  3745. return null;
  3746. }
  3747. _diff.subVectors( this.origin, a );
  3748. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3749. // b1 < 0, no intersection
  3750. if ( DdQxE2 < 0 ) {
  3751. return null;
  3752. }
  3753. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3754. // b2 < 0, no intersection
  3755. if ( DdE1xQ < 0 ) {
  3756. return null;
  3757. }
  3758. // b1+b2 > 1, no intersection
  3759. if ( DdQxE2 + DdE1xQ > DdN ) {
  3760. return null;
  3761. }
  3762. // Line intersects triangle, check if ray does.
  3763. const QdN = - sign * _diff.dot( _normal );
  3764. // t < 0, no intersection
  3765. if ( QdN < 0 ) {
  3766. return null;
  3767. }
  3768. // Ray intersects triangle.
  3769. return this.at( QdN / DdN, target );
  3770. }
  3771. applyMatrix4( matrix4 ) {
  3772. this.origin.applyMatrix4( matrix4 );
  3773. this.direction.transformDirection( matrix4 );
  3774. return this;
  3775. }
  3776. equals( ray ) {
  3777. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3778. }
  3779. }
  3780. class Matrix4 {
  3781. constructor() {
  3782. Object.defineProperty( this, 'isMatrix4', { value: true } );
  3783. this.elements = [
  3784. 1, 0, 0, 0,
  3785. 0, 1, 0, 0,
  3786. 0, 0, 1, 0,
  3787. 0, 0, 0, 1
  3788. ];
  3789. if ( arguments.length > 0 ) {
  3790. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3791. }
  3792. }
  3793. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3794. const te = this.elements;
  3795. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3796. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3797. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3798. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3799. return this;
  3800. }
  3801. identity() {
  3802. this.set(
  3803. 1, 0, 0, 0,
  3804. 0, 1, 0, 0,
  3805. 0, 0, 1, 0,
  3806. 0, 0, 0, 1
  3807. );
  3808. return this;
  3809. }
  3810. clone() {
  3811. return new Matrix4().fromArray( this.elements );
  3812. }
  3813. copy( m ) {
  3814. const te = this.elements;
  3815. const me = m.elements;
  3816. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3817. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3818. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3819. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3820. return this;
  3821. }
  3822. copyPosition( m ) {
  3823. const te = this.elements, me = m.elements;
  3824. te[ 12 ] = me[ 12 ];
  3825. te[ 13 ] = me[ 13 ];
  3826. te[ 14 ] = me[ 14 ];
  3827. return this;
  3828. }
  3829. extractBasis( xAxis, yAxis, zAxis ) {
  3830. xAxis.setFromMatrixColumn( this, 0 );
  3831. yAxis.setFromMatrixColumn( this, 1 );
  3832. zAxis.setFromMatrixColumn( this, 2 );
  3833. return this;
  3834. }
  3835. makeBasis( xAxis, yAxis, zAxis ) {
  3836. this.set(
  3837. xAxis.x, yAxis.x, zAxis.x, 0,
  3838. xAxis.y, yAxis.y, zAxis.y, 0,
  3839. xAxis.z, yAxis.z, zAxis.z, 0,
  3840. 0, 0, 0, 1
  3841. );
  3842. return this;
  3843. }
  3844. extractRotation( m ) {
  3845. // this method does not support reflection matrices
  3846. const te = this.elements;
  3847. const me = m.elements;
  3848. const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length();
  3849. const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length();
  3850. const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length();
  3851. te[ 0 ] = me[ 0 ] * scaleX;
  3852. te[ 1 ] = me[ 1 ] * scaleX;
  3853. te[ 2 ] = me[ 2 ] * scaleX;
  3854. te[ 3 ] = 0;
  3855. te[ 4 ] = me[ 4 ] * scaleY;
  3856. te[ 5 ] = me[ 5 ] * scaleY;
  3857. te[ 6 ] = me[ 6 ] * scaleY;
  3858. te[ 7 ] = 0;
  3859. te[ 8 ] = me[ 8 ] * scaleZ;
  3860. te[ 9 ] = me[ 9 ] * scaleZ;
  3861. te[ 10 ] = me[ 10 ] * scaleZ;
  3862. te[ 11 ] = 0;
  3863. te[ 12 ] = 0;
  3864. te[ 13 ] = 0;
  3865. te[ 14 ] = 0;
  3866. te[ 15 ] = 1;
  3867. return this;
  3868. }
  3869. makeRotationFromEuler( euler ) {
  3870. if ( ! ( euler && euler.isEuler ) ) {
  3871. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3872. }
  3873. const te = this.elements;
  3874. const x = euler.x, y = euler.y, z = euler.z;
  3875. const a = Math.cos( x ), b = Math.sin( x );
  3876. const c = Math.cos( y ), d = Math.sin( y );
  3877. const e = Math.cos( z ), f = Math.sin( z );
  3878. if ( euler.order === 'XYZ' ) {
  3879. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3880. te[ 0 ] = c * e;
  3881. te[ 4 ] = - c * f;
  3882. te[ 8 ] = d;
  3883. te[ 1 ] = af + be * d;
  3884. te[ 5 ] = ae - bf * d;
  3885. te[ 9 ] = - b * c;
  3886. te[ 2 ] = bf - ae * d;
  3887. te[ 6 ] = be + af * d;
  3888. te[ 10 ] = a * c;
  3889. } else if ( euler.order === 'YXZ' ) {
  3890. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3891. te[ 0 ] = ce + df * b;
  3892. te[ 4 ] = de * b - cf;
  3893. te[ 8 ] = a * d;
  3894. te[ 1 ] = a * f;
  3895. te[ 5 ] = a * e;
  3896. te[ 9 ] = - b;
  3897. te[ 2 ] = cf * b - de;
  3898. te[ 6 ] = df + ce * b;
  3899. te[ 10 ] = a * c;
  3900. } else if ( euler.order === 'ZXY' ) {
  3901. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3902. te[ 0 ] = ce - df * b;
  3903. te[ 4 ] = - a * f;
  3904. te[ 8 ] = de + cf * b;
  3905. te[ 1 ] = cf + de * b;
  3906. te[ 5 ] = a * e;
  3907. te[ 9 ] = df - ce * b;
  3908. te[ 2 ] = - a * d;
  3909. te[ 6 ] = b;
  3910. te[ 10 ] = a * c;
  3911. } else if ( euler.order === 'ZYX' ) {
  3912. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3913. te[ 0 ] = c * e;
  3914. te[ 4 ] = be * d - af;
  3915. te[ 8 ] = ae * d + bf;
  3916. te[ 1 ] = c * f;
  3917. te[ 5 ] = bf * d + ae;
  3918. te[ 9 ] = af * d - be;
  3919. te[ 2 ] = - d;
  3920. te[ 6 ] = b * c;
  3921. te[ 10 ] = a * c;
  3922. } else if ( euler.order === 'YZX' ) {
  3923. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3924. te[ 0 ] = c * e;
  3925. te[ 4 ] = bd - ac * f;
  3926. te[ 8 ] = bc * f + ad;
  3927. te[ 1 ] = f;
  3928. te[ 5 ] = a * e;
  3929. te[ 9 ] = - b * e;
  3930. te[ 2 ] = - d * e;
  3931. te[ 6 ] = ad * f + bc;
  3932. te[ 10 ] = ac - bd * f;
  3933. } else if ( euler.order === 'XZY' ) {
  3934. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3935. te[ 0 ] = c * e;
  3936. te[ 4 ] = - f;
  3937. te[ 8 ] = d * e;
  3938. te[ 1 ] = ac * f + bd;
  3939. te[ 5 ] = a * e;
  3940. te[ 9 ] = ad * f - bc;
  3941. te[ 2 ] = bc * f - ad;
  3942. te[ 6 ] = b * e;
  3943. te[ 10 ] = bd * f + ac;
  3944. }
  3945. // bottom row
  3946. te[ 3 ] = 0;
  3947. te[ 7 ] = 0;
  3948. te[ 11 ] = 0;
  3949. // last column
  3950. te[ 12 ] = 0;
  3951. te[ 13 ] = 0;
  3952. te[ 14 ] = 0;
  3953. te[ 15 ] = 1;
  3954. return this;
  3955. }
  3956. makeRotationFromQuaternion( q ) {
  3957. return this.compose( _zero, q, _one );
  3958. }
  3959. lookAt( eye, target, up ) {
  3960. const te = this.elements;
  3961. _z.subVectors( eye, target );
  3962. if ( _z.lengthSq() === 0 ) {
  3963. // eye and target are in the same position
  3964. _z.z = 1;
  3965. }
  3966. _z.normalize();
  3967. _x.crossVectors( up, _z );
  3968. if ( _x.lengthSq() === 0 ) {
  3969. // up and z are parallel
  3970. if ( Math.abs( up.z ) === 1 ) {
  3971. _z.x += 0.0001;
  3972. } else {
  3973. _z.z += 0.0001;
  3974. }
  3975. _z.normalize();
  3976. _x.crossVectors( up, _z );
  3977. }
  3978. _x.normalize();
  3979. _y.crossVectors( _z, _x );
  3980. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3981. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3982. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3983. return this;
  3984. }
  3985. multiply( m, n ) {
  3986. if ( n !== undefined ) {
  3987. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3988. return this.multiplyMatrices( m, n );
  3989. }
  3990. return this.multiplyMatrices( this, m );
  3991. }
  3992. premultiply( m ) {
  3993. return this.multiplyMatrices( m, this );
  3994. }
  3995. multiplyMatrices( a, b ) {
  3996. const ae = a.elements;
  3997. const be = b.elements;
  3998. const te = this.elements;
  3999. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4000. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4001. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4002. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4003. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4004. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4005. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4006. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4007. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4008. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4009. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4010. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4011. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4012. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4013. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4014. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4015. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4016. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4017. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4018. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4019. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4020. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4021. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4022. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4023. return this;
  4024. }
  4025. multiplyScalar( s ) {
  4026. const te = this.elements;
  4027. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4028. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4029. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4030. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4031. return this;
  4032. }
  4033. determinant() {
  4034. const te = this.elements;
  4035. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4036. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4037. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4038. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4039. //TODO: make this more efficient
  4040. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4041. return (
  4042. n41 * (
  4043. + n14 * n23 * n32
  4044. - n13 * n24 * n32
  4045. - n14 * n22 * n33
  4046. + n12 * n24 * n33
  4047. + n13 * n22 * n34
  4048. - n12 * n23 * n34
  4049. ) +
  4050. n42 * (
  4051. + n11 * n23 * n34
  4052. - n11 * n24 * n33
  4053. + n14 * n21 * n33
  4054. - n13 * n21 * n34
  4055. + n13 * n24 * n31
  4056. - n14 * n23 * n31
  4057. ) +
  4058. n43 * (
  4059. + n11 * n24 * n32
  4060. - n11 * n22 * n34
  4061. - n14 * n21 * n32
  4062. + n12 * n21 * n34
  4063. + n14 * n22 * n31
  4064. - n12 * n24 * n31
  4065. ) +
  4066. n44 * (
  4067. - n13 * n22 * n31
  4068. - n11 * n23 * n32
  4069. + n11 * n22 * n33
  4070. + n13 * n21 * n32
  4071. - n12 * n21 * n33
  4072. + n12 * n23 * n31
  4073. )
  4074. );
  4075. }
  4076. transpose() {
  4077. const te = this.elements;
  4078. let tmp;
  4079. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4080. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4081. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4082. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4083. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4084. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4085. return this;
  4086. }
  4087. setPosition( x, y, z ) {
  4088. const te = this.elements;
  4089. if ( x.isVector3 ) {
  4090. te[ 12 ] = x.x;
  4091. te[ 13 ] = x.y;
  4092. te[ 14 ] = x.z;
  4093. } else {
  4094. te[ 12 ] = x;
  4095. te[ 13 ] = y;
  4096. te[ 14 ] = z;
  4097. }
  4098. return this;
  4099. }
  4100. invert() {
  4101. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4102. const te = this.elements,
  4103. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4104. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4105. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4106. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4107. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4108. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4109. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4110. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4111. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4112. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4113. const detInv = 1 / det;
  4114. te[ 0 ] = t11 * detInv;
  4115. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4116. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4117. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4118. te[ 4 ] = t12 * detInv;
  4119. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4120. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4121. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4122. te[ 8 ] = t13 * detInv;
  4123. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4124. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4125. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4126. te[ 12 ] = t14 * detInv;
  4127. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4128. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4129. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4130. return this;
  4131. }
  4132. scale( v ) {
  4133. const te = this.elements;
  4134. const x = v.x, y = v.y, z = v.z;
  4135. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4136. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4137. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4138. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4139. return this;
  4140. }
  4141. getMaxScaleOnAxis() {
  4142. const te = this.elements;
  4143. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4144. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4145. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4146. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4147. }
  4148. makeTranslation( x, y, z ) {
  4149. this.set(
  4150. 1, 0, 0, x,
  4151. 0, 1, 0, y,
  4152. 0, 0, 1, z,
  4153. 0, 0, 0, 1
  4154. );
  4155. return this;
  4156. }
  4157. makeRotationX( theta ) {
  4158. const c = Math.cos( theta ), s = Math.sin( theta );
  4159. this.set(
  4160. 1, 0, 0, 0,
  4161. 0, c, - s, 0,
  4162. 0, s, c, 0,
  4163. 0, 0, 0, 1
  4164. );
  4165. return this;
  4166. }
  4167. makeRotationY( theta ) {
  4168. const c = Math.cos( theta ), s = Math.sin( theta );
  4169. this.set(
  4170. c, 0, s, 0,
  4171. 0, 1, 0, 0,
  4172. - s, 0, c, 0,
  4173. 0, 0, 0, 1
  4174. );
  4175. return this;
  4176. }
  4177. makeRotationZ( theta ) {
  4178. const c = Math.cos( theta ), s = Math.sin( theta );
  4179. this.set(
  4180. c, - s, 0, 0,
  4181. s, c, 0, 0,
  4182. 0, 0, 1, 0,
  4183. 0, 0, 0, 1
  4184. );
  4185. return this;
  4186. }
  4187. makeRotationAxis( axis, angle ) {
  4188. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4189. const c = Math.cos( angle );
  4190. const s = Math.sin( angle );
  4191. const t = 1 - c;
  4192. const x = axis.x, y = axis.y, z = axis.z;
  4193. const tx = t * x, ty = t * y;
  4194. this.set(
  4195. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4196. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4197. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4198. 0, 0, 0, 1
  4199. );
  4200. return this;
  4201. }
  4202. makeScale( x, y, z ) {
  4203. this.set(
  4204. x, 0, 0, 0,
  4205. 0, y, 0, 0,
  4206. 0, 0, z, 0,
  4207. 0, 0, 0, 1
  4208. );
  4209. return this;
  4210. }
  4211. makeShear( x, y, z ) {
  4212. this.set(
  4213. 1, y, z, 0,
  4214. x, 1, z, 0,
  4215. x, y, 1, 0,
  4216. 0, 0, 0, 1
  4217. );
  4218. return this;
  4219. }
  4220. compose( position, quaternion, scale ) {
  4221. const te = this.elements;
  4222. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4223. const x2 = x + x, y2 = y + y, z2 = z + z;
  4224. const xx = x * x2, xy = x * y2, xz = x * z2;
  4225. const yy = y * y2, yz = y * z2, zz = z * z2;
  4226. const wx = w * x2, wy = w * y2, wz = w * z2;
  4227. const sx = scale.x, sy = scale.y, sz = scale.z;
  4228. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4229. te[ 1 ] = ( xy + wz ) * sx;
  4230. te[ 2 ] = ( xz - wy ) * sx;
  4231. te[ 3 ] = 0;
  4232. te[ 4 ] = ( xy - wz ) * sy;
  4233. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4234. te[ 6 ] = ( yz + wx ) * sy;
  4235. te[ 7 ] = 0;
  4236. te[ 8 ] = ( xz + wy ) * sz;
  4237. te[ 9 ] = ( yz - wx ) * sz;
  4238. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4239. te[ 11 ] = 0;
  4240. te[ 12 ] = position.x;
  4241. te[ 13 ] = position.y;
  4242. te[ 14 ] = position.z;
  4243. te[ 15 ] = 1;
  4244. return this;
  4245. }
  4246. decompose( position, quaternion, scale ) {
  4247. const te = this.elements;
  4248. let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4249. const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4250. const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4251. // if determine is negative, we need to invert one scale
  4252. const det = this.determinant();
  4253. if ( det < 0 ) sx = - sx;
  4254. position.x = te[ 12 ];
  4255. position.y = te[ 13 ];
  4256. position.z = te[ 14 ];
  4257. // scale the rotation part
  4258. _m1.copy( this );
  4259. const invSX = 1 / sx;
  4260. const invSY = 1 / sy;
  4261. const invSZ = 1 / sz;
  4262. _m1.elements[ 0 ] *= invSX;
  4263. _m1.elements[ 1 ] *= invSX;
  4264. _m1.elements[ 2 ] *= invSX;
  4265. _m1.elements[ 4 ] *= invSY;
  4266. _m1.elements[ 5 ] *= invSY;
  4267. _m1.elements[ 6 ] *= invSY;
  4268. _m1.elements[ 8 ] *= invSZ;
  4269. _m1.elements[ 9 ] *= invSZ;
  4270. _m1.elements[ 10 ] *= invSZ;
  4271. quaternion.setFromRotationMatrix( _m1 );
  4272. scale.x = sx;
  4273. scale.y = sy;
  4274. scale.z = sz;
  4275. return this;
  4276. }
  4277. makePerspective( left, right, top, bottom, near, far ) {
  4278. if ( far === undefined ) {
  4279. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4280. }
  4281. const te = this.elements;
  4282. const x = 2 * near / ( right - left );
  4283. const y = 2 * near / ( top - bottom );
  4284. const a = ( right + left ) / ( right - left );
  4285. const b = ( top + bottom ) / ( top - bottom );
  4286. const c = - ( far + near ) / ( far - near );
  4287. const d = - 2 * far * near / ( far - near );
  4288. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4289. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4290. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4291. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4292. return this;
  4293. }
  4294. makeOrthographic( left, right, top, bottom, near, far ) {
  4295. const te = this.elements;
  4296. const w = 1.0 / ( right - left );
  4297. const h = 1.0 / ( top - bottom );
  4298. const p = 1.0 / ( far - near );
  4299. const x = ( right + left ) * w;
  4300. const y = ( top + bottom ) * h;
  4301. const z = ( far + near ) * p;
  4302. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4303. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4304. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4305. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4306. return this;
  4307. }
  4308. equals( matrix ) {
  4309. const te = this.elements;
  4310. const me = matrix.elements;
  4311. for ( let i = 0; i < 16; i ++ ) {
  4312. if ( te[ i ] !== me[ i ] ) return false;
  4313. }
  4314. return true;
  4315. }
  4316. fromArray( array, offset = 0 ) {
  4317. for ( let i = 0; i < 16; i ++ ) {
  4318. this.elements[ i ] = array[ i + offset ];
  4319. }
  4320. return this;
  4321. }
  4322. toArray( array = [], offset = 0 ) {
  4323. const te = this.elements;
  4324. array[ offset ] = te[ 0 ];
  4325. array[ offset + 1 ] = te[ 1 ];
  4326. array[ offset + 2 ] = te[ 2 ];
  4327. array[ offset + 3 ] = te[ 3 ];
  4328. array[ offset + 4 ] = te[ 4 ];
  4329. array[ offset + 5 ] = te[ 5 ];
  4330. array[ offset + 6 ] = te[ 6 ];
  4331. array[ offset + 7 ] = te[ 7 ];
  4332. array[ offset + 8 ] = te[ 8 ];
  4333. array[ offset + 9 ] = te[ 9 ];
  4334. array[ offset + 10 ] = te[ 10 ];
  4335. array[ offset + 11 ] = te[ 11 ];
  4336. array[ offset + 12 ] = te[ 12 ];
  4337. array[ offset + 13 ] = te[ 13 ];
  4338. array[ offset + 14 ] = te[ 14 ];
  4339. array[ offset + 15 ] = te[ 15 ];
  4340. return array;
  4341. }
  4342. }
  4343. const _v1$1 = /*@__PURE__*/ new Vector3();
  4344. const _m1 = /*@__PURE__*/ new Matrix4();
  4345. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4346. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4347. const _x = /*@__PURE__*/ new Vector3();
  4348. const _y = /*@__PURE__*/ new Vector3();
  4349. const _z = /*@__PURE__*/ new Vector3();
  4350. class Euler {
  4351. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4352. Object.defineProperty( this, 'isEuler', { value: true } );
  4353. this._x = x;
  4354. this._y = y;
  4355. this._z = z;
  4356. this._order = order;
  4357. }
  4358. get x() {
  4359. return this._x;
  4360. }
  4361. set x( value ) {
  4362. this._x = value;
  4363. this._onChangeCallback();
  4364. }
  4365. get y() {
  4366. return this._y;
  4367. }
  4368. set y( value ) {
  4369. this._y = value;
  4370. this._onChangeCallback();
  4371. }
  4372. get z() {
  4373. return this._z;
  4374. }
  4375. set z( value ) {
  4376. this._z = value;
  4377. this._onChangeCallback();
  4378. }
  4379. get order() {
  4380. return this._order;
  4381. }
  4382. set order( value ) {
  4383. this._order = value;
  4384. this._onChangeCallback();
  4385. }
  4386. set( x, y, z, order ) {
  4387. this._x = x;
  4388. this._y = y;
  4389. this._z = z;
  4390. this._order = order || this._order;
  4391. this._onChangeCallback();
  4392. return this;
  4393. }
  4394. clone() {
  4395. return new this.constructor( this._x, this._y, this._z, this._order );
  4396. }
  4397. copy( euler ) {
  4398. this._x = euler._x;
  4399. this._y = euler._y;
  4400. this._z = euler._z;
  4401. this._order = euler._order;
  4402. this._onChangeCallback();
  4403. return this;
  4404. }
  4405. setFromRotationMatrix( m, order, update ) {
  4406. const clamp = MathUtils.clamp;
  4407. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4408. const te = m.elements;
  4409. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4410. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4411. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4412. order = order || this._order;
  4413. switch ( order ) {
  4414. case 'XYZ':
  4415. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4416. if ( Math.abs( m13 ) < 0.9999999 ) {
  4417. this._x = Math.atan2( - m23, m33 );
  4418. this._z = Math.atan2( - m12, m11 );
  4419. } else {
  4420. this._x = Math.atan2( m32, m22 );
  4421. this._z = 0;
  4422. }
  4423. break;
  4424. case 'YXZ':
  4425. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4426. if ( Math.abs( m23 ) < 0.9999999 ) {
  4427. this._y = Math.atan2( m13, m33 );
  4428. this._z = Math.atan2( m21, m22 );
  4429. } else {
  4430. this._y = Math.atan2( - m31, m11 );
  4431. this._z = 0;
  4432. }
  4433. break;
  4434. case 'ZXY':
  4435. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4436. if ( Math.abs( m32 ) < 0.9999999 ) {
  4437. this._y = Math.atan2( - m31, m33 );
  4438. this._z = Math.atan2( - m12, m22 );
  4439. } else {
  4440. this._y = 0;
  4441. this._z = Math.atan2( m21, m11 );
  4442. }
  4443. break;
  4444. case 'ZYX':
  4445. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4446. if ( Math.abs( m31 ) < 0.9999999 ) {
  4447. this._x = Math.atan2( m32, m33 );
  4448. this._z = Math.atan2( m21, m11 );
  4449. } else {
  4450. this._x = 0;
  4451. this._z = Math.atan2( - m12, m22 );
  4452. }
  4453. break;
  4454. case 'YZX':
  4455. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4456. if ( Math.abs( m21 ) < 0.9999999 ) {
  4457. this._x = Math.atan2( - m23, m22 );
  4458. this._y = Math.atan2( - m31, m11 );
  4459. } else {
  4460. this._x = 0;
  4461. this._y = Math.atan2( m13, m33 );
  4462. }
  4463. break;
  4464. case 'XZY':
  4465. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4466. if ( Math.abs( m12 ) < 0.9999999 ) {
  4467. this._x = Math.atan2( m32, m22 );
  4468. this._y = Math.atan2( m13, m11 );
  4469. } else {
  4470. this._x = Math.atan2( - m23, m33 );
  4471. this._y = 0;
  4472. }
  4473. break;
  4474. default:
  4475. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4476. }
  4477. this._order = order;
  4478. if ( update !== false ) this._onChangeCallback();
  4479. return this;
  4480. }
  4481. setFromQuaternion( q, order, update ) {
  4482. _matrix.makeRotationFromQuaternion( q );
  4483. return this.setFromRotationMatrix( _matrix, order, update );
  4484. }
  4485. setFromVector3( v, order ) {
  4486. return this.set( v.x, v.y, v.z, order || this._order );
  4487. }
  4488. reorder( newOrder ) {
  4489. // WARNING: this discards revolution information -bhouston
  4490. _quaternion$1.setFromEuler( this );
  4491. return this.setFromQuaternion( _quaternion$1, newOrder );
  4492. }
  4493. equals( euler ) {
  4494. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4495. }
  4496. fromArray( array ) {
  4497. this._x = array[ 0 ];
  4498. this._y = array[ 1 ];
  4499. this._z = array[ 2 ];
  4500. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4501. this._onChangeCallback();
  4502. return this;
  4503. }
  4504. toArray( array = [], offset = 0 ) {
  4505. array[ offset ] = this._x;
  4506. array[ offset + 1 ] = this._y;
  4507. array[ offset + 2 ] = this._z;
  4508. array[ offset + 3 ] = this._order;
  4509. return array;
  4510. }
  4511. toVector3( optionalResult ) {
  4512. if ( optionalResult ) {
  4513. return optionalResult.set( this._x, this._y, this._z );
  4514. } else {
  4515. return new Vector3( this._x, this._y, this._z );
  4516. }
  4517. }
  4518. _onChange( callback ) {
  4519. this._onChangeCallback = callback;
  4520. return this;
  4521. }
  4522. _onChangeCallback() {}
  4523. }
  4524. Euler.DefaultOrder = 'XYZ';
  4525. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4526. const _matrix = /*@__PURE__*/ new Matrix4();
  4527. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  4528. class Layers {
  4529. constructor() {
  4530. this.mask = 1 | 0;
  4531. }
  4532. set( channel ) {
  4533. this.mask = 1 << channel | 0;
  4534. }
  4535. enable( channel ) {
  4536. this.mask |= 1 << channel | 0;
  4537. }
  4538. enableAll() {
  4539. this.mask = 0xffffffff | 0;
  4540. }
  4541. toggle( channel ) {
  4542. this.mask ^= 1 << channel | 0;
  4543. }
  4544. disable( channel ) {
  4545. this.mask &= ~ ( 1 << channel | 0 );
  4546. }
  4547. disableAll() {
  4548. this.mask = 0;
  4549. }
  4550. test( layers ) {
  4551. return ( this.mask & layers.mask ) !== 0;
  4552. }
  4553. }
  4554. let _object3DId = 0;
  4555. const _v1$2 = new Vector3();
  4556. const _q1 = new Quaternion();
  4557. const _m1$1 = new Matrix4();
  4558. const _target = new Vector3();
  4559. const _position = new Vector3();
  4560. const _scale = new Vector3();
  4561. const _quaternion$2 = new Quaternion();
  4562. const _xAxis = new Vector3( 1, 0, 0 );
  4563. const _yAxis = new Vector3( 0, 1, 0 );
  4564. const _zAxis = new Vector3( 0, 0, 1 );
  4565. const _addedEvent = { type: 'added' };
  4566. const _removedEvent = { type: 'removed' };
  4567. function Object3D() {
  4568. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4569. this.uuid = MathUtils.generateUUID();
  4570. this.name = '';
  4571. this.type = 'Object3D';
  4572. this.parent = null;
  4573. this.children = [];
  4574. this.up = Object3D.DefaultUp.clone();
  4575. const position = new Vector3();
  4576. const rotation = new Euler();
  4577. const quaternion = new Quaternion();
  4578. const scale = new Vector3( 1, 1, 1 );
  4579. function onRotationChange() {
  4580. quaternion.setFromEuler( rotation, false );
  4581. }
  4582. function onQuaternionChange() {
  4583. rotation.setFromQuaternion( quaternion, undefined, false );
  4584. }
  4585. rotation._onChange( onRotationChange );
  4586. quaternion._onChange( onQuaternionChange );
  4587. Object.defineProperties( this, {
  4588. position: {
  4589. configurable: true,
  4590. enumerable: true,
  4591. value: position
  4592. },
  4593. rotation: {
  4594. configurable: true,
  4595. enumerable: true,
  4596. value: rotation
  4597. },
  4598. quaternion: {
  4599. configurable: true,
  4600. enumerable: true,
  4601. value: quaternion
  4602. },
  4603. scale: {
  4604. configurable: true,
  4605. enumerable: true,
  4606. value: scale
  4607. },
  4608. modelViewMatrix: {
  4609. value: new Matrix4()
  4610. },
  4611. normalMatrix: {
  4612. value: new Matrix3()
  4613. }
  4614. } );
  4615. this.matrix = new Matrix4();
  4616. this.matrixWorld = new Matrix4();
  4617. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4618. this.matrixWorldNeedsUpdate = false;
  4619. this.layers = new Layers();
  4620. this.visible = true;
  4621. this.castShadow = false;
  4622. this.receiveShadow = false;
  4623. this.frustumCulled = true;
  4624. this.renderOrder = 0;
  4625. this.animations = [];
  4626. this.userData = {};
  4627. }
  4628. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4629. Object3D.DefaultMatrixAutoUpdate = true;
  4630. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  4631. constructor: Object3D,
  4632. isObject3D: true,
  4633. onBeforeRender: function () {},
  4634. onAfterRender: function () {},
  4635. applyMatrix4: function ( matrix ) {
  4636. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4637. this.matrix.premultiply( matrix );
  4638. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4639. },
  4640. applyQuaternion: function ( q ) {
  4641. this.quaternion.premultiply( q );
  4642. return this;
  4643. },
  4644. setRotationFromAxisAngle: function ( axis, angle ) {
  4645. // assumes axis is normalized
  4646. this.quaternion.setFromAxisAngle( axis, angle );
  4647. },
  4648. setRotationFromEuler: function ( euler ) {
  4649. this.quaternion.setFromEuler( euler, true );
  4650. },
  4651. setRotationFromMatrix: function ( m ) {
  4652. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4653. this.quaternion.setFromRotationMatrix( m );
  4654. },
  4655. setRotationFromQuaternion: function ( q ) {
  4656. // assumes q is normalized
  4657. this.quaternion.copy( q );
  4658. },
  4659. rotateOnAxis: function ( axis, angle ) {
  4660. // rotate object on axis in object space
  4661. // axis is assumed to be normalized
  4662. _q1.setFromAxisAngle( axis, angle );
  4663. this.quaternion.multiply( _q1 );
  4664. return this;
  4665. },
  4666. rotateOnWorldAxis: function ( axis, angle ) {
  4667. // rotate object on axis in world space
  4668. // axis is assumed to be normalized
  4669. // method assumes no rotated parent
  4670. _q1.setFromAxisAngle( axis, angle );
  4671. this.quaternion.premultiply( _q1 );
  4672. return this;
  4673. },
  4674. rotateX: function ( angle ) {
  4675. return this.rotateOnAxis( _xAxis, angle );
  4676. },
  4677. rotateY: function ( angle ) {
  4678. return this.rotateOnAxis( _yAxis, angle );
  4679. },
  4680. rotateZ: function ( angle ) {
  4681. return this.rotateOnAxis( _zAxis, angle );
  4682. },
  4683. translateOnAxis: function ( axis, distance ) {
  4684. // translate object by distance along axis in object space
  4685. // axis is assumed to be normalized
  4686. _v1$2.copy( axis ).applyQuaternion( this.quaternion );
  4687. this.position.add( _v1$2.multiplyScalar( distance ) );
  4688. return this;
  4689. },
  4690. translateX: function ( distance ) {
  4691. return this.translateOnAxis( _xAxis, distance );
  4692. },
  4693. translateY: function ( distance ) {
  4694. return this.translateOnAxis( _yAxis, distance );
  4695. },
  4696. translateZ: function ( distance ) {
  4697. return this.translateOnAxis( _zAxis, distance );
  4698. },
  4699. localToWorld: function ( vector ) {
  4700. return vector.applyMatrix4( this.matrixWorld );
  4701. },
  4702. worldToLocal: function ( vector ) {
  4703. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4704. },
  4705. lookAt: function ( x, y, z ) {
  4706. // This method does not support objects having non-uniformly-scaled parent(s)
  4707. if ( x.isVector3 ) {
  4708. _target.copy( x );
  4709. } else {
  4710. _target.set( x, y, z );
  4711. }
  4712. const parent = this.parent;
  4713. this.updateWorldMatrix( true, false );
  4714. _position.setFromMatrixPosition( this.matrixWorld );
  4715. if ( this.isCamera || this.isLight ) {
  4716. _m1$1.lookAt( _position, _target, this.up );
  4717. } else {
  4718. _m1$1.lookAt( _target, _position, this.up );
  4719. }
  4720. this.quaternion.setFromRotationMatrix( _m1$1 );
  4721. if ( parent ) {
  4722. _m1$1.extractRotation( parent.matrixWorld );
  4723. _q1.setFromRotationMatrix( _m1$1 );
  4724. this.quaternion.premultiply( _q1.invert() );
  4725. }
  4726. },
  4727. add: function ( object ) {
  4728. if ( arguments.length > 1 ) {
  4729. for ( let i = 0; i < arguments.length; i ++ ) {
  4730. this.add( arguments[ i ] );
  4731. }
  4732. return this;
  4733. }
  4734. if ( object === this ) {
  4735. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4736. return this;
  4737. }
  4738. if ( object && object.isObject3D ) {
  4739. if ( object.parent !== null ) {
  4740. object.parent.remove( object );
  4741. }
  4742. object.parent = this;
  4743. this.children.push( object );
  4744. object.dispatchEvent( _addedEvent );
  4745. } else {
  4746. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4747. }
  4748. return this;
  4749. },
  4750. remove: function ( object ) {
  4751. if ( arguments.length > 1 ) {
  4752. for ( let i = 0; i < arguments.length; i ++ ) {
  4753. this.remove( arguments[ i ] );
  4754. }
  4755. return this;
  4756. }
  4757. const index = this.children.indexOf( object );
  4758. if ( index !== - 1 ) {
  4759. object.parent = null;
  4760. this.children.splice( index, 1 );
  4761. object.dispatchEvent( _removedEvent );
  4762. }
  4763. return this;
  4764. },
  4765. clear: function () {
  4766. for ( let i = 0; i < this.children.length; i ++ ) {
  4767. const object = this.children[ i ];
  4768. object.parent = null;
  4769. object.dispatchEvent( _removedEvent );
  4770. }
  4771. this.children.length = 0;
  4772. return this;
  4773. },
  4774. attach: function ( object ) {
  4775. // adds object as a child of this, while maintaining the object's world transform
  4776. this.updateWorldMatrix( true, false );
  4777. _m1$1.copy( this.matrixWorld ).invert();
  4778. if ( object.parent !== null ) {
  4779. object.parent.updateWorldMatrix( true, false );
  4780. _m1$1.multiply( object.parent.matrixWorld );
  4781. }
  4782. object.applyMatrix4( _m1$1 );
  4783. object.updateWorldMatrix( false, false );
  4784. this.add( object );
  4785. return this;
  4786. },
  4787. getObjectById: function ( id ) {
  4788. return this.getObjectByProperty( 'id', id );
  4789. },
  4790. getObjectByName: function ( name ) {
  4791. return this.getObjectByProperty( 'name', name );
  4792. },
  4793. getObjectByProperty: function ( name, value ) {
  4794. if ( this[ name ] === value ) return this;
  4795. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4796. const child = this.children[ i ];
  4797. const object = child.getObjectByProperty( name, value );
  4798. if ( object !== undefined ) {
  4799. return object;
  4800. }
  4801. }
  4802. return undefined;
  4803. },
  4804. getWorldPosition: function ( target ) {
  4805. if ( target === undefined ) {
  4806. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4807. target = new Vector3();
  4808. }
  4809. this.updateWorldMatrix( true, false );
  4810. return target.setFromMatrixPosition( this.matrixWorld );
  4811. },
  4812. getWorldQuaternion: function ( target ) {
  4813. if ( target === undefined ) {
  4814. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4815. target = new Quaternion();
  4816. }
  4817. this.updateWorldMatrix( true, false );
  4818. this.matrixWorld.decompose( _position, target, _scale );
  4819. return target;
  4820. },
  4821. getWorldScale: function ( target ) {
  4822. if ( target === undefined ) {
  4823. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4824. target = new Vector3();
  4825. }
  4826. this.updateWorldMatrix( true, false );
  4827. this.matrixWorld.decompose( _position, _quaternion$2, target );
  4828. return target;
  4829. },
  4830. getWorldDirection: function ( target ) {
  4831. if ( target === undefined ) {
  4832. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4833. target = new Vector3();
  4834. }
  4835. this.updateWorldMatrix( true, false );
  4836. const e = this.matrixWorld.elements;
  4837. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4838. },
  4839. raycast: function () {},
  4840. traverse: function ( callback ) {
  4841. let result = callback( this );
  4842. if(result && result.stopContinue){//xzw add
  4843. return
  4844. }
  4845. const children = this.children;
  4846. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4847. children[ i ].traverse( callback );
  4848. }
  4849. },
  4850. traverseVisible: function ( callback ) {
  4851. if ( this.visible === false ) return;
  4852. callback( this );
  4853. const children = this.children;
  4854. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4855. children[ i ].traverseVisible( callback );
  4856. }
  4857. },
  4858. traverseAncestors: function ( callback ) {
  4859. const parent = this.parent;
  4860. if ( parent !== null ) {
  4861. callback( parent );
  4862. parent.traverseAncestors( callback );
  4863. }
  4864. },
  4865. updateMatrix: function () {
  4866. this.matrix.compose( this.position, this.quaternion, this.scale );
  4867. this.matrixWorldNeedsUpdate = true;
  4868. },
  4869. updateMatrixWorld: function ( force ) {
  4870. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4871. if ( this.matrixWorldNeedsUpdate || force ) {
  4872. if ( this.parent === null ) {
  4873. this.matrixWorld.copy( this.matrix );
  4874. } else {
  4875. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4876. }
  4877. this.matrixWorldNeedsUpdate = false;
  4878. force = true;
  4879. }
  4880. // update children
  4881. const children = this.children;
  4882. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4883. children[ i ].updateMatrixWorld( force );
  4884. }
  4885. },
  4886. updateWorldMatrix: function ( updateParents, updateChildren ) {
  4887. const parent = this.parent;
  4888. if ( updateParents === true && parent !== null ) {
  4889. parent.updateWorldMatrix( true, false );
  4890. }
  4891. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4892. if ( this.parent === null ) {
  4893. this.matrixWorld.copy( this.matrix );
  4894. } else {
  4895. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4896. }
  4897. // update children
  4898. if ( updateChildren === true ) {
  4899. const children = this.children;
  4900. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4901. children[ i ].updateWorldMatrix( false, true );
  4902. }
  4903. }
  4904. },
  4905. toJSON: function ( meta ) {
  4906. // meta is a string when called from JSON.stringify
  4907. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4908. const output = {};
  4909. // meta is a hash used to collect geometries, materials.
  4910. // not providing it implies that this is the root object
  4911. // being serialized.
  4912. if ( isRootObject ) {
  4913. // initialize meta obj
  4914. meta = {
  4915. geometries: {},
  4916. materials: {},
  4917. textures: {},
  4918. images: {},
  4919. shapes: {},
  4920. skeletons: {},
  4921. animations: {}
  4922. };
  4923. output.metadata = {
  4924. version: 4.5,
  4925. type: 'Object',
  4926. generator: 'Object3D.toJSON'
  4927. };
  4928. }
  4929. // standard Object3D serialization
  4930. const object = {};
  4931. object.uuid = this.uuid;
  4932. object.type = this.type;
  4933. if ( this.name !== '' ) object.name = this.name;
  4934. if ( this.castShadow === true ) object.castShadow = true;
  4935. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4936. if ( this.visible === false ) object.visible = false;
  4937. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4938. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4939. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4940. object.layers = this.layers.mask;
  4941. object.matrix = this.matrix.toArray();
  4942. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4943. // object specific properties
  4944. if ( this.isInstancedMesh ) {
  4945. object.type = 'InstancedMesh';
  4946. object.count = this.count;
  4947. object.instanceMatrix = this.instanceMatrix.toJSON();
  4948. }
  4949. //
  4950. function serialize( library, element ) {
  4951. if ( library[ element.uuid ] === undefined ) {
  4952. library[ element.uuid ] = element.toJSON( meta );
  4953. }
  4954. return element.uuid;
  4955. }
  4956. if ( this.isMesh || this.isLine || this.isPoints ) {
  4957. object.geometry = serialize( meta.geometries, this.geometry );
  4958. const parameters = this.geometry.parameters;
  4959. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4960. const shapes = parameters.shapes;
  4961. if ( Array.isArray( shapes ) ) {
  4962. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4963. const shape = shapes[ i ];
  4964. serialize( meta.shapes, shape );
  4965. }
  4966. } else {
  4967. serialize( meta.shapes, shapes );
  4968. }
  4969. }
  4970. }
  4971. if ( this.isSkinnedMesh ) {
  4972. object.bindMode = this.bindMode;
  4973. object.bindMatrix = this.bindMatrix.toArray();
  4974. if ( this.skeleton !== undefined ) {
  4975. serialize( meta.skeletons, this.skeleton );
  4976. object.skeleton = this.skeleton.uuid;
  4977. }
  4978. }
  4979. if ( this.material !== undefined ) {
  4980. if ( Array.isArray( this.material ) ) {
  4981. const uuids = [];
  4982. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4983. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4984. }
  4985. object.material = uuids;
  4986. } else {
  4987. object.material = serialize( meta.materials, this.material );
  4988. }
  4989. }
  4990. //
  4991. if ( this.children.length > 0 ) {
  4992. object.children = [];
  4993. for ( let i = 0; i < this.children.length; i ++ ) {
  4994. object.children.push( this.children[ i ].toJSON( meta ).object );
  4995. }
  4996. }
  4997. //
  4998. if ( this.animations.length > 0 ) {
  4999. object.animations = [];
  5000. for ( let i = 0; i < this.animations.length; i ++ ) {
  5001. const animation = this.animations[ i ];
  5002. object.animations.push( serialize( meta.animations, animation ) );
  5003. }
  5004. }
  5005. if ( isRootObject ) {
  5006. const geometries = extractFromCache( meta.geometries );
  5007. const materials = extractFromCache( meta.materials );
  5008. const textures = extractFromCache( meta.textures );
  5009. const images = extractFromCache( meta.images );
  5010. const shapes = extractFromCache( meta.shapes );
  5011. const skeletons = extractFromCache( meta.skeletons );
  5012. const animations = extractFromCache( meta.animations );
  5013. if ( geometries.length > 0 ) output.geometries = geometries;
  5014. if ( materials.length > 0 ) output.materials = materials;
  5015. if ( textures.length > 0 ) output.textures = textures;
  5016. if ( images.length > 0 ) output.images = images;
  5017. if ( shapes.length > 0 ) output.shapes = shapes;
  5018. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  5019. if ( animations.length > 0 ) output.animations = animations;
  5020. }
  5021. output.object = object;
  5022. return output;
  5023. // extract data from the cache hash
  5024. // remove metadata on each item
  5025. // and return as array
  5026. function extractFromCache( cache ) {
  5027. const values = [];
  5028. for ( const key in cache ) {
  5029. const data = cache[ key ];
  5030. delete data.metadata;
  5031. values.push( data );
  5032. }
  5033. return values;
  5034. }
  5035. },
  5036. clone: function ( recursive ) {
  5037. return new this.constructor().copy( this, recursive );
  5038. },
  5039. copy: function ( source, recursive = true ) {
  5040. this.name = source.name;
  5041. this.up.copy( source.up );
  5042. this.position.copy( source.position );
  5043. this.rotation.order = source.rotation.order;
  5044. this.quaternion.copy( source.quaternion );
  5045. this.scale.copy( source.scale );
  5046. this.matrix.copy( source.matrix );
  5047. this.matrixWorld.copy( source.matrixWorld );
  5048. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5049. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5050. this.layers.mask = source.layers.mask;
  5051. this.visible = source.visible;
  5052. this.castShadow = source.castShadow;
  5053. this.receiveShadow = source.receiveShadow;
  5054. this.frustumCulled = source.frustumCulled;
  5055. this.renderOrder = source.renderOrder;
  5056. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5057. if ( recursive === true ) {
  5058. for ( let i = 0; i < source.children.length; i ++ ) {
  5059. const child = source.children[ i ];
  5060. this.add( child.clone() );
  5061. }
  5062. }
  5063. return this;
  5064. }
  5065. } );
  5066. const _vector1 = /*@__PURE__*/ new Vector3();
  5067. const _vector2 = /*@__PURE__*/ new Vector3();
  5068. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  5069. class Plane {
  5070. constructor( normal, constant ) {
  5071. Object.defineProperty( this, 'isPlane', { value: true } );
  5072. // normal is assumed to be normalized
  5073. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5074. this.constant = ( constant !== undefined ) ? constant : 0;
  5075. }
  5076. set( normal, constant ) {
  5077. this.normal.copy( normal );
  5078. this.constant = constant;
  5079. return this;
  5080. }
  5081. setComponents( x, y, z, w ) {
  5082. this.normal.set( x, y, z );
  5083. this.constant = w;
  5084. return this;
  5085. }
  5086. setFromNormalAndCoplanarPoint( normal, point ) {
  5087. this.normal.copy( normal );
  5088. this.constant = - point.dot( this.normal );
  5089. return this;
  5090. }
  5091. setFromCoplanarPoints( a, b, c ) {
  5092. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  5093. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5094. this.setFromNormalAndCoplanarPoint( normal, a );
  5095. return this;
  5096. }
  5097. clone() {
  5098. return new this.constructor().copy( this );
  5099. }
  5100. copy( plane ) {
  5101. this.normal.copy( plane.normal );
  5102. this.constant = plane.constant;
  5103. return this;
  5104. }
  5105. normalize() {
  5106. // Note: will lead to a divide by zero if the plane is invalid.
  5107. const inverseNormalLength = 1.0 / this.normal.length();
  5108. this.normal.multiplyScalar( inverseNormalLength );
  5109. this.constant *= inverseNormalLength;
  5110. return this;
  5111. }
  5112. negate() {
  5113. this.constant *= - 1;
  5114. this.normal.negate();
  5115. return this;
  5116. }
  5117. distanceToPoint( point ) {
  5118. return this.normal.dot( point ) + this.constant;
  5119. }
  5120. distanceToSphere( sphere ) {
  5121. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5122. }
  5123. projectPoint( point, target ) {
  5124. if ( target === undefined ) {
  5125. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  5126. target = new Vector3();
  5127. }
  5128. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5129. }
  5130. intersectLine( line, target ) {
  5131. if ( target === undefined ) {
  5132. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  5133. target = new Vector3();
  5134. }
  5135. const direction = line.delta( _vector1 );
  5136. const denominator = this.normal.dot( direction );
  5137. if ( denominator === 0 ) {
  5138. // line is coplanar, return origin
  5139. if ( this.distanceToPoint( line.start ) === 0 ) {
  5140. return target.copy( line.start );
  5141. }
  5142. // Unsure if this is the correct method to handle this case.
  5143. return undefined;
  5144. }
  5145. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5146. if ( t < 0 || t > 1 ) {
  5147. return undefined;
  5148. }
  5149. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  5150. }
  5151. intersectsLine( line ) {
  5152. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5153. const startSign = this.distanceToPoint( line.start );
  5154. const endSign = this.distanceToPoint( line.end );
  5155. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5156. }
  5157. intersectsBox( box ) {
  5158. return box.intersectsPlane( this );
  5159. }
  5160. intersectsSphere( sphere ) {
  5161. return sphere.intersectsPlane( this );
  5162. }
  5163. coplanarPoint( target ) {
  5164. if ( target === undefined ) {
  5165. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  5166. target = new Vector3();
  5167. }
  5168. return target.copy( this.normal ).multiplyScalar( - this.constant );
  5169. }
  5170. applyMatrix4( matrix, optionalNormalMatrix ) {
  5171. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  5172. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  5173. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5174. this.constant = - referencePoint.dot( normal );
  5175. return this;
  5176. }
  5177. translate( offset ) {
  5178. this.constant -= offset.dot( this.normal );
  5179. return this;
  5180. }
  5181. equals( plane ) {
  5182. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5183. }
  5184. }
  5185. const _v0$1 = /*@__PURE__*/ new Vector3();
  5186. const _v1$3 = /*@__PURE__*/ new Vector3();
  5187. const _v2$1 = /*@__PURE__*/ new Vector3();
  5188. const _v3 = /*@__PURE__*/ new Vector3();
  5189. const _vab = /*@__PURE__*/ new Vector3();
  5190. const _vac = /*@__PURE__*/ new Vector3();
  5191. const _vbc = /*@__PURE__*/ new Vector3();
  5192. const _vap = /*@__PURE__*/ new Vector3();
  5193. const _vbp = /*@__PURE__*/ new Vector3();
  5194. const _vcp = /*@__PURE__*/ new Vector3();
  5195. class Triangle {
  5196. constructor( a, b, c ) {
  5197. this.a = ( a !== undefined ) ? a : new Vector3();
  5198. this.b = ( b !== undefined ) ? b : new Vector3();
  5199. this.c = ( c !== undefined ) ? c : new Vector3();
  5200. }
  5201. static getNormal( a, b, c, target ) {
  5202. if ( target === undefined ) {
  5203. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  5204. target = new Vector3();
  5205. }
  5206. target.subVectors( c, b );
  5207. _v0$1.subVectors( a, b );
  5208. target.cross( _v0$1 );
  5209. const targetLengthSq = target.lengthSq();
  5210. if ( targetLengthSq > 0 ) {
  5211. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5212. }
  5213. return target.set( 0, 0, 0 );
  5214. }
  5215. // static/instance method to calculate barycentric coordinates
  5216. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5217. static getBarycoord( point, a, b, c, target ) {
  5218. _v0$1.subVectors( c, a );
  5219. _v1$3.subVectors( b, a );
  5220. _v2$1.subVectors( point, a );
  5221. const dot00 = _v0$1.dot( _v0$1 );
  5222. const dot01 = _v0$1.dot( _v1$3 );
  5223. const dot02 = _v0$1.dot( _v2$1 );
  5224. const dot11 = _v1$3.dot( _v1$3 );
  5225. const dot12 = _v1$3.dot( _v2$1 );
  5226. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5227. if ( target === undefined ) {
  5228. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  5229. target = new Vector3();
  5230. }
  5231. // collinear or singular triangle
  5232. if ( denom === 0 ) {
  5233. // arbitrary location outside of triangle?
  5234. // not sure if this is the best idea, maybe should be returning undefined
  5235. return target.set( - 2, - 1, - 1 );
  5236. }
  5237. const invDenom = 1 / denom;
  5238. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5239. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5240. // barycentric coordinates must always sum to 1
  5241. return target.set( 1 - u - v, v, u );
  5242. }
  5243. static containsPoint( point, a, b, c ) {
  5244. this.getBarycoord( point, a, b, c, _v3 );
  5245. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  5246. }
  5247. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5248. this.getBarycoord( point, p1, p2, p3, _v3 );
  5249. target.set( 0, 0 );
  5250. target.addScaledVector( uv1, _v3.x );
  5251. target.addScaledVector( uv2, _v3.y );
  5252. target.addScaledVector( uv3, _v3.z );
  5253. return target;
  5254. }
  5255. static isFrontFacing( a, b, c, direction ) {
  5256. _v0$1.subVectors( c, b );
  5257. _v1$3.subVectors( a, b );
  5258. // strictly front facing
  5259. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5260. }
  5261. set( a, b, c ) {
  5262. this.a.copy( a );
  5263. this.b.copy( b );
  5264. this.c.copy( c );
  5265. return this;
  5266. }
  5267. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5268. this.a.copy( points[ i0 ] );
  5269. this.b.copy( points[ i1 ] );
  5270. this.c.copy( points[ i2 ] );
  5271. return this;
  5272. }
  5273. clone() {
  5274. return new this.constructor().copy( this );
  5275. }
  5276. copy( triangle ) {
  5277. this.a.copy( triangle.a );
  5278. this.b.copy( triangle.b );
  5279. this.c.copy( triangle.c );
  5280. return this;
  5281. }
  5282. getArea() {
  5283. _v0$1.subVectors( this.c, this.b );
  5284. _v1$3.subVectors( this.a, this.b );
  5285. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5286. }
  5287. getMidpoint( target ) {
  5288. if ( target === undefined ) {
  5289. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  5290. target = new Vector3();
  5291. }
  5292. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5293. }
  5294. getNormal( target ) {
  5295. return Triangle.getNormal( this.a, this.b, this.c, target );
  5296. }
  5297. getPlane( target ) {
  5298. if ( target === undefined ) {
  5299. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  5300. target = new Plane();
  5301. }
  5302. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5303. }
  5304. getBarycoord( point, target ) {
  5305. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5306. }
  5307. getUV( point, uv1, uv2, uv3, target ) {
  5308. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5309. }
  5310. containsPoint( point ) {
  5311. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5312. }
  5313. isFrontFacing( direction ) {
  5314. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5315. }
  5316. intersectsBox( box ) {
  5317. return box.intersectsTriangle( this );
  5318. }
  5319. closestPointToPoint( p, target ) {
  5320. if ( target === undefined ) {
  5321. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  5322. target = new Vector3();
  5323. }
  5324. const a = this.a, b = this.b, c = this.c;
  5325. let v, w;
  5326. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5327. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5328. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5329. // basically, we're distinguishing which of the voronoi regions of the triangle
  5330. // the point lies in with the minimum amount of redundant computation.
  5331. _vab.subVectors( b, a );
  5332. _vac.subVectors( c, a );
  5333. _vap.subVectors( p, a );
  5334. const d1 = _vab.dot( _vap );
  5335. const d2 = _vac.dot( _vap );
  5336. if ( d1 <= 0 && d2 <= 0 ) {
  5337. // vertex region of A; barycentric coords (1, 0, 0)
  5338. return target.copy( a );
  5339. }
  5340. _vbp.subVectors( p, b );
  5341. const d3 = _vab.dot( _vbp );
  5342. const d4 = _vac.dot( _vbp );
  5343. if ( d3 >= 0 && d4 <= d3 ) {
  5344. // vertex region of B; barycentric coords (0, 1, 0)
  5345. return target.copy( b );
  5346. }
  5347. const vc = d1 * d4 - d3 * d2;
  5348. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5349. v = d1 / ( d1 - d3 );
  5350. // edge region of AB; barycentric coords (1-v, v, 0)
  5351. return target.copy( a ).addScaledVector( _vab, v );
  5352. }
  5353. _vcp.subVectors( p, c );
  5354. const d5 = _vab.dot( _vcp );
  5355. const d6 = _vac.dot( _vcp );
  5356. if ( d6 >= 0 && d5 <= d6 ) {
  5357. // vertex region of C; barycentric coords (0, 0, 1)
  5358. return target.copy( c );
  5359. }
  5360. const vb = d5 * d2 - d1 * d6;
  5361. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5362. w = d2 / ( d2 - d6 );
  5363. // edge region of AC; barycentric coords (1-w, 0, w)
  5364. return target.copy( a ).addScaledVector( _vac, w );
  5365. }
  5366. const va = d3 * d6 - d5 * d4;
  5367. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5368. _vbc.subVectors( c, b );
  5369. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5370. // edge region of BC; barycentric coords (0, 1-w, w)
  5371. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5372. }
  5373. // face region
  5374. const denom = 1 / ( va + vb + vc );
  5375. // u = va * denom
  5376. v = vb * denom;
  5377. w = vc * denom;
  5378. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5379. }
  5380. equals( triangle ) {
  5381. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5382. }
  5383. }
  5384. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5385. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5386. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5387. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5388. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5389. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5390. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5391. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5392. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5393. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5394. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5395. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5396. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5397. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5398. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5399. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5400. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5401. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5402. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5403. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5404. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5405. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5406. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5407. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5408. const _hslA = { h: 0, s: 0, l: 0 };
  5409. const _hslB = { h: 0, s: 0, l: 0 };
  5410. function hue2rgb( p, q, t ) {
  5411. if ( t < 0 ) t += 1;
  5412. if ( t > 1 ) t -= 1;
  5413. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5414. if ( t < 1 / 2 ) return q;
  5415. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5416. return p;
  5417. }
  5418. function SRGBToLinear( c ) {
  5419. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5420. }
  5421. function LinearToSRGB( c ) {
  5422. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5423. }
  5424. class Color {
  5425. constructor( r, g, b ) {
  5426. Object.defineProperty( this, 'isColor', { value: true } );
  5427. if ( g === undefined && b === undefined ) {
  5428. // r is THREE.Color, hex or string
  5429. return this.set( r );
  5430. }
  5431. return this.setRGB( r, g, b );
  5432. }
  5433. set( value ) {
  5434. if ( value && value.isColor ) {
  5435. this.copy( value );
  5436. } else if ( typeof value === 'number' ) {
  5437. this.setHex( value );
  5438. } else if ( typeof value === 'string' ) {
  5439. this.setStyle( value );
  5440. }
  5441. return this;
  5442. }
  5443. setScalar( scalar ) {
  5444. this.r = scalar;
  5445. this.g = scalar;
  5446. this.b = scalar;
  5447. return this;
  5448. }
  5449. setHex( hex ) {
  5450. hex = Math.floor( hex );
  5451. this.r = ( hex >> 16 & 255 ) / 255;
  5452. this.g = ( hex >> 8 & 255 ) / 255;
  5453. this.b = ( hex & 255 ) / 255;
  5454. return this;
  5455. }
  5456. setRGB( r, g, b ) {
  5457. this.r = r;
  5458. this.g = g;
  5459. this.b = b;
  5460. return this;
  5461. }
  5462. setHSL( h, s, l ) {
  5463. // h,s,l ranges are in 0.0 - 1.0
  5464. h = MathUtils.euclideanModulo( h, 1 );
  5465. s = MathUtils.clamp( s, 0, 1 );
  5466. l = MathUtils.clamp( l, 0, 1 );
  5467. if ( s === 0 ) {
  5468. this.r = this.g = this.b = l;
  5469. } else {
  5470. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5471. const q = ( 2 * l ) - p;
  5472. this.r = hue2rgb( q, p, h + 1 / 3 );
  5473. this.g = hue2rgb( q, p, h );
  5474. this.b = hue2rgb( q, p, h - 1 / 3 );
  5475. }
  5476. return this;
  5477. }
  5478. setStyle( style ) {
  5479. function handleAlpha( string ) {
  5480. if ( string === undefined ) return;
  5481. if ( parseFloat( string ) < 1 ) {
  5482. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5483. }
  5484. }
  5485. let m;
  5486. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  5487. // rgb / hsl
  5488. let color;
  5489. const name = m[ 1 ];
  5490. const components = m[ 2 ];
  5491. switch ( name ) {
  5492. case 'rgb':
  5493. case 'rgba':
  5494. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5495. // rgb(255,0,0) rgba(255,0,0,0.5)
  5496. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5497. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5498. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5499. handleAlpha( color[ 4 ] );
  5500. return this;
  5501. }
  5502. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5503. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5504. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5505. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5506. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5507. handleAlpha( color[ 4 ] );
  5508. return this;
  5509. }
  5510. break;
  5511. case 'hsl':
  5512. case 'hsla':
  5513. if ( color = /^(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5514. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5515. const h = parseFloat( color[ 1 ] ) / 360;
  5516. const s = parseInt( color[ 2 ], 10 ) / 100;
  5517. const l = parseInt( color[ 3 ], 10 ) / 100;
  5518. handleAlpha( color[ 4 ] );
  5519. return this.setHSL( h, s, l );
  5520. }
  5521. break;
  5522. }
  5523. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5524. // hex color
  5525. const hex = m[ 1 ];
  5526. const size = hex.length;
  5527. if ( size === 3 ) {
  5528. // #ff0
  5529. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5530. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5531. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5532. return this;
  5533. } else if ( size === 6 ) {
  5534. // #ff0000
  5535. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5536. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5537. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5538. return this;
  5539. }
  5540. }
  5541. if ( style && style.length > 0 ) {
  5542. return this.setColorName( style );
  5543. }
  5544. return this;
  5545. }
  5546. setColorName( style ) {
  5547. // color keywords
  5548. const hex = _colorKeywords[ style ];
  5549. if ( hex !== undefined ) {
  5550. // red
  5551. this.setHex( hex );
  5552. } else {
  5553. // unknown color
  5554. console.warn( 'THREE.Color: Unknown color ' + style );
  5555. }
  5556. return this;
  5557. }
  5558. clone() {
  5559. return new this.constructor( this.r, this.g, this.b );
  5560. }
  5561. copy( color ) {
  5562. this.r = color.r;
  5563. this.g = color.g;
  5564. this.b = color.b;
  5565. return this;
  5566. }
  5567. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5568. this.r = Math.pow( color.r, gammaFactor );
  5569. this.g = Math.pow( color.g, gammaFactor );
  5570. this.b = Math.pow( color.b, gammaFactor );
  5571. return this;
  5572. }
  5573. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5574. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5575. this.r = Math.pow( color.r, safeInverse );
  5576. this.g = Math.pow( color.g, safeInverse );
  5577. this.b = Math.pow( color.b, safeInverse );
  5578. return this;
  5579. }
  5580. convertGammaToLinear( gammaFactor ) {
  5581. this.copyGammaToLinear( this, gammaFactor );
  5582. return this;
  5583. }
  5584. convertLinearToGamma( gammaFactor ) {
  5585. this.copyLinearToGamma( this, gammaFactor );
  5586. return this;
  5587. }
  5588. copySRGBToLinear( color ) {
  5589. this.r = SRGBToLinear( color.r );
  5590. this.g = SRGBToLinear( color.g );
  5591. this.b = SRGBToLinear( color.b );
  5592. return this;
  5593. }
  5594. copyLinearToSRGB( color ) {
  5595. this.r = LinearToSRGB( color.r );
  5596. this.g = LinearToSRGB( color.g );
  5597. this.b = LinearToSRGB( color.b );
  5598. return this;
  5599. }
  5600. convertSRGBToLinear() {
  5601. this.copySRGBToLinear( this );
  5602. return this;
  5603. }
  5604. convertLinearToSRGB() {
  5605. this.copyLinearToSRGB( this );
  5606. return this;
  5607. }
  5608. getHex() {
  5609. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5610. }
  5611. getHexString() {
  5612. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5613. }
  5614. getHSL( target ) {
  5615. // h,s,l ranges are in 0.0 - 1.0
  5616. if ( target === undefined ) {
  5617. console.warn( 'THREE.Color: .getHSL() target is now required' );
  5618. target = { h: 0, s: 0, l: 0 };
  5619. }
  5620. const r = this.r, g = this.g, b = this.b;
  5621. const max = Math.max( r, g, b );
  5622. const min = Math.min( r, g, b );
  5623. let hue, saturation;
  5624. const lightness = ( min + max ) / 2.0;
  5625. if ( min === max ) {
  5626. hue = 0;
  5627. saturation = 0;
  5628. } else {
  5629. const delta = max - min;
  5630. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5631. switch ( max ) {
  5632. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5633. case g: hue = ( b - r ) / delta + 2; break;
  5634. case b: hue = ( r - g ) / delta + 4; break;
  5635. }
  5636. hue /= 6;
  5637. }
  5638. target.h = hue;
  5639. target.s = saturation;
  5640. target.l = lightness;
  5641. return target;
  5642. }
  5643. getStyle() {
  5644. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5645. }
  5646. offsetHSL( h, s, l ) {
  5647. this.getHSL( _hslA );
  5648. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5649. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5650. return this;
  5651. }
  5652. add( color ) {
  5653. this.r += color.r;
  5654. this.g += color.g;
  5655. this.b += color.b;
  5656. return this;
  5657. }
  5658. addColors( color1, color2 ) {
  5659. this.r = color1.r + color2.r;
  5660. this.g = color1.g + color2.g;
  5661. this.b = color1.b + color2.b;
  5662. return this;
  5663. }
  5664. addScalar( s ) {
  5665. this.r += s;
  5666. this.g += s;
  5667. this.b += s;
  5668. return this;
  5669. }
  5670. sub( color ) {
  5671. this.r = Math.max( 0, this.r - color.r );
  5672. this.g = Math.max( 0, this.g - color.g );
  5673. this.b = Math.max( 0, this.b - color.b );
  5674. return this;
  5675. }
  5676. multiply( color ) {
  5677. this.r *= color.r;
  5678. this.g *= color.g;
  5679. this.b *= color.b;
  5680. return this;
  5681. }
  5682. multiplyScalar( s ) {
  5683. this.r *= s;
  5684. this.g *= s;
  5685. this.b *= s;
  5686. return this;
  5687. }
  5688. lerp( color, alpha ) {
  5689. this.r += ( color.r - this.r ) * alpha;
  5690. this.g += ( color.g - this.g ) * alpha;
  5691. this.b += ( color.b - this.b ) * alpha;
  5692. return this;
  5693. }
  5694. lerpHSL( color, alpha ) {
  5695. this.getHSL( _hslA );
  5696. color.getHSL( _hslB );
  5697. const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  5698. const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  5699. const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  5700. this.setHSL( h, s, l );
  5701. return this;
  5702. }
  5703. equals( c ) {
  5704. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5705. }
  5706. fromArray( array, offset = 0 ) {
  5707. this.r = array[ offset ];
  5708. this.g = array[ offset + 1 ];
  5709. this.b = array[ offset + 2 ];
  5710. return this;
  5711. }
  5712. toArray( array = [], offset = 0 ) {
  5713. array[ offset ] = this.r;
  5714. array[ offset + 1 ] = this.g;
  5715. array[ offset + 2 ] = this.b;
  5716. return array;
  5717. }
  5718. fromBufferAttribute( attribute, index ) {
  5719. this.r = attribute.getX( index );
  5720. this.g = attribute.getY( index );
  5721. this.b = attribute.getZ( index );
  5722. if ( attribute.normalized === true ) {
  5723. // assuming Uint8Array
  5724. this.r /= 255;
  5725. this.g /= 255;
  5726. this.b /= 255;
  5727. }
  5728. return this;
  5729. }
  5730. toJSON() {
  5731. return this.getHex();
  5732. }
  5733. }
  5734. Color.NAMES = _colorKeywords;
  5735. Color.prototype.r = 1;
  5736. Color.prototype.g = 1;
  5737. Color.prototype.b = 1;
  5738. class Face3 {
  5739. constructor( a, b, c, normal, color, materialIndex = 0 ) {
  5740. this.a = a;
  5741. this.b = b;
  5742. this.c = c;
  5743. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  5744. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5745. this.color = ( color && color.isColor ) ? color : new Color();
  5746. this.vertexColors = Array.isArray( color ) ? color : [];
  5747. this.materialIndex = materialIndex;
  5748. }
  5749. clone() {
  5750. return new this.constructor().copy( this );
  5751. }
  5752. copy( source ) {
  5753. this.a = source.a;
  5754. this.b = source.b;
  5755. this.c = source.c;
  5756. this.normal.copy( source.normal );
  5757. this.color.copy( source.color );
  5758. this.materialIndex = source.materialIndex;
  5759. for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5760. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5761. }
  5762. for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5763. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5764. }
  5765. return this;
  5766. }
  5767. }
  5768. let materialId = 0;
  5769. function Material() {
  5770. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5771. this.uuid = MathUtils.generateUUID();
  5772. this.name = '';
  5773. this.type = 'Material';
  5774. this.fog = true;
  5775. this.blending = NormalBlending;
  5776. this.side = FrontSide;
  5777. this.flatShading = false;
  5778. this.vertexColors = false;
  5779. this.opacity = 1;
  5780. this.transparent = false;
  5781. this.blendSrc = SrcAlphaFactor;
  5782. this.blendDst = OneMinusSrcAlphaFactor;
  5783. this.blendEquation = AddEquation;
  5784. this.blendSrcAlpha = null;
  5785. this.blendDstAlpha = null;
  5786. this.blendEquationAlpha = null;
  5787. this.depthFunc = LessEqualDepth;
  5788. this.depthTest = true;
  5789. this.depthWrite = true;
  5790. this.stencilWriteMask = 0xff;
  5791. this.stencilFunc = AlwaysStencilFunc;
  5792. this.stencilRef = 0;
  5793. this.stencilFuncMask = 0xff;
  5794. this.stencilFail = KeepStencilOp;
  5795. this.stencilZFail = KeepStencilOp;
  5796. this.stencilZPass = KeepStencilOp;
  5797. this.stencilWrite = false;
  5798. this.clippingPlanes = null;
  5799. this.clipIntersection = false;
  5800. this.clipShadows = false;
  5801. this.shadowSide = null;
  5802. this.colorWrite = true;
  5803. this.precision = null; // override the renderer's default precision for this material
  5804. this.polygonOffset = false;
  5805. this.polygonOffsetFactor = 0;
  5806. this.polygonOffsetUnits = 0;
  5807. this.dithering = false;
  5808. this.alphaTest = 0;
  5809. this.premultipliedAlpha = false;
  5810. this.visible = true;
  5811. this.toneMapped = true;
  5812. this.userData = {};
  5813. this.version = 0;
  5814. }
  5815. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5816. constructor: Material,
  5817. isMaterial: true,
  5818. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  5819. customProgramCacheKey: function () {
  5820. return this.onBeforeCompile.toString();
  5821. },
  5822. setValues: function ( values ) {
  5823. if ( values === undefined ) return;
  5824. for ( const key in values ) {
  5825. const newValue = values[ key ];
  5826. if ( newValue === undefined ) {
  5827. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5828. continue;
  5829. }
  5830. // for backward compatability if shading is set in the constructor
  5831. if ( key === 'shading' ) {
  5832. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5833. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5834. continue;
  5835. }
  5836. const currentValue = this[ key ];
  5837. if ( currentValue === undefined ) {
  5838. //console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5839. continue;
  5840. }
  5841. if ( currentValue && currentValue.isColor ) {
  5842. currentValue.set( newValue );
  5843. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5844. currentValue.copy( newValue );
  5845. } else {
  5846. this[ key ] = newValue;
  5847. }
  5848. }
  5849. },
  5850. toJSON: function ( meta ) {
  5851. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5852. if ( isRoot ) {
  5853. meta = {
  5854. textures: {},
  5855. images: {}
  5856. };
  5857. }
  5858. const data = {
  5859. metadata: {
  5860. version: 4.5,
  5861. type: 'Material',
  5862. generator: 'Material.toJSON'
  5863. }
  5864. };
  5865. // standard Material serialization
  5866. data.uuid = this.uuid;
  5867. data.type = this.type;
  5868. if ( this.name !== '' ) data.name = this.name;
  5869. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5870. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5871. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5872. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  5873. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5874. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5875. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5876. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5877. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5878. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5879. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5880. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5881. }
  5882. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5883. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5884. }
  5885. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5886. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5887. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5888. }
  5889. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5890. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5891. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5892. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5893. if ( this.aoMap && this.aoMap.isTexture ) {
  5894. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5895. data.aoMapIntensity = this.aoMapIntensity;
  5896. }
  5897. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5898. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5899. data.bumpScale = this.bumpScale;
  5900. }
  5901. if ( this.normalMap && this.normalMap.isTexture ) {
  5902. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5903. data.normalMapType = this.normalMapType;
  5904. data.normalScale = this.normalScale.toArray();
  5905. }
  5906. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5907. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5908. data.displacementScale = this.displacementScale;
  5909. data.displacementBias = this.displacementBias;
  5910. }
  5911. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5912. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5913. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5914. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5915. if ( this.envMap && this.envMap.isTexture ) {
  5916. data.envMap = this.envMap.toJSON( meta ).uuid;
  5917. data.reflectivity = this.reflectivity; // Scale behind envMap
  5918. data.refractionRatio = this.refractionRatio;
  5919. if ( this.combine !== undefined ) data.combine = this.combine;
  5920. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5921. }
  5922. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5923. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5924. }
  5925. if ( this.size !== undefined ) data.size = this.size;
  5926. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5927. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5928. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5929. if ( this.side !== FrontSide ) data.side = this.side;
  5930. if ( this.vertexColors ) data.vertexColors = true;
  5931. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5932. if ( this.transparent === true ) data.transparent = this.transparent;
  5933. data.depthFunc = this.depthFunc;
  5934. data.depthTest = this.depthTest;
  5935. data.depthWrite = this.depthWrite;
  5936. data.stencilWrite = this.stencilWrite;
  5937. data.stencilWriteMask = this.stencilWriteMask;
  5938. data.stencilFunc = this.stencilFunc;
  5939. data.stencilRef = this.stencilRef;
  5940. data.stencilFuncMask = this.stencilFuncMask;
  5941. data.stencilFail = this.stencilFail;
  5942. data.stencilZFail = this.stencilZFail;
  5943. data.stencilZPass = this.stencilZPass;
  5944. // rotation (SpriteMaterial)
  5945. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5946. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5947. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5948. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5949. if ( this.lineWidth && this.lineWidth !== 1 ) data.lineWidth = this.lineWidth;
  5950. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5951. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5952. if ( this.scale !== undefined ) data.scale = this.scale;
  5953. if ( this.dithering === true ) data.dithering = true;
  5954. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5955. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5956. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5957. if ( this.wireframelineWidth > 1 ) data.wireframelineWidth = this.wireframelineWidth;
  5958. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5959. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5960. if ( this.morphTargets === true ) data.morphTargets = true;
  5961. if ( this.morphNormals === true ) data.morphNormals = true;
  5962. if ( this.skinning === true ) data.skinning = true;
  5963. if ( this.visible === false ) data.visible = false;
  5964. if ( this.toneMapped === false ) data.toneMapped = false;
  5965. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5966. // TODO: Copied from Object3D.toJSON
  5967. function extractFromCache( cache ) {
  5968. const values = [];
  5969. for ( const key in cache ) {
  5970. const data = cache[ key ];
  5971. delete data.metadata;
  5972. values.push( data );
  5973. }
  5974. return values;
  5975. }
  5976. if ( isRoot ) {
  5977. const textures = extractFromCache( meta.textures );
  5978. const images = extractFromCache( meta.images );
  5979. if ( textures.length > 0 ) data.textures = textures;
  5980. if ( images.length > 0 ) data.images = images;
  5981. }
  5982. return data;
  5983. },
  5984. clone: function () {
  5985. return new this.constructor().copy( this );
  5986. },
  5987. copy: function ( source ) {
  5988. this.name = source.name;
  5989. this.fog = source.fog;
  5990. this.blending = source.blending;
  5991. this.side = source.side;
  5992. this.flatShading = source.flatShading;
  5993. this.vertexColors = source.vertexColors;
  5994. this.opacity = source.opacity;
  5995. this.transparent = source.transparent;
  5996. this.blendSrc = source.blendSrc;
  5997. this.blendDst = source.blendDst;
  5998. this.blendEquation = source.blendEquation;
  5999. this.blendSrcAlpha = source.blendSrcAlpha;
  6000. this.blendDstAlpha = source.blendDstAlpha;
  6001. this.blendEquationAlpha = source.blendEquationAlpha;
  6002. this.depthFunc = source.depthFunc;
  6003. this.depthTest = source.depthTest;
  6004. this.depthWrite = source.depthWrite;
  6005. this.stencilWriteMask = source.stencilWriteMask;
  6006. this.stencilFunc = source.stencilFunc;
  6007. this.stencilRef = source.stencilRef;
  6008. this.stencilFuncMask = source.stencilFuncMask;
  6009. this.stencilFail = source.stencilFail;
  6010. this.stencilZFail = source.stencilZFail;
  6011. this.stencilZPass = source.stencilZPass;
  6012. this.stencilWrite = source.stencilWrite;
  6013. const srcPlanes = source.clippingPlanes;
  6014. let dstPlanes = null;
  6015. if ( srcPlanes !== null ) {
  6016. const n = srcPlanes.length;
  6017. dstPlanes = new Array( n );
  6018. for ( let i = 0; i !== n; ++ i ) {
  6019. dstPlanes[ i ] = srcPlanes[ i ].clone();
  6020. }
  6021. }
  6022. this.clippingPlanes = dstPlanes;
  6023. this.clipIntersection = source.clipIntersection;
  6024. this.clipShadows = source.clipShadows;
  6025. this.shadowSide = source.shadowSide;
  6026. this.colorWrite = source.colorWrite;
  6027. this.precision = source.precision;
  6028. this.polygonOffset = source.polygonOffset;
  6029. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6030. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6031. this.dithering = source.dithering;
  6032. this.alphaTest = source.alphaTest;
  6033. this.premultipliedAlpha = source.premultipliedAlpha;
  6034. this.visible = source.visible;
  6035. this.toneMapped = source.toneMapped;
  6036. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6037. return this;
  6038. },
  6039. dispose: function () {
  6040. this.dispatchEvent( { type: 'dispose' } );
  6041. }
  6042. } );
  6043. Object.defineProperty( Material.prototype, 'needsUpdate', {
  6044. set: function ( value ) {
  6045. if ( value === true ) this.version ++;
  6046. }
  6047. } );
  6048. /**
  6049. * parameters = {
  6050. * color: <hex>,
  6051. * opacity: <float>,
  6052. * map: new THREE.Texture( <Image> ),
  6053. *
  6054. * lightMap: new THREE.Texture( <Image> ),
  6055. * lightMapIntensity: <float>
  6056. *
  6057. * aoMap: new THREE.Texture( <Image> ),
  6058. * aoMapIntensity: <float>
  6059. *
  6060. * specularMap: new THREE.Texture( <Image> ),
  6061. *
  6062. * alphaMap: new THREE.Texture( <Image> ),
  6063. *
  6064. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6065. * combine: THREE.Multiply,
  6066. * reflectivity: <float>,
  6067. * refractionRatio: <float>,
  6068. *
  6069. * depthTest: <bool>,
  6070. * depthWrite: <bool>,
  6071. *
  6072. * wireframe: <boolean>,
  6073. * wireframelineWidth: <float>,
  6074. *
  6075. * skinning: <bool>,
  6076. * morphTargets: <bool>
  6077. * }
  6078. */
  6079. function MeshBasicMaterial( parameters ) {
  6080. Material.call( this );
  6081. this.type = 'MeshBasicMaterial';
  6082. this.color = new Color( 0xffffff ); // emissive
  6083. this.map = null;
  6084. this.lightMap = null;
  6085. this.lightMapIntensity = 1.0;
  6086. this.aoMap = null;
  6087. this.aoMapIntensity = 1.0;
  6088. this.specularMap = null;
  6089. this.alphaMap = null;
  6090. this.envMap = null;
  6091. this.combine = MultiplyOperation;
  6092. this.reflectivity = 1;
  6093. this.refractionRatio = 0.98;
  6094. this.wireframe = false;
  6095. this.wireframelineWidth = 1;
  6096. this.wireframeLinecap = 'round';
  6097. this.wireframeLinejoin = 'round';
  6098. this.skinning = false;
  6099. this.morphTargets = false;
  6100. this.setValues( parameters );
  6101. }
  6102. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  6103. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6104. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6105. MeshBasicMaterial.prototype.copy = function ( source ) {
  6106. Material.prototype.copy.call( this, source );
  6107. this.color.copy( source.color );
  6108. this.map = source.map;
  6109. this.lightMap = source.lightMap;
  6110. this.lightMapIntensity = source.lightMapIntensity;
  6111. this.aoMap = source.aoMap;
  6112. this.aoMapIntensity = source.aoMapIntensity;
  6113. this.specularMap = source.specularMap;
  6114. this.alphaMap = source.alphaMap;
  6115. this.envMap = source.envMap;
  6116. this.combine = source.combine;
  6117. this.reflectivity = source.reflectivity;
  6118. this.refractionRatio = source.refractionRatio;
  6119. this.wireframe = source.wireframe;
  6120. this.wireframelineWidth = source.wireframelineWidth;
  6121. this.wireframeLinecap = source.wireframeLinecap;
  6122. this.wireframeLinejoin = source.wireframeLinejoin;
  6123. this.skinning = source.skinning;
  6124. this.morphTargets = source.morphTargets;
  6125. return this;
  6126. };
  6127. const _vector$3 = new Vector3();
  6128. const _vector2$1 = new Vector2$1();
  6129. function BufferAttribute( array, itemSize, normalized ) {
  6130. if ( Array.isArray( array ) ) {
  6131. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  6132. }
  6133. this.name = '';
  6134. this.array = array;
  6135. this.itemSize = itemSize;
  6136. this.count = array !== undefined ? array.length / itemSize : 0;
  6137. this.normalized = normalized === true;
  6138. this.usage = StaticDrawUsage;
  6139. this.updateRange = { offset: 0, count: - 1 };
  6140. this.version = 0;
  6141. }
  6142. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  6143. set: function ( value ) {
  6144. if ( value === true ) this.version ++;
  6145. }
  6146. } );
  6147. Object.assign( BufferAttribute.prototype, {
  6148. isBufferAttribute: true,
  6149. onUploadCallback: function () {},
  6150. setUsage: function ( value ) {
  6151. this.usage = value;
  6152. return this;
  6153. },
  6154. copy: function ( source ) {
  6155. this.name = source.name;
  6156. this.array = new source.array.constructor( source.array );
  6157. this.itemSize = source.itemSize;
  6158. this.count = source.count;
  6159. this.normalized = source.normalized;
  6160. this.usage = source.usage;
  6161. return this;
  6162. },
  6163. copyAt: function ( index1, attribute, index2 ) {
  6164. index1 *= this.itemSize;
  6165. index2 *= attribute.itemSize;
  6166. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6167. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6168. }
  6169. return this;
  6170. },
  6171. copyArray: function ( array ) {
  6172. this.array.set( array );
  6173. return this;
  6174. },
  6175. copyColorsArray: function ( colors ) {
  6176. const array = this.array;
  6177. let offset = 0;
  6178. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  6179. let color = colors[ i ];
  6180. if ( color === undefined ) {
  6181. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  6182. color = new Color();
  6183. }
  6184. array[ offset ++ ] = color.r;
  6185. array[ offset ++ ] = color.g;
  6186. array[ offset ++ ] = color.b;
  6187. }
  6188. return this;
  6189. },
  6190. copyVector2sArray: function ( vectors ) {
  6191. const array = this.array;
  6192. let offset = 0;
  6193. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6194. let vector = vectors[ i ];
  6195. if ( vector === undefined ) {
  6196. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  6197. vector = new Vector2$1();
  6198. }
  6199. array[ offset ++ ] = vector.x;
  6200. array[ offset ++ ] = vector.y;
  6201. }
  6202. return this;
  6203. },
  6204. copyVector3sArray: function ( vectors ) {
  6205. const array = this.array;
  6206. let offset = 0;
  6207. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6208. let vector = vectors[ i ];
  6209. if ( vector === undefined ) {
  6210. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  6211. vector = new Vector3();
  6212. }
  6213. array[ offset ++ ] = vector.x;
  6214. array[ offset ++ ] = vector.y;
  6215. array[ offset ++ ] = vector.z;
  6216. }
  6217. return this;
  6218. },
  6219. copyVector4sArray: function ( vectors ) {
  6220. const array = this.array;
  6221. let offset = 0;
  6222. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6223. let vector = vectors[ i ];
  6224. if ( vector === undefined ) {
  6225. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  6226. vector = new Vector4();
  6227. }
  6228. array[ offset ++ ] = vector.x;
  6229. array[ offset ++ ] = vector.y;
  6230. array[ offset ++ ] = vector.z;
  6231. array[ offset ++ ] = vector.w;
  6232. }
  6233. return this;
  6234. },
  6235. applyMatrix3: function ( m ) {
  6236. if ( this.itemSize === 2 ) {
  6237. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6238. _vector2$1.fromBufferAttribute( this, i );
  6239. _vector2$1.applyMatrix3( m );
  6240. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6241. }
  6242. } else if ( this.itemSize === 3 ) {
  6243. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6244. _vector$3.fromBufferAttribute( this, i );
  6245. _vector$3.applyMatrix3( m );
  6246. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6247. }
  6248. }
  6249. return this;
  6250. },
  6251. applyMatrix4: function ( m ) {
  6252. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6253. _vector$3.x = this.getX( i );
  6254. _vector$3.y = this.getY( i );
  6255. _vector$3.z = this.getZ( i );
  6256. _vector$3.applyMatrix4( m );
  6257. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6258. }
  6259. return this;
  6260. },
  6261. applyNormalMatrix: function ( m ) {
  6262. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6263. _vector$3.x = this.getX( i );
  6264. _vector$3.y = this.getY( i );
  6265. _vector$3.z = this.getZ( i );
  6266. _vector$3.applyNormalMatrix( m );
  6267. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6268. }
  6269. return this;
  6270. },
  6271. transformDirection: function ( m ) {
  6272. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6273. _vector$3.x = this.getX( i );
  6274. _vector$3.y = this.getY( i );
  6275. _vector$3.z = this.getZ( i );
  6276. _vector$3.transformDirection( m );
  6277. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6278. }
  6279. return this;
  6280. },
  6281. set: function ( value, offset = 0 ) {
  6282. this.array.set( value, offset );
  6283. return this;
  6284. },
  6285. getX: function ( index ) {
  6286. return this.array[ index * this.itemSize ];
  6287. },
  6288. setX: function ( index, x ) {
  6289. this.array[ index * this.itemSize ] = x;
  6290. return this;
  6291. },
  6292. getY: function ( index ) {
  6293. return this.array[ index * this.itemSize + 1 ];
  6294. },
  6295. setY: function ( index, y ) {
  6296. this.array[ index * this.itemSize + 1 ] = y;
  6297. return this;
  6298. },
  6299. getZ: function ( index ) {
  6300. return this.array[ index * this.itemSize + 2 ];
  6301. },
  6302. setZ: function ( index, z ) {
  6303. this.array[ index * this.itemSize + 2 ] = z;
  6304. return this;
  6305. },
  6306. getW: function ( index ) {
  6307. return this.array[ index * this.itemSize + 3 ];
  6308. },
  6309. setW: function ( index, w ) {
  6310. this.array[ index * this.itemSize + 3 ] = w;
  6311. return this;
  6312. },
  6313. setXY: function ( index, x, y ) {
  6314. index *= this.itemSize;
  6315. this.array[ index + 0 ] = x;
  6316. this.array[ index + 1 ] = y;
  6317. return this;
  6318. },
  6319. setXYZ: function ( index, x, y, z ) {
  6320. index *= this.itemSize;
  6321. this.array[ index + 0 ] = x;
  6322. this.array[ index + 1 ] = y;
  6323. this.array[ index + 2 ] = z;
  6324. return this;
  6325. },
  6326. setXYZW: function ( index, x, y, z, w ) {
  6327. index *= this.itemSize;
  6328. this.array[ index + 0 ] = x;
  6329. this.array[ index + 1 ] = y;
  6330. this.array[ index + 2 ] = z;
  6331. this.array[ index + 3 ] = w;
  6332. return this;
  6333. },
  6334. onUpload: function ( callback ) {
  6335. this.onUploadCallback = callback;
  6336. return this;
  6337. },
  6338. clone: function () {
  6339. return new this.constructor( this.array, this.itemSize ).copy( this );
  6340. },
  6341. toJSON: function () {
  6342. return {
  6343. itemSize: this.itemSize,
  6344. type: this.array.constructor.name,
  6345. array: Array.prototype.slice.call( this.array ),
  6346. normalized: this.normalized
  6347. };
  6348. }
  6349. } );
  6350. //
  6351. function Int8BufferAttribute( array, itemSize, normalized ) {
  6352. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  6353. }
  6354. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6355. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6356. function Uint8BufferAttribute( array, itemSize, normalized ) {
  6357. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  6358. }
  6359. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6360. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6361. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  6362. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  6363. }
  6364. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6365. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6366. function Int16BufferAttribute( array, itemSize, normalized ) {
  6367. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  6368. }
  6369. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6370. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6371. function Uint16BufferAttribute( array, itemSize, normalized ) {
  6372. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  6373. }
  6374. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6375. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6376. function Int32BufferAttribute( array, itemSize, normalized ) {
  6377. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  6378. }
  6379. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6380. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6381. function Uint32BufferAttribute( array, itemSize, normalized ) {
  6382. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  6383. }
  6384. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6385. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6386. function Float16BufferAttribute( array, itemSize, normalized ) {
  6387. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  6388. }
  6389. Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6390. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  6391. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6392. function Float32BufferAttribute( array, itemSize, normalized ) {
  6393. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  6394. }
  6395. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6396. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6397. function Float64BufferAttribute( array, itemSize, normalized ) {
  6398. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  6399. }
  6400. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6401. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6402. class DirectGeometry {
  6403. constructor() {
  6404. this.vertices = [];
  6405. this.normals = [];
  6406. this.colors = [];
  6407. this.uvs = [];
  6408. this.uvs2 = [];
  6409. this.groups = [];
  6410. this.morphTargets = {};
  6411. this.skinWeights = [];
  6412. this.skinIndices = [];
  6413. // this.lineDistances = [];
  6414. this.boundingBox = null;
  6415. this.boundingSphere = null;
  6416. // update flags
  6417. this.verticesNeedUpdate = false;
  6418. this.normalsNeedUpdate = false;
  6419. this.colorsNeedUpdate = false;
  6420. this.uvsNeedUpdate = false;
  6421. this.groupsNeedUpdate = false;
  6422. }
  6423. computeGroups( geometry ) {
  6424. const groups = [];
  6425. let group, i;
  6426. let materialIndex = undefined;
  6427. const faces = geometry.faces;
  6428. for ( i = 0; i < faces.length; i ++ ) {
  6429. const face = faces[ i ];
  6430. // materials
  6431. if ( face.materialIndex !== materialIndex ) {
  6432. materialIndex = face.materialIndex;
  6433. if ( group !== undefined ) {
  6434. group.count = ( i * 3 ) - group.start;
  6435. groups.push( group );
  6436. }
  6437. group = {
  6438. start: i * 3,
  6439. materialIndex: materialIndex
  6440. };
  6441. }
  6442. }
  6443. if ( group !== undefined ) {
  6444. group.count = ( i * 3 ) - group.start;
  6445. groups.push( group );
  6446. }
  6447. this.groups = groups;
  6448. }
  6449. fromGeometry( geometry ) {
  6450. const faces = geometry.faces;
  6451. const vertices = geometry.vertices;
  6452. const faceVertexUvs = geometry.faceVertexUvs;
  6453. const hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6454. const hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6455. // morphs
  6456. const morphTargets = geometry.morphTargets;
  6457. const morphTargetsLength = morphTargets.length;
  6458. let morphTargetsPosition;
  6459. if ( morphTargetsLength > 0 ) {
  6460. morphTargetsPosition = [];
  6461. for ( let i = 0; i < morphTargetsLength; i ++ ) {
  6462. morphTargetsPosition[ i ] = {
  6463. name: morphTargets[ i ].name,
  6464. data: []
  6465. };
  6466. }
  6467. this.morphTargets.position = morphTargetsPosition;
  6468. }
  6469. const morphNormals = geometry.morphNormals;
  6470. const morphNormalsLength = morphNormals.length;
  6471. let morphTargetsNormal;
  6472. if ( morphNormalsLength > 0 ) {
  6473. morphTargetsNormal = [];
  6474. for ( let i = 0; i < morphNormalsLength; i ++ ) {
  6475. morphTargetsNormal[ i ] = {
  6476. name: morphNormals[ i ].name,
  6477. data: []
  6478. };
  6479. }
  6480. this.morphTargets.normal = morphTargetsNormal;
  6481. }
  6482. // skins
  6483. const skinIndices = geometry.skinIndices;
  6484. const skinWeights = geometry.skinWeights;
  6485. const hasSkinIndices = skinIndices.length === vertices.length;
  6486. const hasSkinWeights = skinWeights.length === vertices.length;
  6487. //
  6488. if ( vertices.length > 0 && faces.length === 0 ) {
  6489. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  6490. }
  6491. for ( let i = 0; i < faces.length; i ++ ) {
  6492. const face = faces[ i ];
  6493. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6494. const vertexNormals = face.vertexNormals;
  6495. if ( vertexNormals.length === 3 ) {
  6496. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6497. } else {
  6498. const normal = face.normal;
  6499. this.normals.push( normal, normal, normal );
  6500. }
  6501. const vertexColors = face.vertexColors;
  6502. if ( vertexColors.length === 3 ) {
  6503. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6504. } else {
  6505. const color = face.color;
  6506. this.colors.push( color, color, color );
  6507. }
  6508. if ( hasFaceVertexUv === true ) {
  6509. const vertexUvs = faceVertexUvs[ 0 ][ i ];
  6510. if ( vertexUvs !== undefined ) {
  6511. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6512. } else {
  6513. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6514. this.uvs.push( new Vector2$1(), new Vector2$1(), new Vector2$1() );
  6515. }
  6516. }
  6517. if ( hasFaceVertexUv2 === true ) {
  6518. const vertexUvs = faceVertexUvs[ 1 ][ i ];
  6519. if ( vertexUvs !== undefined ) {
  6520. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6521. } else {
  6522. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6523. this.uvs2.push( new Vector2$1(), new Vector2$1(), new Vector2$1() );
  6524. }
  6525. }
  6526. // morphs
  6527. for ( let j = 0; j < morphTargetsLength; j ++ ) {
  6528. const morphTarget = morphTargets[ j ].vertices;
  6529. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6530. }
  6531. for ( let j = 0; j < morphNormalsLength; j ++ ) {
  6532. const morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6533. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  6534. }
  6535. // skins
  6536. if ( hasSkinIndices ) {
  6537. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6538. }
  6539. if ( hasSkinWeights ) {
  6540. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6541. }
  6542. }
  6543. this.computeGroups( geometry );
  6544. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6545. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6546. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6547. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6548. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6549. if ( geometry.boundingSphere !== null ) {
  6550. this.boundingSphere = geometry.boundingSphere.clone();
  6551. }
  6552. if ( geometry.boundingBox !== null ) {
  6553. this.boundingBox = geometry.boundingBox.clone();
  6554. }
  6555. return this;
  6556. }
  6557. }
  6558. function arrayMax( array ) {
  6559. if ( array.length === 0 ) return - Infinity;
  6560. let max = array[ 0 ];
  6561. for ( let i = 1, l = array.length; i < l; ++ i ) {
  6562. if ( array[ i ] > max ) max = array[ i ];
  6563. }
  6564. return max;
  6565. }
  6566. const TYPED_ARRAYS = {
  6567. Int8Array: Int8Array,
  6568. Uint8Array: Uint8Array,
  6569. // Workaround for IE11 pre KB2929437. See #11440
  6570. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  6571. Int16Array: Int16Array,
  6572. Uint16Array: Uint16Array,
  6573. Int32Array: Int32Array,
  6574. Uint32Array: Uint32Array,
  6575. Float32Array: Float32Array,
  6576. Float64Array: Float64Array
  6577. };
  6578. function getTypedArray( type, buffer ) {
  6579. return new TYPED_ARRAYS[ type ]( buffer );
  6580. }
  6581. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6582. const _m1$2 = new Matrix4();
  6583. const _obj = new Object3D();
  6584. const _offset = new Vector3();
  6585. const _box$2 = new Box3();
  6586. const _boxMorphTargets = new Box3();
  6587. const _vector$4 = new Vector3();
  6588. function BufferGeometry() {
  6589. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  6590. this.uuid = MathUtils.generateUUID();
  6591. this.name = '';
  6592. this.type = 'BufferGeometry';
  6593. this.index = null;
  6594. this.attributes = {};
  6595. this.morphAttributes = {};
  6596. this.morphTargetsRelative = false;
  6597. this.groups = [];
  6598. this.boundingBox = null;
  6599. this.boundingSphere = null;
  6600. this.drawRange = { start: 0, count: Infinity };
  6601. this.userData = {};
  6602. }
  6603. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6604. constructor: BufferGeometry,
  6605. isBufferGeometry: true,
  6606. getIndex: function () {
  6607. return this.index;
  6608. },
  6609. setIndex: function ( index ) {
  6610. if ( Array.isArray( index ) ) {
  6611. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6612. } else {
  6613. this.index = index;
  6614. }
  6615. return this;
  6616. },
  6617. getAttribute: function ( name ) {
  6618. return this.attributes[ name ];
  6619. },
  6620. setAttribute: function ( name, attribute ) {
  6621. this.attributes[ name ] = attribute;
  6622. return this;
  6623. },
  6624. deleteAttribute: function ( name ) {
  6625. delete this.attributes[ name ];
  6626. return this;
  6627. },
  6628. hasAttribute: function ( name ) {
  6629. return this.attributes[ name ] !== undefined;
  6630. },
  6631. addGroup: function ( start, count, materialIndex = 0 ) {
  6632. this.groups.push( {
  6633. start: start,
  6634. count: count,
  6635. materialIndex: materialIndex
  6636. } );
  6637. },
  6638. clearGroups: function () {
  6639. this.groups = [];
  6640. },
  6641. setDrawRange: function ( start, count ) {
  6642. this.drawRange.start = start;
  6643. this.drawRange.count = count;
  6644. },
  6645. applyMatrix4: function ( matrix ) {
  6646. const position = this.attributes.position;
  6647. if ( position !== undefined ) {
  6648. position.applyMatrix4( matrix );
  6649. position.needsUpdate = true;
  6650. }
  6651. const normal = this.attributes.normal;
  6652. if ( normal !== undefined ) {
  6653. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6654. normal.applyNormalMatrix( normalMatrix );
  6655. normal.needsUpdate = true;
  6656. }
  6657. const tangent = this.attributes.tangent;
  6658. if ( tangent !== undefined ) {
  6659. tangent.transformDirection( matrix );
  6660. tangent.needsUpdate = true;
  6661. }
  6662. if ( this.boundingBox !== null ) {
  6663. this.computeBoundingBox();
  6664. }
  6665. if ( this.boundingSphere !== null ) {
  6666. this.computeBoundingSphere();
  6667. }
  6668. return this;
  6669. },
  6670. rotateX: function ( angle ) {
  6671. // rotate geometry around world x-axis
  6672. _m1$2.makeRotationX( angle );
  6673. this.applyMatrix4( _m1$2 );
  6674. return this;
  6675. },
  6676. rotateY: function ( angle ) {
  6677. // rotate geometry around world y-axis
  6678. _m1$2.makeRotationY( angle );
  6679. this.applyMatrix4( _m1$2 );
  6680. return this;
  6681. },
  6682. rotateZ: function ( angle ) {
  6683. // rotate geometry around world z-axis
  6684. _m1$2.makeRotationZ( angle );
  6685. this.applyMatrix4( _m1$2 );
  6686. return this;
  6687. },
  6688. translate: function ( x, y, z ) {
  6689. // translate geometry
  6690. _m1$2.makeTranslation( x, y, z );
  6691. this.applyMatrix4( _m1$2 );
  6692. return this;
  6693. },
  6694. scale: function ( x, y, z ) {
  6695. // scale geometry
  6696. _m1$2.makeScale( x, y, z );
  6697. this.applyMatrix4( _m1$2 );
  6698. return this;
  6699. },
  6700. lookAt: function ( vector ) {
  6701. _obj.lookAt( vector );
  6702. _obj.updateMatrix();
  6703. this.applyMatrix4( _obj.matrix );
  6704. return this;
  6705. },
  6706. center: function () {
  6707. this.computeBoundingBox();
  6708. this.boundingBox.getCenter( _offset ).negate();
  6709. this.translate( _offset.x, _offset.y, _offset.z );
  6710. return this;
  6711. },
  6712. setFromObject: function ( object ) {
  6713. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6714. const geometry = object.geometry;
  6715. if ( object.isPoints || object.isLine ) {
  6716. const positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  6717. const colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  6718. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6719. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6720. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6721. const lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  6722. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6723. }
  6724. if ( geometry.boundingSphere !== null ) {
  6725. this.boundingSphere = geometry.boundingSphere.clone();
  6726. }
  6727. if ( geometry.boundingBox !== null ) {
  6728. this.boundingBox = geometry.boundingBox.clone();
  6729. }
  6730. } else if ( object.isMesh ) {
  6731. if ( geometry && geometry.isGeometry ) {
  6732. this.fromGeometry( geometry );
  6733. }
  6734. }
  6735. return this;
  6736. },
  6737. setFromPoints: function ( points ) {
  6738. const position = [];
  6739. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6740. const point = points[ i ];
  6741. position.push( point.x, point.y, point.z || 0 );
  6742. }
  6743. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6744. return this;
  6745. },
  6746. updateFromObject: function ( object ) {
  6747. let geometry = object.geometry;
  6748. if ( object.isMesh ) {
  6749. let direct = geometry.__directGeometry;
  6750. if ( geometry.elementsNeedUpdate === true ) {
  6751. direct = undefined;
  6752. geometry.elementsNeedUpdate = false;
  6753. }
  6754. if ( direct === undefined ) {
  6755. return this.fromGeometry( geometry );
  6756. }
  6757. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6758. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6759. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6760. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6761. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6762. geometry.verticesNeedUpdate = false;
  6763. geometry.normalsNeedUpdate = false;
  6764. geometry.colorsNeedUpdate = false;
  6765. geometry.uvsNeedUpdate = false;
  6766. geometry.groupsNeedUpdate = false;
  6767. geometry = direct;
  6768. }
  6769. if ( geometry.verticesNeedUpdate === true ) {
  6770. const attribute = this.attributes.position;
  6771. if ( attribute !== undefined ) {
  6772. attribute.copyVector3sArray( geometry.vertices );
  6773. attribute.needsUpdate = true;
  6774. }
  6775. geometry.verticesNeedUpdate = false;
  6776. }
  6777. if ( geometry.normalsNeedUpdate === true ) {
  6778. const attribute = this.attributes.normal;
  6779. if ( attribute !== undefined ) {
  6780. attribute.copyVector3sArray( geometry.normals );
  6781. attribute.needsUpdate = true;
  6782. }
  6783. geometry.normalsNeedUpdate = false;
  6784. }
  6785. if ( geometry.colorsNeedUpdate === true ) {
  6786. const attribute = this.attributes.color;
  6787. if ( attribute !== undefined ) {
  6788. attribute.copyColorsArray( geometry.colors );
  6789. attribute.needsUpdate = true;
  6790. }
  6791. geometry.colorsNeedUpdate = false;
  6792. }
  6793. if ( geometry.uvsNeedUpdate ) {
  6794. const attribute = this.attributes.uv;
  6795. if ( attribute !== undefined ) {
  6796. attribute.copyVector2sArray( geometry.uvs );
  6797. attribute.needsUpdate = true;
  6798. }
  6799. geometry.uvsNeedUpdate = false;
  6800. }
  6801. if ( geometry.lineDistancesNeedUpdate ) {
  6802. const attribute = this.attributes.lineDistance;
  6803. if ( attribute !== undefined ) {
  6804. attribute.copyArray( geometry.lineDistances );
  6805. attribute.needsUpdate = true;
  6806. }
  6807. geometry.lineDistancesNeedUpdate = false;
  6808. }
  6809. if ( geometry.groupsNeedUpdate ) {
  6810. geometry.computeGroups( object.geometry );
  6811. this.groups = geometry.groups;
  6812. geometry.groupsNeedUpdate = false;
  6813. }
  6814. return this;
  6815. },
  6816. fromGeometry: function ( geometry ) {
  6817. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  6818. return this.fromDirectGeometry( geometry.__directGeometry );
  6819. },
  6820. fromDirectGeometry: function ( geometry ) {
  6821. const positions = new Float32Array( geometry.vertices.length * 3 );
  6822. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6823. if ( geometry.normals.length > 0 ) {
  6824. const normals = new Float32Array( geometry.normals.length * 3 );
  6825. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6826. }
  6827. if ( geometry.colors.length > 0 ) {
  6828. const colors = new Float32Array( geometry.colors.length * 3 );
  6829. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6830. }
  6831. if ( geometry.uvs.length > 0 ) {
  6832. const uvs = new Float32Array( geometry.uvs.length * 2 );
  6833. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6834. }
  6835. if ( geometry.uvs2.length > 0 ) {
  6836. const uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6837. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6838. }
  6839. // groups
  6840. this.groups = geometry.groups;
  6841. // morphs
  6842. for ( const name in geometry.morphTargets ) {
  6843. const array = [];
  6844. const morphTargets = geometry.morphTargets[ name ];
  6845. for ( let i = 0, l = morphTargets.length; i < l; i ++ ) {
  6846. const morphTarget = morphTargets[ i ];
  6847. const attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  6848. attribute.name = morphTarget.name;
  6849. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  6850. }
  6851. this.morphAttributes[ name ] = array;
  6852. }
  6853. // skinning
  6854. if ( geometry.skinIndices.length > 0 ) {
  6855. const skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  6856. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6857. }
  6858. if ( geometry.skinWeights.length > 0 ) {
  6859. const skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  6860. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6861. }
  6862. //
  6863. if ( geometry.boundingSphere !== null ) {
  6864. this.boundingSphere = geometry.boundingSphere.clone();
  6865. }
  6866. if ( geometry.boundingBox !== null ) {
  6867. this.boundingBox = geometry.boundingBox.clone();
  6868. }
  6869. return this;
  6870. },
  6871. computeBoundingBox: function () {
  6872. if ( this.boundingBox === null ) {
  6873. this.boundingBox = new Box3();
  6874. }
  6875. const position = this.attributes.position;
  6876. const morphAttributesPosition = this.morphAttributes.position;
  6877. if ( position && position.isGLBufferAttribute ) {
  6878. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6879. this.boundingBox.set(
  6880. new Vector3( - Infinity, - Infinity, - Infinity ),
  6881. new Vector3( + Infinity, + Infinity, + Infinity )
  6882. );
  6883. return;
  6884. }
  6885. if ( position !== undefined ) {
  6886. this.boundingBox.setFromBufferAttribute( position );
  6887. // process morph attributes if present
  6888. if ( morphAttributesPosition ) {
  6889. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6890. const morphAttribute = morphAttributesPosition[ i ];
  6891. _box$2.setFromBufferAttribute( morphAttribute );
  6892. if ( this.morphTargetsRelative ) {
  6893. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  6894. this.boundingBox.expandByPoint( _vector$4 );
  6895. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  6896. this.boundingBox.expandByPoint( _vector$4 );
  6897. } else {
  6898. this.boundingBox.expandByPoint( _box$2.min );
  6899. this.boundingBox.expandByPoint( _box$2.max );
  6900. }
  6901. }
  6902. }
  6903. } else {
  6904. this.boundingBox.makeEmpty();
  6905. }
  6906. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6907. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6908. }
  6909. },
  6910. computeBoundingSphere: function () {
  6911. if ( this.boundingSphere === null ) {
  6912. this.boundingSphere = new Sphere();
  6913. }
  6914. const position = this.attributes.position;
  6915. const morphAttributesPosition = this.morphAttributes.position;
  6916. if ( position && position.isGLBufferAttribute ) {
  6917. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6918. this.boundingSphere.set( new Vector3(), Infinity );
  6919. return;
  6920. }
  6921. if ( position ) {
  6922. // first, find the center of the bounding sphere
  6923. const center = this.boundingSphere.center;
  6924. _box$2.setFromBufferAttribute( position );
  6925. // process morph attributes if present
  6926. if ( morphAttributesPosition ) {
  6927. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6928. const morphAttribute = morphAttributesPosition[ i ];
  6929. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6930. if ( this.morphTargetsRelative ) {
  6931. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  6932. _box$2.expandByPoint( _vector$4 );
  6933. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  6934. _box$2.expandByPoint( _vector$4 );
  6935. } else {
  6936. _box$2.expandByPoint( _boxMorphTargets.min );
  6937. _box$2.expandByPoint( _boxMorphTargets.max );
  6938. }
  6939. }
  6940. }
  6941. _box$2.getCenter( center );
  6942. // second, try to find a boundingSphere with a radius smaller than the
  6943. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6944. let maxRadiusSq = 0;
  6945. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6946. _vector$4.fromBufferAttribute( position, i );
  6947. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6948. }
  6949. // process morph attributes if present
  6950. if ( morphAttributesPosition ) {
  6951. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6952. const morphAttribute = morphAttributesPosition[ i ];
  6953. const morphTargetsRelative = this.morphTargetsRelative;
  6954. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6955. _vector$4.fromBufferAttribute( morphAttribute, j );
  6956. if ( morphTargetsRelative ) {
  6957. _offset.fromBufferAttribute( position, j );
  6958. _vector$4.add( _offset );
  6959. }
  6960. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6961. }
  6962. }
  6963. }
  6964. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6965. if ( isNaN( this.boundingSphere.radius ) ) {
  6966. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6967. }
  6968. }
  6969. },
  6970. computeFaceNormals: function () {
  6971. // backwards compatibility
  6972. },
  6973. computeVertexNormals: function () {
  6974. const index = this.index;
  6975. const positionAttribute = this.getAttribute( 'position' );
  6976. if ( positionAttribute !== undefined ) {
  6977. let normalAttribute = this.getAttribute( 'normal' );
  6978. if ( normalAttribute === undefined ) {
  6979. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6980. this.setAttribute( 'normal', normalAttribute );
  6981. } else {
  6982. // reset existing normals to zero
  6983. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6984. normalAttribute.setXYZ( i, 0, 0, 0 );
  6985. }
  6986. }
  6987. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6988. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6989. const cb = new Vector3(), ab = new Vector3();
  6990. // indexed elements
  6991. if ( index ) {
  6992. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6993. const vA = index.getX( i + 0 );
  6994. const vB = index.getX( i + 1 );
  6995. const vC = index.getX( i + 2 );
  6996. pA.fromBufferAttribute( positionAttribute, vA );
  6997. pB.fromBufferAttribute( positionAttribute, vB );
  6998. pC.fromBufferAttribute( positionAttribute, vC );
  6999. cb.subVectors( pC, pB );
  7000. ab.subVectors( pA, pB );
  7001. cb.cross( ab );
  7002. nA.fromBufferAttribute( normalAttribute, vA );
  7003. nB.fromBufferAttribute( normalAttribute, vB );
  7004. nC.fromBufferAttribute( normalAttribute, vC );
  7005. nA.add( cb );
  7006. nB.add( cb );
  7007. nC.add( cb );
  7008. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  7009. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  7010. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  7011. }
  7012. } else {
  7013. // non-indexed elements (unconnected triangle soup)
  7014. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  7015. pA.fromBufferAttribute( positionAttribute, i + 0 );
  7016. pB.fromBufferAttribute( positionAttribute, i + 1 );
  7017. pC.fromBufferAttribute( positionAttribute, i + 2 );
  7018. cb.subVectors( pC, pB );
  7019. ab.subVectors( pA, pB );
  7020. cb.cross( ab );
  7021. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  7022. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  7023. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  7024. }
  7025. }
  7026. this.normalizeNormals();
  7027. normalAttribute.needsUpdate = true;
  7028. }
  7029. },
  7030. merge: function ( geometry, offset ) {
  7031. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  7032. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7033. return;
  7034. }
  7035. if ( offset === undefined ) {
  7036. offset = 0;
  7037. console.warn(
  7038. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  7039. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  7040. );
  7041. }
  7042. const attributes = this.attributes;
  7043. for ( const key in attributes ) {
  7044. if ( geometry.attributes[ key ] === undefined ) continue;
  7045. const attribute1 = attributes[ key ];
  7046. const attributeArray1 = attribute1.array;
  7047. const attribute2 = geometry.attributes[ key ];
  7048. const attributeArray2 = attribute2.array;
  7049. const attributeOffset = attribute2.itemSize * offset;
  7050. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  7051. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  7052. attributeArray1[ j ] = attributeArray2[ i ];
  7053. }
  7054. }
  7055. return this;
  7056. },
  7057. normalizeNormals: function () {
  7058. const normals = this.attributes.normal;
  7059. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  7060. _vector$4.fromBufferAttribute( normals, i );
  7061. _vector$4.normalize();
  7062. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  7063. }
  7064. },
  7065. toNonIndexed: function () {
  7066. function convertBufferAttribute( attribute, indices ) {
  7067. const array = attribute.array;
  7068. const itemSize = attribute.itemSize;
  7069. const normalized = attribute.normalized;
  7070. const array2 = new array.constructor( indices.length * itemSize );
  7071. let index = 0, index2 = 0;
  7072. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  7073. index = indices[ i ] * itemSize;
  7074. for ( let j = 0; j < itemSize; j ++ ) {
  7075. array2[ index2 ++ ] = array[ index ++ ];
  7076. }
  7077. }
  7078. return new BufferAttribute( array2, itemSize, normalized );
  7079. }
  7080. //
  7081. if ( this.index === null ) {
  7082. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7083. return this;
  7084. }
  7085. const geometry2 = new BufferGeometry();
  7086. const indices = this.index.array;
  7087. const attributes = this.attributes;
  7088. // attributes
  7089. for ( const name in attributes ) {
  7090. const attribute = attributes[ name ];
  7091. const newAttribute = convertBufferAttribute( attribute, indices );
  7092. geometry2.setAttribute( name, newAttribute );
  7093. }
  7094. // morph attributes
  7095. const morphAttributes = this.morphAttributes;
  7096. for ( const name in morphAttributes ) {
  7097. const morphArray = [];
  7098. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7099. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  7100. const attribute = morphAttribute[ i ];
  7101. const newAttribute = convertBufferAttribute( attribute, indices );
  7102. morphArray.push( newAttribute );
  7103. }
  7104. geometry2.morphAttributes[ name ] = morphArray;
  7105. }
  7106. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  7107. // groups
  7108. const groups = this.groups;
  7109. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7110. const group = groups[ i ];
  7111. geometry2.addGroup( group.start, group.count, group.materialIndex );
  7112. }
  7113. return geometry2;
  7114. },
  7115. toJSON: function () {
  7116. const data = {
  7117. metadata: {
  7118. version: 4.5,
  7119. type: 'BufferGeometry',
  7120. generator: 'BufferGeometry.toJSON'
  7121. }
  7122. };
  7123. // standard BufferGeometry serialization
  7124. data.uuid = this.uuid;
  7125. data.type = this.type;
  7126. if ( this.name !== '' ) data.name = this.name;
  7127. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7128. if ( this.parameters !== undefined ) {
  7129. const parameters = this.parameters;
  7130. for ( const key in parameters ) {
  7131. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7132. }
  7133. return data;
  7134. }
  7135. data.data = { attributes: {} };
  7136. const index = this.index;
  7137. if ( index !== null ) {
  7138. data.data.index = {
  7139. type: index.array.constructor.name,
  7140. array: Array.prototype.slice.call( index.array )
  7141. };
  7142. }
  7143. const attributes = this.attributes;
  7144. for ( const key in attributes ) {
  7145. const attribute = attributes[ key ];
  7146. const attributeData = attribute.toJSON( data.data );
  7147. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  7148. data.data.attributes[ key ] = attributeData;
  7149. }
  7150. const morphAttributes = {};
  7151. let hasMorphAttributes = false;
  7152. for ( const key in this.morphAttributes ) {
  7153. const attributeArray = this.morphAttributes[ key ];
  7154. const array = [];
  7155. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  7156. const attribute = attributeArray[ i ];
  7157. const attributeData = attribute.toJSON( data.data );
  7158. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  7159. array.push( attributeData );
  7160. }
  7161. if ( array.length > 0 ) {
  7162. morphAttributes[ key ] = array;
  7163. hasMorphAttributes = true;
  7164. }
  7165. }
  7166. if ( hasMorphAttributes ) {
  7167. data.data.morphAttributes = morphAttributes;
  7168. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7169. }
  7170. const groups = this.groups;
  7171. if ( groups.length > 0 ) {
  7172. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7173. }
  7174. const boundingSphere = this.boundingSphere;
  7175. if ( boundingSphere !== null ) {
  7176. data.data.boundingSphere = {
  7177. center: boundingSphere.center.toArray(),
  7178. radius: boundingSphere.radius
  7179. };
  7180. }
  7181. return data;
  7182. },
  7183. clone: function () {
  7184. /*
  7185. // Handle primitives
  7186. const parameters = this.parameters;
  7187. if ( parameters !== undefined ) {
  7188. const values = [];
  7189. for ( const key in parameters ) {
  7190. values.push( parameters[ key ] );
  7191. }
  7192. const geometry = Object.create( this.constructor.prototype );
  7193. this.constructor.apply( geometry, values );
  7194. return geometry;
  7195. }
  7196. return new this.constructor().copy( this );
  7197. */
  7198. return new BufferGeometry().copy( this );
  7199. },
  7200. copy: function ( source ) {
  7201. // reset
  7202. this.index = null;
  7203. this.attributes = {};
  7204. this.morphAttributes = {};
  7205. this.groups = [];
  7206. this.boundingBox = null;
  7207. this.boundingSphere = null;
  7208. // used for storing cloned, shared data
  7209. const data = {};
  7210. // name
  7211. this.name = source.name;
  7212. // index
  7213. const index = source.index;
  7214. if ( index !== null ) {
  7215. this.setIndex( index.clone( data ) );
  7216. }
  7217. // attributes
  7218. const attributes = source.attributes;
  7219. for ( const name in attributes ) {
  7220. const attribute = attributes[ name ];
  7221. this.setAttribute( name, attribute.clone( data ) );
  7222. }
  7223. // morph attributes
  7224. const morphAttributes = source.morphAttributes;
  7225. for ( const name in morphAttributes ) {
  7226. const array = [];
  7227. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7228. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  7229. array.push( morphAttribute[ i ].clone( data ) );
  7230. }
  7231. this.morphAttributes[ name ] = array;
  7232. }
  7233. this.morphTargetsRelative = source.morphTargetsRelative;
  7234. // groups
  7235. const groups = source.groups;
  7236. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7237. const group = groups[ i ];
  7238. this.addGroup( group.start, group.count, group.materialIndex );
  7239. }
  7240. // bounding box
  7241. const boundingBox = source.boundingBox;
  7242. if ( boundingBox !== null ) {
  7243. this.boundingBox = boundingBox.clone();
  7244. }
  7245. // bounding sphere
  7246. const boundingSphere = source.boundingSphere;
  7247. if ( boundingSphere !== null ) {
  7248. this.boundingSphere = boundingSphere.clone();
  7249. }
  7250. // draw range
  7251. this.drawRange.start = source.drawRange.start;
  7252. this.drawRange.count = source.drawRange.count;
  7253. // user data
  7254. this.userData = source.userData;
  7255. return this;
  7256. },
  7257. dispose: function () {
  7258. this.dispatchEvent( { type: 'dispose' } );
  7259. }
  7260. } );
  7261. const _inverseMatrix = new Matrix4();
  7262. const _ray = new Ray();
  7263. const _sphere = new Sphere();
  7264. const _vA = new Vector3();
  7265. const _vB = new Vector3();
  7266. const _vC = new Vector3();
  7267. const _tempA = new Vector3();
  7268. const _tempB = new Vector3();
  7269. const _tempC = new Vector3();
  7270. const _morphA = new Vector3();
  7271. const _morphB = new Vector3();
  7272. const _morphC = new Vector3();
  7273. const _uvA = new Vector2$1();
  7274. const _uvB = new Vector2$1();
  7275. const _uvC = new Vector2$1();
  7276. const _intersectionPoint = new Vector3();
  7277. const _intersectionPointWorld = new Vector3();
  7278. function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  7279. Object3D.call( this );
  7280. this.type = 'Mesh';
  7281. this.geometry = geometry;
  7282. this.material = material;
  7283. this.updateMorphTargets();
  7284. }
  7285. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7286. constructor: Mesh,
  7287. isMesh: true,
  7288. copy: function ( source ) {
  7289. Object3D.prototype.copy.call( this, source );
  7290. if ( source.morphTargetInfluences !== undefined ) {
  7291. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7292. }
  7293. if ( source.morphTargetDictionary !== undefined ) {
  7294. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  7295. }
  7296. this.material = source.material;
  7297. this.geometry = source.geometry;
  7298. return this;
  7299. },
  7300. updateMorphTargets: function () {
  7301. const geometry = this.geometry;
  7302. if ( geometry.isBufferGeometry ) {
  7303. const morphAttributes = geometry.morphAttributes;
  7304. const keys = Object.keys( morphAttributes );
  7305. if ( keys.length > 0 ) {
  7306. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  7307. if ( morphAttribute !== undefined ) {
  7308. this.morphTargetInfluences = [];
  7309. this.morphTargetDictionary = {};
  7310. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  7311. const name = morphAttribute[ m ].name || String( m );
  7312. this.morphTargetInfluences.push( 0 );
  7313. this.morphTargetDictionary[ name ] = m;
  7314. }
  7315. }
  7316. }
  7317. } else {
  7318. const morphTargets = geometry.morphTargets;
  7319. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  7320. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7321. }
  7322. }
  7323. },
  7324. raycast: function ( raycaster, intersects ) {
  7325. const geometry = this.geometry;
  7326. const material = this.material;
  7327. const matrixWorld = this.matrixWorld;
  7328. if ( material === undefined ) return;
  7329. // Checking boundingSphere distance to ray
  7330. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7331. _sphere.copy( geometry.boundingSphere );
  7332. _sphere.applyMatrix4( matrixWorld );
  7333. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  7334. //
  7335. _inverseMatrix.copy( matrixWorld ).invert();
  7336. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  7337. // Check boundingBox before continuing
  7338. if ( geometry.boundingBox !== null ) {
  7339. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
  7340. }
  7341. let intersection;
  7342. if ( geometry.isBufferGeometry ) {
  7343. const index = geometry.index;
  7344. const position = geometry.attributes.position;
  7345. const morphPosition = geometry.morphAttributes.position;
  7346. const morphTargetsRelative = geometry.morphTargetsRelative;
  7347. const uv = geometry.attributes.uv;
  7348. const uv2 = geometry.attributes.uv2;
  7349. const groups = geometry.groups;
  7350. const drawRange = geometry.drawRange;
  7351. if ( index !== null ) {
  7352. // indexed buffer geometry
  7353. if ( Array.isArray( material ) ) {
  7354. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7355. const group = groups[ i ];
  7356. const groupMaterial = material[ group.materialIndex ];
  7357. const start = Math.max( group.start, drawRange.start );
  7358. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7359. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7360. const a = index.getX( j );
  7361. const b = index.getX( j + 1 );
  7362. const c = index.getX( j + 2 );
  7363. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7364. if ( intersection ) {
  7365. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7366. intersection.face.materialIndex = group.materialIndex;
  7367. intersects.push( intersection );
  7368. }
  7369. }
  7370. }
  7371. } else {
  7372. const start = Math.max( 0, drawRange.start );
  7373. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7374. for ( let i = start, il = end; i < il; i += 3 ) {
  7375. const a = index.getX( i );
  7376. const b = index.getX( i + 1 );
  7377. const c = index.getX( i + 2 );
  7378. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7379. if ( intersection ) {
  7380. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7381. intersects.push( intersection );
  7382. }
  7383. }
  7384. }
  7385. } else if ( position !== undefined ) {
  7386. // non-indexed buffer geometry
  7387. if ( Array.isArray( material ) ) {
  7388. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7389. const group = groups[ i ];
  7390. const groupMaterial = material[ group.materialIndex ];
  7391. const start = Math.max( group.start, drawRange.start );
  7392. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7393. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7394. const a = j;
  7395. const b = j + 1;
  7396. const c = j + 2;
  7397. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7398. if ( intersection ) {
  7399. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7400. intersection.face.materialIndex = group.materialIndex;
  7401. intersects.push( intersection );
  7402. }
  7403. }
  7404. }
  7405. } else {
  7406. const start = Math.max( 0, drawRange.start );
  7407. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7408. for ( let i = start, il = end; i < il; i += 3 ) {
  7409. const a = i;
  7410. const b = i + 1;
  7411. const c = i + 2;
  7412. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7413. if ( intersection ) {
  7414. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7415. intersects.push( intersection );
  7416. }
  7417. }
  7418. }
  7419. }
  7420. } else if ( geometry.isGeometry ) {
  7421. const isMultiMaterial = Array.isArray( material );
  7422. const vertices = geometry.vertices;
  7423. const faces = geometry.faces;
  7424. let uvs;
  7425. const faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  7426. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  7427. for ( let f = 0, fl = faces.length; f < fl; f ++ ) {
  7428. const face = faces[ f ];
  7429. const faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  7430. if ( faceMaterial === undefined ) continue;
  7431. const fvA = vertices[ face.a ];
  7432. const fvB = vertices[ face.b ];
  7433. const fvC = vertices[ face.c ];
  7434. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  7435. if ( intersection ) {
  7436. if ( uvs && uvs[ f ] ) {
  7437. const uvs_f = uvs[ f ];
  7438. _uvA.copy( uvs_f[ 0 ] );
  7439. _uvB.copy( uvs_f[ 1 ] );
  7440. _uvC.copy( uvs_f[ 2 ] );
  7441. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2$1() );
  7442. }
  7443. intersection.face = face;
  7444. intersection.faceIndex = f;
  7445. intersects.push( intersection );
  7446. }
  7447. }
  7448. }
  7449. }
  7450. } );
  7451. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7452. let intersect;
  7453. if ( material.side === BackSide ) {
  7454. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7455. } else {
  7456. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  7457. }
  7458. if ( intersect === null ) return null;
  7459. _intersectionPointWorld.copy( point );
  7460. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7461. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7462. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7463. return {
  7464. distance: distance,
  7465. point: _intersectionPointWorld.clone(),
  7466. object: object
  7467. };
  7468. }
  7469. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  7470. _vA.fromBufferAttribute( position, a );
  7471. _vB.fromBufferAttribute( position, b );
  7472. _vC.fromBufferAttribute( position, c );
  7473. const morphInfluences = object.morphTargetInfluences;
  7474. if ( material.morphTargets && morphPosition && morphInfluences ) {
  7475. _morphA.set( 0, 0, 0 );
  7476. _morphB.set( 0, 0, 0 );
  7477. _morphC.set( 0, 0, 0 );
  7478. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  7479. const influence = morphInfluences[ i ];
  7480. const morphAttribute = morphPosition[ i ];
  7481. if ( influence === 0 ) continue;
  7482. _tempA.fromBufferAttribute( morphAttribute, a );
  7483. _tempB.fromBufferAttribute( morphAttribute, b );
  7484. _tempC.fromBufferAttribute( morphAttribute, c );
  7485. if ( morphTargetsRelative ) {
  7486. _morphA.addScaledVector( _tempA, influence );
  7487. _morphB.addScaledVector( _tempB, influence );
  7488. _morphC.addScaledVector( _tempC, influence );
  7489. } else {
  7490. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  7491. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  7492. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  7493. }
  7494. }
  7495. _vA.add( _morphA );
  7496. _vB.add( _morphB );
  7497. _vC.add( _morphC );
  7498. }
  7499. if ( object.isSkinnedMesh ) {
  7500. object.boneTransform( a, _vA );
  7501. object.boneTransform( b, _vB );
  7502. object.boneTransform( c, _vC );
  7503. }
  7504. const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  7505. if ( intersection ) {
  7506. if ( uv ) {
  7507. _uvA.fromBufferAttribute( uv, a );
  7508. _uvB.fromBufferAttribute( uv, b );
  7509. _uvC.fromBufferAttribute( uv, c );
  7510. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2$1() );
  7511. }
  7512. if ( uv2 ) {
  7513. _uvA.fromBufferAttribute( uv2, a );
  7514. _uvB.fromBufferAttribute( uv2, b );
  7515. _uvC.fromBufferAttribute( uv2, c );
  7516. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2$1() );
  7517. }
  7518. const face = new Face3( a, b, c );
  7519. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  7520. intersection.face = face;
  7521. }
  7522. return intersection;
  7523. }
  7524. class BoxBufferGeometry extends BufferGeometry {
  7525. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7526. super();
  7527. this.type = 'BoxBufferGeometry';
  7528. this.parameters = {
  7529. width: width,
  7530. height: height,
  7531. depth: depth,
  7532. widthSegments: widthSegments,
  7533. heightSegments: heightSegments,
  7534. depthSegments: depthSegments
  7535. };
  7536. const scope = this;
  7537. // segments
  7538. widthSegments = Math.floor( widthSegments );
  7539. heightSegments = Math.floor( heightSegments );
  7540. depthSegments = Math.floor( depthSegments );
  7541. // buffers
  7542. const indices = [];
  7543. const vertices = [];
  7544. const normals = [];
  7545. const uvs = [];
  7546. // helper variables
  7547. let numberOfVertices = 0;
  7548. let groupStart = 0;
  7549. // build each side of the box geometry
  7550. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7551. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7552. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7553. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7554. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7555. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7556. // build geometry
  7557. this.setIndex( indices );
  7558. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7559. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7560. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7561. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7562. const segmentWidth = width / gridX;
  7563. const segmentHeight = height / gridY;
  7564. const widthHalf = width / 2;
  7565. const heightHalf = height / 2;
  7566. const depthHalf = depth / 2;
  7567. const gridX1 = gridX + 1;
  7568. const gridY1 = gridY + 1;
  7569. let vertexCounter = 0;
  7570. let groupCount = 0;
  7571. const vector = new Vector3();
  7572. // generate vertices, normals and uvs
  7573. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7574. const y = iy * segmentHeight - heightHalf;
  7575. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7576. const x = ix * segmentWidth - widthHalf;
  7577. // set values to correct vector component
  7578. vector[ u ] = x * udir;
  7579. vector[ v ] = y * vdir;
  7580. vector[ w ] = depthHalf;
  7581. // now apply vector to vertex buffer
  7582. vertices.push( vector.x, vector.y, vector.z );
  7583. // set values to correct vector component
  7584. vector[ u ] = 0;
  7585. vector[ v ] = 0;
  7586. vector[ w ] = depth > 0 ? 1 : - 1;
  7587. // now apply vector to normal buffer
  7588. normals.push( vector.x, vector.y, vector.z );
  7589. // uvs
  7590. uvs.push( ix / gridX );
  7591. uvs.push( 1 - ( iy / gridY ) );
  7592. // counters
  7593. vertexCounter += 1;
  7594. }
  7595. }
  7596. // indices
  7597. // 1. you need three indices to draw a single face
  7598. // 2. a single segment consists of two faces
  7599. // 3. so we need to generate six (2*3) indices per segment
  7600. for ( let iy = 0; iy < gridY; iy ++ ) {
  7601. for ( let ix = 0; ix < gridX; ix ++ ) {
  7602. const a = numberOfVertices + ix + gridX1 * iy;
  7603. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7604. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7605. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7606. // faces
  7607. indices.push( a, b, d );
  7608. indices.push( b, c, d );
  7609. // increase counter
  7610. groupCount += 6;
  7611. }
  7612. }
  7613. // add a group to the geometry. this will ensure multi material support
  7614. scope.addGroup( groupStart, groupCount, materialIndex );
  7615. // calculate new start value for groups
  7616. groupStart += groupCount;
  7617. // update total number of vertices
  7618. numberOfVertices += vertexCounter;
  7619. }
  7620. }
  7621. }
  7622. /**
  7623. * Uniform Utilities
  7624. */
  7625. function cloneUniforms( src ) {
  7626. const dst = {};
  7627. for ( const u in src ) {
  7628. dst[ u ] = {};
  7629. for ( const p in src[ u ] ) {
  7630. const property = src[ u ][ p ];
  7631. if ( property && ( property.isColor ||
  7632. property.isMatrix3 || property.isMatrix4 ||
  7633. property.isVector2 || property.isVector3 || property.isVector4 ||
  7634. property.isTexture ) ) {
  7635. dst[ u ][ p ] = property.clone();
  7636. } else if ( Array.isArray( property ) ) {
  7637. dst[ u ][ p ] = property.slice();
  7638. } else {
  7639. dst[ u ][ p ] = property;
  7640. }
  7641. }
  7642. }
  7643. return dst;
  7644. }
  7645. function mergeUniforms( uniforms ) {
  7646. const merged = {};
  7647. for ( let u = 0; u < uniforms.length; u ++ ) {
  7648. const tmp = cloneUniforms( uniforms[ u ] );
  7649. for ( const p in tmp ) {
  7650. merged[ p ] = tmp[ p ];
  7651. }
  7652. }
  7653. return merged;
  7654. }
  7655. // Legacy
  7656. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7657. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7658. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7659. /**
  7660. * parameters = {
  7661. * defines: { "label" : "value" },
  7662. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7663. *
  7664. * fragmentShader: <string>,
  7665. * vertexShader: <string>,
  7666. *
  7667. * wireframe: <boolean>,
  7668. * wireframelineWidth: <float>,
  7669. *
  7670. * lights: <bool>,
  7671. *
  7672. * skinning: <bool>,
  7673. * morphTargets: <bool>,
  7674. * morphNormals: <bool>
  7675. * }
  7676. */
  7677. function ShaderMaterial( parameters ) {
  7678. Material.call( this );
  7679. this.type = 'ShaderMaterial';
  7680. this.defines = {};
  7681. this.uniforms = {};
  7682. this.vertexShader = default_vertex;
  7683. this.fragmentShader = default_fragment;
  7684. this.lineWidth = 1;
  7685. this.wireframe = false;
  7686. this.wireframelineWidth = 1;
  7687. this.fog = false; // set to use scene fog
  7688. this.lights = false; // set to use scene lights
  7689. this.clipping = false; // set to use user-defined clipping planes
  7690. this.skinning = false; // set to use skinning attribute streams
  7691. this.morphTargets = false; // set to use morph targets
  7692. this.morphNormals = false; // set to use morph normals
  7693. this.extensions = {
  7694. derivatives: false, // set to use derivatives
  7695. fragDepth: false, // set to use fragment depth values
  7696. drawBuffers: false, // set to use draw buffers
  7697. shaderTextureLOD: false // set to use shader texture LOD
  7698. };
  7699. // When rendered geometry doesn't include these attributes but the material does,
  7700. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7701. this.defaultAttributeValues = {
  7702. 'color': [ 1, 1, 1 ],
  7703. 'uv': [ 0, 0 ],
  7704. 'uv2': [ 0, 0 ]
  7705. };
  7706. this.index0AttributeName = undefined;
  7707. this.uniformsNeedUpdate = false;
  7708. this.glslVersion = null;
  7709. if ( parameters !== undefined ) {
  7710. if ( parameters.attributes !== undefined ) {
  7711. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  7712. }
  7713. this.setValues( parameters );
  7714. }
  7715. }
  7716. ShaderMaterial.prototype = Object.create( Material.prototype );
  7717. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7718. ShaderMaterial.prototype.isShaderMaterial = true;
  7719. ShaderMaterial.prototype.copy = function ( source ) {
  7720. Material.prototype.copy.call( this, source );
  7721. this.fragmentShader = source.fragmentShader;
  7722. this.vertexShader = source.vertexShader;
  7723. this.uniforms = cloneUniforms( source.uniforms );
  7724. this.defines = Object.assign( {}, source.defines );
  7725. this.wireframe = source.wireframe;
  7726. this.wireframelineWidth = source.wireframelineWidth;
  7727. this.lights = source.lights;
  7728. this.clipping = source.clipping;
  7729. this.skinning = source.skinning;
  7730. this.morphTargets = source.morphTargets;
  7731. this.morphNormals = source.morphNormals;
  7732. this.extensions = Object.assign( {}, source.extensions );
  7733. this.glslVersion = source.glslVersion;
  7734. return this;
  7735. };
  7736. ShaderMaterial.prototype.toJSON = function ( meta ) {
  7737. const data = Material.prototype.toJSON.call( this, meta );
  7738. data.glslVersion = this.glslVersion;
  7739. data.uniforms = {};
  7740. for ( const name in this.uniforms ) {
  7741. const uniform = this.uniforms[ name ];
  7742. const value = uniform.value;
  7743. if ( value && value.isTexture ) {
  7744. data.uniforms[ name ] = {
  7745. type: 't',
  7746. value: value.toJSON( meta ).uuid
  7747. };
  7748. } else if ( value && value.isColor ) {
  7749. data.uniforms[ name ] = {
  7750. type: 'c',
  7751. value: value.getHex()
  7752. };
  7753. } else if ( value && value.isVector2 ) {
  7754. data.uniforms[ name ] = {
  7755. type: 'v2',
  7756. value: value.toArray()
  7757. };
  7758. } else if ( value && value.isVector3 ) {
  7759. data.uniforms[ name ] = {
  7760. type: 'v3',
  7761. value: value.toArray()
  7762. };
  7763. } else if ( value && value.isVector4 ) {
  7764. data.uniforms[ name ] = {
  7765. type: 'v4',
  7766. value: value.toArray()
  7767. };
  7768. } else if ( value && value.isMatrix3 ) {
  7769. data.uniforms[ name ] = {
  7770. type: 'm3',
  7771. value: value.toArray()
  7772. };
  7773. } else if ( value && value.isMatrix4 ) {
  7774. data.uniforms[ name ] = {
  7775. type: 'm4',
  7776. value: value.toArray()
  7777. };
  7778. } else {
  7779. data.uniforms[ name ] = {
  7780. value: value
  7781. };
  7782. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7783. }
  7784. }
  7785. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7786. data.vertexShader = this.vertexShader;
  7787. data.fragmentShader = this.fragmentShader;
  7788. const extensions = {};
  7789. for ( const key in this.extensions ) {
  7790. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7791. }
  7792. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7793. return data;
  7794. };
  7795. function Camera() {
  7796. Object3D.call( this );
  7797. this.type = 'Camera';
  7798. this.matrixWorldInverse = new Matrix4();
  7799. this.projectionMatrix = new Matrix4();
  7800. this.projectionMatrixInverse = new Matrix4();
  7801. }
  7802. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7803. constructor: Camera,
  7804. isCamera: true,
  7805. copy: function ( source, recursive ) {
  7806. Object3D.prototype.copy.call( this, source, recursive );
  7807. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7808. this.projectionMatrix.copy( source.projectionMatrix );
  7809. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7810. return this;
  7811. },
  7812. getWorldDirection: function ( target ) {
  7813. if ( target === undefined ) {
  7814. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  7815. target = new Vector3();
  7816. }
  7817. this.updateWorldMatrix( true, false );
  7818. const e = this.matrixWorld.elements;
  7819. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7820. },
  7821. updateMatrixWorld: function ( force ) {
  7822. Object3D.prototype.updateMatrixWorld.call( this, force );
  7823. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7824. },
  7825. updateWorldMatrix: function ( updateParents, updateChildren ) {
  7826. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  7827. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7828. },
  7829. clone: function () {
  7830. return new this.constructor().copy( this );
  7831. }
  7832. } );
  7833. function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7834. Camera.call( this );
  7835. this.type = 'PerspectiveCamera';
  7836. this.fov = fov;
  7837. this.zoom = 1;
  7838. this.near = near;
  7839. this.far = far;
  7840. this.focus = 10;
  7841. this.aspect = aspect;
  7842. this.view = null;
  7843. this.filmGauge = 35; // width of the film (default in millimeters)
  7844. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7845. this.updateProjectionMatrix();
  7846. }
  7847. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  7848. constructor: PerspectiveCamera,
  7849. isPerspectiveCamera: true,
  7850. copy: function ( source, recursive ) {
  7851. Camera.prototype.copy.call( this, source, recursive );
  7852. this.fov = source.fov;
  7853. this.zoom = source.zoom;
  7854. this.near = source.near;
  7855. this.far = source.far;
  7856. this.focus = source.focus;
  7857. this.aspect = source.aspect;
  7858. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7859. this.filmGauge = source.filmGauge;
  7860. this.filmOffset = source.filmOffset;
  7861. return this;
  7862. },
  7863. /**
  7864. * Sets the FOV by focal length in respect to the current .filmGauge.
  7865. *
  7866. * The default film gauge is 35, so that the focal length can be specified for
  7867. * a 35mm (full frame) camera.
  7868. *
  7869. * Values for focal length and film gauge must have the same unit.
  7870. */
  7871. setFocalLength: function ( focalLength ) {
  7872. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7873. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7874. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  7875. this.updateProjectionMatrix();
  7876. },
  7877. /**
  7878. * Calculates the focal length from the current .fov and .filmGauge.
  7879. */
  7880. getFocalLength: function () {
  7881. const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  7882. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7883. },
  7884. getEffectiveFOV: function () {
  7885. return MathUtils.RAD2DEG * 2 * Math.atan(
  7886. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7887. },
  7888. getFilmWidth: function () {
  7889. // film not completely covered in portrait format (aspect < 1)
  7890. return this.filmGauge * Math.min( this.aspect, 1 );
  7891. },
  7892. getFilmHeight: function () {
  7893. // film not completely covered in landscape format (aspect > 1)
  7894. return this.filmGauge / Math.max( this.aspect, 1 );
  7895. },
  7896. /**
  7897. * Sets an offset in a larger frustum. This is useful for multi-window or
  7898. * multi-monitor/multi-machine setups.
  7899. *
  7900. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7901. * the monitors are in grid like this
  7902. *
  7903. * +---+---+---+
  7904. * | A | B | C |
  7905. * +---+---+---+
  7906. * | D | E | F |
  7907. * +---+---+---+
  7908. *
  7909. * then for each monitor you would call it like this
  7910. *
  7911. * const w = 1920;
  7912. * const h = 1080;
  7913. * const fullWidth = w * 3;
  7914. * const fullHeight = h * 2;
  7915. *
  7916. * --A--
  7917. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7918. * --B--
  7919. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7920. * --C--
  7921. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7922. * --D--
  7923. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7924. * --E--
  7925. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7926. * --F--
  7927. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7928. *
  7929. * Note there is no reason monitors have to be the same size or in a grid.
  7930. */
  7931. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  7932. this.aspect = fullWidth / fullHeight;
  7933. if ( this.view === null ) {
  7934. this.view = {
  7935. enabled: true,
  7936. fullWidth: 1,
  7937. fullHeight: 1,
  7938. offsetX: 0,
  7939. offsetY: 0,
  7940. width: 1,
  7941. height: 1
  7942. };
  7943. }
  7944. this.view.enabled = true;
  7945. this.view.fullWidth = fullWidth;
  7946. this.view.fullHeight = fullHeight;
  7947. this.view.offsetX = x;
  7948. this.view.offsetY = y;
  7949. this.view.width = width;
  7950. this.view.height = height;
  7951. this.updateProjectionMatrix();
  7952. },
  7953. clearViewOffset: function () {
  7954. if ( this.view !== null ) {
  7955. this.view.enabled = false;
  7956. }
  7957. this.updateProjectionMatrix();
  7958. },
  7959. updateProjectionMatrix: function () {
  7960. const near = this.near;
  7961. let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7962. let height = 2 * top;
  7963. let width = this.aspect * height;
  7964. let left = - 0.5 * width;
  7965. const view = this.view;
  7966. if ( this.view !== null && this.view.enabled ) {
  7967. const fullWidth = view.fullWidth,
  7968. fullHeight = view.fullHeight;
  7969. left += view.offsetX * width / fullWidth;
  7970. top -= view.offsetY * height / fullHeight;
  7971. width *= view.width / fullWidth;
  7972. height *= view.height / fullHeight;
  7973. }
  7974. const skew = this.filmOffset;
  7975. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7976. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7977. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7978. },
  7979. toJSON: function ( meta ) {
  7980. const data = Object3D.prototype.toJSON.call( this, meta );
  7981. data.object.fov = this.fov;
  7982. data.object.zoom = this.zoom;
  7983. data.object.near = this.near;
  7984. data.object.far = this.far;
  7985. data.object.focus = this.focus;
  7986. data.object.aspect = this.aspect;
  7987. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7988. data.object.filmGauge = this.filmGauge;
  7989. data.object.filmOffset = this.filmOffset;
  7990. return data;
  7991. }
  7992. } );
  7993. const fov = 90, aspect = 1;
  7994. function CubeCamera( near, far, renderTarget ) {
  7995. Object3D.call( this );
  7996. this.type = 'CubeCamera';
  7997. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7998. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7999. return;
  8000. }
  8001. this.renderTarget = renderTarget;
  8002. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  8003. cameraPX.layers = this.layers;
  8004. cameraPX.up.set( 0, - 1, 0 );
  8005. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  8006. this.add( cameraPX );
  8007. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  8008. cameraNX.layers = this.layers;
  8009. cameraNX.up.set( 0, - 1, 0 );
  8010. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  8011. this.add( cameraNX );
  8012. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  8013. cameraPY.layers = this.layers;
  8014. cameraPY.up.set( 0, 0, 1 );
  8015. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  8016. this.add( cameraPY );
  8017. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  8018. cameraNY.layers = this.layers;
  8019. cameraNY.up.set( 0, 0, - 1 );
  8020. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  8021. this.add( cameraNY );
  8022. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  8023. cameraPZ.layers = this.layers;
  8024. cameraPZ.up.set( 0, - 1, 0 );
  8025. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  8026. this.add( cameraPZ );
  8027. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  8028. cameraNZ.layers = this.layers;
  8029. cameraNZ.up.set( 0, - 1, 0 );
  8030. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  8031. this.add( cameraNZ );
  8032. this.update = function ( renderer, scene ) {
  8033. if ( this.parent === null ) this.updateMatrixWorld();
  8034. const currentXrEnabled = renderer.xr.enabled;
  8035. const currentRenderTarget = renderer.getRenderTarget();
  8036. renderer.xr.enabled = false;
  8037. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8038. renderTarget.texture.generateMipmaps = false;
  8039. renderer.setRenderTarget( renderTarget, 0 );
  8040. renderer.render( scene, cameraPX );
  8041. renderer.setRenderTarget( renderTarget, 1 );
  8042. renderer.render( scene, cameraNX );
  8043. renderer.setRenderTarget( renderTarget, 2 );
  8044. renderer.render( scene, cameraPY );
  8045. renderer.setRenderTarget( renderTarget, 3 );
  8046. renderer.render( scene, cameraNY );
  8047. renderer.setRenderTarget( renderTarget, 4 );
  8048. renderer.render( scene, cameraPZ );
  8049. renderTarget.texture.generateMipmaps = generateMipmaps;
  8050. renderer.setRenderTarget( renderTarget, 5 );
  8051. renderer.render( scene, cameraNZ );
  8052. renderer.setRenderTarget( currentRenderTarget );
  8053. renderer.xr.enabled = currentXrEnabled;
  8054. };
  8055. }
  8056. CubeCamera.prototype = Object.create( Object3D.prototype );
  8057. CubeCamera.prototype.constructor = CubeCamera;
  8058. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8059. images = images !== undefined ? images : [];
  8060. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8061. format = format !== undefined ? format : RGBFormat;
  8062. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8063. this.flipY = false;
  8064. // Why CubeTexture._needsFlipEnvMap is necessary:
  8065. //
  8066. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8067. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8068. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8069. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8070. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  8071. // when using WebGLCubeRenderTarget.texture as a cube texture.
  8072. this._needsFlipEnvMap = true;
  8073. }
  8074. CubeTexture.prototype = Object.create( Texture.prototype );
  8075. CubeTexture.prototype.constructor = CubeTexture;
  8076. CubeTexture.prototype.isCubeTexture = true;
  8077. Object.defineProperty( CubeTexture.prototype, 'images', {
  8078. get: function () {
  8079. return this.image;
  8080. },
  8081. set: function ( value ) {
  8082. this.image = value;
  8083. }
  8084. } );
  8085. function WebGLCubeRenderTarget( size, options, dummy ) {
  8086. if ( Number.isInteger( options ) ) {
  8087. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  8088. options = dummy;
  8089. }
  8090. WebGLRenderTarget.call( this, size, size, options );
  8091. options = options || {};
  8092. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  8093. this.texture._needsFlipEnvMap = false;
  8094. }
  8095. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  8096. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8097. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8098. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  8099. this.texture.type = texture.type;
  8100. this.texture.format = RGBAFormat; // see #18859
  8101. this.texture.encoding = texture.encoding;
  8102. this.texture.generateMipmaps = texture.generateMipmaps;
  8103. this.texture.minFilter = texture.minFilter;
  8104. this.texture.magFilter = texture.magFilter;
  8105. const shader = {
  8106. uniforms: {
  8107. tEquirect: { value: null },
  8108. },
  8109. vertexShader: /* glsl */`
  8110. varying vec3 vWorldDirection;
  8111. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8112. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8113. }
  8114. void main() {
  8115. vWorldDirection = transformDirection( position, modelMatrix );
  8116. #include <begin_vertex>
  8117. #include <project_vertex>
  8118. }
  8119. `,
  8120. fragmentShader: /* glsl */`
  8121. uniform sampler2D tEquirect;
  8122. varying vec3 vWorldDirection;
  8123. #include <common>
  8124. void main() {
  8125. vec3 direction = normalize( vWorldDirection );
  8126. vec2 sampleUV = equirectUv( direction );
  8127. gl_FragColor = texture2D( tEquirect, sampleUV );
  8128. }
  8129. `
  8130. };
  8131. const geometry = new BoxBufferGeometry( 5, 5, 5 );
  8132. const material = new ShaderMaterial( {
  8133. name: 'CubemapFromEquirect',
  8134. uniforms: cloneUniforms( shader.uniforms ),
  8135. vertexShader: shader.vertexShader,
  8136. fragmentShader: shader.fragmentShader,
  8137. side: BackSide,
  8138. blending: NoBlending
  8139. } );
  8140. material.uniforms.tEquirect.value = texture;
  8141. const mesh = new Mesh( geometry, material );
  8142. const currentMinFilter = texture.minFilter;
  8143. // Avoid blurred poles
  8144. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  8145. const camera = new CubeCamera( 1, 10, this );
  8146. camera.update( renderer, mesh );
  8147. texture.minFilter = currentMinFilter;
  8148. mesh.geometry.dispose();
  8149. mesh.material.dispose();
  8150. return this;
  8151. };
  8152. WebGLCubeRenderTarget.prototype.clear = function ( renderer, color, depth, stencil ) {
  8153. const currentRenderTarget = renderer.getRenderTarget();
  8154. for ( let i = 0; i < 6; i ++ ) {
  8155. renderer.setRenderTarget( this, i );
  8156. renderer.clear( color, depth, stencil );
  8157. }
  8158. renderer.setRenderTarget( currentRenderTarget );
  8159. };
  8160. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  8161. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8162. this.image = { data: data || null, width: width || 1, height: height || 1 };
  8163. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8164. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8165. this.generateMipmaps = false;
  8166. this.flipY = false;
  8167. this.unpackAlignment = 1;
  8168. this.needsUpdate = true;
  8169. }
  8170. DataTexture.prototype = Object.create( Texture.prototype );
  8171. DataTexture.prototype.constructor = DataTexture;
  8172. DataTexture.prototype.isDataTexture = true;
  8173. const _sphere$1 = /*@__PURE__*/ new Sphere();
  8174. const _vector$5 = /*@__PURE__*/ new Vector3();
  8175. class Frustum {
  8176. constructor( p0, p1, p2, p3, p4, p5 ) {
  8177. this.planes = [
  8178. ( p0 !== undefined ) ? p0 : new Plane(),
  8179. ( p1 !== undefined ) ? p1 : new Plane(),
  8180. ( p2 !== undefined ) ? p2 : new Plane(),
  8181. ( p3 !== undefined ) ? p3 : new Plane(),
  8182. ( p4 !== undefined ) ? p4 : new Plane(),
  8183. ( p5 !== undefined ) ? p5 : new Plane()
  8184. ];
  8185. }
  8186. set( p0, p1, p2, p3, p4, p5 ) {
  8187. const planes = this.planes;
  8188. planes[ 0 ].copy( p0 );
  8189. planes[ 1 ].copy( p1 );
  8190. planes[ 2 ].copy( p2 );
  8191. planes[ 3 ].copy( p3 );
  8192. planes[ 4 ].copy( p4 );
  8193. planes[ 5 ].copy( p5 );
  8194. return this;
  8195. }
  8196. clone() {
  8197. return new this.constructor().copy( this );
  8198. }
  8199. copy( frustum ) {
  8200. const planes = this.planes;
  8201. for ( let i = 0; i < 6; i ++ ) {
  8202. planes[ i ].copy( frustum.planes[ i ] );
  8203. }
  8204. return this;
  8205. }
  8206. setFromProjectionMatrix( m ) {
  8207. const planes = this.planes;
  8208. const me = m.elements;
  8209. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8210. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8211. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8212. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8213. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8214. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8215. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8216. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8217. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8218. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8219. return this;
  8220. }
  8221. intersectsObject( object ) {
  8222. const geometry = object.geometry;
  8223. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8224. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8225. return this.intersectsSphere( _sphere$1 );
  8226. }
  8227. intersectsSprite( sprite ) {
  8228. _sphere$1.center.set( 0, 0, 0 );
  8229. _sphere$1.radius = 0.7071067811865476;
  8230. _sphere$1.applyMatrix4( sprite.matrixWorld );
  8231. return this.intersectsSphere( _sphere$1 );
  8232. }
  8233. intersectsSphere( sphere ) {
  8234. const planes = this.planes;
  8235. const center = sphere.center;
  8236. const negRadius = - sphere.radius;
  8237. for ( let i = 0; i < 6; i ++ ) {
  8238. const distance = planes[ i ].distanceToPoint( center );
  8239. if ( distance < negRadius ) {
  8240. return false;
  8241. }
  8242. }
  8243. return true;
  8244. }
  8245. intersectsBox( box ) {
  8246. const planes = this.planes;
  8247. for ( let i = 0; i < 6; i ++ ) {
  8248. const plane = planes[ i ];
  8249. // corner at max distance
  8250. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8251. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8252. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8253. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  8254. return false;
  8255. }
  8256. }
  8257. return true;
  8258. }
  8259. containsPoint( point ) {
  8260. const planes = this.planes;
  8261. for ( let i = 0; i < 6; i ++ ) {
  8262. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8263. return false;
  8264. }
  8265. }
  8266. return true;
  8267. }
  8268. }
  8269. function WebGLAnimation() {
  8270. let context = null;
  8271. let isAnimating = false;
  8272. let animationLoop = null;
  8273. let requestId = null;
  8274. function onAnimationFrame( time, frame ) {
  8275. animationLoop( time, frame );
  8276. requestId = context.requestAnimationFrame( onAnimationFrame );
  8277. }
  8278. return {
  8279. start: function () {
  8280. if ( isAnimating === true ) return;
  8281. if ( animationLoop === null ) return;
  8282. requestId = context.requestAnimationFrame( onAnimationFrame );
  8283. isAnimating = true;
  8284. },
  8285. stop: function () {
  8286. context.cancelAnimationFrame( requestId );
  8287. isAnimating = false;
  8288. },
  8289. setAnimationLoop: function ( callback ) {
  8290. animationLoop = callback;
  8291. },
  8292. setContext: function ( value ) {
  8293. context = value;
  8294. }
  8295. };
  8296. }
  8297. function WebGLAttributes( gl, capabilities ) {
  8298. const isWebGL2 = capabilities.isWebGL2;
  8299. const buffers = new WeakMap();
  8300. function createBuffer( attribute, bufferType ) {
  8301. const array = attribute.array;
  8302. const usage = attribute.usage;
  8303. const buffer = gl.createBuffer();
  8304. gl.bindBuffer( bufferType, buffer );
  8305. gl.bufferData( bufferType, array, usage );
  8306. attribute.onUploadCallback();
  8307. let type = 5126;
  8308. if ( array instanceof Float32Array ) {
  8309. type = 5126;
  8310. } else if ( array instanceof Float64Array ) {
  8311. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8312. } else if ( array instanceof Uint16Array ) {
  8313. if ( attribute.isFloat16BufferAttribute ) {
  8314. if ( isWebGL2 ) {
  8315. type = 5131;
  8316. } else {
  8317. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8318. }
  8319. } else {
  8320. type = 5123;
  8321. }
  8322. } else if ( array instanceof Int16Array ) {
  8323. type = 5122;
  8324. } else if ( array instanceof Uint32Array ) {
  8325. type = 5125;
  8326. } else if ( array instanceof Int32Array ) {
  8327. type = 5124;
  8328. } else if ( array instanceof Int8Array ) {
  8329. type = 5120;
  8330. } else if ( array instanceof Uint8Array ) {
  8331. type = 5121;
  8332. }
  8333. return {
  8334. buffer: buffer,
  8335. type: type,
  8336. bytesPerElement: array.BYTES_PER_ELEMENT,
  8337. version: attribute.version
  8338. };
  8339. }
  8340. function updateBuffer( buffer, attribute, bufferType ) {
  8341. const array = attribute.array;
  8342. const updateRange = attribute.updateRange;
  8343. gl.bindBuffer( bufferType, buffer );
  8344. if ( updateRange.count === - 1 ) {
  8345. // Not using update ranges
  8346. gl.bufferSubData( bufferType, 0, array );
  8347. } else {
  8348. if ( isWebGL2 ) {
  8349. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8350. array, updateRange.offset, updateRange.count );
  8351. } else {
  8352. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8353. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8354. }
  8355. updateRange.count = - 1; // reset range
  8356. }
  8357. }
  8358. //
  8359. function get( attribute ) {
  8360. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8361. return buffers.get( attribute );
  8362. }
  8363. function remove( attribute ) {
  8364. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8365. const data = buffers.get( attribute );
  8366. if ( data ) {
  8367. gl.deleteBuffer( data.buffer );
  8368. buffers.delete( attribute );
  8369. }
  8370. }
  8371. function update( attribute, bufferType ) {
  8372. if ( attribute.isGLBufferAttribute ) {
  8373. const cached = buffers.get( attribute );
  8374. if ( ! cached || cached.version < attribute.version ) {
  8375. buffers.set( attribute, {
  8376. buffer: attribute.buffer,
  8377. type: attribute.type,
  8378. bytesPerElement: attribute.elementSize,
  8379. version: attribute.version
  8380. } );
  8381. }
  8382. return;
  8383. }
  8384. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8385. const data = buffers.get( attribute );
  8386. if ( data === undefined ) {
  8387. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8388. } else if ( data.version < attribute.version ) {
  8389. updateBuffer( data.buffer, attribute, bufferType );
  8390. data.version = attribute.version;
  8391. }
  8392. }
  8393. return {
  8394. get: get,
  8395. remove: remove,
  8396. update: update
  8397. };
  8398. }
  8399. class PlaneBufferGeometry extends BufferGeometry {
  8400. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8401. super();
  8402. this.type = 'PlaneBufferGeometry';
  8403. this.parameters = {
  8404. width: width,
  8405. height: height,
  8406. widthSegments: widthSegments,
  8407. heightSegments: heightSegments
  8408. };
  8409. const width_half = width / 2;
  8410. const height_half = height / 2;
  8411. const gridX = Math.floor( widthSegments );
  8412. const gridY = Math.floor( heightSegments );
  8413. const gridX1 = gridX + 1;
  8414. const gridY1 = gridY + 1;
  8415. const segment_width = width / gridX;
  8416. const segment_height = height / gridY;
  8417. //
  8418. const indices = [];
  8419. const vertices = [];
  8420. const normals = [];
  8421. const uvs = [];
  8422. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8423. const y = iy * segment_height - height_half;
  8424. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8425. const x = ix * segment_width - width_half;
  8426. vertices.push( x, - y, 0 );
  8427. normals.push( 0, 0, 1 );
  8428. uvs.push( ix / gridX );
  8429. uvs.push( 1 - ( iy / gridY ) );
  8430. }
  8431. }
  8432. for ( let iy = 0; iy < gridY; iy ++ ) {
  8433. for ( let ix = 0; ix < gridX; ix ++ ) {
  8434. const a = ix + gridX1 * iy;
  8435. const b = ix + gridX1 * ( iy + 1 );
  8436. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8437. const d = ( ix + 1 ) + gridX1 * iy;
  8438. indices.push( a, b, d );
  8439. indices.push( b, c, d );
  8440. }
  8441. }
  8442. this.setIndex( indices );
  8443. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8444. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8445. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8446. }
  8447. }
  8448. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8449. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8450. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8451. 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";
  8452. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8453. var begin_vertex = "vec3 transformed = vec3( position );";
  8454. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8455. 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";
  8456. 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";
  8457. 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";
  8458. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8459. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8460. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8461. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8462. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8463. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8464. 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";
  8465. 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}";
  8466. 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";
  8467. 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";
  8468. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8469. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8470. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8471. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8472. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8473. 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}";
  8474. 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";
  8475. 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";
  8476. 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";
  8477. 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";
  8478. 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";
  8479. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8480. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8481. 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";
  8482. 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";
  8483. 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}";
  8484. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8485. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8486. 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";
  8487. 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";
  8488. 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";
  8489. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8490. 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)";
  8491. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8492. 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)";
  8493. 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";
  8494. 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}";
  8495. 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";
  8496. 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";
  8497. 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";
  8498. 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";
  8499. 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";
  8500. 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";
  8501. 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";
  8502. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8503. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8504. 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";
  8505. 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";
  8506. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8507. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8508. 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";
  8509. 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";
  8510. 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";
  8511. 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;";
  8512. 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";
  8513. 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";
  8514. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8515. 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";
  8516. 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";
  8517. 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}";
  8518. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8519. 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;";
  8520. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8521. 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";
  8522. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8523. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8524. 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";
  8525. 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";
  8526. 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";
  8527. 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}";
  8528. 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";
  8529. 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";
  8530. 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";
  8531. 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";
  8532. 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";
  8533. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8534. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8535. 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; }";
  8536. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8537. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8538. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8539. 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";
  8540. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8541. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8542. 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";
  8543. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8544. 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";
  8545. 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}";
  8546. 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}";
  8547. 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}";
  8548. 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}";
  8549. 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}";
  8550. 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}";
  8551. 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}";
  8552. 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}";
  8553. 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}";
  8554. 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}";
  8555. 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}";
  8556. 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}";
  8557. 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}";
  8558. 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}";
  8559. 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}";
  8560. 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}";
  8561. 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}";
  8562. 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}";
  8563. 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}";
  8564. 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}";
  8565. 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}";
  8566. 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}";
  8567. 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}";
  8568. 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}";
  8569. 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}";
  8570. 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}";
  8571. 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}";
  8572. 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}";
  8573. 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}";
  8574. 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}";
  8575. 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}";
  8576. 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}";
  8577. const ShaderChunk = {
  8578. alphamap_fragment: alphamap_fragment,
  8579. alphamap_pars_fragment: alphamap_pars_fragment,
  8580. alphatest_fragment: alphatest_fragment,
  8581. aomap_fragment: aomap_fragment,
  8582. aomap_pars_fragment: aomap_pars_fragment,
  8583. begin_vertex: begin_vertex,
  8584. beginnormal_vertex: beginnormal_vertex,
  8585. bsdfs: bsdfs,
  8586. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8587. clipping_planes_fragment: clipping_planes_fragment,
  8588. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8589. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8590. clipping_planes_vertex: clipping_planes_vertex,
  8591. color_fragment: color_fragment,
  8592. color_pars_fragment: color_pars_fragment,
  8593. color_pars_vertex: color_pars_vertex,
  8594. color_vertex: color_vertex,
  8595. common: common,
  8596. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8597. defaultnormal_vertex: defaultnormal_vertex,
  8598. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8599. displacementmap_vertex: displacementmap_vertex,
  8600. emissivemap_fragment: emissivemap_fragment,
  8601. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8602. encodings_fragment: encodings_fragment,
  8603. encodings_pars_fragment: encodings_pars_fragment,
  8604. envmap_fragment: envmap_fragment,
  8605. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8606. envmap_pars_fragment: envmap_pars_fragment,
  8607. envmap_pars_vertex: envmap_pars_vertex,
  8608. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8609. envmap_vertex: envmap_vertex,
  8610. fog_vertex: fog_vertex,
  8611. fog_pars_vertex: fog_pars_vertex,
  8612. fog_fragment: fog_fragment,
  8613. fog_pars_fragment: fog_pars_fragment,
  8614. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8615. lightmap_fragment: lightmap_fragment,
  8616. lightmap_pars_fragment: lightmap_pars_fragment,
  8617. lights_lambert_vertex: lights_lambert_vertex,
  8618. lights_pars_begin: lights_pars_begin,
  8619. lights_toon_fragment: lights_toon_fragment,
  8620. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8621. lights_phong_fragment: lights_phong_fragment,
  8622. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8623. lights_physical_fragment: lights_physical_fragment,
  8624. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8625. lights_fragment_begin: lights_fragment_begin,
  8626. lights_fragment_maps: lights_fragment_maps,
  8627. lights_fragment_end: lights_fragment_end,
  8628. logdepthbuf_fragment: logdepthbuf_fragment,
  8629. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8630. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8631. logdepthbuf_vertex: logdepthbuf_vertex,
  8632. map_fragment: map_fragment,
  8633. map_pars_fragment: map_pars_fragment,
  8634. map_particle_fragment: map_particle_fragment,
  8635. map_particle_pars_fragment: map_particle_pars_fragment,
  8636. metalnessmap_fragment: metalnessmap_fragment,
  8637. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8638. morphnormal_vertex: morphnormal_vertex,
  8639. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8640. morphtarget_vertex: morphtarget_vertex,
  8641. normal_fragment_begin: normal_fragment_begin,
  8642. normal_fragment_maps: normal_fragment_maps,
  8643. normalmap_pars_fragment: normalmap_pars_fragment,
  8644. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8645. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8646. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8647. packing: packing,
  8648. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8649. project_vertex: project_vertex,
  8650. dithering_fragment: dithering_fragment,
  8651. dithering_pars_fragment: dithering_pars_fragment,
  8652. roughnessmap_fragment: roughnessmap_fragment,
  8653. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8654. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8655. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8656. shadowmap_vertex: shadowmap_vertex,
  8657. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8658. skinbase_vertex: skinbase_vertex,
  8659. skinning_pars_vertex: skinning_pars_vertex,
  8660. skinning_vertex: skinning_vertex,
  8661. skinnormal_vertex: skinnormal_vertex,
  8662. specularmap_fragment: specularmap_fragment,
  8663. specularmap_pars_fragment: specularmap_pars_fragment,
  8664. tonemapping_fragment: tonemapping_fragment,
  8665. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8666. transmissionmap_fragment: transmissionmap_fragment,
  8667. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8668. uv_pars_fragment: uv_pars_fragment,
  8669. uv_pars_vertex: uv_pars_vertex,
  8670. uv_vertex: uv_vertex,
  8671. uv2_pars_fragment: uv2_pars_fragment,
  8672. uv2_pars_vertex: uv2_pars_vertex,
  8673. uv2_vertex: uv2_vertex,
  8674. worldpos_vertex: worldpos_vertex,
  8675. background_frag: background_frag,
  8676. background_vert: background_vert,
  8677. cube_frag: cube_frag,
  8678. cube_vert: cube_vert,
  8679. depth_frag: depth_frag,
  8680. depth_vert: depth_vert,
  8681. distanceRGBA_frag: distanceRGBA_frag,
  8682. distanceRGBA_vert: distanceRGBA_vert,
  8683. equirect_frag: equirect_frag,
  8684. equirect_vert: equirect_vert,
  8685. linedashed_frag: linedashed_frag,
  8686. linedashed_vert: linedashed_vert,
  8687. meshbasic_frag: meshbasic_frag,
  8688. meshbasic_vert: meshbasic_vert,
  8689. meshlambert_frag: meshlambert_frag,
  8690. meshlambert_vert: meshlambert_vert,
  8691. meshmatcap_frag: meshmatcap_frag,
  8692. meshmatcap_vert: meshmatcap_vert,
  8693. meshtoon_frag: meshtoon_frag,
  8694. meshtoon_vert: meshtoon_vert,
  8695. meshphong_frag: meshphong_frag,
  8696. meshphong_vert: meshphong_vert,
  8697. meshphysical_frag: meshphysical_frag,
  8698. meshphysical_vert: meshphysical_vert,
  8699. normal_frag: normal_frag,
  8700. normal_vert: normal_vert,
  8701. points_frag: points_frag,
  8702. points_vert: points_vert,
  8703. shadow_frag: shadow_frag,
  8704. shadow_vert: shadow_vert,
  8705. sprite_frag: sprite_frag,
  8706. sprite_vert: sprite_vert
  8707. };
  8708. /**
  8709. * Uniforms library for shared webgl shaders
  8710. */
  8711. const UniformsLib = {
  8712. common: {
  8713. diffuse: { value: new Color( 0xeeeeee ) },
  8714. opacity: { value: 1.0 },
  8715. map: { value: null },
  8716. uvTransform: { value: new Matrix3() },
  8717. uv2Transform: { value: new Matrix3() },
  8718. alphaMap: { value: null },
  8719. },
  8720. specularmap: {
  8721. specularMap: { value: null },
  8722. },
  8723. envmap: {
  8724. envMap: { value: null },
  8725. flipEnvMap: { value: - 1 },
  8726. reflectivity: { value: 1.0 },
  8727. refractionRatio: { value: 0.98 },
  8728. maxMipLevel: { value: 0 }
  8729. },
  8730. aomap: {
  8731. aoMap: { value: null },
  8732. aoMapIntensity: { value: 1 }
  8733. },
  8734. lightmap: {
  8735. lightMap: { value: null },
  8736. lightMapIntensity: { value: 1 }
  8737. },
  8738. emissivemap: {
  8739. emissiveMap: { value: null }
  8740. },
  8741. bumpmap: {
  8742. bumpMap: { value: null },
  8743. bumpScale: { value: 1 }
  8744. },
  8745. normalmap: {
  8746. normalMap: { value: null },
  8747. normalScale: { value: new Vector2$1( 1, 1 ) }
  8748. },
  8749. displacementmap: {
  8750. displacementMap: { value: null },
  8751. displacementScale: { value: 1 },
  8752. displacementBias: { value: 0 }
  8753. },
  8754. roughnessmap: {
  8755. roughnessMap: { value: null }
  8756. },
  8757. metalnessmap: {
  8758. metalnessMap: { value: null }
  8759. },
  8760. gradientmap: {
  8761. gradientMap: { value: null }
  8762. },
  8763. fog: {
  8764. fogDensity: { value: 0.00025 },
  8765. fogNear: { value: 1 },
  8766. fogFar: { value: 2000 },
  8767. fogColor: { value: new Color( 0xffffff ) }
  8768. },
  8769. lights: {
  8770. ambientLightColor: { value: [] },
  8771. lightProbe: { value: [] },
  8772. directionalLights: { value: [], properties: {
  8773. direction: {},
  8774. color: {}
  8775. } },
  8776. directionalLightShadows: { value: [], properties: {
  8777. shadowBias: {},
  8778. shadowNormalBias: {},
  8779. shadowRadius: {},
  8780. shadowMapSize: {}
  8781. } },
  8782. directionalShadowMap: { value: [] },
  8783. directionalShadowMatrix: { value: [] },
  8784. spotLights: { value: [], properties: {
  8785. color: {},
  8786. position: {},
  8787. direction: {},
  8788. distance: {},
  8789. coneCos: {},
  8790. penumbraCos: {},
  8791. decay: {}
  8792. } },
  8793. spotLightShadows: { value: [], properties: {
  8794. shadowBias: {},
  8795. shadowNormalBias: {},
  8796. shadowRadius: {},
  8797. shadowMapSize: {}
  8798. } },
  8799. spotShadowMap: { value: [] },
  8800. spotShadowMatrix: { value: [] },
  8801. pointLights: { value: [], properties: {
  8802. color: {},
  8803. position: {},
  8804. decay: {},
  8805. distance: {}
  8806. } },
  8807. pointLightShadows: { value: [], properties: {
  8808. shadowBias: {},
  8809. shadowNormalBias: {},
  8810. shadowRadius: {},
  8811. shadowMapSize: {},
  8812. shadowCameraNear: {},
  8813. shadowCameraFar: {}
  8814. } },
  8815. pointShadowMap: { value: [] },
  8816. pointShadowMatrix: { value: [] },
  8817. hemisphereLights: { value: [], properties: {
  8818. direction: {},
  8819. skyColor: {},
  8820. groundColor: {}
  8821. } },
  8822. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8823. rectAreaLights: { value: [], properties: {
  8824. color: {},
  8825. position: {},
  8826. width: {},
  8827. height: {}
  8828. } },
  8829. ltc_1: { value: null },
  8830. ltc_2: { value: null }
  8831. },
  8832. points: {
  8833. diffuse: { value: new Color( 0xeeeeee ) },
  8834. opacity: { value: 1.0 },
  8835. size: { value: 1.0 },
  8836. scale: { value: 1.0 },
  8837. map: { value: null },
  8838. alphaMap: { value: null },
  8839. uvTransform: { value: new Matrix3() }
  8840. },
  8841. sprite: {
  8842. diffuse: { value: new Color( 0xeeeeee ) },
  8843. opacity: { value: 1.0 },
  8844. center: { value: new Vector2$1( 0.5, 0.5 ) },
  8845. rotation: { value: 0.0 },
  8846. map: { value: null },
  8847. alphaMap: { value: null },
  8848. uvTransform: { value: new Matrix3() }
  8849. }
  8850. };
  8851. const ShaderLib = {
  8852. basic: {
  8853. uniforms: mergeUniforms( [
  8854. UniformsLib.common,
  8855. UniformsLib.specularmap,
  8856. UniformsLib.envmap,
  8857. UniformsLib.aomap,
  8858. UniformsLib.lightmap,
  8859. UniformsLib.fog
  8860. ] ),
  8861. vertexShader: ShaderChunk.meshbasic_vert,
  8862. fragmentShader: ShaderChunk.meshbasic_frag
  8863. },
  8864. lambert: {
  8865. uniforms: mergeUniforms( [
  8866. UniformsLib.common,
  8867. UniformsLib.specularmap,
  8868. UniformsLib.envmap,
  8869. UniformsLib.aomap,
  8870. UniformsLib.lightmap,
  8871. UniformsLib.emissivemap,
  8872. UniformsLib.fog,
  8873. UniformsLib.lights,
  8874. {
  8875. emissive: { value: new Color( 0x000000 ) }
  8876. }
  8877. ] ),
  8878. vertexShader: ShaderChunk.meshlambert_vert,
  8879. fragmentShader: ShaderChunk.meshlambert_frag
  8880. },
  8881. phong: {
  8882. uniforms: mergeUniforms( [
  8883. UniformsLib.common,
  8884. UniformsLib.specularmap,
  8885. UniformsLib.envmap,
  8886. UniformsLib.aomap,
  8887. UniformsLib.lightmap,
  8888. UniformsLib.emissivemap,
  8889. UniformsLib.bumpmap,
  8890. UniformsLib.normalmap,
  8891. UniformsLib.displacementmap,
  8892. UniformsLib.fog,
  8893. UniformsLib.lights,
  8894. {
  8895. emissive: { value: new Color( 0x000000 ) },
  8896. specular: { value: new Color( 0x111111 ) },
  8897. shininess: { value: 30 }
  8898. }
  8899. ] ),
  8900. vertexShader: ShaderChunk.meshphong_vert,
  8901. fragmentShader: ShaderChunk.meshphong_frag
  8902. },
  8903. standard: {
  8904. uniforms: mergeUniforms( [
  8905. UniformsLib.common,
  8906. UniformsLib.envmap,
  8907. UniformsLib.aomap,
  8908. UniformsLib.lightmap,
  8909. UniformsLib.emissivemap,
  8910. UniformsLib.bumpmap,
  8911. UniformsLib.normalmap,
  8912. UniformsLib.displacementmap,
  8913. UniformsLib.roughnessmap,
  8914. UniformsLib.metalnessmap,
  8915. UniformsLib.fog,
  8916. UniformsLib.lights,
  8917. {
  8918. emissive: { value: new Color( 0x000000 ) },
  8919. roughness: { value: 1.0 },
  8920. metalness: { value: 0.0 },
  8921. envMapIntensity: { value: 1 } // temporary
  8922. }
  8923. ] ),
  8924. vertexShader: ShaderChunk.meshphysical_vert,
  8925. fragmentShader: ShaderChunk.meshphysical_frag
  8926. },
  8927. toon: {
  8928. uniforms: mergeUniforms( [
  8929. UniformsLib.common,
  8930. UniformsLib.aomap,
  8931. UniformsLib.lightmap,
  8932. UniformsLib.emissivemap,
  8933. UniformsLib.bumpmap,
  8934. UniformsLib.normalmap,
  8935. UniformsLib.displacementmap,
  8936. UniformsLib.gradientmap,
  8937. UniformsLib.fog,
  8938. UniformsLib.lights,
  8939. {
  8940. emissive: { value: new Color( 0x000000 ) }
  8941. }
  8942. ] ),
  8943. vertexShader: ShaderChunk.meshtoon_vert,
  8944. fragmentShader: ShaderChunk.meshtoon_frag
  8945. },
  8946. matcap: {
  8947. uniforms: mergeUniforms( [
  8948. UniformsLib.common,
  8949. UniformsLib.bumpmap,
  8950. UniformsLib.normalmap,
  8951. UniformsLib.displacementmap,
  8952. UniformsLib.fog,
  8953. {
  8954. matcap: { value: null }
  8955. }
  8956. ] ),
  8957. vertexShader: ShaderChunk.meshmatcap_vert,
  8958. fragmentShader: ShaderChunk.meshmatcap_frag
  8959. },
  8960. points: {
  8961. uniforms: mergeUniforms( [
  8962. UniformsLib.points,
  8963. UniformsLib.fog
  8964. ] ),
  8965. vertexShader: ShaderChunk.points_vert,
  8966. fragmentShader: ShaderChunk.points_frag
  8967. },
  8968. dashed: {
  8969. uniforms: mergeUniforms( [
  8970. UniformsLib.common,
  8971. UniformsLib.fog,
  8972. {
  8973. scale: { value: 1 },
  8974. dashSize: { value: 1 },
  8975. totalSize: { value: 2 }
  8976. }
  8977. ] ),
  8978. vertexShader: ShaderChunk.linedashed_vert,
  8979. fragmentShader: ShaderChunk.linedashed_frag
  8980. },
  8981. depth: {
  8982. uniforms: mergeUniforms( [
  8983. UniformsLib.common,
  8984. UniformsLib.displacementmap
  8985. ] ),
  8986. vertexShader: ShaderChunk.depth_vert,
  8987. fragmentShader: ShaderChunk.depth_frag
  8988. },
  8989. normal: {
  8990. uniforms: mergeUniforms( [
  8991. UniformsLib.common,
  8992. UniformsLib.bumpmap,
  8993. UniformsLib.normalmap,
  8994. UniformsLib.displacementmap,
  8995. {
  8996. opacity: { value: 1.0 }
  8997. }
  8998. ] ),
  8999. vertexShader: ShaderChunk.normal_vert,
  9000. fragmentShader: ShaderChunk.normal_frag
  9001. },
  9002. sprite: {
  9003. uniforms: mergeUniforms( [
  9004. UniformsLib.sprite,
  9005. UniformsLib.fog
  9006. ] ),
  9007. vertexShader: ShaderChunk.sprite_vert,
  9008. fragmentShader: ShaderChunk.sprite_frag
  9009. },
  9010. background: {
  9011. uniforms: {
  9012. uvTransform: { value: new Matrix3() },
  9013. t2D: { value: null },
  9014. },
  9015. vertexShader: ShaderChunk.background_vert,
  9016. fragmentShader: ShaderChunk.background_frag
  9017. },
  9018. /* -------------------------------------------------------------------------
  9019. // Cube map shader
  9020. ------------------------------------------------------------------------- */
  9021. cube: {
  9022. uniforms: mergeUniforms( [
  9023. UniformsLib.envmap,
  9024. {
  9025. opacity: { value: 1.0 }
  9026. }
  9027. ] ),
  9028. vertexShader: ShaderChunk.cube_vert,
  9029. fragmentShader: ShaderChunk.cube_frag
  9030. },
  9031. equirect: {
  9032. uniforms: {
  9033. tEquirect: { value: null },
  9034. },
  9035. vertexShader: ShaderChunk.equirect_vert,
  9036. fragmentShader: ShaderChunk.equirect_frag
  9037. },
  9038. distanceRGBA: {
  9039. uniforms: mergeUniforms( [
  9040. UniformsLib.common,
  9041. UniformsLib.displacementmap,
  9042. {
  9043. referencePosition: { value: new Vector3() },
  9044. nearDistance: { value: 1 },
  9045. farDistance: { value: 1000 }
  9046. }
  9047. ] ),
  9048. vertexShader: ShaderChunk.distanceRGBA_vert,
  9049. fragmentShader: ShaderChunk.distanceRGBA_frag
  9050. },
  9051. shadow: {
  9052. uniforms: mergeUniforms( [
  9053. UniformsLib.lights,
  9054. UniformsLib.fog,
  9055. {
  9056. color: { value: new Color( 0x00000 ) },
  9057. opacity: { value: 1.0 }
  9058. },
  9059. ] ),
  9060. vertexShader: ShaderChunk.shadow_vert,
  9061. fragmentShader: ShaderChunk.shadow_frag
  9062. }
  9063. };
  9064. ShaderLib.physical = {
  9065. uniforms: mergeUniforms( [
  9066. ShaderLib.standard.uniforms,
  9067. {
  9068. clearcoat: { value: 0 },
  9069. clearcoatMap: { value: null },
  9070. clearcoatRoughness: { value: 0 },
  9071. clearcoatRoughnessMap: { value: null },
  9072. clearcoatNormalScale: { value: new Vector2$1( 1, 1 ) },
  9073. clearcoatNormalMap: { value: null },
  9074. sheen: { value: new Color( 0x000000 ) },
  9075. transmission: { value: 0 },
  9076. transmissionMap: { value: null },
  9077. }
  9078. ] ),
  9079. vertexShader: ShaderChunk.meshphysical_vert,
  9080. fragmentShader: ShaderChunk.meshphysical_frag
  9081. };
  9082. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  9083. const clearColor = new Color( 0x000000 );
  9084. let clearAlpha = 0;
  9085. let planeMesh;
  9086. let boxMesh;
  9087. let currentBackground = null;
  9088. let currentBackgroundVersion = 0;
  9089. let currentTonemapping = null;
  9090. function render( renderList, scene, camera, forceClear ) {
  9091. let background = scene.isScene === true ? scene.background : null;
  9092. if ( background && background.isTexture ) {
  9093. background = cubemaps.get( background );
  9094. }
  9095. // Ignore background in AR
  9096. // TODO: Reconsider this.
  9097. const xr = renderer.xr;
  9098. const session = xr.getSession && xr.getSession();
  9099. if ( session && session.environmentBlendMode === 'additive' ) {
  9100. background = null;
  9101. }
  9102. if ( background === null ) {
  9103. setClear( clearColor, clearAlpha );
  9104. } else if ( background && background.isColor ) {
  9105. setClear( background, 1 );
  9106. forceClear = true;
  9107. }
  9108. if ( renderer.autoClear || forceClear ) {
  9109. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9110. }
  9111. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
  9112. if ( boxMesh === undefined ) {
  9113. boxMesh = new Mesh(
  9114. new BoxBufferGeometry( 1, 1, 1 ),
  9115. new ShaderMaterial( {
  9116. name: 'BackgroundCubeMaterial',
  9117. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  9118. vertexShader: ShaderLib.cube.vertexShader,
  9119. fragmentShader: ShaderLib.cube.fragmentShader,
  9120. side: BackSide,
  9121. depthTest: false,
  9122. depthWrite: false,
  9123. fog: false
  9124. } )
  9125. );
  9126. boxMesh.geometry.deleteAttribute( 'normal' );
  9127. boxMesh.geometry.deleteAttribute( 'uv' );
  9128. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9129. this.matrixWorld.copyPosition( camera.matrixWorld );
  9130. };
  9131. // enable code injection for non-built-in material
  9132. Object.defineProperty( boxMesh.material, 'envMap', {
  9133. get: function () {
  9134. return this.uniforms.envMap.value;
  9135. }
  9136. } );
  9137. objects.update( boxMesh );
  9138. }
  9139. if ( background.isWebGLCubeRenderTarget ) {
  9140. // TODO Deprecate
  9141. background = background.texture;
  9142. }
  9143. boxMesh.material.uniforms.envMap.value = background;
  9144. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  9145. if ( currentBackground !== background ||
  9146. currentBackgroundVersion !== background.version ||
  9147. currentTonemapping !== renderer.toneMapping ) {
  9148. boxMesh.material.needsUpdate = true;
  9149. currentBackground = background;
  9150. currentBackgroundVersion = background.version;
  9151. currentTonemapping = renderer.toneMapping;
  9152. }
  9153. // push to the pre-sorted opaque render list
  9154. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9155. } else if ( background && background.isTexture ) {
  9156. if ( planeMesh === undefined ) {
  9157. planeMesh = new Mesh(
  9158. new PlaneBufferGeometry( 2, 2 ),
  9159. new ShaderMaterial( {
  9160. name: 'BackgroundMaterial',
  9161. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9162. vertexShader: ShaderLib.background.vertexShader,
  9163. fragmentShader: ShaderLib.background.fragmentShader,
  9164. side: FrontSide,
  9165. depthTest: false,
  9166. depthWrite: false,
  9167. fog: false
  9168. } )
  9169. );
  9170. planeMesh.geometry.deleteAttribute( 'normal' );
  9171. // enable code injection for non-built-in material
  9172. Object.defineProperty( planeMesh.material, 'map', {
  9173. get: function () {
  9174. return this.uniforms.t2D.value;
  9175. }
  9176. } );
  9177. objects.update( planeMesh );
  9178. }
  9179. planeMesh.material.uniforms.t2D.value = background;
  9180. if ( background.matrixAutoUpdate === true ) {
  9181. background.updateMatrix();
  9182. }
  9183. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9184. if ( currentBackground !== background ||
  9185. currentBackgroundVersion !== background.version ||
  9186. currentTonemapping !== renderer.toneMapping ) {
  9187. planeMesh.material.needsUpdate = true;
  9188. currentBackground = background;
  9189. currentBackgroundVersion = background.version;
  9190. currentTonemapping = renderer.toneMapping;
  9191. }
  9192. // push to the pre-sorted opaque render list
  9193. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9194. }
  9195. }
  9196. function setClear( color, alpha ) {
  9197. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9198. }
  9199. return {
  9200. getClearColor: function () {
  9201. return clearColor;
  9202. },
  9203. setClearColor: function ( color, alpha = 1 ) {
  9204. clearColor.set( color );
  9205. clearAlpha = alpha;
  9206. setClear( clearColor, clearAlpha );
  9207. },
  9208. getClearAlpha: function () {
  9209. return clearAlpha;
  9210. },
  9211. setClearAlpha: function ( alpha ) {
  9212. clearAlpha = alpha;
  9213. setClear( clearColor, clearAlpha );
  9214. },
  9215. render: render
  9216. };
  9217. }
  9218. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9219. const maxVertexAttributes = gl.getParameter( 34921 );
  9220. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9221. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9222. const bindingStates = {};
  9223. const defaultState = createBindingState( null );
  9224. let currentState = defaultState;
  9225. function setup( object, material, program, geometry, index ) {
  9226. let updateBuffers = false;
  9227. if ( vaoAvailable ) {
  9228. const state = getBindingState( geometry, program, material );
  9229. if ( currentState !== state ) {
  9230. currentState = state;
  9231. bindVertexArrayObject( currentState.object );
  9232. }
  9233. updateBuffers = needsUpdate( geometry, index );
  9234. if ( updateBuffers ) saveCache( geometry, index );
  9235. } else {
  9236. const wireframe = ( material.wireframe === true );
  9237. if ( currentState.geometry !== geometry.id ||
  9238. currentState.program !== program.id ||
  9239. currentState.wireframe !== wireframe ) {
  9240. currentState.geometry = geometry.id;
  9241. currentState.program = program.id;
  9242. currentState.wireframe = wireframe;
  9243. updateBuffers = true;
  9244. }
  9245. }
  9246. if ( object.isInstancedMesh === true ) {
  9247. updateBuffers = true;
  9248. }
  9249. if ( index !== null ) {
  9250. attributes.update( index, 34963 );
  9251. }
  9252. if ( updateBuffers ) {
  9253. setupVertexAttributes( object, material, program, geometry );
  9254. if ( index !== null ) {
  9255. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  9256. }
  9257. }
  9258. }
  9259. function createVertexArrayObject() {
  9260. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9261. return extension.createVertexArrayOES();
  9262. }
  9263. function bindVertexArrayObject( vao ) {
  9264. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9265. return extension.bindVertexArrayOES( vao );
  9266. }
  9267. function deleteVertexArrayObject( vao ) {
  9268. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9269. return extension.deleteVertexArrayOES( vao );
  9270. }
  9271. function getBindingState( geometry, program, material ) {
  9272. const wireframe = ( material.wireframe === true );
  9273. let programMap = bindingStates[ geometry.id ];
  9274. if ( programMap === undefined ) {
  9275. programMap = {};
  9276. bindingStates[ geometry.id ] = programMap;
  9277. }
  9278. let stateMap = programMap[ program.id ];
  9279. if ( stateMap === undefined ) {
  9280. stateMap = {};
  9281. programMap[ program.id ] = stateMap;
  9282. }
  9283. let state = stateMap[ wireframe ];
  9284. if ( state === undefined ) {
  9285. state = createBindingState( createVertexArrayObject() );
  9286. stateMap[ wireframe ] = state;
  9287. }
  9288. return state;
  9289. }
  9290. function createBindingState( vao ) {
  9291. const newAttributes = [];
  9292. const enabledAttributes = [];
  9293. const attributeDivisors = [];
  9294. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9295. newAttributes[ i ] = 0;
  9296. enabledAttributes[ i ] = 0;
  9297. attributeDivisors[ i ] = 0;
  9298. }
  9299. return {
  9300. // for backward compatibility on non-VAO support browser
  9301. geometry: null,
  9302. program: null,
  9303. wireframe: false,
  9304. newAttributes: newAttributes,
  9305. enabledAttributes: enabledAttributes,
  9306. attributeDivisors: attributeDivisors,
  9307. object: vao,
  9308. attributes: {},
  9309. index: null
  9310. };
  9311. }
  9312. function needsUpdate( geometry, index ) {
  9313. const cachedAttributes = currentState.attributes;
  9314. const geometryAttributes = geometry.attributes;
  9315. let attributesNum = 0;
  9316. for ( const key in geometryAttributes ) {
  9317. const cachedAttribute = cachedAttributes[ key ];
  9318. const geometryAttribute = geometryAttributes[ key ];
  9319. if ( cachedAttribute === undefined ) return true;
  9320. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9321. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  9322. attributesNum ++;
  9323. }
  9324. if ( currentState.attributesNum !== attributesNum ) return true;
  9325. if ( currentState.index !== index ) return true;
  9326. return false;
  9327. }
  9328. function saveCache( geometry, index ) {
  9329. const cache = {};
  9330. const attributes = geometry.attributes;
  9331. let attributesNum = 0;
  9332. for ( const key in attributes ) {
  9333. const attribute = attributes[ key ];
  9334. const data = {};
  9335. data.attribute = attribute;
  9336. if ( attribute.data ) {
  9337. data.data = attribute.data;
  9338. }
  9339. cache[ key ] = data;
  9340. attributesNum ++;
  9341. }
  9342. currentState.attributes = cache;
  9343. currentState.attributesNum = attributesNum;
  9344. currentState.index = index;
  9345. }
  9346. function initAttributes() {
  9347. const newAttributes = currentState.newAttributes;
  9348. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9349. newAttributes[ i ] = 0;
  9350. }
  9351. }
  9352. function enableAttribute( attribute ) {
  9353. enableAttributeAndDivisor( attribute, 0 );
  9354. }
  9355. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9356. const newAttributes = currentState.newAttributes;
  9357. const enabledAttributes = currentState.enabledAttributes;
  9358. const attributeDivisors = currentState.attributeDivisors;
  9359. newAttributes[ attribute ] = 1;
  9360. if ( enabledAttributes[ attribute ] === 0 ) {
  9361. gl.enableVertexAttribArray( attribute );
  9362. enabledAttributes[ attribute ] = 1;
  9363. }
  9364. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9365. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9366. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9367. attributeDivisors[ attribute ] = meshPerAttribute;
  9368. }
  9369. }
  9370. function disableUnusedAttributes() {
  9371. const newAttributes = currentState.newAttributes;
  9372. const enabledAttributes = currentState.enabledAttributes;
  9373. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9374. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9375. gl.disableVertexAttribArray( i );
  9376. enabledAttributes[ i ] = 0;
  9377. }
  9378. }
  9379. }
  9380. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9381. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  9382. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9383. } else {
  9384. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9385. }
  9386. }
  9387. function setupVertexAttributes( object, material, program, geometry ) {
  9388. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9389. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9390. }
  9391. initAttributes();
  9392. const geometryAttributes = geometry.attributes;
  9393. const programAttributes = program.getAttributes();
  9394. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9395. for ( const name in programAttributes ) {
  9396. const programAttribute = programAttributes[ name ];
  9397. if ( programAttribute >= 0 ) {
  9398. const geometryAttribute = geometryAttributes[ name ];
  9399. if ( geometryAttribute !== undefined ) {
  9400. const normalized = geometryAttribute.normalized;
  9401. const size = geometryAttribute.itemSize;
  9402. const attribute = attributes.get( geometryAttribute );
  9403. // TODO Attribute may not be available on context restore
  9404. if ( attribute === undefined ) continue;
  9405. const buffer = attribute.buffer;
  9406. const type = attribute.type;
  9407. const bytesPerElement = attribute.bytesPerElement;
  9408. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9409. const data = geometryAttribute.data;
  9410. const stride = data.stride;
  9411. const offset = geometryAttribute.offset;
  9412. if ( data && data.isInstancedInterleavedBuffer ) {
  9413. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  9414. if ( geometry._maxInstanceCount === undefined ) {
  9415. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9416. }
  9417. } else {
  9418. enableAttribute( programAttribute );
  9419. }
  9420. gl.bindBuffer( 34962, buffer );
  9421. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  9422. } else {
  9423. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9424. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  9425. if ( geometry._maxInstanceCount === undefined ) {
  9426. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9427. }
  9428. } else {
  9429. enableAttribute( programAttribute );
  9430. }
  9431. gl.bindBuffer( 34962, buffer );
  9432. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  9433. }
  9434. } else if ( name === 'instanceMatrix' ) {
  9435. const attribute = attributes.get( object.instanceMatrix );
  9436. // TODO Attribute may not be available on context restore
  9437. if ( attribute === undefined ) continue;
  9438. const buffer = attribute.buffer;
  9439. const type = attribute.type;
  9440. enableAttributeAndDivisor( programAttribute + 0, 1 );
  9441. enableAttributeAndDivisor( programAttribute + 1, 1 );
  9442. enableAttributeAndDivisor( programAttribute + 2, 1 );
  9443. enableAttributeAndDivisor( programAttribute + 3, 1 );
  9444. gl.bindBuffer( 34962, buffer );
  9445. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  9446. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  9447. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  9448. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  9449. } else if ( name === 'instanceColor' ) {
  9450. const attribute = attributes.get( object.instanceColor );
  9451. // TODO Attribute may not be available on context restore
  9452. if ( attribute === undefined ) continue;
  9453. const buffer = attribute.buffer;
  9454. const type = attribute.type;
  9455. enableAttributeAndDivisor( programAttribute, 1 );
  9456. gl.bindBuffer( 34962, buffer );
  9457. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  9458. } else if ( materialDefaultAttributeValues !== undefined ) {
  9459. const value = materialDefaultAttributeValues[ name ];
  9460. if ( value !== undefined ) {
  9461. switch ( value.length ) {
  9462. case 2:
  9463. gl.vertexAttrib2fv( programAttribute, value );
  9464. break;
  9465. case 3:
  9466. gl.vertexAttrib3fv( programAttribute, value );
  9467. break;
  9468. case 4:
  9469. gl.vertexAttrib4fv( programAttribute, value );
  9470. break;
  9471. default:
  9472. gl.vertexAttrib1fv( programAttribute, value );
  9473. }
  9474. }
  9475. }
  9476. }
  9477. }
  9478. disableUnusedAttributes();
  9479. }
  9480. function dispose() {
  9481. reset();
  9482. for ( const geometryId in bindingStates ) {
  9483. const programMap = bindingStates[ geometryId ];
  9484. for ( const programId in programMap ) {
  9485. const stateMap = programMap[ programId ];
  9486. for ( const wireframe in stateMap ) {
  9487. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9488. delete stateMap[ wireframe ];
  9489. }
  9490. delete programMap[ programId ];
  9491. }
  9492. delete bindingStates[ geometryId ];
  9493. }
  9494. }
  9495. function releaseStatesOfGeometry( geometry ) {
  9496. if ( bindingStates[ geometry.id ] === undefined ) return;
  9497. const programMap = bindingStates[ geometry.id ];
  9498. for ( const programId in programMap ) {
  9499. const stateMap = programMap[ programId ];
  9500. for ( const wireframe in stateMap ) {
  9501. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9502. delete stateMap[ wireframe ];
  9503. }
  9504. delete programMap[ programId ];
  9505. }
  9506. delete bindingStates[ geometry.id ];
  9507. }
  9508. function releaseStatesOfProgram( program ) {
  9509. for ( const geometryId in bindingStates ) {
  9510. const programMap = bindingStates[ geometryId ];
  9511. if ( programMap[ program.id ] === undefined ) continue;
  9512. const stateMap = programMap[ program.id ];
  9513. for ( const wireframe in stateMap ) {
  9514. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9515. delete stateMap[ wireframe ];
  9516. }
  9517. delete programMap[ program.id ];
  9518. }
  9519. }
  9520. function reset() {
  9521. resetDefaultState();
  9522. if ( currentState === defaultState ) return;
  9523. currentState = defaultState;
  9524. bindVertexArrayObject( currentState.object );
  9525. }
  9526. // for backward-compatilibity
  9527. function resetDefaultState() {
  9528. defaultState.geometry = null;
  9529. defaultState.program = null;
  9530. defaultState.wireframe = false;
  9531. }
  9532. return {
  9533. setup: setup,
  9534. reset: reset,
  9535. resetDefaultState: resetDefaultState,
  9536. dispose: dispose,
  9537. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9538. releaseStatesOfProgram: releaseStatesOfProgram,
  9539. initAttributes: initAttributes,
  9540. enableAttribute: enableAttribute,
  9541. disableUnusedAttributes: disableUnusedAttributes
  9542. };
  9543. }
  9544. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9545. const isWebGL2 = capabilities.isWebGL2;
  9546. let mode;
  9547. function setMode( value ) {
  9548. mode = value;
  9549. }
  9550. function render( start, count ) {
  9551. gl.drawArrays( mode, start, count );
  9552. info.update( count, mode, 1 );
  9553. }
  9554. function renderInstances( start, count, primcount ) {
  9555. if ( primcount === 0 ) return;
  9556. let extension, methodName;
  9557. if ( isWebGL2 ) {
  9558. extension = gl;
  9559. methodName = 'drawArraysInstanced';
  9560. } else {
  9561. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9562. methodName = 'drawArraysInstancedANGLE';
  9563. if ( extension === null ) {
  9564. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9565. return;
  9566. }
  9567. }
  9568. extension[ methodName ]( mode, start, count, primcount );
  9569. info.update( count, mode, primcount );
  9570. }
  9571. //
  9572. this.setMode = setMode;
  9573. this.render = render;
  9574. this.renderInstances = renderInstances;
  9575. }
  9576. function WebGLCapabilities( gl, extensions, parameters ) {
  9577. let maxAnisotropy;
  9578. function getMaxAnisotropy() {
  9579. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9580. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9581. if ( extension !== null ) {
  9582. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9583. } else {
  9584. maxAnisotropy = 0;
  9585. }
  9586. return maxAnisotropy;
  9587. }
  9588. function getMaxPrecision( precision ) {
  9589. if ( precision === 'highp' ) {
  9590. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9591. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9592. return 'highp';
  9593. }
  9594. precision = 'mediump';
  9595. }
  9596. if ( precision === 'mediump' ) {
  9597. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9598. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9599. return 'mediump';
  9600. }
  9601. }
  9602. return 'lowp';
  9603. }
  9604. /* eslint-disable no-undef */
  9605. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  9606. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  9607. /* eslint-enable no-undef */
  9608. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9609. const maxPrecision = getMaxPrecision( precision );
  9610. if ( maxPrecision !== precision ) {
  9611. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9612. precision = maxPrecision;
  9613. }
  9614. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9615. const maxTextures = gl.getParameter( 34930 );
  9616. const maxVertexTextures = gl.getParameter( 35660 );
  9617. const maxTextureSize = gl.getParameter( 3379 );
  9618. const maxCubemapSize = gl.getParameter( 34076 );
  9619. const maxAttributes = gl.getParameter( 34921 );
  9620. const maxVertexUniforms = gl.getParameter( 36347 );
  9621. const maxVaryings = gl.getParameter( 36348 );
  9622. const maxFragmentUniforms = gl.getParameter( 36349 );
  9623. const vertexTextures = maxVertexTextures > 0;
  9624. const floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  9625. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9626. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9627. return {
  9628. isWebGL2: isWebGL2,
  9629. getMaxAnisotropy: getMaxAnisotropy,
  9630. getMaxPrecision: getMaxPrecision,
  9631. precision: precision,
  9632. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9633. maxTextures: maxTextures,
  9634. maxVertexTextures: maxVertexTextures,
  9635. maxTextureSize: maxTextureSize,
  9636. maxCubemapSize: maxCubemapSize,
  9637. maxAttributes: maxAttributes,
  9638. maxVertexUniforms: maxVertexUniforms,
  9639. maxVaryings: maxVaryings,
  9640. maxFragmentUniforms: maxFragmentUniforms,
  9641. vertexTextures: vertexTextures,
  9642. floatFragmentTextures: floatFragmentTextures,
  9643. floatVertexTextures: floatVertexTextures,
  9644. maxSamples: maxSamples
  9645. };
  9646. }
  9647. function WebGLClipping( properties ) {
  9648. const scope = this;
  9649. let globalState = null,
  9650. numGlobalPlanes = 0,
  9651. localClippingEnabled = false,
  9652. renderingShadows = false;
  9653. const plane = new Plane(),
  9654. viewNormalMatrix = new Matrix3(),
  9655. uniform = { value: null, needsUpdate: false };
  9656. this.uniform = uniform;
  9657. this.numPlanes = 0;
  9658. this.numIntersection = 0;
  9659. this.init = function ( planes, enableLocalClipping, camera ) {
  9660. const enabled =
  9661. planes.length !== 0 ||
  9662. enableLocalClipping ||
  9663. // enable state of previous frame - the clipping code has to
  9664. // run another frame in order to reset the state:
  9665. numGlobalPlanes !== 0 ||
  9666. localClippingEnabled;
  9667. localClippingEnabled = enableLocalClipping;
  9668. globalState = projectPlanes( planes, camera, 0 );
  9669. numGlobalPlanes = planes.length;
  9670. return enabled;
  9671. };
  9672. this.beginShadows = function () {
  9673. renderingShadows = true;
  9674. projectPlanes( null );
  9675. };
  9676. this.endShadows = function () {
  9677. renderingShadows = false;
  9678. resetGlobalState();
  9679. };
  9680. this.setState = function ( material, camera, useCache ) {
  9681. const planes = material.clippingPlanes,
  9682. clipIntersection = material.clipIntersection,
  9683. clipShadows = material.clipShadows;
  9684. const materialProperties = properties.get( material );
  9685. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9686. // there's no local clipping
  9687. if ( renderingShadows ) {
  9688. // there's no global clipping
  9689. projectPlanes( null );
  9690. } else {
  9691. resetGlobalState();
  9692. }
  9693. } else {
  9694. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9695. lGlobal = nGlobal * 4;
  9696. let dstArray = materialProperties.clippingState || null;
  9697. uniform.value = dstArray; // ensure unique state
  9698. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9699. for ( let i = 0; i !== lGlobal; ++ i ) {
  9700. dstArray[ i ] = globalState[ i ];
  9701. }
  9702. materialProperties.clippingState = dstArray;
  9703. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9704. this.numPlanes += nGlobal;
  9705. }
  9706. };
  9707. function resetGlobalState() {
  9708. if ( uniform.value !== globalState ) {
  9709. uniform.value = globalState;
  9710. uniform.needsUpdate = numGlobalPlanes > 0;
  9711. }
  9712. scope.numPlanes = numGlobalPlanes;
  9713. scope.numIntersection = 0;
  9714. }
  9715. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9716. const nPlanes = planes !== null ? planes.length : 0;
  9717. let dstArray = null;
  9718. if ( nPlanes !== 0 ) {
  9719. dstArray = uniform.value;
  9720. if ( skipTransform !== true || dstArray === null ) {
  9721. const flatSize = dstOffset + nPlanes * 4,
  9722. viewMatrix = camera.matrixWorldInverse;
  9723. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9724. if ( dstArray === null || dstArray.length < flatSize ) {
  9725. dstArray = new Float32Array( flatSize );
  9726. }
  9727. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9728. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9729. plane.normal.toArray( dstArray, i4 );
  9730. dstArray[ i4 + 3 ] = plane.constant;
  9731. }
  9732. }
  9733. uniform.value = dstArray;
  9734. uniform.needsUpdate = true;
  9735. }
  9736. scope.numPlanes = nPlanes;
  9737. scope.numIntersection = 0;
  9738. return dstArray;
  9739. }
  9740. }
  9741. function WebGLCubeMaps( renderer ) {
  9742. let cubemaps = new WeakMap();
  9743. function mapTextureMapping( texture, mapping ) {
  9744. if ( mapping === EquirectangularReflectionMapping ) {
  9745. texture.mapping = CubeReflectionMapping;
  9746. } else if ( mapping === EquirectangularRefractionMapping ) {
  9747. texture.mapping = CubeRefractionMapping;
  9748. }
  9749. return texture;
  9750. }
  9751. function get( texture ) {
  9752. if ( texture && texture.isTexture ) {
  9753. const mapping = texture.mapping;
  9754. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9755. if ( cubemaps.has( texture ) ) {
  9756. const cubemap = cubemaps.get( texture ).texture;
  9757. return mapTextureMapping( cubemap, texture.mapping );
  9758. } else {
  9759. const image = texture.image;
  9760. if ( image && image.height > 0 ) {
  9761. const currentRenderList = renderer.getRenderList();
  9762. const currentRenderTarget = renderer.getRenderTarget();
  9763. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9764. renderTarget.fromEquirectangularTexture( renderer, texture );
  9765. cubemaps.set( texture, renderTarget );
  9766. renderer.setRenderTarget( currentRenderTarget );
  9767. renderer.setRenderList( currentRenderList );
  9768. texture.addEventListener( 'dispose', onTextureDispose );
  9769. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9770. } else {
  9771. // image not yet ready. try the conversion next frame
  9772. return null;
  9773. }
  9774. }
  9775. }
  9776. }
  9777. return texture;
  9778. }
  9779. function onTextureDispose( event ) {
  9780. const texture = event.target;
  9781. texture.removeEventListener( 'dispose', onTextureDispose );
  9782. const cubemap = cubemaps.get( texture );
  9783. if ( cubemap !== undefined ) {
  9784. cubemaps.delete( texture );
  9785. cubemap.dispose();
  9786. }
  9787. }
  9788. function dispose() {
  9789. cubemaps = new WeakMap();
  9790. }
  9791. return {
  9792. get: get,
  9793. dispose: dispose
  9794. };
  9795. }
  9796. function WebGLExtensions( gl ) {
  9797. const extensions = {};
  9798. return {
  9799. has: function ( name ) {
  9800. if ( extensions[ name ] !== undefined ) {
  9801. return extensions[ name ] !== null;
  9802. }
  9803. let extension;
  9804. switch ( name ) {
  9805. case 'WEBGL_depth_texture':
  9806. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9807. break;
  9808. case 'EXT_texture_filter_anisotropic':
  9809. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9810. break;
  9811. case 'WEBGL_compressed_texture_s3tc':
  9812. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9813. break;
  9814. case 'WEBGL_compressed_texture_pvrtc':
  9815. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9816. break;
  9817. default:
  9818. extension = gl.getExtension( name );
  9819. }
  9820. extensions[ name ] = extension;
  9821. return extension !== null;
  9822. },
  9823. get: function ( name ) {
  9824. if ( ! this.has( name ) ) {
  9825. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9826. }
  9827. return extensions[ name ];
  9828. }
  9829. };
  9830. }
  9831. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9832. const geometries = new WeakMap();
  9833. const wireframeAttributes = new WeakMap();
  9834. function onGeometryDispose( event ) {
  9835. const geometry = event.target;
  9836. const buffergeometry = geometries.get( geometry );
  9837. if ( buffergeometry.index !== null ) {
  9838. attributes.remove( buffergeometry.index );
  9839. }
  9840. for ( const name in buffergeometry.attributes ) {
  9841. attributes.remove( buffergeometry.attributes[ name ] );
  9842. }
  9843. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9844. geometries.delete( geometry );
  9845. const attribute = wireframeAttributes.get( buffergeometry );
  9846. if ( attribute ) {
  9847. attributes.remove( attribute );
  9848. wireframeAttributes.delete( buffergeometry );
  9849. }
  9850. bindingStates.releaseStatesOfGeometry( buffergeometry );
  9851. if ( geometry.isInstancedBufferGeometry === true ) {
  9852. delete geometry._maxInstanceCount;
  9853. }
  9854. //
  9855. info.memory.geometries --;
  9856. }
  9857. function get( object, geometry ) {
  9858. let buffergeometry = geometries.get( geometry );
  9859. if ( buffergeometry ) return buffergeometry;
  9860. geometry.addEventListener( 'dispose', onGeometryDispose );
  9861. if ( geometry.isBufferGeometry ) {
  9862. buffergeometry = geometry;
  9863. } else if ( geometry.isGeometry ) {
  9864. if ( geometry._bufferGeometry === undefined ) {
  9865. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9866. }
  9867. buffergeometry = geometry._bufferGeometry;
  9868. }
  9869. geometries.set( geometry, buffergeometry );
  9870. info.memory.geometries ++;
  9871. return buffergeometry;
  9872. }
  9873. function update( geometry ) {
  9874. const geometryAttributes = geometry.attributes;
  9875. // Updating index buffer in VAO now. See WebGLBindingStates.
  9876. for ( const name in geometryAttributes ) {
  9877. attributes.update( geometryAttributes[ name ], 34962 );
  9878. }
  9879. // morph targets
  9880. const morphAttributes = geometry.morphAttributes;
  9881. for ( const name in morphAttributes ) {
  9882. const array = morphAttributes[ name ];
  9883. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9884. attributes.update( array[ i ], 34962 );
  9885. }
  9886. }
  9887. }
  9888. function updateWireframeAttribute( geometry ) {
  9889. const indices = [];
  9890. const geometryIndex = geometry.index;
  9891. const geometryPosition = geometry.attributes.position;
  9892. let version = 0;
  9893. if ( geometryIndex !== null ) {
  9894. const array = geometryIndex.array;
  9895. version = geometryIndex.version;
  9896. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9897. const a = array[ i + 0 ];
  9898. const b = array[ i + 1 ];
  9899. const c = array[ i + 2 ];
  9900. indices.push( a, b, b, c, c, a );
  9901. }
  9902. } else {
  9903. const array = geometryPosition.array;
  9904. version = geometryPosition.version;
  9905. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9906. const a = i + 0;
  9907. const b = i + 1;
  9908. const c = i + 2;
  9909. indices.push( a, b, b, c, c, a );
  9910. }
  9911. }
  9912. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9913. attribute.version = version;
  9914. // Updating index buffer in VAO now. See WebGLBindingStates
  9915. //
  9916. const previousAttribute = wireframeAttributes.get( geometry );
  9917. if ( previousAttribute ) attributes.remove( previousAttribute );
  9918. //
  9919. wireframeAttributes.set( geometry, attribute );
  9920. }
  9921. function getWireframeAttribute( geometry ) {
  9922. const currentAttribute = wireframeAttributes.get( geometry );
  9923. if ( currentAttribute ) {
  9924. const geometryIndex = geometry.index;
  9925. if ( geometryIndex !== null ) {
  9926. // if the attribute is obsolete, create a new one
  9927. if ( currentAttribute.version < geometryIndex.version ) {
  9928. updateWireframeAttribute( geometry );
  9929. }
  9930. }
  9931. } else {
  9932. updateWireframeAttribute( geometry );
  9933. }
  9934. return wireframeAttributes.get( geometry );
  9935. }
  9936. return {
  9937. get: get,
  9938. update: update,
  9939. getWireframeAttribute: getWireframeAttribute
  9940. };
  9941. }
  9942. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9943. const isWebGL2 = capabilities.isWebGL2;
  9944. let mode;
  9945. function setMode( value ) {
  9946. mode = value;
  9947. }
  9948. let type, bytesPerElement;
  9949. function setIndex( value ) {
  9950. type = value.type;
  9951. bytesPerElement = value.bytesPerElement;
  9952. }
  9953. function render( start, count ) {
  9954. gl.drawElements( mode, count, type, start * bytesPerElement );
  9955. info.update( count, mode, 1 );
  9956. }
  9957. function renderInstances( start, count, primcount ) {
  9958. if ( primcount === 0 ) return;
  9959. let extension, methodName;
  9960. if ( isWebGL2 ) {
  9961. extension = gl;
  9962. methodName = 'drawElementsInstanced';
  9963. } else {
  9964. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9965. methodName = 'drawElementsInstancedANGLE';
  9966. if ( extension === null ) {
  9967. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9968. return;
  9969. }
  9970. }
  9971. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9972. info.update( count, mode, primcount );
  9973. }
  9974. //
  9975. this.setMode = setMode;
  9976. this.setIndex = setIndex;
  9977. this.render = render;
  9978. this.renderInstances = renderInstances;
  9979. }
  9980. function WebGLInfo( gl ) {
  9981. const memory = {
  9982. geometries: 0,
  9983. textures: 0
  9984. };
  9985. const render = {
  9986. frame: 0,
  9987. calls: 0,
  9988. triangles: 0,
  9989. points: 0,
  9990. lines: 0
  9991. };
  9992. function update( count, mode, instanceCount ) {
  9993. render.calls ++;
  9994. switch ( mode ) {
  9995. case 4:
  9996. render.triangles += instanceCount * ( count / 3 );
  9997. break;
  9998. case 1:
  9999. render.lines += instanceCount * ( count / 2 );
  10000. break;
  10001. case 3:
  10002. render.lines += instanceCount * ( count - 1 );
  10003. break;
  10004. case 2:
  10005. render.lines += instanceCount * count;
  10006. break;
  10007. case 0:
  10008. render.points += instanceCount * count;
  10009. break;
  10010. default:
  10011. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10012. break;
  10013. }
  10014. }
  10015. function reset() {
  10016. render.frame ++;
  10017. render.calls = 0;
  10018. render.triangles = 0;
  10019. render.points = 0;
  10020. render.lines = 0;
  10021. }
  10022. return {
  10023. memory: memory,
  10024. render: render,
  10025. programs: null,
  10026. autoReset: true,
  10027. reset: reset,
  10028. update: update
  10029. };
  10030. }
  10031. function numericalSort( a, b ) {
  10032. return a[ 0 ] - b[ 0 ];
  10033. }
  10034. function absNumericalSort( a, b ) {
  10035. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10036. }
  10037. function WebGLMorphtargets( gl ) {
  10038. const influencesList = {};
  10039. const morphInfluences = new Float32Array( 8 );
  10040. const workInfluences = [];
  10041. for ( let i = 0; i < 8; i ++ ) {
  10042. workInfluences[ i ] = [ i, 0 ];
  10043. }
  10044. function update( object, geometry, material, program ) {
  10045. const objectInfluences = object.morphTargetInfluences;
  10046. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10047. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10048. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10049. let influences = influencesList[ geometry.id ];
  10050. if ( influences === undefined ) {
  10051. // initialise list
  10052. influences = [];
  10053. for ( let i = 0; i < length; i ++ ) {
  10054. influences[ i ] = [ i, 0 ];
  10055. }
  10056. influencesList[ geometry.id ] = influences;
  10057. }
  10058. // Collect influences
  10059. for ( let i = 0; i < length; i ++ ) {
  10060. const influence = influences[ i ];
  10061. influence[ 0 ] = i;
  10062. influence[ 1 ] = objectInfluences[ i ];
  10063. }
  10064. influences.sort( absNumericalSort );
  10065. for ( let i = 0; i < 8; i ++ ) {
  10066. if ( i < length && influences[ i ][ 1 ] ) {
  10067. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10068. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10069. } else {
  10070. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10071. workInfluences[ i ][ 1 ] = 0;
  10072. }
  10073. }
  10074. workInfluences.sort( numericalSort );
  10075. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10076. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10077. let morphInfluencesSum = 0;
  10078. for ( let i = 0; i < 8; i ++ ) {
  10079. const influence = workInfluences[ i ];
  10080. const index = influence[ 0 ];
  10081. const value = influence[ 1 ];
  10082. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10083. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10084. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10085. }
  10086. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10087. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10088. }
  10089. morphInfluences[ i ] = value;
  10090. morphInfluencesSum += value;
  10091. } else {
  10092. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10093. geometry.deleteAttribute( 'morphTarget' + i );
  10094. }
  10095. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10096. geometry.deleteAttribute( 'morphNormal' + i );
  10097. }
  10098. morphInfluences[ i ] = 0;
  10099. }
  10100. }
  10101. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10102. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10103. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10104. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10105. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10106. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10107. }
  10108. return {
  10109. update: update
  10110. };
  10111. }
  10112. function WebGLObjects( gl, geometries, attributes, info ) {
  10113. let updateMap = new WeakMap();
  10114. function update( object ) {
  10115. const frame = info.render.frame;
  10116. const geometry = object.geometry;
  10117. const buffergeometry = geometries.get( object, geometry );
  10118. // Update once per frame
  10119. if ( updateMap.get( buffergeometry ) !== frame ) {
  10120. if ( geometry.isGeometry ) {
  10121. buffergeometry.updateFromObject( object );
  10122. }
  10123. geometries.update( buffergeometry );
  10124. updateMap.set( buffergeometry, frame );
  10125. }
  10126. if ( object.isInstancedMesh ) {
  10127. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10128. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10129. }
  10130. attributes.update( object.instanceMatrix, 34962 );
  10131. if ( object.instanceColor !== null ) {
  10132. attributes.update( object.instanceColor, 34962 );
  10133. }
  10134. }
  10135. return buffergeometry;
  10136. }
  10137. function dispose() {
  10138. updateMap = new WeakMap();
  10139. }
  10140. function onInstancedMeshDispose( event ) {
  10141. const instancedMesh = event.target;
  10142. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10143. attributes.remove( instancedMesh.instanceMatrix );
  10144. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10145. }
  10146. return {
  10147. update: update,
  10148. dispose: dispose
  10149. };
  10150. }
  10151. function DataTexture2DArray( data = null, width = 1, height = 1, depth = 1 ) {
  10152. Texture.call( this, null );
  10153. this.image = { data, width, height, depth };
  10154. this.magFilter = NearestFilter;
  10155. this.minFilter = NearestFilter;
  10156. this.wrapR = ClampToEdgeWrapping;
  10157. this.generateMipmaps = false;
  10158. this.flipY = false;
  10159. this.needsUpdate = true;
  10160. }
  10161. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  10162. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10163. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10164. function DataTexture3D( data = null, width = 1, height = 1, depth = 1 ) {
  10165. // We're going to add .setXXX() methods for setting properties later.
  10166. // Users can still set in DataTexture3D directly.
  10167. //
  10168. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10169. // texture.anisotropy = 16;
  10170. //
  10171. // See #14839
  10172. Texture.call( this, null );
  10173. this.image = { data, width, height, depth };
  10174. this.magFilter = NearestFilter;
  10175. this.minFilter = NearestFilter;
  10176. this.wrapR = ClampToEdgeWrapping;
  10177. this.generateMipmaps = false;
  10178. this.flipY = false;
  10179. this.needsUpdate = true;
  10180. }
  10181. DataTexture3D.prototype = Object.create( Texture.prototype );
  10182. DataTexture3D.prototype.constructor = DataTexture3D;
  10183. DataTexture3D.prototype.isDataTexture3D = true;
  10184. /**
  10185. * Uniforms of a program.
  10186. * Those form a tree structure with a special top-level container for the root,
  10187. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10188. *
  10189. *
  10190. * Properties of inner nodes including the top-level container:
  10191. *
  10192. * .seq - array of nested uniforms
  10193. * .map - nested uniforms by name
  10194. *
  10195. *
  10196. * Methods of all nodes except the top-level container:
  10197. *
  10198. * .setValue( gl, value, [textures] )
  10199. *
  10200. * uploads a uniform value(s)
  10201. * the 'textures' parameter is needed for sampler uniforms
  10202. *
  10203. *
  10204. * Static methods of the top-level container (textures factorizations):
  10205. *
  10206. * .upload( gl, seq, values, textures )
  10207. *
  10208. * sets uniforms in 'seq' to 'values[id].value'
  10209. *
  10210. * .seqWithValue( seq, values ) : filteredSeq
  10211. *
  10212. * filters 'seq' entries with corresponding entry in values
  10213. *
  10214. *
  10215. * Methods of the top-level container (textures factorizations):
  10216. *
  10217. * .setValue( gl, name, value, textures )
  10218. *
  10219. * sets uniform with name 'name' to 'value'
  10220. *
  10221. * .setOptional( gl, obj, prop )
  10222. *
  10223. * like .set for an optional property of the object
  10224. *
  10225. */
  10226. const emptyTexture = new Texture();
  10227. const emptyTexture2dArray = new DataTexture2DArray();
  10228. const emptyTexture3d = new DataTexture3D();
  10229. const emptyCubeTexture = new CubeTexture();
  10230. // --- Utilities ---
  10231. // Array Caches (provide typed arrays for temporary by size)
  10232. const arrayCacheF32 = [];
  10233. const arrayCacheI32 = [];
  10234. // Float32Array caches used for uploading Matrix uniforms
  10235. const mat4array = new Float32Array( 16 );
  10236. const mat3array = new Float32Array( 9 );
  10237. const mat2array = new Float32Array( 4 );
  10238. // Flattening for arrays of vectors and matrices
  10239. function flatten( array, nBlocks, blockSize ) {
  10240. const firstElem = array[ 0 ];
  10241. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10242. // unoptimized: ! isNaN( firstElem )
  10243. // see http://jacksondunstan.com/articles/983
  10244. const n = nBlocks * blockSize;
  10245. let r = arrayCacheF32[ n ];
  10246. if ( r === undefined ) {
  10247. r = new Float32Array( n );
  10248. arrayCacheF32[ n ] = r;
  10249. }
  10250. if ( nBlocks !== 0 ) {
  10251. firstElem.toArray( r, 0 );
  10252. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10253. offset += blockSize;
  10254. array[ i ].toArray( r, offset );
  10255. }
  10256. }
  10257. return r;
  10258. }
  10259. function arraysEqual( a, b ) {
  10260. if ( a.length !== b.length ) return false;
  10261. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10262. if ( a[ i ] !== b[ i ] ) return false;
  10263. }
  10264. return true;
  10265. }
  10266. function copyArray( a, b ) {
  10267. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10268. a[ i ] = b[ i ];
  10269. }
  10270. }
  10271. // Texture unit allocation
  10272. function allocTexUnits( textures, n ) {
  10273. let r = arrayCacheI32[ n ];
  10274. if ( r === undefined ) {
  10275. r = new Int32Array( n );
  10276. arrayCacheI32[ n ] = r;
  10277. }
  10278. for ( let i = 0; i !== n; ++ i ) {
  10279. r[ i ] = textures.allocateTextureUnit();
  10280. }
  10281. return r;
  10282. }
  10283. // --- Setters ---
  10284. // Note: Defining these methods externally, because they come in a bunch
  10285. // and this way their names minify.
  10286. // Single scalar
  10287. function setValueV1f( gl, v ) {
  10288. const cache = this.cache;
  10289. if ( cache[ 0 ] === v ) return;
  10290. gl.uniform1f( this.addr, v );
  10291. cache[ 0 ] = v;
  10292. }
  10293. // Single float vector (from flat array or THREE.VectorN)
  10294. function setValueV2f( gl, v ) {
  10295. const cache = this.cache;
  10296. if ( v.x !== undefined ) {
  10297. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10298. gl.uniform2f( this.addr, v.x, v.y );
  10299. cache[ 0 ] = v.x;
  10300. cache[ 1 ] = v.y;
  10301. }
  10302. } else {
  10303. if ( arraysEqual( cache, v ) ) return;
  10304. gl.uniform2fv( this.addr, v );
  10305. copyArray( cache, v );
  10306. }
  10307. }
  10308. function setValueV3f( gl, v ) {
  10309. const cache = this.cache;
  10310. if ( v.x !== undefined ) {
  10311. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10312. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10313. cache[ 0 ] = v.x;
  10314. cache[ 1 ] = v.y;
  10315. cache[ 2 ] = v.z;
  10316. }
  10317. } else if ( v.r !== undefined ) {
  10318. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10319. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10320. cache[ 0 ] = v.r;
  10321. cache[ 1 ] = v.g;
  10322. cache[ 2 ] = v.b;
  10323. }
  10324. } else {
  10325. if ( arraysEqual( cache, v ) ) return;
  10326. gl.uniform3fv( this.addr, v );
  10327. copyArray( cache, v );
  10328. }
  10329. }
  10330. function setValueV4f( gl, v ) {
  10331. const cache = this.cache;
  10332. if ( v.x !== undefined ) {
  10333. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10334. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10335. cache[ 0 ] = v.x;
  10336. cache[ 1 ] = v.y;
  10337. cache[ 2 ] = v.z;
  10338. cache[ 3 ] = v.w;
  10339. }
  10340. } else {
  10341. if ( arraysEqual( cache, v ) ) return;
  10342. gl.uniform4fv( this.addr, v );
  10343. copyArray( cache, v );
  10344. }
  10345. }
  10346. // Single matrix (from flat array or MatrixN)
  10347. function setValueM2( gl, v ) {
  10348. const cache = this.cache;
  10349. const elements = v.elements;
  10350. if ( elements === undefined ) {
  10351. if ( arraysEqual( cache, v ) ) return;
  10352. gl.uniformMatrix2fv( this.addr, false, v );
  10353. copyArray( cache, v );
  10354. } else {
  10355. if ( arraysEqual( cache, elements ) ) return;
  10356. mat2array.set( elements );
  10357. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10358. copyArray( cache, elements );
  10359. }
  10360. }
  10361. function setValueM3( gl, v ) {
  10362. const cache = this.cache;
  10363. const elements = v.elements;
  10364. if ( elements === undefined ) {
  10365. if ( arraysEqual( cache, v ) ) return;
  10366. gl.uniformMatrix3fv( this.addr, false, v );
  10367. copyArray( cache, v );
  10368. } else {
  10369. if ( arraysEqual( cache, elements ) ) return;
  10370. mat3array.set( elements );
  10371. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10372. copyArray( cache, elements );
  10373. }
  10374. }
  10375. function setValueM4( gl, v ) {
  10376. const cache = this.cache;
  10377. const elements = v.elements;
  10378. if ( elements === undefined ) {
  10379. if ( arraysEqual( cache, v ) ) return;
  10380. gl.uniformMatrix4fv( this.addr, false, v );
  10381. copyArray( cache, v );
  10382. } else {
  10383. if ( arraysEqual( cache, elements ) ) return;
  10384. mat4array.set( elements );
  10385. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10386. copyArray( cache, elements );
  10387. }
  10388. }
  10389. // Single texture (2D / Cube)
  10390. function setValueT1( gl, v, textures ) {
  10391. const cache = this.cache;
  10392. const unit = textures.allocateTextureUnit();
  10393. if ( cache[ 0 ] !== unit ) {
  10394. gl.uniform1i( this.addr, unit );
  10395. cache[ 0 ] = unit;
  10396. }
  10397. textures.safeSetTexture2D( v || emptyTexture, unit );
  10398. }
  10399. function setValueT2DArray1( gl, v, textures ) {
  10400. const cache = this.cache;
  10401. const unit = textures.allocateTextureUnit();
  10402. if ( cache[ 0 ] !== unit ) {
  10403. gl.uniform1i( this.addr, unit );
  10404. cache[ 0 ] = unit;
  10405. }
  10406. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10407. }
  10408. function setValueT3D1( gl, v, textures ) {
  10409. const cache = this.cache;
  10410. const unit = textures.allocateTextureUnit();
  10411. if ( cache[ 0 ] !== unit ) {
  10412. gl.uniform1i( this.addr, unit );
  10413. cache[ 0 ] = unit;
  10414. }
  10415. textures.setTexture3D( v || emptyTexture3d, unit );
  10416. }
  10417. function setValueT6( gl, v, textures ) {
  10418. const cache = this.cache;
  10419. const unit = textures.allocateTextureUnit();
  10420. if ( cache[ 0 ] !== unit ) {
  10421. gl.uniform1i( this.addr, unit );
  10422. cache[ 0 ] = unit;
  10423. }
  10424. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10425. }
  10426. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10427. function setValueV1i( gl, v ) {
  10428. const cache = this.cache;
  10429. if ( cache[ 0 ] === v ) return;
  10430. gl.uniform1i( this.addr, v );
  10431. cache[ 0 ] = v;
  10432. }
  10433. function setValueV2i( gl, v ) {
  10434. const cache = this.cache;
  10435. if ( arraysEqual( cache, v ) ) return;
  10436. gl.uniform2iv( this.addr, v );
  10437. copyArray( cache, v );
  10438. }
  10439. function setValueV3i( gl, v ) {
  10440. const cache = this.cache;
  10441. if ( arraysEqual( cache, v ) ) return;
  10442. gl.uniform3iv( this.addr, v );
  10443. copyArray( cache, v );
  10444. }
  10445. function setValueV4i( gl, v ) {
  10446. const cache = this.cache;
  10447. if ( arraysEqual( cache, v ) ) return;
  10448. gl.uniform4iv( this.addr, v );
  10449. copyArray( cache, v );
  10450. }
  10451. // uint
  10452. function setValueV1ui( gl, v ) {
  10453. const cache = this.cache;
  10454. if ( cache[ 0 ] === v ) return;
  10455. gl.uniform1ui( this.addr, v );
  10456. cache[ 0 ] = v;
  10457. }
  10458. // Helper to pick the right setter for the singular case
  10459. function getSingularSetter( type ) {
  10460. switch ( type ) {
  10461. case 0x1406: return setValueV1f; // FLOAT
  10462. case 0x8b50: return setValueV2f; // _VEC2
  10463. case 0x8b51: return setValueV3f; // _VEC3
  10464. case 0x8b52: return setValueV4f; // _VEC4
  10465. case 0x8b5a: return setValueM2; // _MAT2
  10466. case 0x8b5b: return setValueM3; // _MAT3
  10467. case 0x8b5c: return setValueM4; // _MAT4
  10468. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10469. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10470. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10471. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10472. case 0x1405: return setValueV1ui; // UINT
  10473. case 0x8b5e: // SAMPLER_2D
  10474. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10475. case 0x8dca: // INT_SAMPLER_2D
  10476. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10477. case 0x8b62: // SAMPLER_2D_SHADOW
  10478. return setValueT1;
  10479. case 0x8b5f: // SAMPLER_3D
  10480. case 0x8dcb: // INT_SAMPLER_3D
  10481. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10482. return setValueT3D1;
  10483. case 0x8b60: // SAMPLER_CUBE
  10484. case 0x8dcc: // INT_SAMPLER_CUBE
  10485. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10486. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10487. return setValueT6;
  10488. case 0x8dc1: // SAMPLER_2D_ARRAY
  10489. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10490. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10491. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10492. return setValueT2DArray1;
  10493. }
  10494. }
  10495. // Array of scalars
  10496. function setValueV1fArray( gl, v ) {
  10497. gl.uniform1fv( this.addr, v );
  10498. }
  10499. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10500. function setValueV1iArray( gl, v ) {
  10501. gl.uniform1iv( this.addr, v );
  10502. }
  10503. function setValueV2iArray( gl, v ) {
  10504. gl.uniform2iv( this.addr, v );
  10505. }
  10506. function setValueV3iArray( gl, v ) {
  10507. gl.uniform3iv( this.addr, v );
  10508. }
  10509. function setValueV4iArray( gl, v ) {
  10510. gl.uniform4iv( this.addr, v );
  10511. }
  10512. // Array of vectors (flat or from THREE classes)
  10513. function setValueV2fArray( gl, v ) {
  10514. const data = flatten( v, this.size, 2 );
  10515. gl.uniform2fv( this.addr, data );
  10516. }
  10517. function setValueV3fArray( gl, v ) {
  10518. const data = flatten( v, this.size, 3 );
  10519. gl.uniform3fv( this.addr, data );
  10520. }
  10521. function setValueV4fArray( gl, v ) {
  10522. const data = flatten( v, this.size, 4 );
  10523. gl.uniform4fv( this.addr, data );
  10524. }
  10525. // Array of matrices (flat or from THREE clases)
  10526. function setValueM2Array( gl, v ) {
  10527. const data = flatten( v, this.size, 4 );
  10528. gl.uniformMatrix2fv( this.addr, false, data );
  10529. }
  10530. function setValueM3Array( gl, v ) {
  10531. const data = flatten( v, this.size, 9 );
  10532. gl.uniformMatrix3fv( this.addr, false, data );
  10533. }
  10534. function setValueM4Array( gl, v ) {
  10535. const data = flatten( v, this.size, 16 );
  10536. gl.uniformMatrix4fv( this.addr, false, data );
  10537. }
  10538. // Array of textures (2D / Cube)
  10539. function setValueT1Array( gl, v, textures ) {
  10540. const n = v.length;
  10541. const units = allocTexUnits( textures, n );
  10542. gl.uniform1iv( this.addr, units );
  10543. for ( let i = 0; i !== n; ++ i ) {
  10544. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10545. }
  10546. }
  10547. function setValueT6Array( gl, v, textures ) {
  10548. const n = v.length;
  10549. const units = allocTexUnits( textures, n );
  10550. gl.uniform1iv( this.addr, units );
  10551. for ( let i = 0; i !== n; ++ i ) {
  10552. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10553. }
  10554. }
  10555. // Helper to pick the right setter for a pure (bottom-level) array
  10556. function getPureArraySetter( type ) {
  10557. switch ( type ) {
  10558. case 0x1406: return setValueV1fArray; // FLOAT
  10559. case 0x8b50: return setValueV2fArray; // _VEC2
  10560. case 0x8b51: return setValueV3fArray; // _VEC3
  10561. case 0x8b52: return setValueV4fArray; // _VEC4
  10562. case 0x8b5a: return setValueM2Array; // _MAT2
  10563. case 0x8b5b: return setValueM3Array; // _MAT3
  10564. case 0x8b5c: return setValueM4Array; // _MAT4
  10565. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10566. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10567. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10568. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10569. case 0x8b5e: // SAMPLER_2D
  10570. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10571. case 0x8dca: // INT_SAMPLER_2D
  10572. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10573. case 0x8b62: // SAMPLER_2D_SHADOW
  10574. return setValueT1Array;
  10575. case 0x8b60: // SAMPLER_CUBE
  10576. case 0x8dcc: // INT_SAMPLER_CUBE
  10577. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10578. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10579. return setValueT6Array;
  10580. }
  10581. }
  10582. // --- Uniform Classes ---
  10583. function SingleUniform( id, activeInfo, addr ) {
  10584. this.id = id;
  10585. this.addr = addr;
  10586. this.cache = [];
  10587. this.setValue = getSingularSetter( activeInfo.type );
  10588. // this.path = activeInfo.name; // DEBUG
  10589. }
  10590. function PureArrayUniform( id, activeInfo, addr ) {
  10591. this.id = id;
  10592. this.addr = addr;
  10593. this.cache = [];
  10594. this.size = activeInfo.size;
  10595. this.setValue = getPureArraySetter( activeInfo.type );
  10596. // this.path = activeInfo.name; // DEBUG
  10597. }
  10598. PureArrayUniform.prototype.updateCache = function ( data ) {
  10599. const cache = this.cache;
  10600. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10601. this.cache = new Float32Array( data.length );
  10602. }
  10603. copyArray( cache, data );
  10604. };
  10605. function StructuredUniform( id ) {
  10606. this.id = id;
  10607. this.seq = [];
  10608. this.map = {};
  10609. }
  10610. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10611. const seq = this.seq;
  10612. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10613. const u = seq[ i ];
  10614. u.setValue( gl, value[ u.id ], textures );
  10615. }
  10616. };
  10617. // --- Top-level ---
  10618. // Parser - builds up the property tree from the path strings
  10619. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10620. // extracts
  10621. // - the identifier (member name or array index)
  10622. // - followed by an optional right bracket (found when array index)
  10623. // - followed by an optional left bracket or dot (type of subscript)
  10624. //
  10625. // Note: These portions can be read in a non-overlapping fashion and
  10626. // allow straightforward parsing of the hierarchy that WebGL encodes
  10627. // in the uniform names.
  10628. function addUniform( container, uniformObject ) {
  10629. container.seq.push( uniformObject );
  10630. container.map[ uniformObject.id ] = uniformObject;
  10631. }
  10632. function parseUniform( activeInfo, addr, container ) {
  10633. const path = activeInfo.name,
  10634. pathLength = path.length;
  10635. // reset RegExp object, because of the early exit of a previous run
  10636. RePathPart.lastIndex = 0;
  10637. while ( true ) {
  10638. const match = RePathPart.exec( path ),
  10639. matchEnd = RePathPart.lastIndex;
  10640. let id = match[ 1 ];
  10641. const idIsIndex = match[ 2 ] === ']',
  10642. subscript = match[ 3 ];
  10643. if ( idIsIndex ) id = id | 0; // convert to integer
  10644. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10645. // bare name or "pure" bottom-level array "[0]" suffix
  10646. addUniform( container, subscript === undefined ?
  10647. new SingleUniform( id, activeInfo, addr ) :
  10648. new PureArrayUniform( id, activeInfo, addr ) );
  10649. break;
  10650. } else {
  10651. // step into inner node / create it in case it doesn't exist
  10652. const map = container.map;
  10653. let next = map[ id ];
  10654. if ( next === undefined ) {
  10655. next = new StructuredUniform( id );
  10656. addUniform( container, next );
  10657. }
  10658. container = next;
  10659. }
  10660. }
  10661. }
  10662. // Root Container
  10663. function WebGLUniforms( gl, program ) {
  10664. this.seq = [];
  10665. this.map = {};
  10666. const n = gl.getProgramParameter( program, 35718 );
  10667. for ( let i = 0; i < n; ++ i ) {
  10668. const info = gl.getActiveUniform( program, i ),
  10669. addr = gl.getUniformLocation( program, info.name );
  10670. parseUniform( info, addr, this );
  10671. }
  10672. }
  10673. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10674. const u = this.map[ name ];
  10675. if ( u !== undefined ) u.setValue( gl, value, textures );
  10676. };
  10677. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10678. const v = object[ name ];
  10679. if ( v !== undefined ) this.setValue( gl, name, v );
  10680. };
  10681. // Static interface
  10682. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10683. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10684. const u = seq[ i ],
  10685. v = values[ u.id ];
  10686. if ( v.needsUpdate !== false ) {
  10687. // note: always updating when .needsUpdate is undefined
  10688. u.setValue( gl, v.value, textures );
  10689. }
  10690. }
  10691. };
  10692. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10693. const r = [];
  10694. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10695. const u = seq[ i ];
  10696. if ( u.id in values ) r.push( u );
  10697. }
  10698. return r;
  10699. };
  10700. function WebGLShader( gl, type, string ) {
  10701. const shader = gl.createShader( type );
  10702. gl.shaderSource( shader, string );
  10703. gl.compileShader( shader );
  10704. return shader;
  10705. }
  10706. let programIdCount = 0;
  10707. function addLineNumbers( string ) {
  10708. const lines = string.split( '\n' );
  10709. for ( let i = 0; i < lines.length; i ++ ) {
  10710. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10711. }
  10712. return lines.join( '\n' );
  10713. }
  10714. function getEncodingComponents( encoding ) {
  10715. switch ( encoding ) {
  10716. case LinearEncoding:
  10717. return [ 'Linear', '( value )' ];
  10718. case sRGBEncoding:
  10719. return [ 'sRGB', '( value )' ];
  10720. case RGBEEncoding:
  10721. return [ 'RGBE', '( value )' ];
  10722. case RGBM7Encoding:
  10723. return [ 'RGBM', '( value, 7.0 )' ];
  10724. case RGBM16Encoding:
  10725. return [ 'RGBM', '( value, 16.0 )' ];
  10726. case RGBDEncoding:
  10727. return [ 'RGBD', '( value, 256.0 )' ];
  10728. case GammaEncoding:
  10729. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10730. case LogLuvEncoding:
  10731. return [ 'LogLuv', '( value )' ];
  10732. default:
  10733. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10734. return [ 'Linear', '( value )' ];
  10735. }
  10736. }
  10737. function getShaderErrors( gl, shader, type ) {
  10738. const status = gl.getShaderParameter( shader, 35713 );
  10739. const log = gl.getShaderInfoLog( shader ).trim();
  10740. if ( status && log === '' ) return '';
  10741. // --enable-privileged-webgl-extension
  10742. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10743. const source = gl.getShaderSource( shader );
  10744. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  10745. }
  10746. function getTexelDecodingFunction( functionName, encoding ) {
  10747. const components = getEncodingComponents( encoding );
  10748. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10749. }
  10750. function getTexelEncodingFunction( functionName, encoding ) {
  10751. const components = getEncodingComponents( encoding );
  10752. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10753. }
  10754. function getToneMappingFunction( functionName, toneMapping ) {
  10755. let toneMappingName;
  10756. switch ( toneMapping ) {
  10757. case LinearToneMapping:
  10758. toneMappingName = 'Linear';
  10759. break;
  10760. case ReinhardToneMapping:
  10761. toneMappingName = 'Reinhard';
  10762. break;
  10763. case CineonToneMapping:
  10764. toneMappingName = 'OptimizedCineon';
  10765. break;
  10766. case ACESFilmicToneMapping:
  10767. toneMappingName = 'ACESFilmic';
  10768. break;
  10769. case CustomToneMapping:
  10770. toneMappingName = 'Custom';
  10771. break;
  10772. default:
  10773. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10774. toneMappingName = 'Linear';
  10775. }
  10776. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10777. }
  10778. function generateExtensions( parameters ) {
  10779. const chunks = [
  10780. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10781. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10782. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10783. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10784. ];
  10785. return chunks.filter( filterEmptyLine ).join( '\n' );
  10786. }
  10787. function generateDefines( defines ) {
  10788. const chunks = [];
  10789. for ( const name in defines ) {
  10790. const value = defines[ name ];
  10791. if ( value === false ) continue;
  10792. chunks.push( '#define ' + name + ' ' + value );
  10793. }
  10794. return chunks.join( '\n' );
  10795. }
  10796. function fetchAttributeLocations( gl, program ) {
  10797. const attributes = {};
  10798. const n = gl.getProgramParameter( program, 35721 );
  10799. for ( let i = 0; i < n; i ++ ) {
  10800. const info = gl.getActiveAttrib( program, i );
  10801. const name = info.name;
  10802. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10803. attributes[ name ] = gl.getAttribLocation( program, name );
  10804. }
  10805. return attributes;
  10806. }
  10807. function filterEmptyLine( string ) {
  10808. return string !== '';
  10809. }
  10810. function replaceLightNums( string, parameters ) {
  10811. return string
  10812. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10813. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10814. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10815. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10816. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10817. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10818. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10819. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10820. }
  10821. function replaceClippingPlaneNums( string, parameters ) {
  10822. return string
  10823. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10824. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10825. }
  10826. // Resolve Includes
  10827. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10828. function resolveIncludes( string ) {
  10829. return string.replace( includePattern, includeReplacer );
  10830. }
  10831. function includeReplacer( match, include ) {
  10832. const string = ShaderChunk[ include ];
  10833. if ( string === undefined ) {
  10834. throw new Error( 'Can not resolve #include <' + include + '>' );
  10835. }
  10836. return resolveIncludes( string );
  10837. }
  10838. // Unroll Loops
  10839. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10840. 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;
  10841. function unrollLoops( string ) {
  10842. return string
  10843. .replace( unrollLoopPattern, loopReplacer )
  10844. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10845. }
  10846. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10847. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10848. return loopReplacer( match, start, end, snippet );
  10849. }
  10850. function loopReplacer( match, start, end, snippet ) {
  10851. let string = '';
  10852. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10853. string += snippet
  10854. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10855. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10856. }
  10857. return string;
  10858. }
  10859. //
  10860. function generatePrecision( parameters ) {
  10861. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10862. if ( parameters.precision === 'highp' ) {
  10863. precisionstring += '\n#define HIGH_PRECISION';
  10864. } else if ( parameters.precision === 'mediump' ) {
  10865. precisionstring += '\n#define MEDIUM_PRECISION';
  10866. } else if ( parameters.precision === 'lowp' ) {
  10867. precisionstring += '\n#define LOW_PRECISION';
  10868. }
  10869. return precisionstring;
  10870. }
  10871. function generateShadowMapTypeDefine( parameters ) {
  10872. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10873. if ( parameters.shadowMapType === PCFShadowMap ) {
  10874. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10875. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10876. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10877. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10878. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10879. }
  10880. return shadowMapTypeDefine;
  10881. }
  10882. function generateEnvMapTypeDefine( parameters ) {
  10883. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10884. if ( parameters.envMap ) {
  10885. switch ( parameters.envMapMode ) {
  10886. case CubeReflectionMapping:
  10887. case CubeRefractionMapping:
  10888. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10889. break;
  10890. case CubeUVReflectionMapping:
  10891. case CubeUVRefractionMapping:
  10892. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10893. break;
  10894. }
  10895. }
  10896. return envMapTypeDefine;
  10897. }
  10898. function generateEnvMapModeDefine( parameters ) {
  10899. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10900. if ( parameters.envMap ) {
  10901. switch ( parameters.envMapMode ) {
  10902. case CubeRefractionMapping:
  10903. case CubeUVRefractionMapping:
  10904. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10905. break;
  10906. }
  10907. }
  10908. return envMapModeDefine;
  10909. }
  10910. function generateEnvMapBlendingDefine( parameters ) {
  10911. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10912. if ( parameters.envMap ) {
  10913. switch ( parameters.combine ) {
  10914. case MultiplyOperation:
  10915. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10916. break;
  10917. case MixOperation:
  10918. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10919. break;
  10920. case AddOperation:
  10921. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10922. break;
  10923. }
  10924. }
  10925. return envMapBlendingDefine;
  10926. }
  10927. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10928. const gl = renderer.getContext();
  10929. const defines = parameters.defines;
  10930. let vertexShader = parameters.vertexShader;
  10931. let fragmentShader = parameters.fragmentShader;
  10932. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10933. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10934. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10935. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10936. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10937. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10938. const customDefines = generateDefines( defines );
  10939. const program = gl.createProgram();
  10940. let prefixVertex, prefixFragment;
  10941. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10942. if ( parameters.isRawShaderMaterial ) {
  10943. prefixVertex = [
  10944. customDefines
  10945. ].filter( filterEmptyLine ).join( '\n' );
  10946. if ( prefixVertex.length > 0 ) {
  10947. prefixVertex += '\n';
  10948. }
  10949. prefixFragment = [
  10950. customExtensions,
  10951. customDefines
  10952. ].filter( filterEmptyLine ).join( '\n' );
  10953. if ( prefixFragment.length > 0 ) {
  10954. prefixFragment += '\n';
  10955. }
  10956. } else {
  10957. prefixVertex = [
  10958. generatePrecision( parameters ),
  10959. '#define SHADER_NAME ' + parameters.shaderName,
  10960. customDefines,
  10961. parameters.instancing ? '#define USE_INSTANCING' : '',
  10962. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10963. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10964. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10965. '#define MAX_BONES ' + parameters.maxBones,
  10966. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10967. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10968. parameters.map ? '#define USE_MAP' : '',
  10969. parameters.envMap ? '#define USE_ENVMAP' : '',
  10970. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10971. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10972. parameters.aoMap ? '#define USE_AOMAP' : '',
  10973. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10974. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10975. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10976. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10977. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10978. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10979. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10980. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10981. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10982. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10983. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10984. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10985. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10986. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10987. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10988. parameters.vertexColors ? '#define USE_COLOR' : '',
  10989. parameters.vertexUvs ? '#define USE_UV' : '',
  10990. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10991. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10992. parameters.skinning ? '#define USE_SKINNING' : '',
  10993. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10994. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10995. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10996. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10997. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10998. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10999. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11000. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11001. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11002. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11003. 'uniform mat4 modelMatrix;',
  11004. 'uniform mat4 modelViewMatrix;',
  11005. 'uniform mat4 projectionMatrix;',
  11006. 'uniform mat4 viewMatrix;',
  11007. 'uniform mat3 normalMatrix;',
  11008. 'uniform vec3 cameraPosition;',
  11009. 'uniform bool isOrthographic;',
  11010. '#ifdef USE_INSTANCING',
  11011. ' attribute mat4 instanceMatrix;',
  11012. '#endif',
  11013. '#ifdef USE_INSTANCING_COLOR',
  11014. ' attribute vec3 instanceColor;',
  11015. '#endif',
  11016. 'attribute vec3 position;',
  11017. 'attribute vec3 normal;',
  11018. 'attribute vec2 uv;',
  11019. '#ifdef USE_TANGENT',
  11020. ' attribute vec4 tangent;',
  11021. '#endif',
  11022. '#ifdef USE_COLOR',
  11023. ' attribute vec3 color;',
  11024. '#endif',
  11025. '#ifdef USE_MORPHTARGETS',
  11026. ' attribute vec3 morphTarget0;',
  11027. ' attribute vec3 morphTarget1;',
  11028. ' attribute vec3 morphTarget2;',
  11029. ' attribute vec3 morphTarget3;',
  11030. ' #ifdef USE_MORPHNORMALS',
  11031. ' attribute vec3 morphNormal0;',
  11032. ' attribute vec3 morphNormal1;',
  11033. ' attribute vec3 morphNormal2;',
  11034. ' attribute vec3 morphNormal3;',
  11035. ' #else',
  11036. ' attribute vec3 morphTarget4;',
  11037. ' attribute vec3 morphTarget5;',
  11038. ' attribute vec3 morphTarget6;',
  11039. ' attribute vec3 morphTarget7;',
  11040. ' #endif',
  11041. '#endif',
  11042. '#ifdef USE_SKINNING',
  11043. ' attribute vec4 skinIndex;',
  11044. ' attribute vec4 skinWeight;',
  11045. '#endif',
  11046. '\n'
  11047. ].filter( filterEmptyLine ).join( '\n' );
  11048. prefixFragment = [
  11049. customExtensions,
  11050. generatePrecision( parameters ),
  11051. '#define SHADER_NAME ' + parameters.shaderName,
  11052. customDefines,
  11053. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  11054. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11055. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11056. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11057. parameters.map ? '#define USE_MAP' : '',
  11058. parameters.matcap ? '#define USE_MATCAP' : '',
  11059. parameters.envMap ? '#define USE_ENVMAP' : '',
  11060. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11061. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11062. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11063. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11064. parameters.aoMap ? '#define USE_AOMAP' : '',
  11065. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11066. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11067. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11068. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11069. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11070. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11071. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11072. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11073. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11074. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11075. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11076. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11077. parameters.sheen ? '#define USE_SHEEN' : '',
  11078. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11079. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11080. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11081. parameters.vertexUvs ? '#define USE_UV' : '',
  11082. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11083. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11084. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11085. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11086. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11087. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11088. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11089. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11090. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11091. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11092. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11093. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11094. 'uniform mat4 viewMatrix;',
  11095. 'uniform vec3 cameraPosition;',
  11096. 'uniform bool isOrthographic;',
  11097. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11098. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11099. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11100. parameters.dithering ? '#define DITHERING' : '',
  11101. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11102. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11103. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11104. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11105. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11106. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11107. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11108. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11109. '\n'
  11110. ].filter( filterEmptyLine ).join( '\n' );
  11111. }
  11112. vertexShader = resolveIncludes( vertexShader );
  11113. vertexShader = replaceLightNums( vertexShader, parameters );
  11114. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11115. fragmentShader = resolveIncludes( fragmentShader );
  11116. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11117. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11118. vertexShader = unrollLoops( vertexShader );
  11119. fragmentShader = unrollLoops( fragmentShader );
  11120. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11121. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11122. versionString = '#version 300 es\n';
  11123. prefixVertex = [
  11124. '#define attribute in',
  11125. '#define varying out',
  11126. '#define texture2D texture'
  11127. ].join( '\n' ) + '\n' + prefixVertex;
  11128. prefixFragment = [
  11129. '#define varying in',
  11130. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11131. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11132. '#define gl_FragDepthEXT gl_FragDepth',
  11133. '#define texture2D texture',
  11134. '#define textureCube texture',
  11135. '#define texture2DProj textureProj',
  11136. '#define texture2DLodEXT textureLod',
  11137. '#define texture2DProjLodEXT textureProjLod',
  11138. '#define textureCubeLodEXT textureLod',
  11139. '#define texture2DGradEXT textureGrad',
  11140. '#define texture2DProjGradEXT textureProjGrad',
  11141. '#define textureCubeGradEXT textureGrad'
  11142. ].join( '\n' ) + '\n' + prefixFragment;
  11143. }
  11144. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11145. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11146. // console.log( '*VERTEX*', vertexGlsl );
  11147. // console.log( '*FRAGMENT*', fragmentGlsl );
  11148. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11149. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11150. gl.attachShader( program, glVertexShader );
  11151. gl.attachShader( program, glFragmentShader );
  11152. // Force a particular attribute to index 0.
  11153. if ( parameters.index0AttributeName !== undefined ) {
  11154. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11155. } else if ( parameters.morphTargets === true ) {
  11156. // programs with morphTargets displace position out of attribute 0
  11157. gl.bindAttribLocation( program, 0, 'position' );
  11158. }
  11159. gl.linkProgram( program );
  11160. // check for link errors
  11161. if ( renderer.debug.checkShaderErrors ) {
  11162. const programLog = gl.getProgramInfoLog( program ).trim();
  11163. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11164. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11165. let runnable = true;
  11166. let haveDiagnostics = true;
  11167. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11168. runnable = false;
  11169. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11170. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11171. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  11172. //add:
  11173. if(fragmentErrors){
  11174. console.log(fragmentGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  11175. }else {
  11176. console.log(vertexGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  11177. }
  11178. } else if ( programLog !== '' ) {
  11179. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  11180. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11181. haveDiagnostics = false;
  11182. }
  11183. if ( haveDiagnostics ) {
  11184. this.diagnostics = {
  11185. runnable: runnable,
  11186. programLog: programLog,
  11187. vertexShader: {
  11188. log: vertexLog,
  11189. prefix: prefixVertex
  11190. },
  11191. fragmentShader: {
  11192. log: fragmentLog,
  11193. prefix: prefixFragment
  11194. }
  11195. };
  11196. }
  11197. }
  11198. // Clean up
  11199. // Crashes in iOS9 and iOS10. #18402
  11200. // gl.detachShader( program, glVertexShader );
  11201. // gl.detachShader( program, glFragmentShader );
  11202. gl.deleteShader( glVertexShader );
  11203. gl.deleteShader( glFragmentShader );
  11204. // set up caching for uniform locations
  11205. let cachedUniforms;
  11206. this.getUniforms = function () {
  11207. if ( cachedUniforms === undefined ) {
  11208. cachedUniforms = new WebGLUniforms( gl, program );
  11209. }
  11210. return cachedUniforms;
  11211. };
  11212. // set up caching for attribute locations
  11213. let cachedAttributes;
  11214. this.getAttributes = function () {
  11215. if ( cachedAttributes === undefined ) {
  11216. cachedAttributes = fetchAttributeLocations( gl, program );
  11217. }
  11218. return cachedAttributes;
  11219. };
  11220. // free resource
  11221. this.destroy = function () {
  11222. bindingStates.releaseStatesOfProgram( this );
  11223. gl.deleteProgram( program );
  11224. this.program = undefined;
  11225. };
  11226. //
  11227. this.name = parameters.shaderName;
  11228. this.id = programIdCount ++;
  11229. this.cacheKey = cacheKey;
  11230. this.usedTimes = 1;
  11231. this.program = program;
  11232. this.vertexShader = glVertexShader;
  11233. this.fragmentShader = glFragmentShader;
  11234. return this;
  11235. }
  11236. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  11237. const programs = [];
  11238. const isWebGL2 = capabilities.isWebGL2;
  11239. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11240. const floatVertexTextures = capabilities.floatVertexTextures;
  11241. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11242. const vertexTextures = capabilities.vertexTextures;
  11243. let precision = capabilities.precision;
  11244. const shaderIDs = {
  11245. MeshDepthMaterial: 'depth',
  11246. MeshDistanceMaterial: 'distanceRGBA',
  11247. MeshNormalMaterial: 'normal',
  11248. MeshBasicMaterial: 'basic',
  11249. MeshLambertMaterial: 'lambert',
  11250. MeshPhongMaterial: 'phong',
  11251. MeshToonMaterial: 'toon',
  11252. MeshStandardMaterial: 'physical',
  11253. MeshPhysicalMaterial: 'physical',
  11254. MeshMatcapMaterial: 'matcap',
  11255. LineBasicMaterial: 'basic',
  11256. LineDashedMaterial: 'dashed',
  11257. PointsMaterial: 'points',
  11258. ShadowMaterial: 'shadow',
  11259. SpriteMaterial: 'sprite'
  11260. };
  11261. const parameterNames = [
  11262. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  11263. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  11264. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  11265. 'roughnessMap', 'metalnessMap', 'gradientMap',
  11266. 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  11267. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  11268. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals',
  11269. 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha',
  11270. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  11271. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  11272. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  11273. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  11274. 'sheen', 'transmissionMap'
  11275. ];
  11276. function getMaxBones( object ) {
  11277. const skeleton = object.skeleton;
  11278. const bones = skeleton.bones;
  11279. if ( floatVertexTextures ) {
  11280. return 1024;
  11281. } else {
  11282. // default for when object is not specified
  11283. // ( for example when prebuilding shader to be used with multiple objects )
  11284. //
  11285. // - leave some extra space for other uniforms
  11286. // - limit here is ANGLE's 254 max uniform vectors
  11287. // (up to 54 should be safe)
  11288. const nVertexUniforms = maxVertexUniforms;
  11289. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11290. const maxBones = Math.min( nVertexMatrices, bones.length );
  11291. if ( maxBones < bones.length ) {
  11292. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11293. return 0;
  11294. }
  11295. return maxBones;
  11296. }
  11297. }
  11298. function getTextureEncodingFromMap( map ) {
  11299. let encoding;
  11300. if ( map && map.isTexture ) {
  11301. encoding = map.encoding;
  11302. } else if ( map && map.isWebGLRenderTarget ) {
  11303. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  11304. encoding = map.texture.encoding;
  11305. } else {
  11306. encoding = LinearEncoding;
  11307. }
  11308. return encoding;
  11309. }
  11310. function getParameters( material, lights, shadows, scene, object ) {
  11311. const fog = scene.fog;
  11312. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11313. const envMap = cubemaps.get( material.envMap || environment );
  11314. const shaderID = shaderIDs[ material.type ];
  11315. // heuristics to create shader parameters according to lights in the scene
  11316. // (not to blow over maxLights budget)
  11317. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11318. if ( material.precision !== null ) {
  11319. precision = capabilities.getMaxPrecision( material.precision );
  11320. if ( precision !== material.precision ) {
  11321. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11322. }
  11323. }
  11324. let vertexShader, fragmentShader;
  11325. if ( shaderID ) {
  11326. const shader = ShaderLib[ shaderID ];
  11327. vertexShader = shader.vertexShader;
  11328. fragmentShader = shader.fragmentShader;
  11329. } else {
  11330. vertexShader = material.vertexShader;
  11331. fragmentShader = material.fragmentShader;
  11332. }
  11333. const currentRenderTarget = renderer.getRenderTarget();
  11334. const parameters = {
  11335. isWebGL2: isWebGL2,
  11336. shaderID: shaderID,
  11337. shaderName: material.type,
  11338. vertexShader: vertexShader,
  11339. fragmentShader: fragmentShader,
  11340. defines: material.defines,
  11341. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11342. glslVersion: material.glslVersion,
  11343. precision: precision,
  11344. instancing: object.isInstancedMesh === true,
  11345. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11346. supportsVertexTextures: vertexTextures,
  11347. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11348. map: !! material.map,
  11349. mapEncoding: getTextureEncodingFromMap( material.map ),
  11350. matcap: !! material.matcap,
  11351. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11352. envMap: !! envMap,
  11353. envMapMode: envMap && envMap.mapping,
  11354. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11355. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11356. lightMap: !! material.lightMap,
  11357. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11358. aoMap: !! material.aoMap,
  11359. emissiveMap: !! material.emissiveMap,
  11360. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11361. bumpMap: !! material.bumpMap,
  11362. normalMap: !! material.normalMap,
  11363. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11364. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11365. clearcoatMap: !! material.clearcoatMap,
  11366. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  11367. clearcoatNormalMap: !! material.clearcoatNormalMap,
  11368. displacementMap: !! material.displacementMap,
  11369. roughnessMap: !! material.roughnessMap,
  11370. metalnessMap: !! material.metalnessMap,
  11371. specularMap: !! material.specularMap,
  11372. alphaMap: !! material.alphaMap,
  11373. gradientMap: !! material.gradientMap,
  11374. sheen: !! material.sheen,
  11375. transmissionMap: !! material.transmissionMap,
  11376. combine: material.combine,
  11377. vertexTangents: ( material.normalMap && material.vertexTangents ),
  11378. vertexColors: material.vertexColors,
  11379. 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,
  11380. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  11381. fog: !! fog,
  11382. useFog: material.fog,
  11383. fogExp2: ( fog && fog.isFogExp2 ),
  11384. flatShading: material.flatShading,
  11385. sizeAttenuation: material.sizeAttenuation,
  11386. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11387. skinning: material.skinning && maxBones > 0,
  11388. maxBones: maxBones,
  11389. useVertexTexture: floatVertexTextures,
  11390. morphTargets: material.morphTargets,
  11391. morphNormals: material.morphNormals,
  11392. maxMorphTargets: renderer.maxMorphTargets,
  11393. maxMorphNormals: renderer.maxMorphNormals,
  11394. numDirLights: lights.directional.length,
  11395. numPointLights: lights.point.length,
  11396. numSpotLights: lights.spot.length,
  11397. numRectAreaLights: lights.rectArea.length,
  11398. numHemiLights: lights.hemi.length,
  11399. numDirLightShadows: lights.directionalShadowMap.length,
  11400. numPointLightShadows: lights.pointShadowMap.length,
  11401. numSpotLightShadows: lights.spotShadowMap.length,
  11402. numClippingPlanes: clipping.numPlanes,
  11403. numClipIntersection: clipping.numIntersection,
  11404. dithering: material.dithering,
  11405. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11406. shadowMapType: renderer.shadowMap.type,
  11407. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11408. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11409. premultipliedAlpha: material.premultipliedAlpha,
  11410. alphaTest: material.alphaTest,
  11411. doubleSided: material.side === DoubleSide,
  11412. flipSided: material.side === BackSide,
  11413. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11414. index0AttributeName: material.index0AttributeName,
  11415. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11416. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11417. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11418. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11419. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11420. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11421. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11422. customProgramCacheKey: material.customProgramCacheKey()
  11423. };
  11424. return parameters;
  11425. }
  11426. function getProgramCacheKey( parameters ) {
  11427. const array = [];
  11428. if ( parameters.shaderID ) {
  11429. array.push( parameters.shaderID );
  11430. } else {
  11431. array.push( parameters.fragmentShader );
  11432. array.push( parameters.vertexShader );
  11433. }
  11434. if ( parameters.defines !== undefined ) {
  11435. for ( const name in parameters.defines ) {
  11436. array.push( name );
  11437. array.push( parameters.defines[ name ] );
  11438. }
  11439. }
  11440. if ( parameters.isRawShaderMaterial === false ) {
  11441. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11442. array.push( parameters[ parameterNames[ i ] ] );
  11443. }
  11444. array.push( renderer.outputEncoding );
  11445. array.push( renderer.gammaFactor );
  11446. }
  11447. array.push( parameters.customProgramCacheKey );
  11448. return array.join();
  11449. }
  11450. function getUniforms( material ) {
  11451. const shaderID = shaderIDs[ material.type ];
  11452. let uniforms;
  11453. if ( shaderID ) {
  11454. const shader = ShaderLib[ shaderID ];
  11455. uniforms = UniformsUtils.clone( shader.uniforms );
  11456. } else {
  11457. uniforms = material.uniforms;
  11458. }
  11459. return uniforms;
  11460. }
  11461. function acquireProgram( parameters, cacheKey ) {
  11462. let program;
  11463. // Check if code has been already compiled
  11464. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11465. const preexistingProgram = programs[ p ];
  11466. if ( preexistingProgram.cacheKey === cacheKey ) {
  11467. program = preexistingProgram;
  11468. ++ program.usedTimes;
  11469. break;
  11470. }
  11471. }
  11472. if ( program === undefined ) {
  11473. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11474. programs.push( program );
  11475. }
  11476. return program;
  11477. }
  11478. function releaseProgram( program ) {
  11479. if ( -- program.usedTimes === 0 ) {
  11480. // Remove from unordered set
  11481. const i = programs.indexOf( program );
  11482. programs[ i ] = programs[ programs.length - 1 ];
  11483. programs.pop();
  11484. // Free WebGL resources
  11485. program.destroy();
  11486. }
  11487. }
  11488. return {
  11489. getParameters: getParameters,
  11490. getProgramCacheKey: getProgramCacheKey,
  11491. getUniforms: getUniforms,
  11492. acquireProgram: acquireProgram,
  11493. releaseProgram: releaseProgram,
  11494. // Exposed for resource monitoring & error feedback via renderer.info:
  11495. programs: programs
  11496. };
  11497. }
  11498. function WebGLProperties() {
  11499. let properties = new WeakMap();
  11500. function get( object ) {
  11501. let map = properties.get( object );
  11502. if ( map === undefined ) {
  11503. map = {};
  11504. properties.set( object, map );
  11505. }
  11506. return map;
  11507. }
  11508. function remove( object ) {
  11509. properties.delete( object );
  11510. }
  11511. function update( object, key, value ) {
  11512. properties.get( object )[ key ] = value;
  11513. }
  11514. function dispose() {
  11515. properties = new WeakMap();
  11516. }
  11517. return {
  11518. get: get,
  11519. remove: remove,
  11520. update: update,
  11521. dispose: dispose
  11522. };
  11523. }
  11524. function painterSortStable( a, b ) {
  11525. if ( a.groupOrder !== b.groupOrder ) {
  11526. return a.groupOrder - b.groupOrder;
  11527. } else if ( a.renderOrder !== b.renderOrder ) {
  11528. return a.renderOrder - b.renderOrder;
  11529. } else if ( a.program !== b.program ) {
  11530. return a.program.id - b.program.id;
  11531. } else if ( a.material.id !== b.material.id ) {
  11532. return a.material.id - b.material.id;
  11533. } else if ( a.z !== b.z ) {
  11534. return a.z - b.z;
  11535. } else {
  11536. return a.id - b.id;
  11537. }
  11538. }
  11539. function reversePainterSortStable( a, b ) {
  11540. if ( a.groupOrder !== b.groupOrder ) {
  11541. return a.groupOrder - b.groupOrder;
  11542. } else if ( a.renderOrder !== b.renderOrder ) {
  11543. return a.renderOrder - b.renderOrder;
  11544. } else if ( a.z !== b.z ) {
  11545. return b.z - a.z;
  11546. } else {
  11547. return a.id - b.id;
  11548. }
  11549. }
  11550. function WebGLRenderList( properties ) {
  11551. const renderItems = [];
  11552. let renderItemsIndex = 0;
  11553. const opaque = [];
  11554. const transparent = [];
  11555. const defaultProgram = { id: - 1 };
  11556. function init() {
  11557. renderItemsIndex = 0;
  11558. opaque.length = 0;
  11559. transparent.length = 0;
  11560. }
  11561. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11562. let renderItem = renderItems[ renderItemsIndex ];
  11563. const materialProperties = properties.get( material );
  11564. if ( renderItem === undefined ) {
  11565. renderItem = {
  11566. id: object.id,
  11567. object: object,
  11568. geometry: geometry,
  11569. material: material,
  11570. program: materialProperties.program || defaultProgram,
  11571. groupOrder: groupOrder,
  11572. renderOrder: object.renderOrder,
  11573. z: z,
  11574. group: group
  11575. };
  11576. renderItems[ renderItemsIndex ] = renderItem;
  11577. } else {
  11578. renderItem.id = object.id;
  11579. renderItem.object = object;
  11580. renderItem.geometry = geometry;
  11581. renderItem.material = material;
  11582. renderItem.program = materialProperties.program || defaultProgram;
  11583. renderItem.groupOrder = groupOrder;
  11584. renderItem.renderOrder = object.renderOrder;
  11585. renderItem.z = z;
  11586. renderItem.group = group;
  11587. }
  11588. renderItemsIndex ++;
  11589. return renderItem;
  11590. }
  11591. function push( object, geometry, material, groupOrder, z, group ) {
  11592. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11593. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  11594. }
  11595. function unshift( object, geometry, material, groupOrder, z, group ) {
  11596. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11597. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  11598. }
  11599. function sort( customOpaqueSort, customTransparentSort ) {
  11600. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11601. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11602. }
  11603. function finish() {
  11604. // Clear references from inactive renderItems in the list
  11605. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11606. const renderItem = renderItems[ i ];
  11607. if ( renderItem.id === null ) break;
  11608. renderItem.id = null;
  11609. renderItem.object = null;
  11610. renderItem.geometry = null;
  11611. renderItem.material = null;
  11612. renderItem.program = null;
  11613. renderItem.group = null;
  11614. }
  11615. }
  11616. return {
  11617. opaque: opaque,
  11618. transparent: transparent,
  11619. init: init,
  11620. push: push,
  11621. unshift: unshift,
  11622. finish: finish,
  11623. sort: sort
  11624. };
  11625. }
  11626. function WebGLRenderLists( properties ) {
  11627. let lists = new WeakMap();
  11628. function get( scene, camera ) {
  11629. const cameras = lists.get( scene );
  11630. let list;
  11631. if ( cameras === undefined ) {
  11632. list = new WebGLRenderList( properties );
  11633. lists.set( scene, new WeakMap() );
  11634. lists.get( scene ).set( camera, list );
  11635. } else {
  11636. list = cameras.get( camera );
  11637. if ( list === undefined ) {
  11638. list = new WebGLRenderList( properties );
  11639. cameras.set( camera, list );
  11640. }
  11641. }
  11642. return list;
  11643. }
  11644. function dispose() {
  11645. lists = new WeakMap();
  11646. }
  11647. return {
  11648. get: get,
  11649. dispose: dispose
  11650. };
  11651. }
  11652. function UniformsCache() {
  11653. const lights = {};
  11654. return {
  11655. get: function ( light ) {
  11656. if ( lights[ light.id ] !== undefined ) {
  11657. return lights[ light.id ];
  11658. }
  11659. let uniforms;
  11660. switch ( light.type ) {
  11661. case 'DirectionalLight':
  11662. uniforms = {
  11663. direction: new Vector3(),
  11664. color: new Color()
  11665. };
  11666. break;
  11667. case 'SpotLight':
  11668. uniforms = {
  11669. position: new Vector3(),
  11670. direction: new Vector3(),
  11671. color: new Color(),
  11672. distance: 0,
  11673. coneCos: 0,
  11674. penumbraCos: 0,
  11675. decay: 0
  11676. };
  11677. break;
  11678. case 'PointLight':
  11679. uniforms = {
  11680. position: new Vector3(),
  11681. color: new Color(),
  11682. distance: 0,
  11683. decay: 0
  11684. };
  11685. break;
  11686. case 'HemisphereLight':
  11687. uniforms = {
  11688. direction: new Vector3(),
  11689. skyColor: new Color(),
  11690. groundColor: new Color()
  11691. };
  11692. break;
  11693. case 'RectAreaLight':
  11694. uniforms = {
  11695. color: new Color(),
  11696. position: new Vector3(),
  11697. halfWidth: new Vector3(),
  11698. halfHeight: new Vector3()
  11699. };
  11700. break;
  11701. }
  11702. lights[ light.id ] = uniforms;
  11703. return uniforms;
  11704. }
  11705. };
  11706. }
  11707. function ShadowUniformsCache() {
  11708. const lights = {};
  11709. return {
  11710. get: function ( light ) {
  11711. if ( lights[ light.id ] !== undefined ) {
  11712. return lights[ light.id ];
  11713. }
  11714. let uniforms;
  11715. switch ( light.type ) {
  11716. case 'DirectionalLight':
  11717. uniforms = {
  11718. shadowBias: 0,
  11719. shadowNormalBias: 0,
  11720. shadowRadius: 1,
  11721. shadowMapSize: new Vector2$1()
  11722. };
  11723. break;
  11724. case 'SpotLight':
  11725. uniforms = {
  11726. shadowBias: 0,
  11727. shadowNormalBias: 0,
  11728. shadowRadius: 1,
  11729. shadowMapSize: new Vector2$1()
  11730. };
  11731. break;
  11732. case 'PointLight':
  11733. uniforms = {
  11734. shadowBias: 0,
  11735. shadowNormalBias: 0,
  11736. shadowRadius: 1,
  11737. shadowMapSize: new Vector2$1(),
  11738. shadowCameraNear: 1,
  11739. shadowCameraFar: 1000
  11740. };
  11741. break;
  11742. // TODO (abelnation): set RectAreaLight shadow uniforms
  11743. }
  11744. lights[ light.id ] = uniforms;
  11745. return uniforms;
  11746. }
  11747. };
  11748. }
  11749. let nextVersion = 0;
  11750. function shadowCastingLightsFirst( lightA, lightB ) {
  11751. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11752. }
  11753. function WebGLLights( extensions, capabilities ) {
  11754. const cache = new UniformsCache();
  11755. const shadowCache = ShadowUniformsCache();
  11756. const state = {
  11757. version: 0,
  11758. hash: {
  11759. directionalLength: - 1,
  11760. pointLength: - 1,
  11761. spotLength: - 1,
  11762. rectAreaLength: - 1,
  11763. hemiLength: - 1,
  11764. numDirectionalShadows: - 1,
  11765. numPointShadows: - 1,
  11766. numSpotShadows: - 1
  11767. },
  11768. ambient: [ 0, 0, 0 ],
  11769. probe: [],
  11770. directional: [],
  11771. directionalShadow: [],
  11772. directionalShadowMap: [],
  11773. directionalShadowMatrix: [],
  11774. spot: [],
  11775. spotShadow: [],
  11776. spotShadowMap: [],
  11777. spotShadowMatrix: [],
  11778. rectArea: [],
  11779. rectAreaLTC1: null,
  11780. rectAreaLTC2: null,
  11781. point: [],
  11782. pointShadow: [],
  11783. pointShadowMap: [],
  11784. pointShadowMatrix: [],
  11785. hemi: []
  11786. };
  11787. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11788. const vector3 = new Vector3();
  11789. const matrix4 = new Matrix4();
  11790. const matrix42 = new Matrix4();
  11791. function setup( lights ) {
  11792. let r = 0, g = 0, b = 0;
  11793. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11794. let directionalLength = 0;
  11795. let pointLength = 0;
  11796. let spotLength = 0;
  11797. let rectAreaLength = 0;
  11798. let hemiLength = 0;
  11799. let numDirectionalShadows = 0;
  11800. let numPointShadows = 0;
  11801. let numSpotShadows = 0;
  11802. lights.sort( shadowCastingLightsFirst );
  11803. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11804. const light = lights[ i ];
  11805. const color = light.color;
  11806. const intensity = light.intensity;
  11807. const distance = light.distance;
  11808. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11809. if ( light.isAmbientLight ) {
  11810. r += color.r * intensity;
  11811. g += color.g * intensity;
  11812. b += color.b * intensity;
  11813. } else if ( light.isLightProbe ) {
  11814. for ( let j = 0; j < 9; j ++ ) {
  11815. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11816. }
  11817. } else if ( light.isDirectionalLight ) {
  11818. const uniforms = cache.get( light );
  11819. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11820. if ( light.castShadow ) {
  11821. const shadow = light.shadow;
  11822. const shadowUniforms = shadowCache.get( light );
  11823. shadowUniforms.shadowBias = shadow.bias;
  11824. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11825. shadowUniforms.shadowRadius = shadow.radius;
  11826. shadowUniforms.shadowMapSize = shadow.mapSize;
  11827. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11828. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11829. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11830. numDirectionalShadows ++;
  11831. }
  11832. state.directional[ directionalLength ] = uniforms;
  11833. directionalLength ++;
  11834. } else if ( light.isSpotLight ) {
  11835. const uniforms = cache.get( light );
  11836. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11837. uniforms.color.copy( color ).multiplyScalar( intensity );
  11838. uniforms.distance = distance;
  11839. uniforms.coneCos = Math.cos( light.angle );
  11840. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11841. uniforms.decay = light.decay;
  11842. if ( light.castShadow ) {
  11843. const shadow = light.shadow;
  11844. const shadowUniforms = shadowCache.get( light );
  11845. shadowUniforms.shadowBias = shadow.bias;
  11846. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11847. shadowUniforms.shadowRadius = shadow.radius;
  11848. shadowUniforms.shadowMapSize = shadow.mapSize;
  11849. state.spotShadow[ spotLength ] = shadowUniforms;
  11850. state.spotShadowMap[ spotLength ] = shadowMap;
  11851. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11852. numSpotShadows ++;
  11853. }
  11854. state.spot[ spotLength ] = uniforms;
  11855. spotLength ++;
  11856. } else if ( light.isRectAreaLight ) {
  11857. const uniforms = cache.get( light );
  11858. // (a) intensity is the total visible light emitted
  11859. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11860. // (b) intensity is the brightness of the light
  11861. uniforms.color.copy( color ).multiplyScalar( intensity );
  11862. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11863. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11864. state.rectArea[ rectAreaLength ] = uniforms;
  11865. rectAreaLength ++;
  11866. } else if ( light.isPointLight ) {
  11867. const uniforms = cache.get( light );
  11868. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11869. uniforms.distance = light.distance;
  11870. uniforms.decay = light.decay;
  11871. if ( light.castShadow ) {
  11872. const shadow = light.shadow;
  11873. const shadowUniforms = shadowCache.get( light );
  11874. shadowUniforms.shadowBias = shadow.bias;
  11875. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11876. shadowUniforms.shadowRadius = shadow.radius;
  11877. shadowUniforms.shadowMapSize = shadow.mapSize;
  11878. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11879. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11880. state.pointShadow[ pointLength ] = shadowUniforms;
  11881. state.pointShadowMap[ pointLength ] = shadowMap;
  11882. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11883. numPointShadows ++;
  11884. }
  11885. state.point[ pointLength ] = uniforms;
  11886. pointLength ++;
  11887. } else if ( light.isHemisphereLight ) {
  11888. const uniforms = cache.get( light );
  11889. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  11890. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  11891. state.hemi[ hemiLength ] = uniforms;
  11892. hemiLength ++;
  11893. }
  11894. }
  11895. if ( rectAreaLength > 0 ) {
  11896. if ( capabilities.isWebGL2 ) {
  11897. // WebGL 2
  11898. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11899. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11900. } else {
  11901. // WebGL 1
  11902. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  11903. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11904. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11905. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  11906. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11907. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11908. } else {
  11909. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  11910. }
  11911. }
  11912. }
  11913. state.ambient[ 0 ] = r;
  11914. state.ambient[ 1 ] = g;
  11915. state.ambient[ 2 ] = b;
  11916. const hash = state.hash;
  11917. if ( hash.directionalLength !== directionalLength ||
  11918. hash.pointLength !== pointLength ||
  11919. hash.spotLength !== spotLength ||
  11920. hash.rectAreaLength !== rectAreaLength ||
  11921. hash.hemiLength !== hemiLength ||
  11922. hash.numDirectionalShadows !== numDirectionalShadows ||
  11923. hash.numPointShadows !== numPointShadows ||
  11924. hash.numSpotShadows !== numSpotShadows ) {
  11925. state.directional.length = directionalLength;
  11926. state.spot.length = spotLength;
  11927. state.rectArea.length = rectAreaLength;
  11928. state.point.length = pointLength;
  11929. state.hemi.length = hemiLength;
  11930. state.directionalShadow.length = numDirectionalShadows;
  11931. state.directionalShadowMap.length = numDirectionalShadows;
  11932. state.pointShadow.length = numPointShadows;
  11933. state.pointShadowMap.length = numPointShadows;
  11934. state.spotShadow.length = numSpotShadows;
  11935. state.spotShadowMap.length = numSpotShadows;
  11936. state.directionalShadowMatrix.length = numDirectionalShadows;
  11937. state.pointShadowMatrix.length = numPointShadows;
  11938. state.spotShadowMatrix.length = numSpotShadows;
  11939. hash.directionalLength = directionalLength;
  11940. hash.pointLength = pointLength;
  11941. hash.spotLength = spotLength;
  11942. hash.rectAreaLength = rectAreaLength;
  11943. hash.hemiLength = hemiLength;
  11944. hash.numDirectionalShadows = numDirectionalShadows;
  11945. hash.numPointShadows = numPointShadows;
  11946. hash.numSpotShadows = numSpotShadows;
  11947. state.version = nextVersion ++;
  11948. }
  11949. }
  11950. function setupView( lights, camera ) {
  11951. let directionalLength = 0;
  11952. let pointLength = 0;
  11953. let spotLength = 0;
  11954. let rectAreaLength = 0;
  11955. let hemiLength = 0;
  11956. const viewMatrix = camera.matrixWorldInverse;
  11957. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11958. const light = lights[ i ];
  11959. if ( light.isDirectionalLight ) {
  11960. const uniforms = state.directional[ directionalLength ];
  11961. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11962. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11963. uniforms.direction.sub( vector3 );
  11964. uniforms.direction.transformDirection( viewMatrix );
  11965. directionalLength ++;
  11966. } else if ( light.isSpotLight ) {
  11967. const uniforms = state.spot[ spotLength ];
  11968. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11969. uniforms.position.applyMatrix4( viewMatrix );
  11970. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11971. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11972. uniforms.direction.sub( vector3 );
  11973. uniforms.direction.transformDirection( viewMatrix );
  11974. spotLength ++;
  11975. } else if ( light.isRectAreaLight ) {
  11976. const uniforms = state.rectArea[ rectAreaLength ];
  11977. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11978. uniforms.position.applyMatrix4( viewMatrix );
  11979. // extract local rotation of light to derive width/height half vectors
  11980. matrix42.identity();
  11981. matrix4.copy( light.matrixWorld );
  11982. matrix4.premultiply( viewMatrix );
  11983. matrix42.extractRotation( matrix4 );
  11984. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11985. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11986. uniforms.halfWidth.applyMatrix4( matrix42 );
  11987. uniforms.halfHeight.applyMatrix4( matrix42 );
  11988. rectAreaLength ++;
  11989. } else if ( light.isPointLight ) {
  11990. const uniforms = state.point[ pointLength ];
  11991. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11992. uniforms.position.applyMatrix4( viewMatrix );
  11993. pointLength ++;
  11994. } else if ( light.isHemisphereLight ) {
  11995. const uniforms = state.hemi[ hemiLength ];
  11996. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11997. uniforms.direction.transformDirection( viewMatrix );
  11998. uniforms.direction.normalize();
  11999. hemiLength ++;
  12000. }
  12001. }
  12002. }
  12003. return {
  12004. setup: setup,
  12005. setupView: setupView,
  12006. state: state
  12007. };
  12008. }
  12009. function WebGLRenderState( extensions, capabilities ) {
  12010. const lights = new WebGLLights( extensions, capabilities );
  12011. const lightsArray = [];
  12012. const shadowsArray = [];
  12013. function init() {
  12014. lightsArray.length = 0;
  12015. shadowsArray.length = 0;
  12016. }
  12017. function pushLight( light ) {
  12018. lightsArray.push( light );
  12019. }
  12020. function pushShadow( shadowLight ) {
  12021. shadowsArray.push( shadowLight );
  12022. }
  12023. function setupLights() {
  12024. lights.setup( lightsArray );
  12025. }
  12026. function setupLightsView( camera ) {
  12027. lights.setupView( lightsArray, camera );
  12028. }
  12029. const state = {
  12030. lightsArray: lightsArray,
  12031. shadowsArray: shadowsArray,
  12032. lights: lights
  12033. };
  12034. return {
  12035. init: init,
  12036. state: state,
  12037. setupLights: setupLights,
  12038. setupLightsView: setupLightsView,
  12039. pushLight: pushLight,
  12040. pushShadow: pushShadow
  12041. };
  12042. }
  12043. function WebGLRenderStates( extensions, capabilities ) {
  12044. let renderStates = new WeakMap();
  12045. function get( scene, renderCallDepth = 0 ) {
  12046. let renderState;
  12047. if ( renderStates.has( scene ) === false ) {
  12048. renderState = new WebGLRenderState( extensions, capabilities );
  12049. renderStates.set( scene, [] );
  12050. renderStates.get( scene ).push( renderState );
  12051. } else {
  12052. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12053. renderState = new WebGLRenderState( extensions, capabilities );
  12054. renderStates.get( scene ).push( renderState );
  12055. } else {
  12056. renderState = renderStates.get( scene )[ renderCallDepth ];
  12057. }
  12058. }
  12059. return renderState;
  12060. }
  12061. function dispose() {
  12062. renderStates = new WeakMap();
  12063. }
  12064. return {
  12065. get: get,
  12066. dispose: dispose
  12067. };
  12068. }
  12069. /**
  12070. * parameters = {
  12071. *
  12072. * opacity: <float>,
  12073. *
  12074. * map: new THREE.Texture( <Image> ),
  12075. *
  12076. * alphaMap: new THREE.Texture( <Image> ),
  12077. *
  12078. * displacementMap: new THREE.Texture( <Image> ),
  12079. * displacementScale: <float>,
  12080. * displacementBias: <float>,
  12081. *
  12082. * wireframe: <boolean>,
  12083. * wireframelineWidth: <float>
  12084. * }
  12085. */
  12086. function MeshDepthMaterial( parameters ) {
  12087. Material.call( this );
  12088. this.type = 'MeshDepthMaterial';
  12089. this.depthPacking = BasicDepthPacking;
  12090. this.skinning = false;
  12091. this.morphTargets = false;
  12092. this.map = null;
  12093. this.alphaMap = null;
  12094. this.displacementMap = null;
  12095. this.displacementScale = 1;
  12096. this.displacementBias = 0;
  12097. this.wireframe = false;
  12098. this.wireframelineWidth = 1;
  12099. this.fog = false;
  12100. this.setValues( parameters );
  12101. }
  12102. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  12103. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12104. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12105. MeshDepthMaterial.prototype.copy = function ( source ) {
  12106. Material.prototype.copy.call( this, source );
  12107. this.depthPacking = source.depthPacking;
  12108. this.skinning = source.skinning;
  12109. this.morphTargets = source.morphTargets;
  12110. this.map = source.map;
  12111. this.alphaMap = source.alphaMap;
  12112. this.displacementMap = source.displacementMap;
  12113. this.displacementScale = source.displacementScale;
  12114. this.displacementBias = source.displacementBias;
  12115. this.wireframe = source.wireframe;
  12116. this.wireframelineWidth = source.wireframelineWidth;
  12117. return this;
  12118. };
  12119. /**
  12120. * parameters = {
  12121. *
  12122. * referencePosition: <float>,
  12123. * nearDistance: <float>,
  12124. * farDistance: <float>,
  12125. *
  12126. * skinning: <bool>,
  12127. * morphTargets: <bool>,
  12128. *
  12129. * map: new THREE.Texture( <Image> ),
  12130. *
  12131. * alphaMap: new THREE.Texture( <Image> ),
  12132. *
  12133. * displacementMap: new THREE.Texture( <Image> ),
  12134. * displacementScale: <float>,
  12135. * displacementBias: <float>
  12136. *
  12137. * }
  12138. */
  12139. function MeshDistanceMaterial( parameters ) {
  12140. Material.call( this );
  12141. this.type = 'MeshDistanceMaterial';
  12142. this.referencePosition = new Vector3();
  12143. this.nearDistance = 1;
  12144. this.farDistance = 1000;
  12145. this.skinning = false;
  12146. this.morphTargets = false;
  12147. this.map = null;
  12148. this.alphaMap = null;
  12149. this.displacementMap = null;
  12150. this.displacementScale = 1;
  12151. this.displacementBias = 0;
  12152. this.fog = false;
  12153. this.setValues( parameters );
  12154. }
  12155. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  12156. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12157. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12158. MeshDistanceMaterial.prototype.copy = function ( source ) {
  12159. Material.prototype.copy.call( this, source );
  12160. this.referencePosition.copy( source.referencePosition );
  12161. this.nearDistance = source.nearDistance;
  12162. this.farDistance = source.farDistance;
  12163. this.skinning = source.skinning;
  12164. this.morphTargets = source.morphTargets;
  12165. this.map = source.map;
  12166. this.alphaMap = source.alphaMap;
  12167. this.displacementMap = source.displacementMap;
  12168. this.displacementScale = source.displacementScale;
  12169. this.displacementBias = source.displacementBias;
  12170. return this;
  12171. };
  12172. 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}";
  12173. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12174. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  12175. let _frustum = new Frustum();
  12176. const _shadowMapSize = new Vector2$1(),
  12177. _viewportSize = new Vector2$1(),
  12178. _viewport = new Vector4(),
  12179. _depthMaterials = [],
  12180. _distanceMaterials = [],
  12181. _materialCache = {};
  12182. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12183. const shadowMaterialVertical = new ShaderMaterial( {
  12184. defines: {
  12185. SAMPLE_RATE: 2.0 / 8.0,
  12186. HALF_SAMPLE_RATE: 1.0 / 8.0
  12187. },
  12188. uniforms: {
  12189. shadow_pass: { value: null },
  12190. resolution: { value: new Vector2$1() },
  12191. radius: { value: 4.0 }
  12192. },
  12193. vertexShader: vsm_vert,
  12194. fragmentShader: vsm_frag
  12195. } );
  12196. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12197. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12198. const fullScreenTri = new BufferGeometry();
  12199. fullScreenTri.setAttribute(
  12200. 'position',
  12201. new BufferAttribute(
  12202. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12203. 3
  12204. )
  12205. );
  12206. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12207. const scope = this;
  12208. this.enabled = false;
  12209. this.autoUpdate = true;
  12210. this.needsUpdate = false;
  12211. this.type = PCFShadowMap;
  12212. this.render = function ( lights, scene, camera ) {
  12213. if ( scope.enabled === false ) return;
  12214. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12215. if ( lights.length === 0 ) return;
  12216. const currentRenderTarget = _renderer.getRenderTarget();
  12217. const activeCubeFace = _renderer.getActiveCubeFace();
  12218. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12219. const _state = _renderer.state;
  12220. // Set GL state for depth map.
  12221. _state.setBlending( NoBlending );
  12222. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12223. _state.buffers.depth.setTest( true );
  12224. _state.setScissorTest( false );
  12225. // render depth map
  12226. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12227. const light = lights[ i ];
  12228. const shadow = light.shadow;
  12229. if ( shadow === undefined ) {
  12230. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12231. continue;
  12232. }
  12233. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12234. _shadowMapSize.copy( shadow.mapSize );
  12235. const shadowFrameExtents = shadow.getFrameExtents();
  12236. _shadowMapSize.multiply( shadowFrameExtents );
  12237. _viewportSize.copy( shadow.mapSize );
  12238. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  12239. if ( _shadowMapSize.x > maxTextureSize ) {
  12240. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  12241. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12242. shadow.mapSize.x = _viewportSize.x;
  12243. }
  12244. if ( _shadowMapSize.y > maxTextureSize ) {
  12245. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  12246. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12247. shadow.mapSize.y = _viewportSize.y;
  12248. }
  12249. }
  12250. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12251. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12252. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12253. shadow.map.texture.name = light.name + '.shadowMap';
  12254. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12255. shadow.camera.updateProjectionMatrix();
  12256. }
  12257. if ( shadow.map === null ) {
  12258. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12259. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12260. shadow.map.texture.name = light.name + '.shadowMap';
  12261. shadow.camera.updateProjectionMatrix();
  12262. }
  12263. _renderer.setRenderTarget( shadow.map );
  12264. _renderer.clear();
  12265. const viewportCount = shadow.getViewportCount();
  12266. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12267. const viewport = shadow.getViewport( vp );
  12268. _viewport.set(
  12269. _viewportSize.x * viewport.x,
  12270. _viewportSize.y * viewport.y,
  12271. _viewportSize.x * viewport.z,
  12272. _viewportSize.y * viewport.w
  12273. );
  12274. _state.viewport( _viewport );
  12275. shadow.updateMatrices( light, vp );
  12276. _frustum = shadow.getFrustum();
  12277. renderObject( scene, camera, shadow.camera, light, this.type );
  12278. }
  12279. // do blur pass for VSM
  12280. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12281. VSMPass( shadow, camera );
  12282. }
  12283. shadow.needsUpdate = false;
  12284. }
  12285. scope.needsUpdate = false;
  12286. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12287. };
  12288. function VSMPass( shadow, camera ) {
  12289. const geometry = _objects.update( fullScreenMesh );
  12290. // vertical pass
  12291. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12292. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12293. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12294. _renderer.setRenderTarget( shadow.mapPass );
  12295. _renderer.clear();
  12296. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12297. // horizontal pass
  12298. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12299. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12300. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12301. _renderer.setRenderTarget( shadow.map );
  12302. _renderer.clear();
  12303. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12304. }
  12305. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12306. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12307. let material = _depthMaterials[ index ];
  12308. if ( material === undefined ) {
  12309. material = new MeshDepthMaterial( {
  12310. depthPacking: RGBADepthPacking,
  12311. morphTargets: useMorphing,
  12312. skinning: useSkinning
  12313. } );
  12314. _depthMaterials[ index ] = material;
  12315. }
  12316. return material;
  12317. }
  12318. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12319. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12320. let material = _distanceMaterials[ index ];
  12321. if ( material === undefined ) {
  12322. material = new MeshDistanceMaterial( {
  12323. morphTargets: useMorphing,
  12324. skinning: useSkinning
  12325. } );
  12326. _distanceMaterials[ index ] = material;
  12327. }
  12328. return material;
  12329. }
  12330. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12331. let result = null;
  12332. let getMaterialVariant = getDepthMaterialVariant;
  12333. let customMaterial = object.customDepthMaterial;
  12334. if ( light.isPointLight === true ) {
  12335. getMaterialVariant = getDistanceMaterialVariant;
  12336. customMaterial = object.customDistanceMaterial;
  12337. }
  12338. if ( customMaterial === undefined ) {
  12339. let useMorphing = false;
  12340. if ( material.morphTargets === true ) {
  12341. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12342. }
  12343. let useSkinning = false;
  12344. if ( object.isSkinnedMesh === true ) {
  12345. if ( material.skinning === true ) {
  12346. useSkinning = true;
  12347. } else {
  12348. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  12349. }
  12350. }
  12351. const useInstancing = object.isInstancedMesh === true;
  12352. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  12353. } else {
  12354. result = customMaterial;
  12355. }
  12356. if ( _renderer.localClippingEnabled &&
  12357. material.clipShadows === true &&
  12358. material.clippingPlanes.length !== 0 ) {
  12359. // in this case we need a unique material instance reflecting the
  12360. // appropriate state
  12361. const keyA = result.uuid, keyB = material.uuid;
  12362. let materialsForVariant = _materialCache[ keyA ];
  12363. if ( materialsForVariant === undefined ) {
  12364. materialsForVariant = {};
  12365. _materialCache[ keyA ] = materialsForVariant;
  12366. }
  12367. let cachedMaterial = materialsForVariant[ keyB ];
  12368. if ( cachedMaterial === undefined ) {
  12369. cachedMaterial = result.clone();
  12370. materialsForVariant[ keyB ] = cachedMaterial;
  12371. }
  12372. result = cachedMaterial;
  12373. }
  12374. result.visible = material.visible;
  12375. result.wireframe = material.wireframe;
  12376. if ( type === VSMShadowMap ) {
  12377. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12378. } else {
  12379. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12380. }
  12381. result.clipShadows = material.clipShadows;
  12382. result.clippingPlanes = material.clippingPlanes;
  12383. result.clipIntersection = material.clipIntersection;
  12384. result.wireframelineWidth = material.wireframelineWidth;
  12385. result.lineWidth = material.lineWidth;
  12386. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12387. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12388. result.nearDistance = shadowCameraNear;
  12389. result.farDistance = shadowCameraFar;
  12390. }
  12391. return result;
  12392. }
  12393. function renderObject( object, camera, shadowCamera, light, type ) {
  12394. if ( object.visible === false ) return;
  12395. const visible = object.layers.test( camera.layers );
  12396. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12397. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12398. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12399. const geometry = _objects.update( object );
  12400. const material = object.material;
  12401. if ( Array.isArray( material ) ) {
  12402. const groups = geometry.groups;
  12403. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12404. const group = groups[ k ];
  12405. const groupMaterial = material[ group.materialIndex ];
  12406. if ( groupMaterial && groupMaterial.visible ) {
  12407. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12408. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12409. }
  12410. }
  12411. } else if ( material.visible ) {
  12412. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12413. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12414. }
  12415. }
  12416. }
  12417. const children = object.children;
  12418. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12419. renderObject( children[ i ], camera, shadowCamera, light, type );
  12420. }
  12421. }
  12422. }
  12423. function WebGLState( gl, extensions, capabilities ) {
  12424. const isWebGL2 = capabilities.isWebGL2;
  12425. function ColorBuffer() {
  12426. let locked = false;
  12427. const color = new Vector4();
  12428. let currentColorMask = null;
  12429. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12430. return {
  12431. setMask: function ( colorMask ) {
  12432. if ( currentColorMask !== colorMask && ! locked ) {
  12433. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12434. currentColorMask = colorMask;
  12435. }
  12436. },
  12437. setLocked: function ( lock ) {
  12438. locked = lock;
  12439. },
  12440. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12441. if ( premultipliedAlpha === true ) {
  12442. r *= a; g *= a; b *= a;
  12443. }
  12444. color.set( r, g, b, a );
  12445. if ( currentColorClear.equals( color ) === false ) {
  12446. gl.clearColor( r, g, b, a );
  12447. currentColorClear.copy( color );
  12448. }
  12449. },
  12450. reset: function () {
  12451. locked = false;
  12452. currentColorMask = null;
  12453. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12454. }
  12455. };
  12456. }
  12457. function DepthBuffer() {
  12458. let locked = false;
  12459. let currentDepthMask = null;
  12460. let currentDepthFunc = null;
  12461. let currentDepthClear = null;
  12462. return {
  12463. setTest: function ( depthTest ) {
  12464. if ( depthTest ) {
  12465. enable( 2929 );
  12466. } else {
  12467. disable( 2929 );
  12468. }
  12469. },
  12470. setMask: function ( depthMask ) {
  12471. if ( currentDepthMask !== depthMask && ! locked ) {
  12472. gl.depthMask( depthMask );
  12473. currentDepthMask = depthMask;
  12474. }
  12475. },
  12476. setFunc: function ( depthFunc ) {
  12477. if ( currentDepthFunc !== depthFunc ) {
  12478. if ( depthFunc ) {
  12479. switch ( depthFunc ) {
  12480. case NeverDepth:
  12481. gl.depthFunc( 512 );
  12482. break;
  12483. case AlwaysDepth:
  12484. gl.depthFunc( 519 );
  12485. break;
  12486. case LessDepth:
  12487. gl.depthFunc( 513 );
  12488. break;
  12489. case LessEqualDepth:
  12490. gl.depthFunc( 515 );
  12491. break;
  12492. case EqualDepth:
  12493. gl.depthFunc( 514 );
  12494. break;
  12495. case GreaterEqualDepth:
  12496. gl.depthFunc( 518 );
  12497. break;
  12498. case GreaterDepth:
  12499. gl.depthFunc( 516 );
  12500. break;
  12501. case NotEqualDepth:
  12502. gl.depthFunc( 517 );
  12503. break;
  12504. default:
  12505. gl.depthFunc( 515 );
  12506. }
  12507. } else {
  12508. gl.depthFunc( 515 );
  12509. }
  12510. currentDepthFunc = depthFunc;
  12511. }
  12512. },
  12513. setLocked: function ( lock ) {
  12514. locked = lock;
  12515. },
  12516. setClear: function ( depth ) {
  12517. if ( currentDepthClear !== depth ) {
  12518. gl.clearDepth( depth );
  12519. currentDepthClear = depth;
  12520. }
  12521. },
  12522. reset: function () {
  12523. locked = false;
  12524. currentDepthMask = null;
  12525. currentDepthFunc = null;
  12526. currentDepthClear = null;
  12527. }
  12528. };
  12529. }
  12530. function StencilBuffer() {
  12531. let locked = false;
  12532. let currentStencilMask = null;
  12533. let currentStencilFunc = null;
  12534. let currentStencilRef = null;
  12535. let currentStencilFuncMask = null;
  12536. let currentStencilFail = null;
  12537. let currentStencilZFail = null;
  12538. let currentStencilZPass = null;
  12539. let currentStencilClear = null;
  12540. return {
  12541. setTest: function ( stencilTest ) {
  12542. if ( ! locked ) {
  12543. if ( stencilTest ) {
  12544. enable( 2960 );
  12545. } else {
  12546. disable( 2960 );
  12547. }
  12548. }
  12549. },
  12550. setMask: function ( stencilMask ) {
  12551. if ( currentStencilMask !== stencilMask && ! locked ) {
  12552. gl.stencilMask( stencilMask );
  12553. currentStencilMask = stencilMask;
  12554. }
  12555. },
  12556. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12557. if ( currentStencilFunc !== stencilFunc ||
  12558. currentStencilRef !== stencilRef ||
  12559. currentStencilFuncMask !== stencilMask ) {
  12560. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12561. currentStencilFunc = stencilFunc;
  12562. currentStencilRef = stencilRef;
  12563. currentStencilFuncMask = stencilMask;
  12564. }
  12565. },
  12566. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12567. if ( currentStencilFail !== stencilFail ||
  12568. currentStencilZFail !== stencilZFail ||
  12569. currentStencilZPass !== stencilZPass ) {
  12570. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12571. currentStencilFail = stencilFail;
  12572. currentStencilZFail = stencilZFail;
  12573. currentStencilZPass = stencilZPass;
  12574. }
  12575. },
  12576. setLocked: function ( lock ) {
  12577. locked = lock;
  12578. },
  12579. setClear: function ( stencil ) {
  12580. if ( currentStencilClear !== stencil ) {
  12581. gl.clearStencil( stencil );
  12582. currentStencilClear = stencil;
  12583. }
  12584. },
  12585. reset: function () {
  12586. locked = false;
  12587. currentStencilMask = null;
  12588. currentStencilFunc = null;
  12589. currentStencilRef = null;
  12590. currentStencilFuncMask = null;
  12591. currentStencilFail = null;
  12592. currentStencilZFail = null;
  12593. currentStencilZPass = null;
  12594. currentStencilClear = null;
  12595. }
  12596. };
  12597. }
  12598. //
  12599. const colorBuffer = new ColorBuffer();
  12600. const depthBuffer = new DepthBuffer();
  12601. const stencilBuffer = new StencilBuffer();
  12602. let enabledCapabilities = {};
  12603. let currentProgram = null;
  12604. let currentBlendingEnabled = null;
  12605. let currentBlending = null;
  12606. let currentBlendEquation = null;
  12607. let currentBlendSrc = null;
  12608. let currentBlendDst = null;
  12609. let currentBlendEquationAlpha = null;
  12610. let currentBlendSrcAlpha = null;
  12611. let currentBlendDstAlpha = null;
  12612. let currentPremultipledAlpha = false;
  12613. let currentFlipSided = null;
  12614. let currentCullFace = null;
  12615. let currentlineWidth = null;
  12616. let currentPolygonOffsetFactor = null;
  12617. let currentPolygonOffsetUnits = null;
  12618. const maxTextures = gl.getParameter( 35661 );
  12619. let lineWidthAvailable = false;
  12620. let version = 0;
  12621. const glVersion = gl.getParameter( 7938 );
  12622. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12623. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12624. lineWidthAvailable = ( version >= 1.0 );
  12625. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12626. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12627. lineWidthAvailable = ( version >= 2.0 );
  12628. }
  12629. let currentTextureSlot = null;
  12630. let currentBoundTextures = {};
  12631. const currentScissor = new Vector4();
  12632. const currentViewport = new Vector4();
  12633. function createTexture( type, target, count ) {
  12634. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12635. const texture = gl.createTexture();
  12636. gl.bindTexture( type, texture );
  12637. gl.texParameteri( type, 10241, 9728 );
  12638. gl.texParameteri( type, 10240, 9728 );
  12639. for ( let i = 0; i < count; i ++ ) {
  12640. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12641. }
  12642. return texture;
  12643. }
  12644. const emptyTextures = {};
  12645. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12646. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12647. // init
  12648. colorBuffer.setClear( 0, 0, 0, 1 );
  12649. depthBuffer.setClear( 1 );
  12650. stencilBuffer.setClear( 0 );
  12651. enable( 2929 );
  12652. depthBuffer.setFunc( LessEqualDepth );
  12653. setFlipSided( false );
  12654. setCullFace( CullFaceBack );
  12655. enable( 2884 );
  12656. setBlending( NoBlending );
  12657. //
  12658. function enable( id ) {
  12659. if ( enabledCapabilities[ id ] !== true ) {
  12660. gl.enable( id );
  12661. enabledCapabilities[ id ] = true;
  12662. }
  12663. }
  12664. function disable( id ) {
  12665. if ( enabledCapabilities[ id ] !== false ) {
  12666. gl.disable( id );
  12667. enabledCapabilities[ id ] = false;
  12668. }
  12669. }
  12670. function useProgram( program ) {
  12671. if ( currentProgram !== program ) {
  12672. gl.useProgram( program );
  12673. currentProgram = program;
  12674. return true;
  12675. }
  12676. return false;
  12677. }
  12678. const equationToGL = {
  12679. [ AddEquation ]: 32774,
  12680. [ SubtractEquation ]: 32778,
  12681. [ ReverseSubtractEquation ]: 32779
  12682. };
  12683. if ( isWebGL2 ) {
  12684. equationToGL[ MinEquation ] = 32775;
  12685. equationToGL[ MaxEquation ] = 32776;
  12686. } else {
  12687. const extension = extensions.get( 'EXT_blend_minmax' );
  12688. if ( extension !== null ) {
  12689. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12690. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12691. }
  12692. }
  12693. const factorToGL = {
  12694. [ ZeroFactor ]: 0,
  12695. [ OneFactor ]: 1,
  12696. [ SrcColorFactor ]: 768,
  12697. [ SrcAlphaFactor ]: 770,
  12698. [ SrcAlphaSaturateFactor ]: 776,
  12699. [ DstColorFactor ]: 774,
  12700. [ DstAlphaFactor ]: 772,
  12701. [ OneMinusSrcColorFactor ]: 769,
  12702. [ OneMinusSrcAlphaFactor ]: 771,
  12703. [ OneMinusDstColorFactor ]: 775,
  12704. [ OneMinusDstAlphaFactor ]: 773
  12705. };
  12706. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12707. if ( blending === NoBlending ) {
  12708. if ( currentBlendingEnabled ) {
  12709. disable( 3042 );
  12710. currentBlendingEnabled = false;
  12711. }
  12712. return;
  12713. }
  12714. if ( ! currentBlendingEnabled ) {
  12715. enable( 3042 );
  12716. currentBlendingEnabled = true;
  12717. }
  12718. if ( blending !== CustomBlending ) {
  12719. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12720. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12721. gl.blendEquation( 32774 );
  12722. currentBlendEquation = AddEquation;
  12723. currentBlendEquationAlpha = AddEquation;
  12724. }
  12725. if ( premultipliedAlpha ) {
  12726. switch ( blending ) {
  12727. case NormalBlending:
  12728. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12729. break;
  12730. case AdditiveBlending:
  12731. gl.blendFunc( 1, 1 );
  12732. break;
  12733. case SubtractiveBlending:
  12734. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12735. break;
  12736. case MultiplyBlending:
  12737. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12738. break;
  12739. default:
  12740. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12741. break;
  12742. }
  12743. } else {
  12744. switch ( blending ) {
  12745. case NormalBlending:
  12746. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12747. break;
  12748. case AdditiveBlending:
  12749. gl.blendFunc( 770, 1 );
  12750. break;
  12751. case SubtractiveBlending:
  12752. gl.blendFunc( 0, 769 );
  12753. break;
  12754. case MultiplyBlending:
  12755. gl.blendFunc( 0, 768 );
  12756. break;
  12757. default:
  12758. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12759. break;
  12760. }
  12761. }
  12762. currentBlendSrc = null;
  12763. currentBlendDst = null;
  12764. currentBlendSrcAlpha = null;
  12765. currentBlendDstAlpha = null;
  12766. currentBlending = blending;
  12767. currentPremultipledAlpha = premultipliedAlpha;
  12768. }
  12769. return;
  12770. }
  12771. // custom blending
  12772. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12773. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12774. blendDstAlpha = blendDstAlpha || blendDst;
  12775. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12776. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12777. currentBlendEquation = blendEquation;
  12778. currentBlendEquationAlpha = blendEquationAlpha;
  12779. }
  12780. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12781. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12782. currentBlendSrc = blendSrc;
  12783. currentBlendDst = blendDst;
  12784. currentBlendSrcAlpha = blendSrcAlpha;
  12785. currentBlendDstAlpha = blendDstAlpha;
  12786. }
  12787. currentBlending = blending;
  12788. currentPremultipledAlpha = null;
  12789. }
  12790. function setMaterial( material, frontFaceCW ) {
  12791. material.side === DoubleSide
  12792. ? disable( 2884 )
  12793. : enable( 2884 );
  12794. let flipSided = ( material.side === BackSide );
  12795. if ( frontFaceCW ) flipSided = ! flipSided;
  12796. setFlipSided( flipSided );
  12797. ( material.blending === NormalBlending && material.transparent === false )
  12798. ? setBlending( NoBlending )
  12799. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12800. depthBuffer.setFunc( material.depthFunc );
  12801. depthBuffer.setTest( material.depthTest );
  12802. depthBuffer.setMask( material.depthWrite );
  12803. colorBuffer.setMask( material.colorWrite );
  12804. const stencilWrite = material.stencilWrite;
  12805. stencilBuffer.setTest( stencilWrite );
  12806. if ( stencilWrite ) {
  12807. stencilBuffer.setMask( material.stencilWriteMask );
  12808. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12809. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12810. }
  12811. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12812. }
  12813. //
  12814. function setFlipSided( flipSided ) {
  12815. if ( currentFlipSided !== flipSided ) {
  12816. if ( flipSided ) {
  12817. gl.frontFace( 2304 );
  12818. } else {
  12819. gl.frontFace( 2305 );
  12820. }
  12821. currentFlipSided = flipSided;
  12822. }
  12823. }
  12824. function setCullFace( cullFace ) {
  12825. if ( cullFace !== CullFaceNone ) {
  12826. enable( 2884 );
  12827. if ( cullFace !== currentCullFace ) {
  12828. if ( cullFace === CullFaceBack ) {
  12829. gl.cullFace( 1029 );
  12830. } else if ( cullFace === CullFaceFront ) {
  12831. gl.cullFace( 1028 );
  12832. } else {
  12833. gl.cullFace( 1032 );
  12834. }
  12835. }
  12836. } else {
  12837. disable( 2884 );
  12838. }
  12839. currentCullFace = cullFace;
  12840. }
  12841. function setlineWidth( width ) {
  12842. if ( width !== currentlineWidth ) {
  12843. if ( lineWidthAvailable ) gl.lineWidth( width );
  12844. currentlineWidth = width;
  12845. }
  12846. }
  12847. function setPolygonOffset( polygonOffset, factor, units ) {
  12848. if ( polygonOffset ) {
  12849. enable( 32823 );
  12850. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12851. gl.polygonOffset( factor, units );
  12852. currentPolygonOffsetFactor = factor;
  12853. currentPolygonOffsetUnits = units;
  12854. }
  12855. } else {
  12856. disable( 32823 );
  12857. }
  12858. }
  12859. function setScissorTest( scissorTest ) {
  12860. if ( scissorTest ) {
  12861. enable( 3089 );
  12862. } else {
  12863. disable( 3089 );
  12864. }
  12865. }
  12866. // texture
  12867. function activeTexture( webglSlot ) {
  12868. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12869. if ( currentTextureSlot !== webglSlot ) {
  12870. gl.activeTexture( webglSlot );
  12871. currentTextureSlot = webglSlot;
  12872. }
  12873. }
  12874. function bindTexture( webglType, webglTexture ) {
  12875. if ( currentTextureSlot === null ) {
  12876. activeTexture();
  12877. }
  12878. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12879. if ( boundTexture === undefined ) {
  12880. boundTexture = { type: undefined, texture: undefined };
  12881. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12882. }
  12883. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12884. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12885. boundTexture.type = webglType;
  12886. boundTexture.texture = webglTexture;
  12887. }
  12888. }
  12889. function unbindTexture() {
  12890. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12891. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12892. gl.bindTexture( boundTexture.type, null );
  12893. boundTexture.type = undefined;
  12894. boundTexture.texture = undefined;
  12895. }
  12896. }
  12897. function compressedTexImage2D() {
  12898. try {
  12899. gl.compressedTexImage2D.apply( gl, arguments );
  12900. } catch ( error ) {
  12901. console.error( 'THREE.WebGLState:', error );
  12902. }
  12903. }
  12904. function texImage2D() {
  12905. try {
  12906. gl.texImage2D.apply( gl, arguments );
  12907. } catch ( error ) {
  12908. console.error( 'THREE.WebGLState:', error );
  12909. }
  12910. }
  12911. function texImage3D() {
  12912. try {
  12913. gl.texImage3D.apply( gl, arguments );
  12914. } catch ( error ) {
  12915. console.error( 'THREE.WebGLState:', error );
  12916. }
  12917. }
  12918. //
  12919. function scissor( scissor ) {
  12920. if ( currentScissor.equals( scissor ) === false ) {
  12921. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12922. currentScissor.copy( scissor );
  12923. }
  12924. }
  12925. function viewport( viewport ) {
  12926. if ( currentViewport.equals( viewport ) === false ) {
  12927. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12928. currentViewport.copy( viewport );
  12929. }
  12930. }
  12931. //
  12932. function reset() {
  12933. enabledCapabilities = {};
  12934. currentTextureSlot = null;
  12935. currentBoundTextures = {};
  12936. currentProgram = null;
  12937. currentBlendingEnabled = null;
  12938. currentBlending = null;
  12939. currentBlendEquation = null;
  12940. currentBlendSrc = null;
  12941. currentBlendDst = null;
  12942. currentBlendEquationAlpha = null;
  12943. currentBlendSrcAlpha = null;
  12944. currentBlendDstAlpha = null;
  12945. currentPremultipledAlpha = false;
  12946. currentFlipSided = null;
  12947. currentCullFace = null;
  12948. currentlineWidth = null;
  12949. currentPolygonOffsetFactor = null;
  12950. currentPolygonOffsetUnits = null;
  12951. colorBuffer.reset();
  12952. depthBuffer.reset();
  12953. stencilBuffer.reset();
  12954. }
  12955. return {
  12956. buffers: {
  12957. color: colorBuffer,
  12958. depth: depthBuffer,
  12959. stencil: stencilBuffer
  12960. },
  12961. enable: enable,
  12962. disable: disable,
  12963. useProgram: useProgram,
  12964. setBlending: setBlending,
  12965. setMaterial: setMaterial,
  12966. setFlipSided: setFlipSided,
  12967. setCullFace: setCullFace,
  12968. setlineWidth: setlineWidth,
  12969. setPolygonOffset: setPolygonOffset,
  12970. setScissorTest: setScissorTest,
  12971. activeTexture: activeTexture,
  12972. bindTexture: bindTexture,
  12973. unbindTexture: unbindTexture,
  12974. compressedTexImage2D: compressedTexImage2D,
  12975. texImage2D: texImage2D,
  12976. texImage3D: texImage3D,
  12977. scissor: scissor,
  12978. viewport: viewport,
  12979. reset: reset
  12980. };
  12981. }
  12982. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12983. const isWebGL2 = capabilities.isWebGL2;
  12984. const maxTextures = capabilities.maxTextures;
  12985. const maxCubemapSize = capabilities.maxCubemapSize;
  12986. const maxTextureSize = capabilities.maxTextureSize;
  12987. const maxSamples = capabilities.maxSamples;
  12988. const _videoTextures = new WeakMap();
  12989. let _canvas;
  12990. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12991. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12992. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12993. let useOffscreenCanvas = false;
  12994. try {
  12995. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12996. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12997. } catch ( err ) {
  12998. // Ignore any errors
  12999. }
  13000. function createCanvas( width, height ) {
  13001. // Use OffscreenCanvas when available. Specially needed in web workers
  13002. return useOffscreenCanvas ?
  13003. new OffscreenCanvas( width, height ) :
  13004. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13005. }
  13006. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13007. let scale = 1;
  13008. // handle case if texture exceeds max size
  13009. if ( image.width > maxSize || image.height > maxSize ) {
  13010. scale = maxSize / Math.max( image.width, image.height );
  13011. }
  13012. // only perform resize if necessary
  13013. if ( scale < 1 || needsPowerOfTwo === true ) {
  13014. // only perform resize for certain image types
  13015. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13016. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13017. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13018. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  13019. const width = floor( scale * image.width );
  13020. const height = floor( scale * image.height );
  13021. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13022. // cube textures can't reuse the same canvas
  13023. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13024. canvas.width = width;
  13025. canvas.height = height;
  13026. const context = canvas.getContext( '2d' );
  13027. context.drawImage( image, 0, 0, width, height );
  13028. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13029. return canvas;
  13030. } else {
  13031. if ( 'data' in image ) {
  13032. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13033. }
  13034. return image;
  13035. }
  13036. }
  13037. return image;
  13038. }
  13039. function isPowerOfTwo( image ) {
  13040. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  13041. }
  13042. function textureNeedsPowerOfTwo( texture ) {
  13043. if ( isWebGL2 ) return false;
  13044. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13045. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13046. }
  13047. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13048. return texture.generateMipmaps && supportsMips &&
  13049. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13050. }
  13051. function generateMipmap( target, texture, width, height ) {
  13052. _gl.generateMipmap( target );
  13053. const textureProperties = properties.get( texture );
  13054. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13055. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  13056. }
  13057. function getInternalFormat( internalFormatName, glFormat, glType ) {
  13058. if ( isWebGL2 === false ) return glFormat;
  13059. if ( internalFormatName !== null ) {
  13060. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13061. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13062. }
  13063. let internalFormat = glFormat;
  13064. if ( glFormat === 6403 ) {
  13065. if ( glType === 5126 ) internalFormat = 33326;
  13066. if ( glType === 5131 ) internalFormat = 33325;
  13067. if ( glType === 5121 ) internalFormat = 33321;
  13068. }
  13069. if ( glFormat === 6407 ) {
  13070. if ( glType === 5126 ) internalFormat = 34837;
  13071. if ( glType === 5131 ) internalFormat = 34843;
  13072. if ( glType === 5121 ) internalFormat = 32849;
  13073. }
  13074. if ( glFormat === 6408 ) {
  13075. if ( glType === 5126 ) internalFormat = 34836;
  13076. if ( glType === 5131 ) internalFormat = 34842;
  13077. if ( glType === 5121 ) internalFormat = 32856;
  13078. }
  13079. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13080. internalFormat === 34842 || internalFormat === 34836 ) {
  13081. extensions.get( 'EXT_color_buffer_float' );
  13082. }
  13083. return internalFormat;
  13084. }
  13085. // Fallback filters for non-power-of-2 textures
  13086. function filterFallback( f ) {
  13087. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13088. return 9728;
  13089. }
  13090. return 9729;
  13091. }
  13092. //
  13093. function onTextureDispose( event ) {
  13094. const texture = event.target;
  13095. texture.removeEventListener( 'dispose', onTextureDispose );
  13096. deallocateTexture( texture );
  13097. if ( texture.isVideoTexture ) {
  13098. _videoTextures.delete( texture );
  13099. }
  13100. info.memory.textures --;
  13101. }
  13102. function onRenderTargetDispose( event ) {
  13103. const renderTarget = event.target;
  13104. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13105. deallocateRenderTarget( renderTarget );
  13106. info.memory.textures --;
  13107. }
  13108. //
  13109. function deallocateTexture( texture ) {
  13110. const textureProperties = properties.get( texture );
  13111. if ( textureProperties.__webglInit === undefined ) return;
  13112. _gl.deleteTexture( textureProperties.__webglTexture );
  13113. properties.remove( texture );
  13114. }
  13115. function deallocateRenderTarget( renderTarget ) {
  13116. const renderTargetProperties = properties.get( renderTarget );
  13117. const textureProperties = properties.get( renderTarget.texture );
  13118. if ( ! renderTarget ) return;
  13119. if ( textureProperties.__webglTexture !== undefined ) {
  13120. _gl.deleteTexture( textureProperties.__webglTexture );
  13121. }
  13122. if ( renderTarget.depthTexture ) {
  13123. renderTarget.depthTexture.dispose();
  13124. }
  13125. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13126. for ( let i = 0; i < 6; i ++ ) {
  13127. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13128. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13129. }
  13130. } else {
  13131. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13132. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13133. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13134. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13135. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13136. }
  13137. properties.remove( renderTarget.texture );
  13138. properties.remove( renderTarget );
  13139. }
  13140. //
  13141. let textureUnits = 0;
  13142. function resetTextureUnits() {
  13143. textureUnits = 0;
  13144. }
  13145. function allocateTextureUnit() {
  13146. const textureUnit = textureUnits;
  13147. if ( textureUnit >= maxTextures ) {
  13148. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13149. }
  13150. textureUnits += 1;
  13151. return textureUnit;
  13152. }
  13153. //
  13154. function setTexture2D( texture, slot ) {
  13155. const textureProperties = properties.get( texture );
  13156. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13157. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13158. const image = texture.image;
  13159. if ( image === undefined ) {
  13160. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13161. } else if ( image.complete === false ) {
  13162. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13163. } else {
  13164. uploadTexture( textureProperties, texture, slot );
  13165. return;
  13166. }
  13167. }
  13168. state.activeTexture( 33984 + slot );
  13169. state.bindTexture( 3553, textureProperties.__webglTexture );
  13170. }
  13171. function setTexture2DArray( texture, slot ) {
  13172. const textureProperties = properties.get( texture );
  13173. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13174. uploadTexture( textureProperties, texture, slot );
  13175. return;
  13176. }
  13177. state.activeTexture( 33984 + slot );
  13178. state.bindTexture( 35866, textureProperties.__webglTexture );
  13179. }
  13180. function setTexture3D( texture, slot ) {
  13181. const textureProperties = properties.get( texture );
  13182. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13183. uploadTexture( textureProperties, texture, slot );
  13184. return;
  13185. }
  13186. state.activeTexture( 33984 + slot );
  13187. state.bindTexture( 32879, textureProperties.__webglTexture );
  13188. }
  13189. function setTextureCube( texture, slot ) {
  13190. const textureProperties = properties.get( texture );
  13191. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13192. uploadCubeTexture( textureProperties, texture, slot );
  13193. return;
  13194. }
  13195. state.activeTexture( 33984 + slot );
  13196. state.bindTexture( 34067, textureProperties.__webglTexture );
  13197. }
  13198. const wrappingToGL = {
  13199. [ RepeatWrapping ]: 10497,
  13200. [ ClampToEdgeWrapping ]: 33071,
  13201. [ MirroredRepeatWrapping ]: 33648
  13202. };
  13203. const filterToGL = {
  13204. [ NearestFilter ]: 9728,
  13205. [ NearestMipmapNearestFilter ]: 9984,
  13206. [ NearestMipmapLinearFilter ]: 9986,
  13207. [ LinearFilter ]: 9729,
  13208. [ LinearMipmapNearestFilter ]: 9985,
  13209. [ LinearMipmapLinearFilter ]: 9987
  13210. };
  13211. function setTextureParameters( textureType, texture, supportsMips ) {
  13212. if ( supportsMips ) {
  13213. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13214. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13215. if ( textureType === 32879 || textureType === 35866 ) {
  13216. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13217. }
  13218. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13219. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13220. } else {
  13221. _gl.texParameteri( textureType, 10242, 33071 );
  13222. _gl.texParameteri( textureType, 10243, 33071 );
  13223. if ( textureType === 32879 || textureType === 35866 ) {
  13224. _gl.texParameteri( textureType, 32882, 33071 );
  13225. }
  13226. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13227. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13228. }
  13229. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13230. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13231. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13232. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13233. }
  13234. }
  13235. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13236. if ( extension ) {
  13237. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  13238. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  13239. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13240. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13241. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13242. }
  13243. }
  13244. }
  13245. function initTexture( textureProperties, texture ) {
  13246. if ( textureProperties.__webglInit === undefined ) {
  13247. textureProperties.__webglInit = true;
  13248. texture.addEventListener( 'dispose', onTextureDispose );
  13249. textureProperties.__webglTexture = _gl.createTexture();
  13250. info.memory.textures ++;
  13251. }
  13252. }
  13253. function uploadTexture( textureProperties, texture, slot ) {
  13254. let textureType = 3553;
  13255. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13256. if ( texture.isDataTexture3D ) textureType = 32879;
  13257. initTexture( textureProperties, texture );
  13258. state.activeTexture( 33984 + slot );
  13259. state.bindTexture( textureType, textureProperties.__webglTexture );
  13260. _gl.pixelStorei( 37440, texture.flipY );
  13261. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13262. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13263. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  13264. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13265. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13266. glFormat = utils.convert( texture.format );
  13267. let glType = utils.convert( texture.type ),
  13268. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13269. setTextureParameters( textureType, texture, supportsMips );
  13270. let mipmap;
  13271. const mipmaps = texture.mipmaps;
  13272. if ( texture.isDepthTexture ) {
  13273. // populate depth texture with dummy data
  13274. glInternalFormat = 6402;
  13275. if ( isWebGL2 ) {
  13276. if ( texture.type === FloatType ) {
  13277. glInternalFormat = 36012;
  13278. } else if ( texture.type === UnsignedIntType ) {
  13279. glInternalFormat = 33190;
  13280. } else if ( texture.type === UnsignedInt248Type$1 ) {
  13281. glInternalFormat = 35056;
  13282. } else {
  13283. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13284. }
  13285. } else {
  13286. if ( texture.type === FloatType ) {
  13287. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13288. }
  13289. }
  13290. // validation checks for WebGL 1
  13291. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13292. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13293. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13294. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13295. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13296. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13297. texture.type = UnsignedShortType;
  13298. glType = utils.convert( texture.type );
  13299. }
  13300. }
  13301. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13302. // Depth stencil textures need the DEPTH_STENCIL internal format
  13303. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13304. glInternalFormat = 34041;
  13305. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13306. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13307. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13308. if ( texture.type !== UnsignedInt248Type$1 ) {
  13309. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13310. texture.type = UnsignedInt248Type$1;
  13311. glType = utils.convert( texture.type );
  13312. }
  13313. }
  13314. //
  13315. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13316. } else if ( texture.isDataTexture ) {
  13317. // use manually created mipmaps if available
  13318. // if there are no manual mipmaps
  13319. // set 0 level mipmap and then use GL to generate other mipmap levels
  13320. if ( mipmaps.length > 0 && supportsMips ) {
  13321. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13322. mipmap = mipmaps[ i ];
  13323. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13324. }
  13325. texture.generateMipmaps = false;
  13326. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13327. } else {
  13328. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13329. textureProperties.__maxMipLevel = 0;
  13330. }
  13331. } else if ( texture.isCompressedTexture ) {
  13332. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13333. mipmap = mipmaps[ i ];
  13334. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13335. if ( glFormat !== null ) {
  13336. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13337. } else {
  13338. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13339. }
  13340. } else {
  13341. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13342. }
  13343. }
  13344. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13345. } else if ( texture.isDataTexture2DArray ) {
  13346. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13347. textureProperties.__maxMipLevel = 0;
  13348. } else if ( texture.isDataTexture3D ) {
  13349. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13350. textureProperties.__maxMipLevel = 0;
  13351. } else {
  13352. // regular Texture (image, video, canvas)
  13353. // use manually created mipmaps if available
  13354. // if there are no manual mipmaps
  13355. // set 0 level mipmap and then use GL to generate other mipmap levels
  13356. if ( mipmaps.length > 0 && supportsMips ) {
  13357. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13358. mipmap = mipmaps[ i ];
  13359. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13360. }
  13361. texture.generateMipmaps = false;
  13362. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13363. } else {
  13364. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13365. textureProperties.__maxMipLevel = 0;
  13366. }
  13367. }
  13368. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13369. generateMipmap( textureType, texture, image.width, image.height );
  13370. }
  13371. textureProperties.__version = texture.version;
  13372. if ( texture.onUpdate ) texture.onUpdate( texture );
  13373. }
  13374. function uploadCubeTexture( textureProperties, texture, slot ) {
  13375. if ( texture.image.length !== 6 ) return;
  13376. initTexture( textureProperties, texture );
  13377. state.activeTexture( 33984 + slot );
  13378. state.bindTexture( 34067, textureProperties.__webglTexture );
  13379. _gl.pixelStorei( 37440, texture.flipY );
  13380. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13381. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13382. const cubeImage = [];
  13383. for ( let i = 0; i < 6; i ++ ) {
  13384. if ( ! isCompressed && ! isDataTexture ) {
  13385. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13386. } else {
  13387. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13388. }
  13389. }
  13390. const image = cubeImage[ 0 ],
  13391. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13392. glFormat = utils.convert( texture.format ),
  13393. glType = utils.convert( texture.type ),
  13394. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13395. setTextureParameters( 34067, texture, supportsMips );
  13396. let mipmaps;
  13397. if ( isCompressed ) {
  13398. for ( let i = 0; i < 6; i ++ ) {
  13399. mipmaps = cubeImage[ i ].mipmaps;
  13400. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13401. const mipmap = mipmaps[ j ];
  13402. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13403. if ( glFormat !== null ) {
  13404. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13405. } else {
  13406. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13407. }
  13408. } else {
  13409. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13410. }
  13411. }
  13412. }
  13413. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13414. } else {
  13415. mipmaps = texture.mipmaps;
  13416. for ( let i = 0; i < 6; i ++ ) {
  13417. if ( isDataTexture ) {
  13418. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13419. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13420. const mipmap = mipmaps[ j ];
  13421. const mipmapImage = mipmap.image[ i ].image;
  13422. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13423. }
  13424. } else {
  13425. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13426. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13427. const mipmap = mipmaps[ j ];
  13428. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13429. }
  13430. }
  13431. }
  13432. textureProperties.__maxMipLevel = mipmaps.length;
  13433. }
  13434. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13435. // We assume images for cube map have the same size.
  13436. generateMipmap( 34067, texture, image.width, image.height );
  13437. }
  13438. textureProperties.__version = texture.version;
  13439. if ( texture.onUpdate ) texture.onUpdate( texture );
  13440. }
  13441. // Render targets
  13442. // Setup storage for target texture and bind it to correct framebuffer
  13443. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  13444. const glFormat = utils.convert( renderTarget.texture.format );
  13445. const glType = utils.convert( renderTarget.texture.type );
  13446. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13447. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13448. _gl.bindFramebuffer( 36160, framebuffer );
  13449. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  13450. _gl.bindFramebuffer( 36160, null );
  13451. }
  13452. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13453. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13454. _gl.bindRenderbuffer( 36161, renderbuffer );
  13455. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13456. let glInternalFormat = 33189;
  13457. if ( isMultisample ) {
  13458. const depthTexture = renderTarget.depthTexture;
  13459. if ( depthTexture && depthTexture.isDepthTexture ) {
  13460. if ( depthTexture.type === FloatType ) {
  13461. glInternalFormat = 36012;
  13462. } else if ( depthTexture.type === UnsignedIntType ) {
  13463. glInternalFormat = 33190;
  13464. }
  13465. }
  13466. const samples = getRenderTargetSamples( renderTarget );
  13467. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13468. } else {
  13469. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13470. }
  13471. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13472. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13473. if ( isMultisample ) {
  13474. const samples = getRenderTargetSamples( renderTarget );
  13475. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13476. } else {
  13477. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13478. }
  13479. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13480. } else {
  13481. const glFormat = utils.convert( renderTarget.texture.format );
  13482. const glType = utils.convert( renderTarget.texture.type );
  13483. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13484. if ( isMultisample ) {
  13485. const samples = getRenderTargetSamples( renderTarget );
  13486. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13487. } else {
  13488. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13489. }
  13490. }
  13491. _gl.bindRenderbuffer( 36161, null );
  13492. }
  13493. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13494. function setupDepthTexture( framebuffer, renderTarget ) {
  13495. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13496. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13497. _gl.bindFramebuffer( 36160, framebuffer );
  13498. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13499. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13500. }
  13501. // upload an empty depth texture with framebuffer size
  13502. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13503. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13504. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13505. renderTarget.depthTexture.image.width = renderTarget.width;
  13506. renderTarget.depthTexture.image.height = renderTarget.height;
  13507. renderTarget.depthTexture.needsUpdate = true;
  13508. }
  13509. setTexture2D( renderTarget.depthTexture, 0 );
  13510. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13511. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13512. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13513. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13514. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13515. } else {
  13516. throw new Error( 'Unknown depthTexture format' );
  13517. }
  13518. }
  13519. // Setup GL resources for a non-texture depth buffer
  13520. function setupDepthRenderbuffer( renderTarget ) {
  13521. const renderTargetProperties = properties.get( renderTarget );
  13522. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13523. if ( renderTarget.depthTexture ) {
  13524. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13525. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13526. } else {
  13527. if ( isCube ) {
  13528. renderTargetProperties.__webglDepthbuffer = [];
  13529. for ( let i = 0; i < 6; i ++ ) {
  13530. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13531. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13532. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13533. }
  13534. } else {
  13535. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13536. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13537. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13538. }
  13539. }
  13540. _gl.bindFramebuffer( 36160, null );
  13541. }
  13542. // Set up GL resources for the render target
  13543. function setupRenderTarget( renderTarget ) {
  13544. const renderTargetProperties = properties.get( renderTarget );
  13545. const textureProperties = properties.get( renderTarget.texture );
  13546. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13547. textureProperties.__webglTexture = _gl.createTexture();
  13548. info.memory.textures ++;
  13549. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13550. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  13551. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13552. // Handles WebGL2 RGBFormat fallback - #18858
  13553. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  13554. renderTarget.texture.format = RGBAFormat;
  13555. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13556. }
  13557. // Setup framebuffer
  13558. if ( isCube ) {
  13559. renderTargetProperties.__webglFramebuffer = [];
  13560. for ( let i = 0; i < 6; i ++ ) {
  13561. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13562. }
  13563. } else {
  13564. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13565. if ( isMultisample ) {
  13566. if ( isWebGL2 ) {
  13567. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13568. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13569. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13570. const glFormat = utils.convert( renderTarget.texture.format );
  13571. const glType = utils.convert( renderTarget.texture.type );
  13572. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13573. const samples = getRenderTargetSamples( renderTarget );
  13574. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13575. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13576. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13577. _gl.bindRenderbuffer( 36161, null );
  13578. if ( renderTarget.depthBuffer ) {
  13579. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13580. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13581. }
  13582. _gl.bindFramebuffer( 36160, null );
  13583. } else {
  13584. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13585. }
  13586. }
  13587. }
  13588. // Setup color buffer
  13589. if ( isCube ) {
  13590. state.bindTexture( 34067, textureProperties.__webglTexture );
  13591. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  13592. for ( let i = 0; i < 6; i ++ ) {
  13593. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  13594. }
  13595. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13596. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  13597. }
  13598. state.bindTexture( 34067, null );
  13599. } else {
  13600. state.bindTexture( 3553, textureProperties.__webglTexture );
  13601. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  13602. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  13603. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13604. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  13605. }
  13606. state.bindTexture( 3553, null );
  13607. }
  13608. // Setup depth and stencil buffers
  13609. if ( renderTarget.depthBuffer ) {
  13610. setupDepthRenderbuffer( renderTarget );
  13611. }
  13612. }
  13613. function updateRenderTargetMipmap( renderTarget ) {
  13614. const texture = renderTarget.texture;
  13615. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13616. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13617. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13618. const webglTexture = properties.get( texture ).__webglTexture;
  13619. state.bindTexture( target, webglTexture );
  13620. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  13621. state.bindTexture( target, null );
  13622. }
  13623. }
  13624. function updateMultisampleRenderTarget( renderTarget ) {
  13625. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  13626. if ( isWebGL2 ) {
  13627. const renderTargetProperties = properties.get( renderTarget );
  13628. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  13629. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  13630. const width = renderTarget.width;
  13631. const height = renderTarget.height;
  13632. let mask = 16384;
  13633. if ( renderTarget.depthBuffer ) mask |= 256;
  13634. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13635. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  13636. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  13637. } else {
  13638. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13639. }
  13640. }
  13641. }
  13642. function getRenderTargetSamples( renderTarget ) {
  13643. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  13644. Math.min( maxSamples, renderTarget.samples ) : 0;
  13645. }
  13646. function updateVideoTexture( texture ) {
  13647. const frame = info.render.frame;
  13648. // Check the last frame we updated the VideoTexture
  13649. if ( _videoTextures.get( texture ) !== frame ) {
  13650. _videoTextures.set( texture, frame );
  13651. texture.update();
  13652. }
  13653. }
  13654. // backwards compatibility
  13655. let warnedTexture2D = false;
  13656. let warnedTextureCube = false;
  13657. function safeSetTexture2D( texture, slot ) {
  13658. if ( texture && texture.isWebGLRenderTarget ) {
  13659. if ( warnedTexture2D === false ) {
  13660. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  13661. warnedTexture2D = true;
  13662. }
  13663. texture = texture.texture;
  13664. }
  13665. setTexture2D( texture, slot );
  13666. }
  13667. function safeSetTextureCube( texture, slot ) {
  13668. if ( texture && texture.isWebGLCubeRenderTarget ) {
  13669. if ( warnedTextureCube === false ) {
  13670. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  13671. warnedTextureCube = true;
  13672. }
  13673. texture = texture.texture;
  13674. }
  13675. setTextureCube( texture, slot );
  13676. }
  13677. //
  13678. this.allocateTextureUnit = allocateTextureUnit;
  13679. this.resetTextureUnits = resetTextureUnits;
  13680. this.setTexture2D = setTexture2D;
  13681. this.setTexture2DArray = setTexture2DArray;
  13682. this.setTexture3D = setTexture3D;
  13683. this.setTextureCube = setTextureCube;
  13684. this.setupRenderTarget = setupRenderTarget;
  13685. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13686. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13687. this.safeSetTexture2D = safeSetTexture2D;
  13688. this.safeSetTextureCube = safeSetTextureCube;
  13689. }
  13690. function WebGLUtils( gl, extensions, capabilities ) {
  13691. const isWebGL2 = capabilities.isWebGL2;
  13692. function convert( p ) {
  13693. let extension;
  13694. if ( p === UnsignedByteType ) return 5121;
  13695. if ( p === UnsignedShort4444Type ) return 32819;
  13696. if ( p === UnsignedShort5551Type ) return 32820;
  13697. if ( p === UnsignedShort565Type ) return 33635;
  13698. if ( p === ByteType ) return 5120;
  13699. if ( p === ShortType ) return 5122;
  13700. if ( p === UnsignedShortType ) return 5123;
  13701. if ( p === IntType ) return 5124;
  13702. if ( p === UnsignedIntType ) return 5125;
  13703. if ( p === FloatType ) return 5126;
  13704. if ( p === HalfFloatType ) {
  13705. if ( isWebGL2 ) return 5131;
  13706. extension = extensions.get( 'OES_texture_half_float' );
  13707. if ( extension !== null ) {
  13708. return extension.HALF_FLOAT_OES;
  13709. } else {
  13710. return null;
  13711. }
  13712. }
  13713. if ( p === AlphaFormat ) return 6406;
  13714. if ( p === RGBFormat ) return 6407;
  13715. if ( p === RGBAFormat ) return 6408;
  13716. if ( p === LuminanceFormat ) return 6409;
  13717. if ( p === LuminanceAlphaFormat ) return 6410;
  13718. if ( p === DepthFormat ) return 6402;
  13719. if ( p === DepthStencilFormat ) return 34041;
  13720. if ( p === RedFormat ) return 6403;
  13721. // WebGL2 formats.
  13722. if ( p === RedIntegerFormat ) return 36244;
  13723. if ( p === RGFormat ) return 33319;
  13724. if ( p === RGIntegerFormat ) return 33320;
  13725. if ( p === RGBIntegerFormat ) return 36248;
  13726. if ( p === RGBAIntegerFormat ) return 36249;
  13727. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format$1 ||
  13728. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format$1 ) {
  13729. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13730. if ( extension !== null ) {
  13731. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13732. if ( p === RGBA_S3TC_DXT1_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13733. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13734. if ( p === RGBA_S3TC_DXT5_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13735. } else {
  13736. return null;
  13737. }
  13738. }
  13739. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13740. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13741. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13742. if ( extension !== null ) {
  13743. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13744. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13745. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13746. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13747. } else {
  13748. return null;
  13749. }
  13750. }
  13751. if ( p === RGB_ETC1_Format ) {
  13752. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13753. if ( extension !== null ) {
  13754. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13755. } else {
  13756. return null;
  13757. }
  13758. }
  13759. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13760. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13761. if ( extension !== null ) {
  13762. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13763. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13764. }
  13765. }
  13766. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13767. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13768. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13769. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13770. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13771. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13772. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13773. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13774. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13775. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13776. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13777. if ( extension !== null ) {
  13778. // TODO Complete?
  13779. return p;
  13780. } else {
  13781. return null;
  13782. }
  13783. }
  13784. if ( p === RGBA_BPTC_Format ) {
  13785. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13786. if ( extension !== null ) {
  13787. // TODO Complete?
  13788. return p;
  13789. } else {
  13790. return null;
  13791. }
  13792. }
  13793. if ( p === UnsignedInt248Type$1 ) {
  13794. if ( isWebGL2 ) return 34042;
  13795. extension = extensions.get( 'WEBGL_depth_texture' );
  13796. if ( extension !== null ) {
  13797. return extension.UNSIGNED_INT_24_8_WEBGL;
  13798. } else {
  13799. return null;
  13800. }
  13801. }
  13802. }
  13803. return { convert: convert };
  13804. }
  13805. function ArrayCamera( array = [] ) {
  13806. PerspectiveCamera.call( this );
  13807. this.cameras = array;
  13808. }
  13809. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  13810. constructor: ArrayCamera,
  13811. isArrayCamera: true
  13812. } );
  13813. function Group() {
  13814. Object3D.call( this );
  13815. this.type = 'Group';
  13816. }
  13817. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13818. constructor: Group,
  13819. isGroup: true
  13820. } );
  13821. function WebXRController() {
  13822. this._targetRay = null;
  13823. this._grip = null;
  13824. this._hand = null;
  13825. }
  13826. Object.assign( WebXRController.prototype, {
  13827. constructor: WebXRController,
  13828. getHandSpace: function () {
  13829. if ( this._hand === null ) {
  13830. this._hand = new Group();
  13831. this._hand.matrixAutoUpdate = false;
  13832. this._hand.visible = false;
  13833. this._hand.joints = [];
  13834. this._hand.inputState = { pinching: false };
  13835. if ( window.XRHand ) {
  13836. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13837. // The transform of this joint will be updated with the joint pose on each frame
  13838. const joint = new Group();
  13839. joint.matrixAutoUpdate = false;
  13840. joint.visible = false;
  13841. this._hand.joints.push( joint );
  13842. // ??
  13843. this._hand.add( joint );
  13844. }
  13845. }
  13846. }
  13847. return this._hand;
  13848. },
  13849. getTargetRaySpace: function () {
  13850. if ( this._targetRay === null ) {
  13851. this._targetRay = new Group();
  13852. this._targetRay.matrixAutoUpdate = false;
  13853. this._targetRay.visible = false;
  13854. }
  13855. return this._targetRay;
  13856. },
  13857. getGripSpace: function () {
  13858. if ( this._grip === null ) {
  13859. this._grip = new Group();
  13860. this._grip.matrixAutoUpdate = false;
  13861. this._grip.visible = false;
  13862. }
  13863. return this._grip;
  13864. },
  13865. dispatchEvent: function ( event ) {
  13866. if ( this._targetRay !== null ) {
  13867. this._targetRay.dispatchEvent( event );
  13868. }
  13869. if ( this._grip !== null ) {
  13870. this._grip.dispatchEvent( event );
  13871. }
  13872. if ( this._hand !== null ) {
  13873. this._hand.dispatchEvent( event );
  13874. }
  13875. return this;
  13876. },
  13877. disconnect: function ( inputSource ) {
  13878. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13879. if ( this._targetRay !== null ) {
  13880. this._targetRay.visible = false;
  13881. }
  13882. if ( this._grip !== null ) {
  13883. this._grip.visible = false;
  13884. }
  13885. if ( this._hand !== null ) {
  13886. this._hand.visible = false;
  13887. }
  13888. return this;
  13889. },
  13890. update: function ( inputSource, frame, referenceSpace ) {
  13891. let inputPose = null;
  13892. let gripPose = null;
  13893. let handPose = null;
  13894. const targetRay = this._targetRay;
  13895. const grip = this._grip;
  13896. const hand = this._hand;
  13897. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13898. if ( hand && inputSource.hand ) {
  13899. handPose = true;
  13900. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13901. if ( inputSource.hand[ i ] ) {
  13902. // Update the joints groups with the XRJoint poses
  13903. const jointPose = frame.getJointPose( inputSource.hand[ i ], referenceSpace );
  13904. const joint = hand.joints[ i ];
  13905. if ( jointPose !== null ) {
  13906. joint.matrix.fromArray( jointPose.transform.matrix );
  13907. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13908. joint.jointRadius = jointPose.radius;
  13909. }
  13910. joint.visible = jointPose !== null;
  13911. // Custom events
  13912. // Check pinch
  13913. const indexTip = hand.joints[ window.XRHand.INDEX_PHALANX_TIP ];
  13914. const thumbTip = hand.joints[ window.XRHand.THUMB_PHALANX_TIP ];
  13915. const distance = indexTip.position.distanceTo( thumbTip.position );
  13916. const distanceToPinch = 0.02;
  13917. const threshold = 0.005;
  13918. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13919. hand.inputState.pinching = false;
  13920. this.dispatchEvent( {
  13921. type: 'pinchend',
  13922. handedness: inputSource.handedness,
  13923. target: this
  13924. } );
  13925. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13926. hand.inputState.pinching = true;
  13927. this.dispatchEvent( {
  13928. type: 'pinchstart',
  13929. handedness: inputSource.handedness,
  13930. target: this
  13931. } );
  13932. }
  13933. }
  13934. }
  13935. } else {
  13936. if ( targetRay !== null ) {
  13937. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13938. if ( inputPose !== null ) {
  13939. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13940. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13941. }
  13942. }
  13943. if ( grip !== null && inputSource.gripSpace ) {
  13944. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13945. if ( gripPose !== null ) {
  13946. grip.matrix.fromArray( gripPose.transform.matrix );
  13947. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13948. }
  13949. }
  13950. }
  13951. }
  13952. if ( targetRay !== null ) {
  13953. targetRay.visible = ( inputPose !== null );
  13954. }
  13955. if ( grip !== null ) {
  13956. grip.visible = ( gripPose !== null );
  13957. }
  13958. if ( hand !== null ) {
  13959. hand.visible = ( handPose !== null );
  13960. }
  13961. return this;
  13962. }
  13963. } );
  13964. function WebXRManager( renderer, gl ) {
  13965. const scope = this;
  13966. let session = null;
  13967. let framebufferScaleFactor = 1.0;
  13968. let referenceSpace = null;
  13969. let referenceSpaceType = 'local-floor';
  13970. let pose = null;
  13971. const controllers = [];
  13972. const inputSourcesMap = new Map();
  13973. //
  13974. const cameraL = new PerspectiveCamera();
  13975. cameraL.layers.enable( 1 );
  13976. cameraL.viewport = new Vector4();
  13977. const cameraR = new PerspectiveCamera();
  13978. cameraR.layers.enable( 2 );
  13979. cameraR.viewport = new Vector4();
  13980. const cameras = [ cameraL, cameraR ];
  13981. const cameraVR = new ArrayCamera();
  13982. cameraVR.layers.enable( 1 );
  13983. cameraVR.layers.enable( 2 );
  13984. let _currentDepthNear = null;
  13985. let _currentDepthFar = null;
  13986. //
  13987. this.enabled = false;
  13988. this.isPresenting = false;
  13989. this.getController = function ( index ) {
  13990. let controller = controllers[ index ];
  13991. if ( controller === undefined ) {
  13992. controller = new WebXRController();
  13993. controllers[ index ] = controller;
  13994. }
  13995. return controller.getTargetRaySpace();
  13996. };
  13997. this.getControllerGrip = function ( index ) {
  13998. let controller = controllers[ index ];
  13999. if ( controller === undefined ) {
  14000. controller = new WebXRController();
  14001. controllers[ index ] = controller;
  14002. }
  14003. return controller.getGripSpace();
  14004. };
  14005. this.getHand = function ( index ) {
  14006. let controller = controllers[ index ];
  14007. if ( controller === undefined ) {
  14008. controller = new WebXRController();
  14009. controllers[ index ] = controller;
  14010. }
  14011. return controller.getHandSpace();
  14012. };
  14013. //
  14014. function onSessionEvent( event ) {
  14015. const controller = inputSourcesMap.get( event.inputSource );
  14016. if ( controller ) {
  14017. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14018. }
  14019. }
  14020. function onSessionEnd() {
  14021. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14022. controller.disconnect( inputSource );
  14023. } );
  14024. inputSourcesMap.clear();
  14025. //
  14026. renderer.setFramebuffer( null );
  14027. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  14028. animation.stop();
  14029. scope.isPresenting = false;
  14030. scope.dispatchEvent( { type: 'sessionend' } );
  14031. }
  14032. function onRequestReferenceSpace( value ) {
  14033. referenceSpace = value;
  14034. animation.setContext( session );
  14035. animation.start();
  14036. scope.isPresenting = true;
  14037. scope.dispatchEvent( { type: 'sessionstart' } );
  14038. }
  14039. this.setFramebufferScaleFactor = function ( value ) {
  14040. framebufferScaleFactor = value;
  14041. if ( scope.isPresenting === true ) {
  14042. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14043. }
  14044. };
  14045. this.setReferenceSpaceType = function ( value ) {
  14046. referenceSpaceType = value;
  14047. if ( scope.isPresenting === true ) {
  14048. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14049. }
  14050. };
  14051. this.getReferenceSpace = function () {
  14052. return referenceSpace;
  14053. };
  14054. this.getSession = function () {
  14055. return session;
  14056. };
  14057. this.setSession = function ( value ) {
  14058. session = value;
  14059. if ( session !== null ) {
  14060. session.addEventListener( 'select', onSessionEvent );
  14061. session.addEventListener( 'selectstart', onSessionEvent );
  14062. session.addEventListener( 'selectend', onSessionEvent );
  14063. session.addEventListener( 'squeeze', onSessionEvent );
  14064. session.addEventListener( 'squeezestart', onSessionEvent );
  14065. session.addEventListener( 'squeezeend', onSessionEvent );
  14066. session.addEventListener( 'end', onSessionEnd );
  14067. const attributes = gl.getContextAttributes();
  14068. if ( attributes.xrCompatible !== true ) {
  14069. gl.makeXRCompatible();
  14070. }
  14071. const layerInit = {
  14072. antialias: attributes.antialias,
  14073. alpha: attributes.alpha,
  14074. depth: attributes.depth,
  14075. stencil: attributes.stencil,
  14076. framebufferScaleFactor: framebufferScaleFactor
  14077. };
  14078. // eslint-disable-next-line no-undef
  14079. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  14080. session.updateRenderState( { baseLayer: baseLayer } );
  14081. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  14082. //
  14083. session.addEventListener( 'inputsourceschange', updateInputSources );
  14084. }
  14085. };
  14086. function updateInputSources( event ) {
  14087. const inputSources = session.inputSources;
  14088. // Assign inputSources to available controllers
  14089. for ( let i = 0; i < controllers.length; i ++ ) {
  14090. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14091. }
  14092. // Notify disconnected
  14093. for ( let i = 0; i < event.removed.length; i ++ ) {
  14094. const inputSource = event.removed[ i ];
  14095. const controller = inputSourcesMap.get( inputSource );
  14096. if ( controller ) {
  14097. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14098. inputSourcesMap.delete( inputSource );
  14099. }
  14100. }
  14101. // Notify connected
  14102. for ( let i = 0; i < event.added.length; i ++ ) {
  14103. const inputSource = event.added[ i ];
  14104. const controller = inputSourcesMap.get( inputSource );
  14105. if ( controller ) {
  14106. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14107. }
  14108. }
  14109. }
  14110. //
  14111. const cameraLPos = new Vector3();
  14112. const cameraRPos = new Vector3();
  14113. /**
  14114. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14115. * the cameras' projection and world matrices have already been set.
  14116. * And that near and far planes are identical for both cameras.
  14117. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14118. */
  14119. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14120. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14121. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14122. const ipd = cameraLPos.distanceTo( cameraRPos );
  14123. const projL = cameraL.projectionMatrix.elements;
  14124. const projR = cameraR.projectionMatrix.elements;
  14125. // VR systems will have identical far and near planes, and
  14126. // most likely identical top and bottom frustum extents.
  14127. // Use the left camera for these values.
  14128. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14129. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14130. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14131. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14132. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14133. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14134. const left = near * leftFov;
  14135. const right = near * rightFov;
  14136. // Calculate the new camera's position offset from the
  14137. // left camera. xOffset should be roughly half `ipd`.
  14138. const zOffset = ipd / ( - leftFov + rightFov );
  14139. const xOffset = zOffset * - leftFov;
  14140. // TODO: Better way to apply this offset?
  14141. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14142. camera.translateX( xOffset );
  14143. camera.translateZ( zOffset );
  14144. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14145. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14146. // Find the union of the frustum values of the cameras and scale
  14147. // the values so that the near plane's position does not change in world space,
  14148. // although must now be relative to the new union camera.
  14149. const near2 = near + zOffset;
  14150. const far2 = far + zOffset;
  14151. const left2 = left - xOffset;
  14152. const right2 = right + ( ipd - xOffset );
  14153. const top2 = topFov * far / far2 * near2;
  14154. const bottom2 = bottomFov * far / far2 * near2;
  14155. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14156. }
  14157. function updateCamera( camera, parent ) {
  14158. if ( parent === null ) {
  14159. camera.matrixWorld.copy( camera.matrix );
  14160. } else {
  14161. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14162. }
  14163. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14164. }
  14165. this.getCamera = function ( camera ) {
  14166. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14167. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14168. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14169. // Note that the new renderState won't apply until the next frame. See #18320
  14170. session.updateRenderState( {
  14171. depthNear: cameraVR.near,
  14172. depthFar: cameraVR.far
  14173. } );
  14174. _currentDepthNear = cameraVR.near;
  14175. _currentDepthFar = cameraVR.far;
  14176. }
  14177. const parent = camera.parent;
  14178. const cameras = cameraVR.cameras;
  14179. updateCamera( cameraVR, parent );
  14180. for ( let i = 0; i < cameras.length; i ++ ) {
  14181. updateCamera( cameras[ i ], parent );
  14182. }
  14183. // update camera and its children
  14184. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14185. const children = camera.children;
  14186. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14187. children[ i ].updateMatrixWorld( true );
  14188. }
  14189. // update projection matrix for proper view frustum culling
  14190. if ( cameras.length === 2 ) {
  14191. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14192. } else {
  14193. // assume single camera setup (AR)
  14194. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14195. }
  14196. return cameraVR;
  14197. };
  14198. // Animation Loop
  14199. let onAnimationFrameCallback = null;
  14200. function onAnimationFrame( time, frame ) {
  14201. pose = frame.getViewerPose( referenceSpace );
  14202. if ( pose !== null ) {
  14203. const views = pose.views;
  14204. const baseLayer = session.renderState.baseLayer;
  14205. renderer.setFramebuffer( baseLayer.framebuffer );
  14206. let cameraVRNeedsUpdate = false;
  14207. // check if it's necessary to rebuild cameraVR's camera list
  14208. if ( views.length !== cameraVR.cameras.length ) {
  14209. cameraVR.cameras.length = 0;
  14210. cameraVRNeedsUpdate = true;
  14211. }
  14212. for ( let i = 0; i < views.length; i ++ ) {
  14213. const view = views[ i ];
  14214. const viewport = baseLayer.getViewport( view );
  14215. const camera = cameras[ i ];
  14216. camera.matrix.fromArray( view.transform.matrix );
  14217. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14218. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14219. if ( i === 0 ) {
  14220. cameraVR.matrix.copy( camera.matrix );
  14221. }
  14222. if ( cameraVRNeedsUpdate === true ) {
  14223. cameraVR.cameras.push( camera );
  14224. }
  14225. }
  14226. }
  14227. //
  14228. const inputSources = session.inputSources;
  14229. for ( let i = 0; i < controllers.length; i ++ ) {
  14230. const controller = controllers[ i ];
  14231. const inputSource = inputSources[ i ];
  14232. controller.update( inputSource, frame, referenceSpace );
  14233. }
  14234. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14235. }
  14236. const animation = new WebGLAnimation();
  14237. animation.setAnimationLoop( onAnimationFrame );
  14238. this.setAnimationLoop = function ( callback ) {
  14239. onAnimationFrameCallback = callback;
  14240. };
  14241. this.dispose = function () {};
  14242. }
  14243. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  14244. function WebGLMaterials( properties ) {
  14245. function refreshFogUniforms( uniforms, fog ) {
  14246. uniforms.fogColor.value.copy( fog.color );
  14247. if ( fog.isFog ) {
  14248. uniforms.fogNear.value = fog.near;
  14249. uniforms.fogFar.value = fog.far;
  14250. } else if ( fog.isFogExp2 ) {
  14251. uniforms.fogDensity.value = fog.density;
  14252. }
  14253. }
  14254. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  14255. if ( material.isMeshBasicMaterial ) {
  14256. refreshUniformsCommon( uniforms, material );
  14257. } else if ( material.isMeshLambertMaterial ) {
  14258. refreshUniformsCommon( uniforms, material );
  14259. refreshUniformsLambert( uniforms, material );
  14260. } else if ( material.isMeshToonMaterial ) {
  14261. refreshUniformsCommon( uniforms, material );
  14262. refreshUniformsToon( uniforms, material );
  14263. } else if ( material.isMeshPhongMaterial ) {
  14264. refreshUniformsCommon( uniforms, material );
  14265. refreshUniformsPhong( uniforms, material );
  14266. } else if ( material.isMeshStandardMaterial ) {
  14267. refreshUniformsCommon( uniforms, material );
  14268. if ( material.isMeshPhysicalMaterial ) {
  14269. refreshUniformsPhysical( uniforms, material );
  14270. } else {
  14271. refreshUniformsStandard( uniforms, material );
  14272. }
  14273. } else if ( material.isMeshMatcapMaterial ) {
  14274. refreshUniformsCommon( uniforms, material );
  14275. refreshUniformsMatcap( uniforms, material );
  14276. } else if ( material.isMeshDepthMaterial ) {
  14277. refreshUniformsCommon( uniforms, material );
  14278. refreshUniformsDepth( uniforms, material );
  14279. } else if ( material.isMeshDistanceMaterial ) {
  14280. refreshUniformsCommon( uniforms, material );
  14281. refreshUniformsDistance( uniforms, material );
  14282. } else if ( material.isMeshNormalMaterial ) {
  14283. refreshUniformsCommon( uniforms, material );
  14284. refreshUniformsNormal( uniforms, material );
  14285. } else if ( material.isLineBasicMaterial ) {
  14286. refreshUniformsLine( uniforms, material );
  14287. if ( material.isLineDashedMaterial ) {
  14288. refreshUniformsDash( uniforms, material );
  14289. }
  14290. } else if ( material.isPointsMaterial ) {
  14291. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14292. } else if ( material.isSpriteMaterial ) {
  14293. refreshUniformsSprites( uniforms, material );
  14294. } else if ( material.isShadowMaterial ) {
  14295. uniforms.color.value.copy( material.color );
  14296. uniforms.opacity.value = material.opacity;
  14297. } else if ( material.isShaderMaterial ) {
  14298. material.uniformsNeedUpdate = false; // #15581
  14299. }
  14300. }
  14301. function refreshUniformsCommon( uniforms, material ) {
  14302. uniforms.opacity.value = material.opacity;
  14303. if ( material.color ) {
  14304. uniforms.diffuse.value.copy( material.color );
  14305. }
  14306. if ( material.emissive ) {
  14307. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14308. }
  14309. if ( material.map ) {
  14310. uniforms.map.value = material.map;
  14311. }
  14312. if ( material.alphaMap ) {
  14313. uniforms.alphaMap.value = material.alphaMap;
  14314. }
  14315. if ( material.specularMap ) {
  14316. uniforms.specularMap.value = material.specularMap;
  14317. }
  14318. const envMap = properties.get( material ).envMap;
  14319. if ( envMap ) {
  14320. uniforms.envMap.value = envMap;
  14321. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  14322. uniforms.reflectivity.value = material.reflectivity;
  14323. uniforms.refractionRatio.value = material.refractionRatio;
  14324. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  14325. if ( maxMipLevel !== undefined ) {
  14326. uniforms.maxMipLevel.value = maxMipLevel;
  14327. }
  14328. }
  14329. if ( material.lightMap ) {
  14330. uniforms.lightMap.value = material.lightMap;
  14331. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14332. }
  14333. if ( material.aoMap ) {
  14334. uniforms.aoMap.value = material.aoMap;
  14335. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14336. }
  14337. // uv repeat and offset setting priorities
  14338. // 1. color map
  14339. // 2. specular map
  14340. // 3. displacementMap map
  14341. // 4. normal map
  14342. // 5. bump map
  14343. // 6. roughnessMap map
  14344. // 7. metalnessMap map
  14345. // 8. alphaMap map
  14346. // 9. emissiveMap map
  14347. // 10. clearcoat map
  14348. // 11. clearcoat normal map
  14349. // 12. clearcoat roughnessMap map
  14350. let uvScaleMap;
  14351. if ( material.map ) {
  14352. uvScaleMap = material.map;
  14353. } else if ( material.specularMap ) {
  14354. uvScaleMap = material.specularMap;
  14355. } else if ( material.displacementMap ) {
  14356. uvScaleMap = material.displacementMap;
  14357. } else if ( material.normalMap ) {
  14358. uvScaleMap = material.normalMap;
  14359. } else if ( material.bumpMap ) {
  14360. uvScaleMap = material.bumpMap;
  14361. } else if ( material.roughnessMap ) {
  14362. uvScaleMap = material.roughnessMap;
  14363. } else if ( material.metalnessMap ) {
  14364. uvScaleMap = material.metalnessMap;
  14365. } else if ( material.alphaMap ) {
  14366. uvScaleMap = material.alphaMap;
  14367. } else if ( material.emissiveMap ) {
  14368. uvScaleMap = material.emissiveMap;
  14369. } else if ( material.clearcoatMap ) {
  14370. uvScaleMap = material.clearcoatMap;
  14371. } else if ( material.clearcoatNormalMap ) {
  14372. uvScaleMap = material.clearcoatNormalMap;
  14373. } else if ( material.clearcoatRoughnessMap ) {
  14374. uvScaleMap = material.clearcoatRoughnessMap;
  14375. }
  14376. if ( uvScaleMap !== undefined ) {
  14377. // backwards compatibility
  14378. if ( uvScaleMap.isWebGLRenderTarget ) {
  14379. uvScaleMap = uvScaleMap.texture;
  14380. }
  14381. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14382. uvScaleMap.updateMatrix();
  14383. }
  14384. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14385. }
  14386. // uv repeat and offset setting priorities for uv2
  14387. // 1. ao map
  14388. // 2. light map
  14389. let uv2ScaleMap;
  14390. if ( material.aoMap ) {
  14391. uv2ScaleMap = material.aoMap;
  14392. } else if ( material.lightMap ) {
  14393. uv2ScaleMap = material.lightMap;
  14394. }
  14395. if ( uv2ScaleMap !== undefined ) {
  14396. // backwards compatibility
  14397. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14398. uv2ScaleMap = uv2ScaleMap.texture;
  14399. }
  14400. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14401. uv2ScaleMap.updateMatrix();
  14402. }
  14403. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14404. }
  14405. }
  14406. function refreshUniformsLine( uniforms, material ) {
  14407. uniforms.diffuse.value.copy( material.color );
  14408. uniforms.opacity.value = material.opacity;
  14409. }
  14410. function refreshUniformsDash( uniforms, material ) {
  14411. uniforms.dashSize.value = material.dashSize;
  14412. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14413. uniforms.scale.value = material.scale;
  14414. }
  14415. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14416. uniforms.diffuse.value.copy( material.color );
  14417. uniforms.opacity.value = material.opacity;
  14418. uniforms.size.value = material.size * pixelRatio;
  14419. uniforms.scale.value = height * 0.5;
  14420. if ( material.map ) {
  14421. uniforms.map.value = material.map;
  14422. }
  14423. if ( material.alphaMap ) {
  14424. uniforms.alphaMap.value = material.alphaMap;
  14425. }
  14426. // uv repeat and offset setting priorities
  14427. // 1. color map
  14428. // 2. alpha map
  14429. let uvScaleMap;
  14430. if ( material.map ) {
  14431. uvScaleMap = material.map;
  14432. } else if ( material.alphaMap ) {
  14433. uvScaleMap = material.alphaMap;
  14434. }
  14435. if ( uvScaleMap !== undefined ) {
  14436. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14437. uvScaleMap.updateMatrix();
  14438. }
  14439. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14440. }
  14441. }
  14442. function refreshUniformsSprites( uniforms, material ) {
  14443. uniforms.diffuse.value.copy( material.color );
  14444. uniforms.opacity.value = material.opacity;
  14445. uniforms.rotation.value = material.rotation;
  14446. if ( material.map ) {
  14447. uniforms.map.value = material.map;
  14448. }
  14449. if ( material.alphaMap ) {
  14450. uniforms.alphaMap.value = material.alphaMap;
  14451. }
  14452. // uv repeat and offset setting priorities
  14453. // 1. color map
  14454. // 2. alpha map
  14455. let uvScaleMap;
  14456. if ( material.map ) {
  14457. uvScaleMap = material.map;
  14458. } else if ( material.alphaMap ) {
  14459. uvScaleMap = material.alphaMap;
  14460. }
  14461. if ( uvScaleMap !== undefined ) {
  14462. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14463. uvScaleMap.updateMatrix();
  14464. }
  14465. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14466. }
  14467. }
  14468. function refreshUniformsLambert( uniforms, material ) {
  14469. if ( material.emissiveMap ) {
  14470. uniforms.emissiveMap.value = material.emissiveMap;
  14471. }
  14472. }
  14473. function refreshUniformsPhong( uniforms, material ) {
  14474. uniforms.specular.value.copy( material.specular );
  14475. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14476. if ( material.emissiveMap ) {
  14477. uniforms.emissiveMap.value = material.emissiveMap;
  14478. }
  14479. if ( material.bumpMap ) {
  14480. uniforms.bumpMap.value = material.bumpMap;
  14481. uniforms.bumpScale.value = material.bumpScale;
  14482. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14483. }
  14484. if ( material.normalMap ) {
  14485. uniforms.normalMap.value = material.normalMap;
  14486. uniforms.normalScale.value.copy( material.normalScale );
  14487. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14488. }
  14489. if ( material.displacementMap ) {
  14490. uniforms.displacementMap.value = material.displacementMap;
  14491. uniforms.displacementScale.value = material.displacementScale;
  14492. uniforms.displacementBias.value = material.displacementBias;
  14493. }
  14494. }
  14495. function refreshUniformsToon( uniforms, material ) {
  14496. if ( material.gradientMap ) {
  14497. uniforms.gradientMap.value = material.gradientMap;
  14498. }
  14499. if ( material.emissiveMap ) {
  14500. uniforms.emissiveMap.value = material.emissiveMap;
  14501. }
  14502. if ( material.bumpMap ) {
  14503. uniforms.bumpMap.value = material.bumpMap;
  14504. uniforms.bumpScale.value = material.bumpScale;
  14505. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14506. }
  14507. if ( material.normalMap ) {
  14508. uniforms.normalMap.value = material.normalMap;
  14509. uniforms.normalScale.value.copy( material.normalScale );
  14510. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14511. }
  14512. if ( material.displacementMap ) {
  14513. uniforms.displacementMap.value = material.displacementMap;
  14514. uniforms.displacementScale.value = material.displacementScale;
  14515. uniforms.displacementBias.value = material.displacementBias;
  14516. }
  14517. }
  14518. function refreshUniformsStandard( uniforms, material ) {
  14519. uniforms.roughness.value = material.roughness;
  14520. uniforms.metalness.value = material.metalness;
  14521. if ( material.roughnessMap ) {
  14522. uniforms.roughnessMap.value = material.roughnessMap;
  14523. }
  14524. if ( material.metalnessMap ) {
  14525. uniforms.metalnessMap.value = material.metalnessMap;
  14526. }
  14527. if ( material.emissiveMap ) {
  14528. uniforms.emissiveMap.value = material.emissiveMap;
  14529. }
  14530. if ( material.bumpMap ) {
  14531. uniforms.bumpMap.value = material.bumpMap;
  14532. uniforms.bumpScale.value = material.bumpScale;
  14533. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14534. }
  14535. if ( material.normalMap ) {
  14536. uniforms.normalMap.value = material.normalMap;
  14537. uniforms.normalScale.value.copy( material.normalScale );
  14538. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14539. }
  14540. if ( material.displacementMap ) {
  14541. uniforms.displacementMap.value = material.displacementMap;
  14542. uniforms.displacementScale.value = material.displacementScale;
  14543. uniforms.displacementBias.value = material.displacementBias;
  14544. }
  14545. const envMap = properties.get( material ).envMap;
  14546. if ( envMap ) {
  14547. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14548. uniforms.envMapIntensity.value = material.envMapIntensity;
  14549. }
  14550. }
  14551. function refreshUniformsPhysical( uniforms, material ) {
  14552. refreshUniformsStandard( uniforms, material );
  14553. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14554. uniforms.clearcoat.value = material.clearcoat;
  14555. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14556. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  14557. if ( material.clearcoatMap ) {
  14558. uniforms.clearcoatMap.value = material.clearcoatMap;
  14559. }
  14560. if ( material.clearcoatRoughnessMap ) {
  14561. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14562. }
  14563. if ( material.clearcoatNormalMap ) {
  14564. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  14565. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14566. if ( material.side === BackSide ) {
  14567. uniforms.clearcoatNormalScale.value.negate();
  14568. }
  14569. }
  14570. uniforms.transmission.value = material.transmission;
  14571. if ( material.transmissionMap ) {
  14572. uniforms.transmissionMap.value = material.transmissionMap;
  14573. }
  14574. }
  14575. function refreshUniformsMatcap( uniforms, material ) {
  14576. if ( material.matcap ) {
  14577. uniforms.matcap.value = material.matcap;
  14578. }
  14579. if ( material.bumpMap ) {
  14580. uniforms.bumpMap.value = material.bumpMap;
  14581. uniforms.bumpScale.value = material.bumpScale;
  14582. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14583. }
  14584. if ( material.normalMap ) {
  14585. uniforms.normalMap.value = material.normalMap;
  14586. uniforms.normalScale.value.copy( material.normalScale );
  14587. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14588. }
  14589. if ( material.displacementMap ) {
  14590. uniforms.displacementMap.value = material.displacementMap;
  14591. uniforms.displacementScale.value = material.displacementScale;
  14592. uniforms.displacementBias.value = material.displacementBias;
  14593. }
  14594. }
  14595. function refreshUniformsDepth( uniforms, material ) {
  14596. if ( material.displacementMap ) {
  14597. uniforms.displacementMap.value = material.displacementMap;
  14598. uniforms.displacementScale.value = material.displacementScale;
  14599. uniforms.displacementBias.value = material.displacementBias;
  14600. }
  14601. }
  14602. function refreshUniformsDistance( uniforms, material ) {
  14603. if ( material.displacementMap ) {
  14604. uniforms.displacementMap.value = material.displacementMap;
  14605. uniforms.displacementScale.value = material.displacementScale;
  14606. uniforms.displacementBias.value = material.displacementBias;
  14607. }
  14608. uniforms.referencePosition.value.copy( material.referencePosition );
  14609. uniforms.nearDistance.value = material.nearDistance;
  14610. uniforms.farDistance.value = material.farDistance;
  14611. }
  14612. function refreshUniformsNormal( uniforms, material ) {
  14613. if ( material.bumpMap ) {
  14614. uniforms.bumpMap.value = material.bumpMap;
  14615. uniforms.bumpScale.value = material.bumpScale;
  14616. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14617. }
  14618. if ( material.normalMap ) {
  14619. uniforms.normalMap.value = material.normalMap;
  14620. uniforms.normalScale.value.copy( material.normalScale );
  14621. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14622. }
  14623. if ( material.displacementMap ) {
  14624. uniforms.displacementMap.value = material.displacementMap;
  14625. uniforms.displacementScale.value = material.displacementScale;
  14626. uniforms.displacementBias.value = material.displacementBias;
  14627. }
  14628. }
  14629. return {
  14630. refreshFogUniforms: refreshFogUniforms,
  14631. refreshMaterialUniforms: refreshMaterialUniforms
  14632. };
  14633. }
  14634. function createCanvasElement() {
  14635. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14636. canvas.style.display = 'block';
  14637. return canvas;
  14638. }
  14639. function WebGLRenderer( parameters ) {
  14640. parameters = parameters || {};
  14641. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14642. _context = parameters.context !== undefined ? parameters.context : null,
  14643. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14644. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14645. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14646. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14647. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14648. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14649. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14650. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14651. let currentRenderList = null;
  14652. let currentRenderState = null;
  14653. // render() can be called from within a callback triggered by another render.
  14654. // We track this so that the nested render call gets its state isolated from the parent render call.
  14655. const renderStateStack = [];
  14656. // public properties
  14657. this.domElement = _canvas;
  14658. // Debug configuration container
  14659. this.debug = {
  14660. /**
  14661. * Enables error checking and reporting when shader programs are being compiled
  14662. * @type {boolean}
  14663. */
  14664. checkShaderErrors: true
  14665. };
  14666. // clearing
  14667. this.autoClear = true;
  14668. this.autoClearColor = true;
  14669. this.autoClearDepth = true;
  14670. this.autoClearStencil = true;
  14671. // scene graph
  14672. this.sortObjects = true;
  14673. // user-defined clipping
  14674. this.clippingPlanes = [];
  14675. this.localClippingEnabled = false;
  14676. // physically based shading
  14677. this.gammaFactor = 2.0; // for backwards compatibility
  14678. this.outputEncoding = LinearEncoding;
  14679. // physical lights
  14680. this.physicallyCorrectLights = false;
  14681. // tone mapping
  14682. this.toneMapping = NoToneMapping;
  14683. this.toneMappingExposure = 1.0;
  14684. // morphs
  14685. this.maxMorphTargets = 8;
  14686. this.maxMorphNormals = 4;
  14687. // internal properties
  14688. const _this = this;
  14689. let _isContextLost = false;
  14690. // internal state cache
  14691. let _framebuffer = null;
  14692. let _currentActiveCubeFace = 0;
  14693. let _currentActiveMipmapLevel = 0;
  14694. let _currentRenderTarget = null;
  14695. let _currentFramebuffer = null;
  14696. let _currentMaterialId = - 1;
  14697. let _currentCamera = null;
  14698. const _currentViewport = new Vector4();
  14699. const _currentScissor = new Vector4();
  14700. let _currentScissorTest = null;
  14701. //
  14702. let _width = _canvas.width;
  14703. let _height = _canvas.height;
  14704. let _pixelRatio = 1;
  14705. let _opaqueSort = null;
  14706. let _transparentSort = null;
  14707. const _viewport = new Vector4( 0, 0, _width, _height );
  14708. const _scissor = new Vector4( 0, 0, _width, _height );
  14709. let _scissorTest = false;
  14710. // frustum
  14711. const _frustum = new Frustum();
  14712. // clipping
  14713. let _clippingEnabled = false;
  14714. let _localClippingEnabled = false;
  14715. // camera matrices cache
  14716. const _projScreenMatrix = new Matrix4();
  14717. const _vector3 = new Vector3();
  14718. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  14719. function getTargetPixelRatio() {
  14720. return _currentRenderTarget === null ? _pixelRatio : 1;
  14721. }
  14722. // initialize
  14723. let _gl = _context;
  14724. function getContext( contextNames, contextAttributes ) {
  14725. for ( let i = 0; i < contextNames.length; i ++ ) {
  14726. const contextName = contextNames[ i ];
  14727. const context = _canvas.getContext( contextName, contextAttributes );
  14728. if ( context !== null ) return context;
  14729. }
  14730. return null;
  14731. }
  14732. try {
  14733. const contextAttributes = {
  14734. alpha: _alpha,
  14735. depth: _depth,
  14736. stencil: _stencil,
  14737. antialias: _antialias,
  14738. premultipliedAlpha: _premultipliedAlpha,
  14739. preserveDrawingBuffer: _preserveDrawingBuffer,
  14740. powerPreference: _powerPreference,
  14741. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14742. };
  14743. // event listeners must be registered before WebGL context is created, see #12753
  14744. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14745. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14746. if ( _gl === null ) {
  14747. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14748. if ( _this.isWebGL1Renderer === true ) {
  14749. contextNames.shift();
  14750. }
  14751. _gl = getContext( contextNames, contextAttributes );
  14752. if ( _gl === null ) {
  14753. if ( getContext( contextNames ) ) {
  14754. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14755. } else {
  14756. throw new Error( 'Error creating WebGL context.' );
  14757. }
  14758. }
  14759. }
  14760. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14761. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14762. _gl.getShaderPrecisionFormat = function () {
  14763. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14764. };
  14765. }
  14766. } catch ( error ) {
  14767. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14768. throw error;
  14769. }
  14770. let extensions, capabilities, state, info;
  14771. let properties, textures, cubemaps, attributes, geometries, objects;
  14772. let programCache, materials, renderLists, renderStates, clipping;
  14773. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14774. let utils, bindingStates;
  14775. function initGLContext() {
  14776. extensions = new WebGLExtensions( _gl );
  14777. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14778. if ( capabilities.isWebGL2 === false ) {
  14779. extensions.get( 'WEBGL_depth_texture' );
  14780. extensions.get( 'OES_texture_float' );
  14781. extensions.get( 'OES_texture_half_float' );
  14782. extensions.get( 'OES_texture_half_float_linear' );
  14783. extensions.get( 'OES_standard_derivatives' );
  14784. extensions.get( 'OES_element_index_uint' );
  14785. extensions.get( 'OES_vertex_array_object' );
  14786. extensions.get( 'ANGLE_instanced_arrays' );
  14787. }
  14788. extensions.get( 'OES_texture_float_linear' );
  14789. utils = new WebGLUtils( _gl, extensions, capabilities );
  14790. state = new WebGLState( _gl, extensions, capabilities );
  14791. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14792. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14793. info = new WebGLInfo( _gl );
  14794. properties = new WebGLProperties();
  14795. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14796. cubemaps = new WebGLCubeMaps( _this );
  14797. attributes = new WebGLAttributes( _gl, capabilities );
  14798. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14799. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14800. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14801. morphtargets = new WebGLMorphtargets( _gl );
  14802. clipping = new WebGLClipping( properties );
  14803. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14804. materials = new WebGLMaterials( properties );
  14805. renderLists = new WebGLRenderLists( properties );
  14806. renderStates = new WebGLRenderStates( extensions, capabilities );
  14807. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14808. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14809. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14810. info.programs = programCache.programs;
  14811. _this.capabilities = capabilities;
  14812. _this.extensions = extensions;
  14813. _this.properties = properties;
  14814. _this.renderLists = renderLists;
  14815. _this.state = state;
  14816. _this.info = info;
  14817. _this._textures = textures;//add
  14818. }
  14819. initGLContext();
  14820. // xr
  14821. const xr = new WebXRManager( _this, _gl );
  14822. this.xr = xr;
  14823. // shadow map
  14824. const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  14825. this.shadowMap = shadowMap;
  14826. // API
  14827. this.getContext = function () {
  14828. return _gl;
  14829. };
  14830. this.getContextAttributes = function () {
  14831. return _gl.getContextAttributes();
  14832. };
  14833. this.forceContextLoss = function () {
  14834. const extension = extensions.get( 'WEBGL_lose_context' );
  14835. if ( extension ) extension.loseContext();
  14836. };
  14837. this.forceContextRestore = function () {
  14838. const extension = extensions.get( 'WEBGL_lose_context' );
  14839. if ( extension ) extension.restoreContext();
  14840. };
  14841. this.getPixelRatio = function () {
  14842. return _pixelRatio;
  14843. };
  14844. this.setPixelRatio = function ( value ) {
  14845. if ( value === undefined ) return;
  14846. _pixelRatio = value;
  14847. this.setSize( _width, _height, false );
  14848. };
  14849. this.getSize = function ( target ) {
  14850. if ( target === undefined ) {
  14851. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  14852. target = new Vector2$1();
  14853. }
  14854. return target.set( _width, _height );
  14855. };
  14856. this.setSize = function ( width, height, updateStyle, devicePixelRatio ) {//改
  14857. if (devicePixelRatio != void 0) _pixelRatio = devicePixelRatio; //add
  14858. if ( xr.isPresenting ) {
  14859. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14860. return;
  14861. }
  14862. _width = width;
  14863. _height = height;
  14864. //if(!window.unableSetSize){
  14865. _canvas.width = Math.floor( width * _pixelRatio );
  14866. _canvas.height = Math.floor( height * _pixelRatio );
  14867. if ( updateStyle !== false ) {
  14868. _canvas.style.width = width + 'px';
  14869. _canvas.style.height = height + 'px';
  14870. }
  14871. this.setViewport( 0, 0, width, height );
  14872. //}
  14873. };
  14874. this.getDrawingBufferSize = function ( target ) {
  14875. if ( target === undefined ) {
  14876. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  14877. target = new Vector2$1();
  14878. }
  14879. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14880. };
  14881. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14882. _width = width;
  14883. _height = height;
  14884. _pixelRatio = pixelRatio;
  14885. _canvas.width = Math.floor( width * pixelRatio );
  14886. _canvas.height = Math.floor( height * pixelRatio );
  14887. this.setViewport( 0, 0, width, height );
  14888. };
  14889. this.getCurrentViewport = function ( target ) {
  14890. if ( target === undefined ) {
  14891. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14892. target = new Vector4();
  14893. }
  14894. return target.copy( _currentViewport );
  14895. };
  14896. this.getViewport = function ( target ) {
  14897. return target.copy( _viewport );
  14898. };
  14899. this.setViewport = function ( x, y, width, height ) {
  14900. if ( x.isVector4 ) {
  14901. _viewport.set( x.x, x.y, x.z, x.w );
  14902. } else {
  14903. _viewport.set( x, y, width, height );
  14904. }
  14905. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14906. };
  14907. this.getScissor = function ( target ) {
  14908. return target.copy( _scissor );
  14909. };
  14910. this.setScissor = function ( x, y, width, height ) {
  14911. if ( x.isVector4 ) {
  14912. _scissor.set( x.x, x.y, x.z, x.w );
  14913. } else {
  14914. _scissor.set( x, y, width, height );
  14915. }
  14916. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14917. };
  14918. this.getScissorTest = function () {
  14919. return _scissorTest;
  14920. };
  14921. this.setScissorTest = function ( boolean ) {
  14922. state.setScissorTest( _scissorTest = boolean );
  14923. };
  14924. this.setOpaqueSort = function ( method ) {
  14925. _opaqueSort = method;
  14926. };
  14927. this.setTransparentSort = function ( method ) {
  14928. _transparentSort = method;
  14929. };
  14930. // Clearing
  14931. this.getClearColor = function ( target ) {
  14932. if ( target === undefined ) {
  14933. console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
  14934. target = new Color();
  14935. }
  14936. return target.copy( background.getClearColor() );
  14937. };
  14938. this.setClearColor = function () {
  14939. background.setClearColor.apply( background, arguments );
  14940. };
  14941. this.getClearAlpha = function () {
  14942. return background.getClearAlpha();
  14943. };
  14944. this.setClearAlpha = function () {
  14945. background.setClearAlpha.apply( background, arguments );
  14946. };
  14947. this.clear = function ( color, depth, stencil ) {
  14948. let bits = 0;
  14949. if ( color === undefined || color ) bits |= 16384;
  14950. if ( depth === undefined || depth ) bits |= 256;
  14951. if ( stencil === undefined || stencil ) bits |= 1024;
  14952. _gl.clear( bits );
  14953. };
  14954. this.clearColor = function () {
  14955. this.clear( true, false, false );
  14956. };
  14957. this.clearDepth = function () {
  14958. this.clear( false, true, false );
  14959. };
  14960. this.clearStencil = function () {
  14961. this.clear( false, false, true );
  14962. };
  14963. //
  14964. this.dispose = function () {
  14965. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14966. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14967. renderLists.dispose();
  14968. renderStates.dispose();
  14969. properties.dispose();
  14970. cubemaps.dispose();
  14971. objects.dispose();
  14972. bindingStates.dispose();
  14973. xr.dispose();
  14974. animation.stop();
  14975. };
  14976. // Events
  14977. function onContextLost( event ) {
  14978. event.preventDefault();
  14979. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14980. _isContextLost = true;
  14981. }
  14982. function onContextRestore( /* event */ ) {
  14983. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14984. _isContextLost = false;
  14985. initGLContext();
  14986. }
  14987. function onMaterialDispose( event ) {
  14988. const material = event.target;
  14989. material.removeEventListener( 'dispose', onMaterialDispose );
  14990. deallocateMaterial( material );
  14991. }
  14992. // Buffer deallocation
  14993. function deallocateMaterial( material ) {
  14994. releaseMaterialProgramReference( material );
  14995. properties.remove( material );
  14996. }
  14997. function releaseMaterialProgramReference( material ) {
  14998. const programInfo = properties.get( material ).program;
  14999. if ( programInfo !== undefined ) {
  15000. programCache.releaseProgram( programInfo );
  15001. }
  15002. }
  15003. // Buffer rendering
  15004. function renderObjectImmediate( object, program ) {
  15005. object.render( function ( object ) {
  15006. _this.renderBufferImmediate( object, program );
  15007. } );
  15008. }
  15009. this.renderBufferImmediate = function ( object, program ) {
  15010. bindingStates.initAttributes();
  15011. const buffers = properties.get( object );
  15012. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15013. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15014. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15015. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15016. const programAttributes = program.getAttributes();
  15017. if ( object.hasPositions ) {
  15018. _gl.bindBuffer( 34962, buffers.position );
  15019. _gl.bufferData( 34962, object.positionArray, 35048 );
  15020. bindingStates.enableAttribute( programAttributes.position );
  15021. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  15022. }
  15023. if ( object.hasNormals ) {
  15024. _gl.bindBuffer( 34962, buffers.normal );
  15025. _gl.bufferData( 34962, object.normalArray, 35048 );
  15026. bindingStates.enableAttribute( programAttributes.normal );
  15027. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  15028. }
  15029. if ( object.hasUvs ) {
  15030. _gl.bindBuffer( 34962, buffers.uv );
  15031. _gl.bufferData( 34962, object.uvArray, 35048 );
  15032. bindingStates.enableAttribute( programAttributes.uv );
  15033. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  15034. }
  15035. if ( object.hasColors ) {
  15036. _gl.bindBuffer( 34962, buffers.color );
  15037. _gl.bufferData( 34962, object.colorArray, 35048 );
  15038. bindingStates.enableAttribute( programAttributes.color );
  15039. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  15040. }
  15041. bindingStates.disableUnusedAttributes();
  15042. _gl.drawArrays( 4, 0, object.count );
  15043. object.count = 0;
  15044. };
  15045. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15046. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15047. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15048. const program = setProgram( camera, scene, material, object );
  15049. state.setMaterial( material, frontFaceCW );
  15050. //
  15051. let index = geometry.index;
  15052. const position = geometry.attributes.position;
  15053. //
  15054. if ( index === null ) {
  15055. if ( position === undefined || position.count === 0 ) return;
  15056. } else if ( index.count === 0 ) {
  15057. return;
  15058. }
  15059. //
  15060. let rangeFactor = 1;
  15061. if ( material.wireframe === true ) {
  15062. index = geometries.getWireframeAttribute( geometry );
  15063. rangeFactor = 2;
  15064. }
  15065. if ( material.morphTargets || material.morphNormals ) {
  15066. morphtargets.update( object, geometry, material, program );
  15067. }
  15068. bindingStates.setup( object, material, program, geometry, index );
  15069. let attribute;
  15070. let renderer = bufferRenderer;
  15071. if ( index !== null ) {
  15072. attribute = attributes.get( index );
  15073. renderer = indexedBufferRenderer;
  15074. renderer.setIndex( attribute );
  15075. }
  15076. //
  15077. const dataCount = ( index !== null ) ? index.count : position.count;
  15078. const rangeStart = geometry.drawRange.start * rangeFactor;
  15079. const rangeCount = geometry.drawRange.count * rangeFactor;
  15080. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15081. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15082. const drawStart = Math.max( rangeStart, groupStart );
  15083. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15084. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15085. if ( drawCount === 0 ) return;
  15086. //
  15087. if ( object.isMesh ) {
  15088. if ( material.wireframe === true ) {
  15089. state.setlineWidth( material.wireframelineWidth * getTargetPixelRatio() );
  15090. renderer.setMode( 1 );
  15091. } else {
  15092. renderer.setMode( 4 );
  15093. }
  15094. } else if ( object.isLine ) {
  15095. let lineWidth = material.lineWidth;
  15096. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15097. state.setlineWidth( lineWidth * getTargetPixelRatio() );
  15098. if ( object.isLineSegments ) {
  15099. renderer.setMode( 1 );
  15100. } else if ( object.isLineLoop ) {
  15101. renderer.setMode( 2 );
  15102. } else {
  15103. renderer.setMode( 3 );
  15104. }
  15105. } else if ( object.isPoints ) {
  15106. renderer.setMode( 0 );
  15107. } else if ( object.isSprite ) {
  15108. renderer.setMode( 4 );
  15109. }
  15110. if ( object.isInstancedMesh ) {
  15111. renderer.renderInstances( drawStart, drawCount, object.count );
  15112. } else if ( geometry.isInstancedBufferGeometry ) {
  15113. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15114. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15115. } else {
  15116. renderer.render( drawStart, drawCount );
  15117. }
  15118. };
  15119. // Compile
  15120. this.compile = function ( scene, camera ) {
  15121. currentRenderState = renderStates.get( scene );
  15122. currentRenderState.init();
  15123. scene.traverseVisible( function ( object ) {
  15124. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15125. currentRenderState.pushLight( object );
  15126. if ( object.castShadow ) {
  15127. currentRenderState.pushShadow( object );
  15128. }
  15129. }
  15130. } );
  15131. currentRenderState.setupLights();
  15132. const compiled = new WeakMap();
  15133. scene.traverse( function ( object ) {
  15134. const material = object.material;
  15135. if ( material ) {
  15136. if ( Array.isArray( material ) ) {
  15137. for ( let i = 0; i < material.length; i ++ ) {
  15138. const material2 = material[ i ];
  15139. if ( compiled.has( material2 ) === false ) {
  15140. initMaterial( material2, scene, object );
  15141. compiled.set( material2 );
  15142. }
  15143. }
  15144. } else if ( compiled.has( material ) === false ) {
  15145. initMaterial( material, scene, object );
  15146. compiled.set( material );
  15147. }
  15148. }
  15149. } );
  15150. };
  15151. // Animation Loop
  15152. let onAnimationFrameCallback = null;
  15153. function onAnimationFrame( time ) {
  15154. if ( xr.isPresenting ) return;
  15155. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15156. }
  15157. const animation = new WebGLAnimation();
  15158. animation.setAnimationLoop( onAnimationFrame );
  15159. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15160. this.setAnimationLoop = function ( callback ) {
  15161. onAnimationFrameCallback = callback;
  15162. xr.setAnimationLoop( callback );
  15163. ( callback === null ) ? animation.stop() : animation.start();
  15164. };
  15165. // Rendering
  15166. this.render = function ( scene, camera ) {
  15167. let renderTarget, forceClear;
  15168. if ( arguments[ 2 ] !== undefined ) {
  15169. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  15170. renderTarget = arguments[ 2 ];
  15171. }
  15172. if ( arguments[ 3 ] !== undefined ) {
  15173. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  15174. forceClear = arguments[ 3 ];
  15175. }
  15176. if ( camera !== undefined && camera.isCamera !== true ) {
  15177. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15178. return;
  15179. }
  15180. if ( _isContextLost === true ) return;
  15181. // reset caching for this frame
  15182. bindingStates.resetDefaultState();
  15183. _currentMaterialId = - 1;
  15184. _currentCamera = null;
  15185. // update scene graph
  15186. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15187. // update camera matrices and frustum
  15188. if ( camera.parent === null ) camera.updateMatrixWorld();
  15189. if ( xr.enabled === true && xr.isPresenting === true ) {
  15190. camera = xr.getCamera( camera );
  15191. }
  15192. //
  15193. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  15194. currentRenderState = renderStates.get( scene, renderStateStack.length );
  15195. currentRenderState.init();
  15196. renderStateStack.push( currentRenderState );
  15197. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15198. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15199. _localClippingEnabled = this.localClippingEnabled;
  15200. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15201. currentRenderList = renderLists.get( scene, camera );
  15202. currentRenderList.init();
  15203. projectObject( scene, camera, 0, _this.sortObjects );
  15204. currentRenderList.finish();
  15205. if ( _this.sortObjects === true ) {
  15206. currentRenderList.sort( _opaqueSort, _transparentSort );
  15207. }
  15208. //
  15209. if ( _clippingEnabled === true ) clipping.beginShadows();
  15210. const shadowsArray = currentRenderState.state.shadowsArray;
  15211. shadowMap.render( shadowsArray, scene, camera );
  15212. currentRenderState.setupLights();
  15213. currentRenderState.setupLightsView( camera );
  15214. if ( _clippingEnabled === true ) clipping.endShadows();
  15215. //
  15216. if ( this.info.autoReset === true ) this.info.reset();
  15217. if ( renderTarget !== undefined ) {
  15218. this.setRenderTarget( renderTarget );
  15219. }
  15220. //
  15221. background.render( currentRenderList, scene, camera, forceClear );
  15222. // render scene
  15223. const opaqueObjects = currentRenderList.opaque;
  15224. const transparentObjects = currentRenderList.transparent;
  15225. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15226. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15227. //
  15228. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15229. //
  15230. if ( _currentRenderTarget !== null ) {
  15231. // Generate mipmap if we're using any kind of mipmap filtering
  15232. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15233. // resolve multisample renderbuffers to a single-sample texture if necessary
  15234. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15235. }
  15236. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15237. state.buffers.depth.setTest( true );
  15238. state.buffers.depth.setMask( true );
  15239. state.buffers.color.setMask( true );
  15240. state.setPolygonOffset( false );
  15241. // _gl.finish();
  15242. renderStateStack.pop();
  15243. if ( renderStateStack.length > 0 ) {
  15244. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  15245. } else {
  15246. currentRenderState = null;
  15247. }
  15248. currentRenderList = null;
  15249. };
  15250. function projectObject( object, camera, groupOrder, sortObjects ) {
  15251. if ( object.visible === false ) return;
  15252. const visible = object.layers.test( camera.layers );
  15253. if ( visible ) {
  15254. if ( object.isGroup ) {
  15255. groupOrder = object.renderOrder;
  15256. } else if ( object.isLOD ) {
  15257. if ( object.autoUpdate === true ) object.update( camera );
  15258. } else if ( object.isLight ) {
  15259. currentRenderState.pushLight( object );
  15260. if ( object.castShadow ) {
  15261. currentRenderState.pushShadow( object );
  15262. }
  15263. } else if ( object.isSprite ) {
  15264. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15265. if ( sortObjects ) {
  15266. _vector3.setFromMatrixPosition( object.matrixWorld )
  15267. .applyMatrix4( _projScreenMatrix );
  15268. }
  15269. const geometry = objects.update( object );
  15270. const material = object.material;
  15271. if ( material.visible ) {
  15272. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15273. }
  15274. }
  15275. } else if ( object.isImmediateRenderObject ) {
  15276. if ( sortObjects ) {
  15277. _vector3.setFromMatrixPosition( object.matrixWorld )
  15278. .applyMatrix4( _projScreenMatrix );
  15279. }
  15280. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  15281. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15282. if ( object.isSkinnedMesh ) {
  15283. // update skeleton only once in a frame
  15284. if ( object.skeleton.frame !== info.render.frame ) {
  15285. object.skeleton.update();
  15286. object.skeleton.frame = info.render.frame;
  15287. }
  15288. }
  15289. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15290. if ( sortObjects ) {
  15291. _vector3.setFromMatrixPosition( object.matrixWorld )
  15292. .applyMatrix4( _projScreenMatrix );
  15293. }
  15294. const geometry = objects.update( object );
  15295. const material = object.material;
  15296. if ( Array.isArray( material ) ) {
  15297. const groups = geometry.groups;
  15298. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15299. const group = groups[ i ];
  15300. const groupMaterial = material[ group.materialIndex ];
  15301. if ( groupMaterial && groupMaterial.visible ) {
  15302. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15303. }
  15304. }
  15305. } else if ( material.visible ) {
  15306. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15307. }
  15308. }
  15309. }
  15310. }
  15311. const children = object.children;
  15312. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15313. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15314. }
  15315. }
  15316. function renderObjects( renderList, scene, camera ) {
  15317. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15318. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15319. const renderItem = renderList[ i ];
  15320. const object = renderItem.object;
  15321. const geometry = renderItem.geometry;
  15322. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15323. const group = renderItem.group;
  15324. if ( camera.isArrayCamera ) {
  15325. const cameras = camera.cameras;
  15326. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  15327. const camera2 = cameras[ j ];
  15328. if ( object.layers.test( camera2.layers ) ) {
  15329. state.viewport( _currentViewport.copy( camera2.viewport ) );
  15330. currentRenderState.setupLightsView( camera2 );
  15331. renderObject( object, scene, camera2, geometry, material, group );
  15332. }
  15333. }
  15334. } else {
  15335. renderObject( object, scene, camera, geometry, material, group );
  15336. }
  15337. }
  15338. }
  15339. function renderObject( object, scene, camera, geometry, material, group ) {
  15340. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15341. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15342. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15343. if ( object.isImmediateRenderObject ) {
  15344. const program = setProgram( camera, scene, material, object );
  15345. state.setMaterial( material );
  15346. bindingStates.reset();
  15347. renderObjectImmediate( object, program );
  15348. } else {
  15349. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15350. }
  15351. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15352. }
  15353. function initMaterial( material, scene, object ) {
  15354. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15355. const materialProperties = properties.get( material );
  15356. const lights = currentRenderState.state.lights;
  15357. const shadowsArray = currentRenderState.state.shadowsArray;
  15358. const lightsStateVersion = lights.state.version;
  15359. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15360. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15361. let program = materialProperties.program;
  15362. let programChange = true;
  15363. if ( program === undefined ) {
  15364. // new material
  15365. material.addEventListener( 'dispose', onMaterialDispose );
  15366. } else if ( program.cacheKey !== programCacheKey ) {
  15367. // changed glsl or parameters
  15368. releaseMaterialProgramReference( material );
  15369. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  15370. programChange = false;
  15371. } else if ( parameters.shaderID !== undefined ) {
  15372. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15373. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15374. materialProperties.envMap = cubemaps.get( material.envMap || environment );
  15375. return;
  15376. } else {
  15377. // only rebuild uniform list
  15378. programChange = false;
  15379. }
  15380. if ( programChange ) {
  15381. parameters.uniforms = programCache.getUniforms( material );
  15382. material.onBeforeCompile( parameters, _this );
  15383. program = programCache.acquireProgram( parameters, programCacheKey );
  15384. materialProperties.program = program;
  15385. materialProperties.uniforms = parameters.uniforms;
  15386. materialProperties.outputEncoding = parameters.outputEncoding;
  15387. }
  15388. const uniforms = materialProperties.uniforms;
  15389. if ( ! material.isShaderMaterial &&
  15390. ! material.isRawShaderMaterial ||
  15391. material.clipping === true ) {
  15392. materialProperties.numClippingPlanes = clipping.numPlanes;
  15393. materialProperties.numIntersection = clipping.numIntersection;
  15394. uniforms.clippingPlanes = clipping.uniform;
  15395. }
  15396. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15397. materialProperties.fog = scene.fog;
  15398. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  15399. // store the light setup it was created for
  15400. materialProperties.needsLights = materialNeedsLights( material );
  15401. materialProperties.lightsStateVersion = lightsStateVersion;
  15402. if ( materialProperties.needsLights ) {
  15403. // wire up the material to this renderer's lighting state
  15404. uniforms.ambientLightColor.value = lights.state.ambient;
  15405. uniforms.lightProbe.value = lights.state.probe;
  15406. uniforms.directionalLights.value = lights.state.directional;
  15407. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15408. uniforms.spotLights.value = lights.state.spot;
  15409. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15410. uniforms.rectAreaLights.value = lights.state.rectArea;
  15411. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15412. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15413. uniforms.pointLights.value = lights.state.point;
  15414. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15415. uniforms.hemisphereLights.value = lights.state.hemi;
  15416. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15417. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15418. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15419. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15420. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15421. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15422. // TODO (abelnation): add area lights shadow info to uniforms
  15423. }
  15424. const progUniforms = materialProperties.program.getUniforms();
  15425. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15426. materialProperties.uniformsList = uniformsList;
  15427. }
  15428. function setProgram( camera, scene, material, object ) {
  15429. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15430. textures.resetTextureUnits();
  15431. const fog = scene.fog;
  15432. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15433. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15434. const envMap = cubemaps.get( material.envMap || environment );
  15435. const materialProperties = properties.get( material );
  15436. const lights = currentRenderState.state.lights;
  15437. if ( _clippingEnabled === true ) {
  15438. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  15439. const useCache =
  15440. camera === _currentCamera &&
  15441. material.id === _currentMaterialId;
  15442. // we might want to call this function with some ClippingGroup
  15443. // object instead of the material, once it becomes feasible
  15444. // (#8465, #8379)
  15445. clipping.setState( material, camera, useCache );
  15446. }
  15447. }
  15448. if ( material.version === materialProperties.__version ) {
  15449. if ( material.fog && materialProperties.fog !== fog ) {
  15450. initMaterial( material, scene, object );
  15451. } else if ( materialProperties.environment !== environment ) {
  15452. initMaterial( material, scene, object );
  15453. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  15454. initMaterial( material, scene, object );
  15455. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15456. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  15457. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  15458. initMaterial( material, scene, object );
  15459. } else if ( materialProperties.outputEncoding !== encoding ) {
  15460. initMaterial( material, scene, object );
  15461. } else if ( materialProperties.envMap !== envMap ) {
  15462. initMaterial( material, scene, object );
  15463. }
  15464. } else {
  15465. initMaterial( material, scene, object );
  15466. materialProperties.__version = material.version;
  15467. }
  15468. let refreshProgram = false;
  15469. let refreshMaterial = false;
  15470. let refreshLights = false;
  15471. const program = materialProperties.program,
  15472. p_uniforms = program.getUniforms(),
  15473. m_uniforms = materialProperties.uniforms;
  15474. if ( state.useProgram( program.program ) ) {
  15475. refreshProgram = true;
  15476. refreshMaterial = true;
  15477. refreshLights = true;
  15478. }
  15479. if ( material.id !== _currentMaterialId ) {
  15480. _currentMaterialId = material.id;
  15481. refreshMaterial = true;
  15482. }
  15483. if ( refreshProgram || _currentCamera !== camera ) {
  15484. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  15485. if ( capabilities.logarithmicDepthBuffer ) {
  15486. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15487. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15488. }
  15489. if ( _currentCamera !== camera ) {
  15490. _currentCamera = camera;
  15491. // lighting uniforms depend on the camera so enforce an update
  15492. // now, in case this material supports lights - or later, when
  15493. // the next material that does gets activated:
  15494. refreshMaterial = true; // set to true on material change
  15495. refreshLights = true; // remains set until update done
  15496. }
  15497. // load material specific uniforms
  15498. // (shader material also gets them for the sake of genericity)
  15499. if ( material.isShaderMaterial ||
  15500. material.isMeshPhongMaterial ||
  15501. material.isMeshToonMaterial ||
  15502. material.isMeshStandardMaterial ||
  15503. material.envMap ) {
  15504. const uCamPos = p_uniforms.map.cameraPosition;
  15505. if ( uCamPos !== undefined ) {
  15506. uCamPos.setValue( _gl,
  15507. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15508. }
  15509. }
  15510. if ( material.isMeshPhongMaterial ||
  15511. material.isMeshToonMaterial ||
  15512. material.isMeshLambertMaterial ||
  15513. material.isMeshBasicMaterial ||
  15514. material.isMeshStandardMaterial ||
  15515. material.isShaderMaterial ) {
  15516. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  15517. }
  15518. if ( material.isMeshPhongMaterial ||
  15519. material.isMeshToonMaterial ||
  15520. material.isMeshLambertMaterial ||
  15521. material.isMeshBasicMaterial ||
  15522. material.isMeshStandardMaterial ||
  15523. material.isShaderMaterial ||
  15524. material.isShadowMaterial ||
  15525. material.skinning ) {
  15526. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15527. }
  15528. }
  15529. // skinning uniforms must be set even if material didn't change
  15530. // auto-setting of texture unit for bone texture must go before other textures
  15531. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15532. if ( material.skinning ) {
  15533. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15534. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15535. const skeleton = object.skeleton;
  15536. if ( skeleton ) {
  15537. const bones = skeleton.bones;
  15538. if ( capabilities.floatVertexTextures ) {
  15539. if ( skeleton.boneTexture === null ) {
  15540. // layout (1 matrix = 4 pixels)
  15541. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15542. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15543. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15544. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15545. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15546. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  15547. size = MathUtils.ceilPowerOfTwo( size );
  15548. size = Math.max( size, 4 );
  15549. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15550. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  15551. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  15552. skeleton.boneMatrices = boneMatrices;
  15553. skeleton.boneTexture = boneTexture;
  15554. skeleton.boneTextureSize = size;
  15555. }
  15556. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  15557. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  15558. } else {
  15559. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15560. }
  15561. }
  15562. }
  15563. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  15564. materialProperties.receiveShadow = object.receiveShadow;
  15565. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  15566. }
  15567. if ( refreshMaterial ) {
  15568. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  15569. if ( materialProperties.needsLights ) {
  15570. // the current material requires lighting info
  15571. // note: all lighting uniforms are always set correctly
  15572. // they simply reference the renderer's state for their
  15573. // values
  15574. //
  15575. // use the current material's .needsUpdate flags to set
  15576. // the GL state when required
  15577. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15578. }
  15579. // refresh uniforms common to several materials
  15580. if ( fog && material.fog ) {
  15581. materials.refreshFogUniforms( m_uniforms, fog );
  15582. }
  15583. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  15584. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15585. }
  15586. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  15587. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15588. material.uniformsNeedUpdate = false;
  15589. }
  15590. if ( material.isSpriteMaterial ) {
  15591. p_uniforms.setValue( _gl, 'center', object.center );
  15592. }
  15593. // common matrices
  15594. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  15595. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  15596. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15597. return program;
  15598. }
  15599. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15600. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  15601. uniforms.ambientLightColor.needsUpdate = value;
  15602. uniforms.lightProbe.needsUpdate = value;
  15603. uniforms.directionalLights.needsUpdate = value;
  15604. uniforms.directionalLightShadows.needsUpdate = value;
  15605. uniforms.pointLights.needsUpdate = value;
  15606. uniforms.pointLightShadows.needsUpdate = value;
  15607. uniforms.spotLights.needsUpdate = value;
  15608. uniforms.spotLightShadows.needsUpdate = value;
  15609. uniforms.rectAreaLights.needsUpdate = value;
  15610. uniforms.hemisphereLights.needsUpdate = value;
  15611. }
  15612. function materialNeedsLights( material ) {
  15613. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  15614. material.isMeshStandardMaterial || material.isShadowMaterial ||
  15615. ( material.isShaderMaterial && material.lights === true );
  15616. }
  15617. //
  15618. this.setFramebuffer = function ( value ) {
  15619. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );
  15620. _framebuffer = value;
  15621. };
  15622. this.getActiveCubeFace = function () {
  15623. return _currentActiveCubeFace;
  15624. };
  15625. this.getActiveMipmapLevel = function () {
  15626. return _currentActiveMipmapLevel;
  15627. };
  15628. this.getRenderList = function () {
  15629. return currentRenderList;
  15630. };
  15631. this.setRenderList = function ( renderList ) {
  15632. currentRenderList = renderList;
  15633. };
  15634. this.getRenderTarget = function () {
  15635. return _currentRenderTarget;
  15636. };
  15637. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  15638. _currentRenderTarget = renderTarget;
  15639. _currentActiveCubeFace = activeCubeFace;
  15640. _currentActiveMipmapLevel = activeMipmapLevel;
  15641. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  15642. textures.setupRenderTarget( renderTarget );
  15643. }
  15644. let framebuffer = _framebuffer;
  15645. let isCube = false;
  15646. if ( renderTarget ) {
  15647. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15648. if ( renderTarget.isWebGLCubeRenderTarget ) {
  15649. framebuffer = __webglFramebuffer[ activeCubeFace ];
  15650. isCube = true;
  15651. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15652. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  15653. } else {
  15654. framebuffer = __webglFramebuffer;
  15655. }
  15656. _currentViewport.copy( renderTarget.viewport );
  15657. _currentScissor.copy( renderTarget.scissor );
  15658. _currentScissorTest = renderTarget.scissorTest;
  15659. } else {
  15660. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  15661. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  15662. _currentScissorTest = _scissorTest;
  15663. }
  15664. if ( _currentFramebuffer !== framebuffer ) {
  15665. _gl.bindFramebuffer( 36160, framebuffer );
  15666. _currentFramebuffer = framebuffer;
  15667. }
  15668. state.viewport( _currentViewport );
  15669. state.scissor( _currentScissor );
  15670. state.setScissorTest( _currentScissorTest );
  15671. if ( isCube ) {
  15672. const textureProperties = properties.get( renderTarget.texture );
  15673. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  15674. }
  15675. };
  15676. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  15677. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  15678. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  15679. return;
  15680. }
  15681. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15682. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  15683. framebuffer = framebuffer[ activeCubeFaceIndex ];
  15684. }
  15685. if ( framebuffer ) {
  15686. let restore = false;
  15687. if ( framebuffer !== _currentFramebuffer ) {
  15688. _gl.bindFramebuffer( 36160, framebuffer );
  15689. restore = true;
  15690. }
  15691. try {
  15692. const texture = renderTarget.texture;
  15693. const textureFormat = texture.format;
  15694. const textureType = texture.type;
  15695. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  15696. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  15697. return;
  15698. }
  15699. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15700. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  15701. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  15702. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  15703. return;
  15704. }
  15705. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  15706. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15707. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  15708. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  15709. }
  15710. } else {
  15711. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  15712. }
  15713. } finally {
  15714. if ( restore ) {
  15715. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  15716. }
  15717. }
  15718. }
  15719. };
  15720. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  15721. const levelScale = Math.pow( 2, - level );
  15722. const width = Math.floor( texture.image.width * levelScale );
  15723. const height = Math.floor( texture.image.height * levelScale );
  15724. const glFormat = utils.convert( texture.format );
  15725. textures.setTexture2D( texture, 0 );
  15726. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  15727. state.unbindTexture();
  15728. };
  15729. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  15730. const width = srcTexture.image.width;
  15731. const height = srcTexture.image.height;
  15732. const glFormat = utils.convert( dstTexture.format );
  15733. const glType = utils.convert( dstTexture.type );
  15734. textures.setTexture2D( dstTexture, 0 );
  15735. // As another texture upload may have changed pixelStorei
  15736. // parameters, make sure they are correct for the dstTexture
  15737. _gl.pixelStorei( 37440, dstTexture.flipY );
  15738. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15739. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15740. if ( srcTexture.isDataTexture ) {
  15741. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  15742. } else {
  15743. if ( srcTexture.isCompressedTexture ) {
  15744. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  15745. } else {
  15746. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  15747. }
  15748. }
  15749. // Generate mipmaps only when copying level 0
  15750. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15751. state.unbindTexture();
  15752. };
  15753. this.initTexture = function ( texture ) {
  15754. textures.setTexture2D( texture, 0 );
  15755. state.unbindTexture();
  15756. };
  15757. this.resetState = function () {
  15758. state.reset();
  15759. bindingStates.reset();
  15760. };
  15761. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15762. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15763. }
  15764. }
  15765. function WebGL1Renderer( parameters ) {
  15766. WebGLRenderer.call( this, parameters );
  15767. }
  15768. WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {
  15769. constructor: WebGL1Renderer,
  15770. isWebGL1Renderer: true
  15771. } );
  15772. class FogExp2 {
  15773. constructor( color, density ) {
  15774. Object.defineProperty( this, 'isFogExp2', { value: true } );
  15775. this.name = '';
  15776. this.color = new Color( color );
  15777. this.density = ( density !== undefined ) ? density : 0.00025;
  15778. }
  15779. clone() {
  15780. return new FogExp2( this.color, this.density );
  15781. }
  15782. toJSON( /* meta */ ) {
  15783. return {
  15784. type: 'FogExp2',
  15785. color: this.color.getHex(),
  15786. density: this.density
  15787. };
  15788. }
  15789. }
  15790. class Fog {
  15791. constructor( color, near, far ) {
  15792. Object.defineProperty( this, 'isFog', { value: true } );
  15793. this.name = '';
  15794. this.color = new Color( color );
  15795. this.near = ( near !== undefined ) ? near : 1;
  15796. this.far = ( far !== undefined ) ? far : 1000;
  15797. }
  15798. clone() {
  15799. return new Fog( this.color, this.near, this.far );
  15800. }
  15801. toJSON( /* meta */ ) {
  15802. return {
  15803. type: 'Fog',
  15804. color: this.color.getHex(),
  15805. near: this.near,
  15806. far: this.far
  15807. };
  15808. }
  15809. }
  15810. class Scene extends Object3D {
  15811. constructor() {
  15812. super();
  15813. Object.defineProperty( this, 'isScene', { value: true } );
  15814. this.type = 'Scene';
  15815. this.background = null;
  15816. this.environment = null;
  15817. this.fog = null;
  15818. this.overrideMaterial = null;
  15819. this.autoUpdate = true; // checked by the renderer
  15820. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15821. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15822. }
  15823. }
  15824. copy( source, recursive ) {
  15825. super.copy( source, recursive );
  15826. if ( source.background !== null ) this.background = source.background.clone();
  15827. if ( source.environment !== null ) this.environment = source.environment.clone();
  15828. if ( source.fog !== null ) this.fog = source.fog.clone();
  15829. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15830. this.autoUpdate = source.autoUpdate;
  15831. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15832. return this;
  15833. }
  15834. toJSON( meta ) {
  15835. const data = super.toJSON( meta );
  15836. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15837. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15838. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15839. return data;
  15840. }
  15841. }
  15842. function InterleavedBuffer( array, stride ) {
  15843. this.array = array;
  15844. this.stride = stride;
  15845. this.count = array !== undefined ? array.length / stride : 0;
  15846. this.usage = StaticDrawUsage;
  15847. this.updateRange = { offset: 0, count: - 1 };
  15848. this.version = 0;
  15849. this.uuid = MathUtils.generateUUID();
  15850. }
  15851. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  15852. set: function ( value ) {
  15853. if ( value === true ) this.version ++;
  15854. }
  15855. } );
  15856. Object.assign( InterleavedBuffer.prototype, {
  15857. isInterleavedBuffer: true,
  15858. onUploadCallback: function () {},
  15859. setUsage: function ( value ) {
  15860. this.usage = value;
  15861. return this;
  15862. },
  15863. copy: function ( source ) {
  15864. this.array = new source.array.constructor( source.array );
  15865. this.count = source.count;
  15866. this.stride = source.stride;
  15867. this.usage = source.usage;
  15868. return this;
  15869. },
  15870. copyAt: function ( index1, attribute, index2 ) {
  15871. index1 *= this.stride;
  15872. index2 *= attribute.stride;
  15873. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15874. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15875. }
  15876. return this;
  15877. },
  15878. set: function ( value, offset = 0 ) {
  15879. this.array.set( value, offset );
  15880. return this;
  15881. },
  15882. clone: function ( data ) {
  15883. if ( data.arrayBuffers === undefined ) {
  15884. data.arrayBuffers = {};
  15885. }
  15886. if ( this.array.buffer._uuid === undefined ) {
  15887. this.array.buffer._uuid = MathUtils.generateUUID();
  15888. }
  15889. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15890. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15891. }
  15892. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15893. const ib = new InterleavedBuffer( array, this.stride );
  15894. ib.setUsage( this.usage );
  15895. return ib;
  15896. },
  15897. onUpload: function ( callback ) {
  15898. this.onUploadCallback = callback;
  15899. return this;
  15900. },
  15901. toJSON: function ( data ) {
  15902. if ( data.arrayBuffers === undefined ) {
  15903. data.arrayBuffers = {};
  15904. }
  15905. // generate UUID for array buffer if necessary
  15906. if ( this.array.buffer._uuid === undefined ) {
  15907. this.array.buffer._uuid = MathUtils.generateUUID();
  15908. }
  15909. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15910. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15911. }
  15912. //
  15913. return {
  15914. uuid: this.uuid,
  15915. buffer: this.array.buffer._uuid,
  15916. type: this.array.constructor.name,
  15917. stride: this.stride
  15918. };
  15919. }
  15920. } );
  15921. const _vector$6 = new Vector3();
  15922. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  15923. this.name = '';
  15924. this.data = interleavedBuffer;
  15925. this.itemSize = itemSize;
  15926. this.offset = offset;
  15927. this.normalized = normalized === true;
  15928. }
  15929. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  15930. count: {
  15931. get: function () {
  15932. return this.data.count;
  15933. }
  15934. },
  15935. array: {
  15936. get: function () {
  15937. return this.data.array;
  15938. }
  15939. },
  15940. needsUpdate: {
  15941. set: function ( value ) {
  15942. this.data.needsUpdate = value;
  15943. }
  15944. }
  15945. } );
  15946. Object.assign( InterleavedBufferAttribute.prototype, {
  15947. isInterleavedBufferAttribute: true,
  15948. applyMatrix4: function ( m ) {
  15949. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15950. _vector$6.x = this.getX( i );
  15951. _vector$6.y = this.getY( i );
  15952. _vector$6.z = this.getZ( i );
  15953. _vector$6.applyMatrix4( m );
  15954. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15955. }
  15956. return this;
  15957. },
  15958. setX: function ( index, x ) {
  15959. this.data.array[ index * this.data.stride + this.offset ] = x;
  15960. return this;
  15961. },
  15962. setY: function ( index, y ) {
  15963. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15964. return this;
  15965. },
  15966. setZ: function ( index, z ) {
  15967. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15968. return this;
  15969. },
  15970. setW: function ( index, w ) {
  15971. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15972. return this;
  15973. },
  15974. getX: function ( index ) {
  15975. return this.data.array[ index * this.data.stride + this.offset ];
  15976. },
  15977. getY: function ( index ) {
  15978. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15979. },
  15980. getZ: function ( index ) {
  15981. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15982. },
  15983. getW: function ( index ) {
  15984. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15985. },
  15986. setXY: function ( index, x, y ) {
  15987. index = index * this.data.stride + this.offset;
  15988. this.data.array[ index + 0 ] = x;
  15989. this.data.array[ index + 1 ] = y;
  15990. return this;
  15991. },
  15992. setXYZ: function ( index, x, y, z ) {
  15993. index = index * this.data.stride + this.offset;
  15994. this.data.array[ index + 0 ] = x;
  15995. this.data.array[ index + 1 ] = y;
  15996. this.data.array[ index + 2 ] = z;
  15997. return this;
  15998. },
  15999. setXYZW: function ( index, x, y, z, w ) {
  16000. index = index * this.data.stride + this.offset;
  16001. this.data.array[ index + 0 ] = x;
  16002. this.data.array[ index + 1 ] = y;
  16003. this.data.array[ index + 2 ] = z;
  16004. this.data.array[ index + 3 ] = w;
  16005. return this;
  16006. },
  16007. clone: function ( data ) {
  16008. if ( data === undefined ) {
  16009. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16010. const array = [];
  16011. for ( let i = 0; i < this.count; i ++ ) {
  16012. const index = i * this.data.stride + this.offset;
  16013. for ( let j = 0; j < this.itemSize; j ++ ) {
  16014. array.push( this.data.array[ index + j ] );
  16015. }
  16016. }
  16017. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16018. } else {
  16019. if ( data.interleavedBuffers === undefined ) {
  16020. data.interleavedBuffers = {};
  16021. }
  16022. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16023. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16024. }
  16025. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16026. }
  16027. },
  16028. toJSON: function ( data ) {
  16029. if ( data === undefined ) {
  16030. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16031. const array = [];
  16032. for ( let i = 0; i < this.count; i ++ ) {
  16033. const index = i * this.data.stride + this.offset;
  16034. for ( let j = 0; j < this.itemSize; j ++ ) {
  16035. array.push( this.data.array[ index + j ] );
  16036. }
  16037. }
  16038. // deinterleave data and save it as an ordinary buffer attribute for now
  16039. return {
  16040. itemSize: this.itemSize,
  16041. type: this.array.constructor.name,
  16042. array: array,
  16043. normalized: this.normalized
  16044. };
  16045. } else {
  16046. // save as true interlaved attribtue
  16047. if ( data.interleavedBuffers === undefined ) {
  16048. data.interleavedBuffers = {};
  16049. }
  16050. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16051. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16052. }
  16053. return {
  16054. isInterleavedBufferAttribute: true,
  16055. itemSize: this.itemSize,
  16056. data: this.data.uuid,
  16057. offset: this.offset,
  16058. normalized: this.normalized
  16059. };
  16060. }
  16061. }
  16062. } );
  16063. /**
  16064. * parameters = {
  16065. * color: <hex>,
  16066. * map: new THREE.Texture( <Image> ),
  16067. * alphaMap: new THREE.Texture( <Image> ),
  16068. * rotation: <float>,
  16069. * sizeAttenuation: <bool>
  16070. * }
  16071. */
  16072. function SpriteMaterial( parameters ) {
  16073. Material.call( this );
  16074. this.type = 'SpriteMaterial';
  16075. this.color = new Color( 0xffffff );
  16076. this.map = null;
  16077. this.alphaMap = null;
  16078. this.rotation = 0;
  16079. this.sizeAttenuation = true;
  16080. this.transparent = true;
  16081. this.setValues( parameters );
  16082. }
  16083. SpriteMaterial.prototype = Object.create( Material.prototype );
  16084. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16085. SpriteMaterial.prototype.isSpriteMaterial = true;
  16086. SpriteMaterial.prototype.copy = function ( source ) {
  16087. Material.prototype.copy.call( this, source );
  16088. this.color.copy( source.color );
  16089. this.map = source.map;
  16090. this.alphaMap = source.alphaMap;
  16091. this.rotation = source.rotation;
  16092. this.sizeAttenuation = source.sizeAttenuation;
  16093. return this;
  16094. };
  16095. let _geometry;
  16096. const _intersectPoint = new Vector3();
  16097. const _worldScale = new Vector3();
  16098. const _mvPosition = new Vector3();
  16099. const _alignedPosition = new Vector2$1();
  16100. const _rotatedPosition = new Vector2$1();
  16101. const _viewWorldMatrix = new Matrix4();
  16102. const _vA$1 = new Vector3();
  16103. const _vB$1 = new Vector3();
  16104. const _vC$1 = new Vector3();
  16105. const _uvA$1 = new Vector2$1();
  16106. const _uvB$1 = new Vector2$1();
  16107. const _uvC$1 = new Vector2$1();
  16108. function Sprite( material ) {
  16109. Object3D.call( this );
  16110. this.type = 'Sprite';
  16111. if ( _geometry === undefined ) {
  16112. _geometry = new BufferGeometry();
  16113. const float32Array = new Float32Array( [
  16114. - 0.5, - 0.5, 0, 0, 0,
  16115. 0.5, - 0.5, 0, 1, 0,
  16116. 0.5, 0.5, 0, 1, 1,
  16117. - 0.5, 0.5, 0, 0, 1
  16118. ] );
  16119. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16120. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16121. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16122. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16123. }
  16124. this.geometry = _geometry;
  16125. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16126. this.center = new Vector2$1( 0.5, 0.5 );
  16127. }
  16128. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16129. constructor: Sprite,
  16130. isSprite: true,
  16131. raycast: function ( raycaster, intersects ) {
  16132. if ( raycaster.camera === null ) {
  16133. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16134. }
  16135. _worldScale.setFromMatrixScale( this.matrixWorld );
  16136. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16137. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16138. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16139. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16140. _worldScale.multiplyScalar( - _mvPosition.z );
  16141. }
  16142. const rotation = this.material.rotation;
  16143. let sin, cos;
  16144. if ( rotation !== 0 ) {
  16145. cos = Math.cos( rotation );
  16146. sin = Math.sin( rotation );
  16147. }
  16148. const center = this.center;
  16149. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16150. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16151. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16152. _uvA$1.set( 0, 0 );
  16153. _uvB$1.set( 1, 0 );
  16154. _uvC$1.set( 1, 1 );
  16155. // check first triangle
  16156. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16157. if ( intersect === null ) {
  16158. // check second triangle
  16159. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16160. _uvB$1.set( 0, 1 );
  16161. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16162. if ( intersect === null ) {
  16163. return;
  16164. }
  16165. }
  16166. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16167. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16168. intersects.push( {
  16169. distance: distance,
  16170. point: _intersectPoint.clone(),
  16171. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2$1() ),
  16172. face: null,
  16173. object: this
  16174. } );
  16175. },
  16176. copy: function ( source ) {
  16177. Object3D.prototype.copy.call( this, source );
  16178. if ( source.center !== undefined ) this.center.copy( source.center );
  16179. this.material = source.material;
  16180. return this;
  16181. }
  16182. } );
  16183. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16184. // compute position in camera space
  16185. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16186. // to check if rotation is not zero
  16187. if ( sin !== undefined ) {
  16188. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16189. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16190. } else {
  16191. _rotatedPosition.copy( _alignedPosition );
  16192. }
  16193. vertexPosition.copy( mvPosition );
  16194. vertexPosition.x += _rotatedPosition.x;
  16195. vertexPosition.y += _rotatedPosition.y;
  16196. // transform to world space
  16197. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16198. }
  16199. const _v1$4 = new Vector3();
  16200. const _v2$2 = new Vector3();
  16201. function LOD() {
  16202. Object3D.call( this );
  16203. this._currentLevel = 0;
  16204. this.type = 'LOD';
  16205. Object.defineProperties( this, {
  16206. levels: {
  16207. enumerable: true,
  16208. value: []
  16209. }
  16210. } );
  16211. this.autoUpdate = true;
  16212. }
  16213. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16214. constructor: LOD,
  16215. isLOD: true,
  16216. copy: function ( source ) {
  16217. Object3D.prototype.copy.call( this, source, false );
  16218. const levels = source.levels;
  16219. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16220. const level = levels[ i ];
  16221. this.addLevel( level.object.clone(), level.distance );
  16222. }
  16223. this.autoUpdate = source.autoUpdate;
  16224. return this;
  16225. },
  16226. addLevel: function ( object, distance = 0 ) {
  16227. distance = Math.abs( distance );
  16228. const levels = this.levels;
  16229. let l;
  16230. for ( l = 0; l < levels.length; l ++ ) {
  16231. if ( distance < levels[ l ].distance ) {
  16232. break;
  16233. }
  16234. }
  16235. levels.splice( l, 0, { distance: distance, object: object } );
  16236. this.add( object );
  16237. return this;
  16238. },
  16239. getCurrentLevel: function () {
  16240. return this._currentLevel;
  16241. },
  16242. getObjectForDistance: function ( distance ) {
  16243. const levels = this.levels;
  16244. if ( levels.length > 0 ) {
  16245. let i, l;
  16246. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16247. if ( distance < levels[ i ].distance ) {
  16248. break;
  16249. }
  16250. }
  16251. return levels[ i - 1 ].object;
  16252. }
  16253. return null;
  16254. },
  16255. raycast: function ( raycaster, intersects ) {
  16256. const levels = this.levels;
  16257. if ( levels.length > 0 ) {
  16258. _v1$4.setFromMatrixPosition( this.matrixWorld );
  16259. const distance = raycaster.ray.origin.distanceTo( _v1$4 );
  16260. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16261. }
  16262. },
  16263. update: function ( camera ) {
  16264. const levels = this.levels;
  16265. if ( levels.length > 1 ) {
  16266. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  16267. _v2$2.setFromMatrixPosition( this.matrixWorld );
  16268. const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  16269. levels[ 0 ].object.visible = true;
  16270. let i, l;
  16271. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16272. if ( distance >= levels[ i ].distance ) {
  16273. levels[ i - 1 ].object.visible = false;
  16274. levels[ i ].object.visible = true;
  16275. } else {
  16276. break;
  16277. }
  16278. }
  16279. this._currentLevel = i - 1;
  16280. for ( ; i < l; i ++ ) {
  16281. levels[ i ].object.visible = false;
  16282. }
  16283. }
  16284. },
  16285. toJSON: function ( meta ) {
  16286. const data = Object3D.prototype.toJSON.call( this, meta );
  16287. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16288. data.object.levels = [];
  16289. const levels = this.levels;
  16290. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16291. const level = levels[ i ];
  16292. data.object.levels.push( {
  16293. object: level.object.uuid,
  16294. distance: level.distance
  16295. } );
  16296. }
  16297. return data;
  16298. }
  16299. } );
  16300. const _basePosition = new Vector3();
  16301. const _skinIndex = new Vector4();
  16302. const _skinWeight = new Vector4();
  16303. const _vector$7 = new Vector3();
  16304. const _matrix$1 = new Matrix4();
  16305. function SkinnedMesh( geometry, material ) {
  16306. if ( geometry && geometry.isGeometry ) {
  16307. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16308. }
  16309. Mesh.call( this, geometry, material );
  16310. this.type = 'SkinnedMesh';
  16311. this.bindMode = 'attached';
  16312. this.bindMatrix = new Matrix4();
  16313. this.bindMatrixInverse = new Matrix4();
  16314. }
  16315. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16316. constructor: SkinnedMesh,
  16317. isSkinnedMesh: true,
  16318. copy: function ( source ) {
  16319. Mesh.prototype.copy.call( this, source );
  16320. this.bindMode = source.bindMode;
  16321. this.bindMatrix.copy( source.bindMatrix );
  16322. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  16323. this.skeleton = source.skeleton;
  16324. return this;
  16325. },
  16326. bind: function ( skeleton, bindMatrix ) {
  16327. this.skeleton = skeleton;
  16328. if ( bindMatrix === undefined ) {
  16329. this.updateMatrixWorld( true );
  16330. this.skeleton.calculateInverses();
  16331. bindMatrix = this.matrixWorld;
  16332. }
  16333. this.bindMatrix.copy( bindMatrix );
  16334. this.bindMatrixInverse.copy( bindMatrix ).invert();
  16335. },
  16336. pose: function () {
  16337. this.skeleton.pose();
  16338. },
  16339. normalizeSkinWeights: function () {
  16340. const vector = new Vector4();
  16341. const skinWeight = this.geometry.attributes.skinWeight;
  16342. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  16343. vector.x = skinWeight.getX( i );
  16344. vector.y = skinWeight.getY( i );
  16345. vector.z = skinWeight.getZ( i );
  16346. vector.w = skinWeight.getW( i );
  16347. const scale = 1.0 / vector.manhattanLength();
  16348. if ( scale !== Infinity ) {
  16349. vector.multiplyScalar( scale );
  16350. } else {
  16351. vector.set( 1, 0, 0, 0 ); // do something reasonable
  16352. }
  16353. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  16354. }
  16355. },
  16356. updateMatrixWorld: function ( force ) {
  16357. Mesh.prototype.updateMatrixWorld.call( this, force );
  16358. if ( this.bindMode === 'attached' ) {
  16359. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  16360. } else if ( this.bindMode === 'detached' ) {
  16361. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  16362. } else {
  16363. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  16364. }
  16365. },
  16366. boneTransform: function ( index, target ) {
  16367. const skeleton = this.skeleton;
  16368. const geometry = this.geometry;
  16369. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  16370. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  16371. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  16372. target.set( 0, 0, 0 );
  16373. for ( let i = 0; i < 4; i ++ ) {
  16374. const weight = _skinWeight.getComponent( i );
  16375. if ( weight !== 0 ) {
  16376. const boneIndex = _skinIndex.getComponent( i );
  16377. _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  16378. target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight );
  16379. }
  16380. }
  16381. return target.applyMatrix4( this.bindMatrixInverse );
  16382. }
  16383. } );
  16384. function Bone() {
  16385. Object3D.call( this );
  16386. this.type = 'Bone';
  16387. }
  16388. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16389. constructor: Bone,
  16390. isBone: true
  16391. } );
  16392. const _offsetMatrix = new Matrix4();
  16393. const _identityMatrix = new Matrix4();
  16394. function Skeleton( bones = [], boneInverses = [] ) {
  16395. this.uuid = MathUtils.generateUUID();
  16396. this.bones = bones.slice( 0 );
  16397. this.boneInverses = boneInverses;
  16398. this.boneMatrices = null;
  16399. this.boneTexture = null;
  16400. this.boneTextureSize = 0;
  16401. this.frame = - 1;
  16402. this.init();
  16403. }
  16404. Object.assign( Skeleton.prototype, {
  16405. init: function () {
  16406. const bones = this.bones;
  16407. const boneInverses = this.boneInverses;
  16408. this.boneMatrices = new Float32Array( bones.length * 16 );
  16409. // calculate inverse bone matrices if necessary
  16410. if ( boneInverses.length === 0 ) {
  16411. this.calculateInverses();
  16412. } else {
  16413. // handle special case
  16414. if ( bones.length !== boneInverses.length ) {
  16415. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  16416. this.boneInverses = [];
  16417. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16418. this.boneInverses.push( new Matrix4() );
  16419. }
  16420. }
  16421. }
  16422. },
  16423. calculateInverses: function () {
  16424. this.boneInverses.length = 0;
  16425. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16426. const inverse = new Matrix4();
  16427. if ( this.bones[ i ] ) {
  16428. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  16429. }
  16430. this.boneInverses.push( inverse );
  16431. }
  16432. },
  16433. pose: function () {
  16434. // recover the bind-time world matrices
  16435. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16436. const bone = this.bones[ i ];
  16437. if ( bone ) {
  16438. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  16439. }
  16440. }
  16441. // compute the local matrices, positions, rotations and scales
  16442. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16443. const bone = this.bones[ i ];
  16444. if ( bone ) {
  16445. if ( bone.parent && bone.parent.isBone ) {
  16446. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  16447. bone.matrix.multiply( bone.matrixWorld );
  16448. } else {
  16449. bone.matrix.copy( bone.matrixWorld );
  16450. }
  16451. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  16452. }
  16453. }
  16454. },
  16455. update: function () {
  16456. const bones = this.bones;
  16457. const boneInverses = this.boneInverses;
  16458. const boneMatrices = this.boneMatrices;
  16459. const boneTexture = this.boneTexture;
  16460. // flatten bone matrices to array
  16461. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  16462. // compute the offset between the current and the original transform
  16463. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  16464. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  16465. _offsetMatrix.toArray( boneMatrices, i * 16 );
  16466. }
  16467. if ( boneTexture !== null ) {
  16468. boneTexture.needsUpdate = true;
  16469. }
  16470. },
  16471. clone: function () {
  16472. return new Skeleton( this.bones, this.boneInverses );
  16473. },
  16474. getBoneByName: function ( name ) {
  16475. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16476. const bone = this.bones[ i ];
  16477. if ( bone.name === name ) {
  16478. return bone;
  16479. }
  16480. }
  16481. return undefined;
  16482. },
  16483. dispose: function ( ) {
  16484. if ( this.boneTexture !== null ) {
  16485. this.boneTexture.dispose();
  16486. this.boneTexture = null;
  16487. }
  16488. },
  16489. fromJSON: function ( json, bones ) {
  16490. this.uuid = json.uuid;
  16491. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  16492. const uuid = json.bones[ i ];
  16493. let bone = bones[ uuid ];
  16494. if ( bone === undefined ) {
  16495. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  16496. bone = new Bone();
  16497. }
  16498. this.bones.push( bone );
  16499. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  16500. }
  16501. this.init();
  16502. return this;
  16503. },
  16504. toJSON: function () {
  16505. const data = {
  16506. metadata: {
  16507. version: 4.5,
  16508. type: 'Skeleton',
  16509. generator: 'Skeleton.toJSON'
  16510. },
  16511. bones: [],
  16512. boneInverses: []
  16513. };
  16514. data.uuid = this.uuid;
  16515. const bones = this.bones;
  16516. const boneInverses = this.boneInverses;
  16517. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  16518. const bone = bones[ i ];
  16519. data.bones.push( bone.uuid );
  16520. const boneInverse = boneInverses[ i ];
  16521. data.boneInverses.push( boneInverse.toArray() );
  16522. }
  16523. return data;
  16524. }
  16525. } );
  16526. const _instanceLocalMatrix = new Matrix4();
  16527. const _instanceWorldMatrix = new Matrix4();
  16528. const _instanceIntersects = [];
  16529. const _mesh = new Mesh();
  16530. function InstancedMesh( geometry, material, count ) {
  16531. Mesh.call( this, geometry, material );
  16532. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  16533. this.instanceColor = null;
  16534. this.count = count;
  16535. this.frustumCulled = false;
  16536. }
  16537. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16538. constructor: InstancedMesh,
  16539. isInstancedMesh: true,
  16540. copy: function ( source ) {
  16541. Mesh.prototype.copy.call( this, source );
  16542. this.instanceMatrix.copy( source.instanceMatrix );
  16543. this.count = source.count;
  16544. return this;
  16545. },
  16546. getColorAt: function ( index, color ) {
  16547. color.fromArray( this.instanceColor.array, index * 3 );
  16548. },
  16549. getMatrixAt: function ( index, matrix ) {
  16550. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  16551. },
  16552. raycast: function ( raycaster, intersects ) {
  16553. const matrixWorld = this.matrixWorld;
  16554. const raycastTimes = this.count;
  16555. _mesh.geometry = this.geometry;
  16556. _mesh.material = this.material;
  16557. if ( _mesh.material === undefined ) return;
  16558. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  16559. // calculate the world matrix for each instance
  16560. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  16561. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  16562. // the mesh represents this single instance
  16563. _mesh.matrixWorld = _instanceWorldMatrix;
  16564. _mesh.raycast( raycaster, _instanceIntersects );
  16565. // process the result of raycast
  16566. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  16567. const intersect = _instanceIntersects[ i ];
  16568. intersect.instanceId = instanceId;
  16569. intersect.object = this;
  16570. intersects.push( intersect );
  16571. }
  16572. _instanceIntersects.length = 0;
  16573. }
  16574. },
  16575. setColorAt: function ( index, color ) {
  16576. if ( this.instanceColor === null ) {
  16577. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  16578. }
  16579. color.toArray( this.instanceColor.array, index * 3 );
  16580. },
  16581. setMatrixAt: function ( index, matrix ) {
  16582. matrix.toArray( this.instanceMatrix.array, index * 16 );
  16583. },
  16584. updateMorphTargets: function () {
  16585. },
  16586. dispose: function () {
  16587. this.dispatchEvent( { type: 'dispose' } );
  16588. }
  16589. } );
  16590. /**
  16591. * parameters = {
  16592. * color: <hex>,
  16593. * opacity: <float>,
  16594. *
  16595. * lineWidth: <float>,
  16596. * linecap: "round",
  16597. * linejoin: "round"
  16598. * }
  16599. */
  16600. function LineBasicMaterial( parameters ) {
  16601. Material.call( this );
  16602. this.type = 'LineBasicMaterial';
  16603. this.color = new Color( 0xffffff );
  16604. this.lineWidth = 1;
  16605. this.linecap = 'round';
  16606. this.linejoin = 'round';
  16607. this.morphTargets = false;
  16608. this.setValues( parameters );
  16609. }
  16610. LineBasicMaterial.prototype = Object.create( Material.prototype );
  16611. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16612. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16613. LineBasicMaterial.prototype.copy = function ( source ) {
  16614. Material.prototype.copy.call( this, source );
  16615. this.color.copy( source.color );
  16616. this.lineWidth = source.lineWidth;
  16617. this.linecap = source.linecap;
  16618. this.linejoin = source.linejoin;
  16619. this.morphTargets = source.morphTargets;
  16620. return this;
  16621. };
  16622. const _start = new Vector3();
  16623. const _end = new Vector3();
  16624. const _inverseMatrix$1 = new Matrix4();
  16625. const _ray$1 = new Ray();
  16626. const _sphere$2 = new Sphere();
  16627. function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  16628. Object3D.call( this );
  16629. this.type = 'Line';
  16630. this.geometry = geometry;
  16631. this.material = material;
  16632. this.updateMorphTargets();
  16633. }
  16634. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16635. constructor: Line,
  16636. isLine: true,
  16637. copy: function ( source ) {
  16638. Object3D.prototype.copy.call( this, source );
  16639. this.material = source.material;
  16640. this.geometry = source.geometry;
  16641. return this;
  16642. },
  16643. computeLineDistances: function () {
  16644. const geometry = this.geometry;
  16645. if ( geometry.isBufferGeometry ) {
  16646. // we assume non-indexed geometry
  16647. if ( geometry.index === null ) {
  16648. const positionAttribute = geometry.attributes.position;
  16649. const lineDistances = [ 0 ];
  16650. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16651. _start.fromBufferAttribute( positionAttribute, i - 1 );
  16652. _end.fromBufferAttribute( positionAttribute, i );
  16653. lineDistances[ i ] = lineDistances[ i - 1 ];
  16654. lineDistances[ i ] += _start.distanceTo( _end );
  16655. }
  16656. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16657. } else {
  16658. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16659. }
  16660. } else if ( geometry.isGeometry ) {
  16661. const vertices = geometry.vertices;
  16662. const lineDistances = geometry.lineDistances;
  16663. lineDistances[ 0 ] = 0;
  16664. for ( let i = 1, l = vertices.length; i < l; i ++ ) {
  16665. lineDistances[ i ] = lineDistances[ i - 1 ];
  16666. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  16667. }
  16668. }
  16669. return this;
  16670. },
  16671. raycast: function ( raycaster, intersects ) {
  16672. const geometry = this.geometry;
  16673. const matrixWorld = this.matrixWorld;
  16674. const threshold = raycaster.params.Line.threshold;
  16675. // Checking boundingSphere distance to ray
  16676. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16677. _sphere$2.copy( geometry.boundingSphere );
  16678. _sphere$2.applyMatrix4( matrixWorld );
  16679. _sphere$2.radius += threshold;
  16680. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  16681. //
  16682. _inverseMatrix$1.copy( matrixWorld ).invert();
  16683. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16684. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16685. const localThresholdSq = localThreshold * localThreshold;
  16686. const vStart = new Vector3();
  16687. const vEnd = new Vector3();
  16688. const interSegment = new Vector3();
  16689. const interRay = new Vector3();
  16690. const step = this.isLineSegments ? 2 : 1;
  16691. if ( geometry.isBufferGeometry ) {
  16692. const index = geometry.index;
  16693. const attributes = geometry.attributes;
  16694. const positionAttribute = attributes.position;
  16695. if ( index !== null ) {
  16696. const indices = index.array;
  16697. for ( let i = 0, l = indices.length - 1; i < l; i += step ) {
  16698. const a = indices[ i ];
  16699. const b = indices[ i + 1 ];
  16700. vStart.fromBufferAttribute( positionAttribute, a );
  16701. vEnd.fromBufferAttribute( positionAttribute, b );
  16702. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16703. if ( distSq > localThresholdSq ) continue;
  16704. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16705. const distance = raycaster.ray.origin.distanceTo( interRay );
  16706. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16707. intersects.push( {
  16708. distance: distance,
  16709. // What do we want? intersection point on the ray or on the segment??
  16710. // point: raycaster.ray.at( distance ),
  16711. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16712. index: i,
  16713. face: null,
  16714. faceIndex: null,
  16715. object: this
  16716. } );
  16717. }
  16718. } else {
  16719. for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) {
  16720. vStart.fromBufferAttribute( positionAttribute, i );
  16721. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  16722. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16723. if ( distSq > localThresholdSq ) continue;
  16724. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16725. const distance = raycaster.ray.origin.distanceTo( interRay );
  16726. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16727. intersects.push( {
  16728. distance: distance,
  16729. // What do we want? intersection point on the ray or on the segment??
  16730. // point: raycaster.ray.at( distance ),
  16731. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16732. index: i,
  16733. face: null,
  16734. faceIndex: null,
  16735. object: this
  16736. } );
  16737. }
  16738. }
  16739. } else if ( geometry.isGeometry ) {
  16740. const vertices = geometry.vertices;
  16741. const nbVertices = vertices.length;
  16742. for ( let i = 0; i < nbVertices - 1; i += step ) {
  16743. const distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  16744. if ( distSq > localThresholdSq ) continue;
  16745. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16746. const distance = raycaster.ray.origin.distanceTo( interRay );
  16747. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16748. intersects.push( {
  16749. distance: distance,
  16750. // What do we want? intersection point on the ray or on the segment??
  16751. // point: raycaster.ray.at( distance ),
  16752. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16753. index: i,
  16754. face: null,
  16755. faceIndex: null,
  16756. object: this
  16757. } );
  16758. }
  16759. }
  16760. },
  16761. updateMorphTargets: function () {
  16762. const geometry = this.geometry;
  16763. if ( geometry.isBufferGeometry ) {
  16764. const morphAttributes = geometry.morphAttributes;
  16765. const keys = Object.keys( morphAttributes );
  16766. if ( keys.length > 0 ) {
  16767. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16768. if ( morphAttribute !== undefined ) {
  16769. this.morphTargetInfluences = [];
  16770. this.morphTargetDictionary = {};
  16771. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16772. const name = morphAttribute[ m ].name || String( m );
  16773. this.morphTargetInfluences.push( 0 );
  16774. this.morphTargetDictionary[ name ] = m;
  16775. }
  16776. }
  16777. }
  16778. } else {
  16779. const morphTargets = geometry.morphTargets;
  16780. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16781. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16782. }
  16783. }
  16784. }
  16785. } );
  16786. const _start$1 = new Vector3();
  16787. const _end$1 = new Vector3();
  16788. function LineSegments( geometry, material ) {
  16789. Line.call( this, geometry, material );
  16790. this.type = 'LineSegments';
  16791. }
  16792. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  16793. constructor: LineSegments,
  16794. isLineSegments: true,
  16795. computeLineDistances: function () {
  16796. const geometry = this.geometry;
  16797. if ( geometry.isBufferGeometry ) {
  16798. // we assume non-indexed geometry
  16799. if ( geometry.index === null ) {
  16800. const positionAttribute = geometry.attributes.position;
  16801. const lineDistances = [];
  16802. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16803. _start$1.fromBufferAttribute( positionAttribute, i );
  16804. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  16805. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16806. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16807. }
  16808. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16809. } else {
  16810. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16811. }
  16812. } else if ( geometry.isGeometry ) {
  16813. const vertices = geometry.vertices;
  16814. const lineDistances = geometry.lineDistances;
  16815. for ( let i = 0, l = vertices.length; i < l; i += 2 ) {
  16816. _start$1.copy( vertices[ i ] );
  16817. _end$1.copy( vertices[ i + 1 ] );
  16818. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16819. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16820. }
  16821. }
  16822. return this;
  16823. }
  16824. } );
  16825. function LineLoop( geometry, material ) {
  16826. Line.call( this, geometry, material );
  16827. this.type = 'LineLoop';
  16828. }
  16829. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  16830. constructor: LineLoop,
  16831. isLineLoop: true,
  16832. } );
  16833. /**
  16834. * parameters = {
  16835. * color: <hex>,
  16836. * opacity: <float>,
  16837. * map: new THREE.Texture( <Image> ),
  16838. * alphaMap: new THREE.Texture( <Image> ),
  16839. *
  16840. * size: <float>,
  16841. * sizeAttenuation: <bool>
  16842. *
  16843. * morphTargets: <bool>
  16844. * }
  16845. */
  16846. function PointsMaterial( parameters ) {
  16847. Material.call( this );
  16848. this.type = 'PointsMaterial';
  16849. this.color = new Color( 0xffffff );
  16850. this.map = null;
  16851. this.alphaMap = null;
  16852. this.size = 1;
  16853. this.sizeAttenuation = true;
  16854. this.morphTargets = false;
  16855. this.setValues( parameters );
  16856. }
  16857. PointsMaterial.prototype = Object.create( Material.prototype );
  16858. PointsMaterial.prototype.constructor = PointsMaterial;
  16859. PointsMaterial.prototype.isPointsMaterial = true;
  16860. PointsMaterial.prototype.copy = function ( source ) {
  16861. Material.prototype.copy.call( this, source );
  16862. this.color.copy( source.color );
  16863. this.map = source.map;
  16864. this.alphaMap = source.alphaMap;
  16865. this.size = source.size;
  16866. this.sizeAttenuation = source.sizeAttenuation;
  16867. this.morphTargets = source.morphTargets;
  16868. return this;
  16869. };
  16870. const _inverseMatrix$2 = new Matrix4();
  16871. const _ray$2 = new Ray();
  16872. const _sphere$3 = new Sphere();
  16873. const _position$1 = new Vector3();
  16874. function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16875. Object3D.call( this );
  16876. this.type = 'Points';
  16877. this.geometry = geometry;
  16878. this.material = material;
  16879. this.updateMorphTargets();
  16880. }
  16881. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16882. constructor: Points,
  16883. isPoints: true,
  16884. copy: function ( source ) {
  16885. Object3D.prototype.copy.call( this, source );
  16886. this.material = source.material;
  16887. this.geometry = source.geometry;
  16888. return this;
  16889. },
  16890. raycast: function ( raycaster, intersects ) {
  16891. const geometry = this.geometry;
  16892. const matrixWorld = this.matrixWorld;
  16893. const threshold = raycaster.params.Points.threshold;
  16894. // Checking boundingSphere distance to ray
  16895. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16896. _sphere$3.copy( geometry.boundingSphere );
  16897. _sphere$3.applyMatrix4( matrixWorld );
  16898. _sphere$3.radius += threshold;
  16899. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  16900. //
  16901. _inverseMatrix$2.copy( matrixWorld ).invert();
  16902. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  16903. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16904. const localThresholdSq = localThreshold * localThreshold;
  16905. if ( geometry.isBufferGeometry ) {
  16906. const index = geometry.index;
  16907. const attributes = geometry.attributes;
  16908. const positionAttribute = attributes.position;
  16909. if ( index !== null ) {
  16910. const indices = index.array;
  16911. for ( let i = 0, il = indices.length; i < il; i ++ ) {
  16912. const a = indices[ i ];
  16913. _position$1.fromBufferAttribute( positionAttribute, a );
  16914. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16915. }
  16916. } else {
  16917. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  16918. _position$1.fromBufferAttribute( positionAttribute, i );
  16919. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16920. }
  16921. }
  16922. } else {
  16923. const vertices = geometry.vertices;
  16924. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  16925. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16926. }
  16927. }
  16928. },
  16929. updateMorphTargets: function () {
  16930. const geometry = this.geometry;
  16931. if ( geometry.isBufferGeometry ) {
  16932. const morphAttributes = geometry.morphAttributes;
  16933. const keys = Object.keys( morphAttributes );
  16934. if ( keys.length > 0 ) {
  16935. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16936. if ( morphAttribute !== undefined ) {
  16937. this.morphTargetInfluences = [];
  16938. this.morphTargetDictionary = {};
  16939. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16940. const name = morphAttribute[ m ].name || String( m );
  16941. this.morphTargetInfluences.push( 0 );
  16942. this.morphTargetDictionary[ name ] = m;
  16943. }
  16944. }
  16945. }
  16946. } else {
  16947. const morphTargets = geometry.morphTargets;
  16948. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16949. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16950. }
  16951. }
  16952. }
  16953. } );
  16954. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16955. const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  16956. if ( rayPointDistanceSq < localThresholdSq ) {
  16957. const intersectPoint = new Vector3();
  16958. _ray$2.closestPointToPoint( point, intersectPoint );
  16959. intersectPoint.applyMatrix4( matrixWorld );
  16960. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16961. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16962. intersects.push( {
  16963. distance: distance,
  16964. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16965. point: intersectPoint,
  16966. index: index,
  16967. face: null,
  16968. object: object
  16969. } );
  16970. }
  16971. }
  16972. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16973. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16974. this.format = format !== undefined ? format : RGBFormat;
  16975. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16976. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16977. this.generateMipmaps = false;
  16978. const scope = this;
  16979. function updateVideo() {
  16980. scope.needsUpdate = true;
  16981. video.requestVideoFrameCallback( updateVideo );
  16982. }
  16983. if ( 'requestVideoFrameCallback' in video ) {
  16984. video.requestVideoFrameCallback( updateVideo );
  16985. }
  16986. }
  16987. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  16988. constructor: VideoTexture,
  16989. clone: function () {
  16990. return new this.constructor( this.image ).copy( this );
  16991. },
  16992. isVideoTexture: true,
  16993. update: function () {
  16994. const video = this.image;
  16995. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16996. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16997. this.needsUpdate = true;
  16998. }
  16999. }
  17000. } );
  17001. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  17002. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17003. this.image = { width: width, height: height };
  17004. this.mipmaps = mipmaps;
  17005. // no flipping for cube textures
  17006. // (also flipping doesn't work for compressed textures )
  17007. this.flipY = false;
  17008. // can't generate mipmaps for compressed textures
  17009. // mips must be embedded in DDS files
  17010. this.generateMipmaps = false;
  17011. }
  17012. CompressedTexture.prototype = Object.create( Texture.prototype );
  17013. CompressedTexture.prototype.constructor = CompressedTexture;
  17014. CompressedTexture.prototype.isCompressedTexture = true;
  17015. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17016. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17017. this.needsUpdate = true;
  17018. }
  17019. CanvasTexture.prototype = Object.create( Texture.prototype );
  17020. CanvasTexture.prototype.constructor = CanvasTexture;
  17021. CanvasTexture.prototype.isCanvasTexture = true;
  17022. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  17023. format = format !== undefined ? format : DepthFormat;
  17024. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17025. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17026. }
  17027. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  17028. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type$1;
  17029. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17030. this.image = { width: width, height: height };
  17031. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17032. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17033. this.flipY = false;
  17034. this.generateMipmaps = false;
  17035. }
  17036. DepthTexture.prototype = Object.create( Texture.prototype );
  17037. DepthTexture.prototype.constructor = DepthTexture;
  17038. DepthTexture.prototype.isDepthTexture = true;
  17039. let _geometryId = 0; // Geometry uses even numbers as Id
  17040. const _m1$3 = new Matrix4();
  17041. const _obj$1 = new Object3D();
  17042. const _offset$1 = new Vector3();
  17043. function Geometry() {
  17044. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  17045. this.uuid = MathUtils.generateUUID();
  17046. this.name = '';
  17047. this.type = 'Geometry';
  17048. this.vertices = [];
  17049. this.colors = [];
  17050. this.faces = [];
  17051. this.faceVertexUvs = [[]];
  17052. this.morphTargets = [];
  17053. this.morphNormals = [];
  17054. this.skinWeights = [];
  17055. this.skinIndices = [];
  17056. this.lineDistances = [];
  17057. this.boundingBox = null;
  17058. this.boundingSphere = null;
  17059. // update flags
  17060. this.elementsNeedUpdate = false;
  17061. this.verticesNeedUpdate = false;
  17062. this.uvsNeedUpdate = false;
  17063. this.normalsNeedUpdate = false;
  17064. this.colorsNeedUpdate = false;
  17065. this.lineDistancesNeedUpdate = false;
  17066. this.groupsNeedUpdate = false;
  17067. }
  17068. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  17069. constructor: Geometry,
  17070. isGeometry: true,
  17071. applyMatrix4: function ( matrix ) {
  17072. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  17073. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  17074. const vertex = this.vertices[ i ];
  17075. vertex.applyMatrix4( matrix );
  17076. }
  17077. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  17078. const face = this.faces[ i ];
  17079. face.normal.applyMatrix3( normalMatrix ).normalize();
  17080. for ( let j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  17081. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  17082. }
  17083. }
  17084. if ( this.boundingBox !== null ) {
  17085. this.computeBoundingBox();
  17086. }
  17087. if ( this.boundingSphere !== null ) {
  17088. this.computeBoundingSphere();
  17089. }
  17090. this.verticesNeedUpdate = true;
  17091. this.normalsNeedUpdate = true;
  17092. return this;
  17093. },
  17094. rotateX: function ( angle ) {
  17095. // rotate geometry around world x-axis
  17096. _m1$3.makeRotationX( angle );
  17097. this.applyMatrix4( _m1$3 );
  17098. return this;
  17099. },
  17100. rotateY: function ( angle ) {
  17101. // rotate geometry around world y-axis
  17102. _m1$3.makeRotationY( angle );
  17103. this.applyMatrix4( _m1$3 );
  17104. return this;
  17105. },
  17106. rotateZ: function ( angle ) {
  17107. // rotate geometry around world z-axis
  17108. _m1$3.makeRotationZ( angle );
  17109. this.applyMatrix4( _m1$3 );
  17110. return this;
  17111. },
  17112. translate: function ( x, y, z ) {
  17113. // translate geometry
  17114. _m1$3.makeTranslation( x, y, z );
  17115. this.applyMatrix4( _m1$3 );
  17116. return this;
  17117. },
  17118. scale: function ( x, y, z ) {
  17119. // scale geometry
  17120. _m1$3.makeScale( x, y, z );
  17121. this.applyMatrix4( _m1$3 );
  17122. return this;
  17123. },
  17124. lookAt: function ( vector ) {
  17125. _obj$1.lookAt( vector );
  17126. _obj$1.updateMatrix();
  17127. this.applyMatrix4( _obj$1.matrix );
  17128. return this;
  17129. },
  17130. fromBufferGeometry: function ( geometry ) {
  17131. const scope = this;
  17132. const index = geometry.index !== null ? geometry.index : undefined;
  17133. const attributes = geometry.attributes;
  17134. if ( attributes.position === undefined ) {
  17135. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  17136. return this;
  17137. }
  17138. const position = attributes.position;
  17139. const normal = attributes.normal;
  17140. const color = attributes.color;
  17141. const uv = attributes.uv;
  17142. const uv2 = attributes.uv2;
  17143. if ( uv2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  17144. for ( let i = 0; i < position.count; i ++ ) {
  17145. scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );
  17146. if ( color !== undefined ) {
  17147. scope.colors.push( new Color().fromBufferAttribute( color, i ) );
  17148. }
  17149. }
  17150. function addFace( a, b, c, materialIndex ) {
  17151. const vertexColors = ( color === undefined ) ? [] : [
  17152. scope.colors[ a ].clone(),
  17153. scope.colors[ b ].clone(),
  17154. scope.colors[ c ].clone()
  17155. ];
  17156. const vertexNormals = ( normal === undefined ) ? [] : [
  17157. new Vector3().fromBufferAttribute( normal, a ),
  17158. new Vector3().fromBufferAttribute( normal, b ),
  17159. new Vector3().fromBufferAttribute( normal, c )
  17160. ];
  17161. const face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  17162. scope.faces.push( face );
  17163. if ( uv !== undefined ) {
  17164. scope.faceVertexUvs[ 0 ].push( [
  17165. new Vector2$1().fromBufferAttribute( uv, a ),
  17166. new Vector2$1().fromBufferAttribute( uv, b ),
  17167. new Vector2$1().fromBufferAttribute( uv, c )
  17168. ] );
  17169. }
  17170. if ( uv2 !== undefined ) {
  17171. scope.faceVertexUvs[ 1 ].push( [
  17172. new Vector2$1().fromBufferAttribute( uv2, a ),
  17173. new Vector2$1().fromBufferAttribute( uv2, b ),
  17174. new Vector2$1().fromBufferAttribute( uv2, c )
  17175. ] );
  17176. }
  17177. }
  17178. const groups = geometry.groups;
  17179. if ( groups.length > 0 ) {
  17180. for ( let i = 0; i < groups.length; i ++ ) {
  17181. const group = groups[ i ];
  17182. const start = group.start;
  17183. const count = group.count;
  17184. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  17185. if ( index !== undefined ) {
  17186. addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );
  17187. } else {
  17188. addFace( j, j + 1, j + 2, group.materialIndex );
  17189. }
  17190. }
  17191. }
  17192. } else {
  17193. if ( index !== undefined ) {
  17194. for ( let i = 0; i < index.count; i += 3 ) {
  17195. addFace( index.getX( i ), index.getX( i + 1 ), index.getX( i + 2 ) );
  17196. }
  17197. } else {
  17198. for ( let i = 0; i < position.count; i += 3 ) {
  17199. addFace( i, i + 1, i + 2 );
  17200. }
  17201. }
  17202. }
  17203. this.computeFaceNormals();
  17204. if ( geometry.boundingBox !== null ) {
  17205. this.boundingBox = geometry.boundingBox.clone();
  17206. }
  17207. if ( geometry.boundingSphere !== null ) {
  17208. this.boundingSphere = geometry.boundingSphere.clone();
  17209. }
  17210. return this;
  17211. },
  17212. center: function () {
  17213. this.computeBoundingBox();
  17214. this.boundingBox.getCenter( _offset$1 ).negate();
  17215. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  17216. return this;
  17217. },
  17218. normalize: function () {
  17219. this.computeBoundingSphere();
  17220. const center = this.boundingSphere.center;
  17221. const radius = this.boundingSphere.radius;
  17222. const s = radius === 0 ? 1 : 1.0 / radius;
  17223. const matrix = new Matrix4();
  17224. matrix.set(
  17225. s, 0, 0, - s * center.x,
  17226. 0, s, 0, - s * center.y,
  17227. 0, 0, s, - s * center.z,
  17228. 0, 0, 0, 1
  17229. );
  17230. this.applyMatrix4( matrix );
  17231. return this;
  17232. },
  17233. computeFaceNormals: function () {
  17234. const cb = new Vector3(), ab = new Vector3();
  17235. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17236. const face = this.faces[ f ];
  17237. const vA = this.vertices[ face.a ];
  17238. const vB = this.vertices[ face.b ];
  17239. const vC = this.vertices[ face.c ];
  17240. cb.subVectors( vC, vB );
  17241. ab.subVectors( vA, vB );
  17242. cb.cross( ab );
  17243. cb.normalize();
  17244. face.normal.copy( cb );
  17245. }
  17246. },
  17247. computeVertexNormals: function ( areaWeighted = true ) {
  17248. const vertices = new Array( this.vertices.length );
  17249. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  17250. vertices[ v ] = new Vector3();
  17251. }
  17252. if ( areaWeighted ) {
  17253. // vertex normals weighted by triangle areas
  17254. // http://www.iquilezles.org/www/articles/normals/normals.htm
  17255. const cb = new Vector3(), ab = new Vector3();
  17256. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17257. const face = this.faces[ f ];
  17258. const vA = this.vertices[ face.a ];
  17259. const vB = this.vertices[ face.b ];
  17260. const vC = this.vertices[ face.c ];
  17261. cb.subVectors( vC, vB );
  17262. ab.subVectors( vA, vB );
  17263. cb.cross( ab );
  17264. vertices[ face.a ].add( cb );
  17265. vertices[ face.b ].add( cb );
  17266. vertices[ face.c ].add( cb );
  17267. }
  17268. } else {
  17269. this.computeFaceNormals();
  17270. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17271. const face = this.faces[ f ];
  17272. vertices[ face.a ].add( face.normal );
  17273. vertices[ face.b ].add( face.normal );
  17274. vertices[ face.c ].add( face.normal );
  17275. }
  17276. }
  17277. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  17278. vertices[ v ].normalize();
  17279. }
  17280. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17281. const face = this.faces[ f ];
  17282. const vertexNormals = face.vertexNormals;
  17283. if ( vertexNormals.length === 3 ) {
  17284. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  17285. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  17286. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  17287. } else {
  17288. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  17289. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  17290. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  17291. }
  17292. }
  17293. if ( this.faces.length > 0 ) {
  17294. this.normalsNeedUpdate = true;
  17295. }
  17296. },
  17297. computeFlatVertexNormals: function () {
  17298. this.computeFaceNormals();
  17299. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17300. const face = this.faces[ f ];
  17301. const vertexNormals = face.vertexNormals;
  17302. if ( vertexNormals.length === 3 ) {
  17303. vertexNormals[ 0 ].copy( face.normal );
  17304. vertexNormals[ 1 ].copy( face.normal );
  17305. vertexNormals[ 2 ].copy( face.normal );
  17306. } else {
  17307. vertexNormals[ 0 ] = face.normal.clone();
  17308. vertexNormals[ 1 ] = face.normal.clone();
  17309. vertexNormals[ 2 ] = face.normal.clone();
  17310. }
  17311. }
  17312. if ( this.faces.length > 0 ) {
  17313. this.normalsNeedUpdate = true;
  17314. }
  17315. },
  17316. computeMorphNormals: function () {
  17317. // save original normals
  17318. // - create temp variables on first access
  17319. // otherwise just copy (for faster repeated calls)
  17320. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17321. const face = this.faces[ f ];
  17322. if ( ! face.__originalFaceNormal ) {
  17323. face.__originalFaceNormal = face.normal.clone();
  17324. } else {
  17325. face.__originalFaceNormal.copy( face.normal );
  17326. }
  17327. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  17328. for ( let i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  17329. if ( ! face.__originalVertexNormals[ i ] ) {
  17330. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  17331. } else {
  17332. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  17333. }
  17334. }
  17335. }
  17336. // use temp geometry to compute face and vertex normals for each morph
  17337. const tmpGeo = new Geometry();
  17338. tmpGeo.faces = this.faces;
  17339. for ( let i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  17340. // create on first access
  17341. if ( ! this.morphNormals[ i ] ) {
  17342. this.morphNormals[ i ] = {};
  17343. this.morphNormals[ i ].faceNormals = [];
  17344. this.morphNormals[ i ].vertexNormals = [];
  17345. const dstNormalsFace = this.morphNormals[ i ].faceNormals;
  17346. const dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  17347. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17348. const faceNormal = new Vector3();
  17349. const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  17350. dstNormalsFace.push( faceNormal );
  17351. dstNormalsVertex.push( vertexNormals );
  17352. }
  17353. }
  17354. const morphNormals = this.morphNormals[ i ];
  17355. // set vertices to morph target
  17356. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  17357. // compute morph normals
  17358. tmpGeo.computeFaceNormals();
  17359. tmpGeo.computeVertexNormals();
  17360. // store morph normals
  17361. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17362. const face = this.faces[ f ];
  17363. const faceNormal = morphNormals.faceNormals[ f ];
  17364. const vertexNormals = morphNormals.vertexNormals[ f ];
  17365. faceNormal.copy( face.normal );
  17366. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  17367. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  17368. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  17369. }
  17370. }
  17371. // restore original normals
  17372. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17373. const face = this.faces[ f ];
  17374. face.normal = face.__originalFaceNormal;
  17375. face.vertexNormals = face.__originalVertexNormals;
  17376. }
  17377. },
  17378. computeBoundingBox: function () {
  17379. if ( this.boundingBox === null ) {
  17380. this.boundingBox = new Box3();
  17381. }
  17382. this.boundingBox.setFromPoints( this.vertices );
  17383. },
  17384. computeBoundingSphere: function () {
  17385. if ( this.boundingSphere === null ) {
  17386. this.boundingSphere = new Sphere();
  17387. }
  17388. this.boundingSphere.setFromPoints( this.vertices );
  17389. },
  17390. merge: function ( geometry, matrix, materialIndexOffset = 0 ) {
  17391. if ( ! ( geometry && geometry.isGeometry ) ) {
  17392. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  17393. return;
  17394. }
  17395. let normalMatrix;
  17396. const vertexOffset = this.vertices.length,
  17397. vertices1 = this.vertices,
  17398. vertices2 = geometry.vertices,
  17399. faces1 = this.faces,
  17400. faces2 = geometry.faces,
  17401. colors1 = this.colors,
  17402. colors2 = geometry.colors;
  17403. if ( matrix !== undefined ) {
  17404. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  17405. }
  17406. // vertices
  17407. for ( let i = 0, il = vertices2.length; i < il; i ++ ) {
  17408. const vertex = vertices2[ i ];
  17409. const vertexCopy = vertex.clone();
  17410. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  17411. vertices1.push( vertexCopy );
  17412. }
  17413. // colors
  17414. for ( let i = 0, il = colors2.length; i < il; i ++ ) {
  17415. colors1.push( colors2[ i ].clone() );
  17416. }
  17417. // faces
  17418. for ( let i = 0, il = faces2.length; i < il; i ++ ) {
  17419. const face = faces2[ i ];
  17420. let normal, color;
  17421. const faceVertexNormals = face.vertexNormals,
  17422. faceVertexColors = face.vertexColors;
  17423. const faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  17424. faceCopy.normal.copy( face.normal );
  17425. if ( normalMatrix !== undefined ) {
  17426. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  17427. }
  17428. for ( let j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  17429. normal = faceVertexNormals[ j ].clone();
  17430. if ( normalMatrix !== undefined ) {
  17431. normal.applyMatrix3( normalMatrix ).normalize();
  17432. }
  17433. faceCopy.vertexNormals.push( normal );
  17434. }
  17435. faceCopy.color.copy( face.color );
  17436. for ( let j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  17437. color = faceVertexColors[ j ];
  17438. faceCopy.vertexColors.push( color.clone() );
  17439. }
  17440. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  17441. faces1.push( faceCopy );
  17442. }
  17443. // uvs
  17444. for ( let i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  17445. const faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  17446. if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];
  17447. for ( let j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  17448. const uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  17449. for ( let k = 0, kl = uvs2.length; k < kl; k ++ ) {
  17450. uvsCopy.push( uvs2[ k ].clone() );
  17451. }
  17452. this.faceVertexUvs[ i ].push( uvsCopy );
  17453. }
  17454. }
  17455. },
  17456. mergeMesh: function ( mesh ) {
  17457. if ( ! ( mesh && mesh.isMesh ) ) {
  17458. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  17459. return;
  17460. }
  17461. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  17462. this.merge( mesh.geometry, mesh.matrix );
  17463. },
  17464. /*
  17465. * Checks for duplicate vertices with hashmap.
  17466. * Duplicated vertices are removed
  17467. * and faces' vertices are updated.
  17468. */
  17469. mergeVertices: function ( precisionPoints = 4 ) {
  17470. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  17471. const unique = [], changes = [];
  17472. const precision = Math.pow( 10, precisionPoints );
  17473. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  17474. const v = this.vertices[ i ];
  17475. const key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  17476. if ( verticesMap[ key ] === undefined ) {
  17477. verticesMap[ key ] = i;
  17478. unique.push( this.vertices[ i ] );
  17479. changes[ i ] = unique.length - 1;
  17480. } else {
  17481. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  17482. changes[ i ] = changes[ verticesMap[ key ] ];
  17483. }
  17484. }
  17485. // if faces are completely degenerate after merging vertices, we
  17486. // have to remove them from the geometry.
  17487. const faceIndicesToRemove = [];
  17488. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  17489. const face = this.faces[ i ];
  17490. face.a = changes[ face.a ];
  17491. face.b = changes[ face.b ];
  17492. face.c = changes[ face.c ];
  17493. const indices = [ face.a, face.b, face.c ];
  17494. // if any duplicate vertices are found in a Face3
  17495. // we have to remove the face as nothing can be saved
  17496. for ( let n = 0; n < 3; n ++ ) {
  17497. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  17498. faceIndicesToRemove.push( i );
  17499. break;
  17500. }
  17501. }
  17502. }
  17503. for ( let i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  17504. const idx = faceIndicesToRemove[ i ];
  17505. this.faces.splice( idx, 1 );
  17506. for ( let j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  17507. this.faceVertexUvs[ j ].splice( idx, 1 );
  17508. }
  17509. }
  17510. // Use unique set of vertices
  17511. const diff = this.vertices.length - unique.length;
  17512. this.vertices = unique;
  17513. return diff;
  17514. },
  17515. setFromPoints: function ( points ) {
  17516. this.vertices = [];
  17517. for ( let i = 0, l = points.length; i < l; i ++ ) {
  17518. const point = points[ i ];
  17519. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  17520. }
  17521. return this;
  17522. },
  17523. sortFacesByMaterialIndex: function () {
  17524. const faces = this.faces;
  17525. const length = faces.length;
  17526. // tag faces
  17527. for ( let i = 0; i < length; i ++ ) {
  17528. faces[ i ]._id = i;
  17529. }
  17530. // sort faces
  17531. function materialIndexSort( a, b ) {
  17532. return a.materialIndex - b.materialIndex;
  17533. }
  17534. faces.sort( materialIndexSort );
  17535. // sort uvs
  17536. const uvs1 = this.faceVertexUvs[ 0 ];
  17537. const uvs2 = this.faceVertexUvs[ 1 ];
  17538. let newUvs1, newUvs2;
  17539. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  17540. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  17541. for ( let i = 0; i < length; i ++ ) {
  17542. const id = faces[ i ]._id;
  17543. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  17544. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  17545. }
  17546. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  17547. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  17548. },
  17549. toJSON: function () {
  17550. const data = {
  17551. metadata: {
  17552. version: 4.5,
  17553. type: 'Geometry',
  17554. generator: 'Geometry.toJSON'
  17555. }
  17556. };
  17557. // standard Geometry serialization
  17558. data.uuid = this.uuid;
  17559. data.type = this.type;
  17560. if ( this.name !== '' ) data.name = this.name;
  17561. if ( this.parameters !== undefined ) {
  17562. const parameters = this.parameters;
  17563. for ( const key in parameters ) {
  17564. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  17565. }
  17566. return data;
  17567. }
  17568. const vertices = [];
  17569. for ( let i = 0; i < this.vertices.length; i ++ ) {
  17570. const vertex = this.vertices[ i ];
  17571. vertices.push( vertex.x, vertex.y, vertex.z );
  17572. }
  17573. const faces = [];
  17574. const normals = [];
  17575. const normalsHash = {};
  17576. const colors = [];
  17577. const colorsHash = {};
  17578. const uvs = [];
  17579. const uvsHash = {};
  17580. for ( let i = 0; i < this.faces.length; i ++ ) {
  17581. const face = this.faces[ i ];
  17582. const hasMaterial = true;
  17583. const hasFaceUv = false; // deprecated
  17584. const hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  17585. const hasFaceNormal = face.normal.length() > 0;
  17586. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  17587. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  17588. const hasFaceVertexColor = face.vertexColors.length > 0;
  17589. let faceType = 0;
  17590. faceType = setBit( faceType, 0, 0 ); // isQuad
  17591. faceType = setBit( faceType, 1, hasMaterial );
  17592. faceType = setBit( faceType, 2, hasFaceUv );
  17593. faceType = setBit( faceType, 3, hasFaceVertexUv );
  17594. faceType = setBit( faceType, 4, hasFaceNormal );
  17595. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  17596. faceType = setBit( faceType, 6, hasFaceColor );
  17597. faceType = setBit( faceType, 7, hasFaceVertexColor );
  17598. faces.push( faceType );
  17599. faces.push( face.a, face.b, face.c );
  17600. faces.push( face.materialIndex );
  17601. if ( hasFaceVertexUv ) {
  17602. const faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  17603. faces.push(
  17604. getUvIndex( faceVertexUvs[ 0 ] ),
  17605. getUvIndex( faceVertexUvs[ 1 ] ),
  17606. getUvIndex( faceVertexUvs[ 2 ] )
  17607. );
  17608. }
  17609. if ( hasFaceNormal ) {
  17610. faces.push( getNormalIndex( face.normal ) );
  17611. }
  17612. if ( hasFaceVertexNormal ) {
  17613. const vertexNormals = face.vertexNormals;
  17614. faces.push(
  17615. getNormalIndex( vertexNormals[ 0 ] ),
  17616. getNormalIndex( vertexNormals[ 1 ] ),
  17617. getNormalIndex( vertexNormals[ 2 ] )
  17618. );
  17619. }
  17620. if ( hasFaceColor ) {
  17621. faces.push( getColorIndex( face.color ) );
  17622. }
  17623. if ( hasFaceVertexColor ) {
  17624. const vertexColors = face.vertexColors;
  17625. faces.push(
  17626. getColorIndex( vertexColors[ 0 ] ),
  17627. getColorIndex( vertexColors[ 1 ] ),
  17628. getColorIndex( vertexColors[ 2 ] )
  17629. );
  17630. }
  17631. }
  17632. function setBit( value, position, enabled ) {
  17633. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  17634. }
  17635. function getNormalIndex( normal ) {
  17636. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  17637. if ( normalsHash[ hash ] !== undefined ) {
  17638. return normalsHash[ hash ];
  17639. }
  17640. normalsHash[ hash ] = normals.length / 3;
  17641. normals.push( normal.x, normal.y, normal.z );
  17642. return normalsHash[ hash ];
  17643. }
  17644. function getColorIndex( color ) {
  17645. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  17646. if ( colorsHash[ hash ] !== undefined ) {
  17647. return colorsHash[ hash ];
  17648. }
  17649. colorsHash[ hash ] = colors.length;
  17650. colors.push( color.getHex() );
  17651. return colorsHash[ hash ];
  17652. }
  17653. function getUvIndex( uv ) {
  17654. const hash = uv.x.toString() + uv.y.toString();
  17655. if ( uvsHash[ hash ] !== undefined ) {
  17656. return uvsHash[ hash ];
  17657. }
  17658. uvsHash[ hash ] = uvs.length / 2;
  17659. uvs.push( uv.x, uv.y );
  17660. return uvsHash[ hash ];
  17661. }
  17662. data.data = {};
  17663. data.data.vertices = vertices;
  17664. data.data.normals = normals;
  17665. if ( colors.length > 0 ) data.data.colors = colors;
  17666. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  17667. data.data.faces = faces;
  17668. return data;
  17669. },
  17670. clone: function () {
  17671. /*
  17672. // Handle primitives
  17673. const parameters = this.parameters;
  17674. if ( parameters !== undefined ) {
  17675. const values = [];
  17676. for ( const key in parameters ) {
  17677. values.push( parameters[ key ] );
  17678. }
  17679. const geometry = Object.create( this.constructor.prototype );
  17680. this.constructor.apply( geometry, values );
  17681. return geometry;
  17682. }
  17683. return new this.constructor().copy( this );
  17684. */
  17685. return new Geometry().copy( this );
  17686. },
  17687. copy: function ( source ) {
  17688. // reset
  17689. this.vertices = [];
  17690. this.colors = [];
  17691. this.faces = [];
  17692. this.faceVertexUvs = [[]];
  17693. this.morphTargets = [];
  17694. this.morphNormals = [];
  17695. this.skinWeights = [];
  17696. this.skinIndices = [];
  17697. this.lineDistances = [];
  17698. this.boundingBox = null;
  17699. this.boundingSphere = null;
  17700. // name
  17701. this.name = source.name;
  17702. // vertices
  17703. const vertices = source.vertices;
  17704. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  17705. this.vertices.push( vertices[ i ].clone() );
  17706. }
  17707. // colors
  17708. const colors = source.colors;
  17709. for ( let i = 0, il = colors.length; i < il; i ++ ) {
  17710. this.colors.push( colors[ i ].clone() );
  17711. }
  17712. // faces
  17713. const faces = source.faces;
  17714. for ( let i = 0, il = faces.length; i < il; i ++ ) {
  17715. this.faces.push( faces[ i ].clone() );
  17716. }
  17717. // face vertex uvs
  17718. for ( let i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  17719. const faceVertexUvs = source.faceVertexUvs[ i ];
  17720. if ( this.faceVertexUvs[ i ] === undefined ) {
  17721. this.faceVertexUvs[ i ] = [];
  17722. }
  17723. for ( let j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  17724. const uvs = faceVertexUvs[ j ], uvsCopy = [];
  17725. for ( let k = 0, kl = uvs.length; k < kl; k ++ ) {
  17726. const uv = uvs[ k ];
  17727. uvsCopy.push( uv.clone() );
  17728. }
  17729. this.faceVertexUvs[ i ].push( uvsCopy );
  17730. }
  17731. }
  17732. // morph targets
  17733. const morphTargets = source.morphTargets;
  17734. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  17735. const morphTarget = {};
  17736. morphTarget.name = morphTargets[ i ].name;
  17737. // vertices
  17738. if ( morphTargets[ i ].vertices !== undefined ) {
  17739. morphTarget.vertices = [];
  17740. for ( let j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  17741. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  17742. }
  17743. }
  17744. // normals
  17745. if ( morphTargets[ i ].normals !== undefined ) {
  17746. morphTarget.normals = [];
  17747. for ( let j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  17748. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  17749. }
  17750. }
  17751. this.morphTargets.push( morphTarget );
  17752. }
  17753. // morph normals
  17754. const morphNormals = source.morphNormals;
  17755. for ( let i = 0, il = morphNormals.length; i < il; i ++ ) {
  17756. const morphNormal = {};
  17757. // vertex normals
  17758. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  17759. morphNormal.vertexNormals = [];
  17760. for ( let j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  17761. const srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  17762. const destVertexNormal = {};
  17763. destVertexNormal.a = srcVertexNormal.a.clone();
  17764. destVertexNormal.b = srcVertexNormal.b.clone();
  17765. destVertexNormal.c = srcVertexNormal.c.clone();
  17766. morphNormal.vertexNormals.push( destVertexNormal );
  17767. }
  17768. }
  17769. // face normals
  17770. if ( morphNormals[ i ].faceNormals !== undefined ) {
  17771. morphNormal.faceNormals = [];
  17772. for ( let j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  17773. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  17774. }
  17775. }
  17776. this.morphNormals.push( morphNormal );
  17777. }
  17778. // skin weights
  17779. const skinWeights = source.skinWeights;
  17780. for ( let i = 0, il = skinWeights.length; i < il; i ++ ) {
  17781. this.skinWeights.push( skinWeights[ i ].clone() );
  17782. }
  17783. // skin indices
  17784. const skinIndices = source.skinIndices;
  17785. for ( let i = 0, il = skinIndices.length; i < il; i ++ ) {
  17786. this.skinIndices.push( skinIndices[ i ].clone() );
  17787. }
  17788. // line distances
  17789. const lineDistances = source.lineDistances;
  17790. for ( let i = 0, il = lineDistances.length; i < il; i ++ ) {
  17791. this.lineDistances.push( lineDistances[ i ] );
  17792. }
  17793. // bounding box
  17794. const boundingBox = source.boundingBox;
  17795. if ( boundingBox !== null ) {
  17796. this.boundingBox = boundingBox.clone();
  17797. }
  17798. // bounding sphere
  17799. const boundingSphere = source.boundingSphere;
  17800. if ( boundingSphere !== null ) {
  17801. this.boundingSphere = boundingSphere.clone();
  17802. }
  17803. // update flags
  17804. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17805. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17806. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17807. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17808. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17809. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17810. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17811. return this;
  17812. },
  17813. dispose: function () {
  17814. this.dispatchEvent( { type: 'dispose' } );
  17815. }
  17816. } );
  17817. class BoxGeometry extends Geometry {
  17818. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17819. super();
  17820. this.type = 'BoxGeometry';
  17821. this.parameters = {
  17822. width: width,
  17823. height: height,
  17824. depth: depth,
  17825. widthSegments: widthSegments,
  17826. heightSegments: heightSegments,
  17827. depthSegments: depthSegments
  17828. };
  17829. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  17830. this.mergeVertices();
  17831. }
  17832. }
  17833. class CircleBufferGeometry extends BufferGeometry {
  17834. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17835. super();
  17836. this.type = 'CircleBufferGeometry';
  17837. this.parameters = {
  17838. radius: radius,
  17839. segments: segments,
  17840. thetaStart: thetaStart,
  17841. thetaLength: thetaLength
  17842. };
  17843. segments = Math.max( 3, segments );
  17844. // buffers
  17845. const indices = [];
  17846. const vertices = [];
  17847. const normals = [];
  17848. const uvs = [];
  17849. // helper variables
  17850. const vertex = new Vector3();
  17851. const uv = new Vector2$1();
  17852. // center point
  17853. vertices.push( 0, 0, 0 );
  17854. normals.push( 0, 0, 1 );
  17855. uvs.push( 0.5, 0.5 );
  17856. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17857. const segment = thetaStart + s / segments * thetaLength;
  17858. // vertex
  17859. vertex.x = radius * Math.cos( segment );
  17860. vertex.y = radius * Math.sin( segment );
  17861. vertices.push( vertex.x, vertex.y, vertex.z );
  17862. // normal
  17863. normals.push( 0, 0, 1 );
  17864. // uvs
  17865. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17866. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17867. uvs.push( uv.x, uv.y );
  17868. }
  17869. // indices
  17870. for ( let i = 1; i <= segments; i ++ ) {
  17871. indices.push( i, i + 1, 0 );
  17872. }
  17873. // build geometry
  17874. this.setIndex( indices );
  17875. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17876. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17877. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17878. }
  17879. }
  17880. class CircleGeometry extends Geometry {
  17881. constructor( radius, segments, thetaStart, thetaLength ) {
  17882. super();
  17883. this.type = 'CircleGeometry';
  17884. this.parameters = {
  17885. radius: radius,
  17886. segments: segments,
  17887. thetaStart: thetaStart,
  17888. thetaLength: thetaLength
  17889. };
  17890. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17891. this.mergeVertices();
  17892. }
  17893. }
  17894. class CylinderBufferGeometry extends BufferGeometry {
  17895. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17896. super();
  17897. this.type = 'CylinderBufferGeometry';
  17898. this.parameters = {
  17899. radiusTop: radiusTop,
  17900. radiusBottom: radiusBottom,
  17901. height: height,
  17902. radialSegments: radialSegments,
  17903. heightSegments: heightSegments,
  17904. openEnded: openEnded,
  17905. thetaStart: thetaStart,
  17906. thetaLength: thetaLength
  17907. };
  17908. const scope = this;
  17909. radialSegments = Math.floor( radialSegments );
  17910. heightSegments = Math.floor( heightSegments );
  17911. // buffers
  17912. const indices = [];
  17913. const vertices = [];
  17914. const normals = [];
  17915. const uvs = [];
  17916. // helper variables
  17917. let index = 0;
  17918. const indexArray = [];
  17919. const halfHeight = height / 2;
  17920. let groupStart = 0;
  17921. // generate geometry
  17922. generateTorso();
  17923. if ( openEnded === false ) {
  17924. if ( radiusTop > 0 ) generateCap( true );
  17925. if ( radiusBottom > 0 ) generateCap( false );
  17926. }
  17927. // build geometry
  17928. this.setIndex( indices );
  17929. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17930. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17931. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17932. function generateTorso() {
  17933. const normal = new Vector3();
  17934. const vertex = new Vector3();
  17935. let groupCount = 0;
  17936. // this will be used to calculate the normal
  17937. const slope = ( radiusBottom - radiusTop ) / height;
  17938. // generate vertices, normals and uvs
  17939. for ( let y = 0; y <= heightSegments; y ++ ) {
  17940. const indexRow = [];
  17941. const v = y / heightSegments;
  17942. // calculate the radius of the current row
  17943. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17944. for ( let x = 0; x <= radialSegments; x ++ ) {
  17945. const u = x / radialSegments;
  17946. const theta = u * thetaLength + thetaStart;
  17947. const sinTheta = Math.sin( theta );
  17948. const cosTheta = Math.cos( theta );
  17949. // vertex
  17950. vertex.x = radius * sinTheta;
  17951. vertex.y = - v * height + halfHeight;
  17952. vertex.z = radius * cosTheta;
  17953. vertices.push( vertex.x, vertex.y, vertex.z );
  17954. // normal
  17955. normal.set( sinTheta, slope, cosTheta ).normalize();
  17956. normals.push( normal.x, normal.y, normal.z );
  17957. // uv
  17958. uvs.push( u, 1 - v );
  17959. // save index of vertex in respective row
  17960. indexRow.push( index ++ );
  17961. }
  17962. // now save vertices of the row in our index array
  17963. indexArray.push( indexRow );
  17964. }
  17965. // generate indices
  17966. for ( let x = 0; x < radialSegments; x ++ ) {
  17967. for ( let y = 0; y < heightSegments; y ++ ) {
  17968. // we use the index array to access the correct indices
  17969. const a = indexArray[ y ][ x ];
  17970. const b = indexArray[ y + 1 ][ x ];
  17971. const c = indexArray[ y + 1 ][ x + 1 ];
  17972. const d = indexArray[ y ][ x + 1 ];
  17973. // faces
  17974. indices.push( a, b, d );
  17975. indices.push( b, c, d );
  17976. // update group counter
  17977. groupCount += 6;
  17978. }
  17979. }
  17980. // add a group to the geometry. this will ensure multi material support
  17981. scope.addGroup( groupStart, groupCount, 0 );
  17982. // calculate new start value for groups
  17983. groupStart += groupCount;
  17984. }
  17985. function generateCap( top ) {
  17986. // save the index of the first center vertex
  17987. const centerIndexStart = index;
  17988. const uv = new Vector2$1();
  17989. const vertex = new Vector3();
  17990. let groupCount = 0;
  17991. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17992. const sign = ( top === true ) ? 1 : - 1;
  17993. // first we generate the center vertex data of the cap.
  17994. // because the geometry needs one set of uvs per face,
  17995. // we must generate a center vertex per face/segment
  17996. for ( let x = 1; x <= radialSegments; x ++ ) {
  17997. // vertex
  17998. vertices.push( 0, halfHeight * sign, 0 );
  17999. // normal
  18000. normals.push( 0, sign, 0 );
  18001. // uv
  18002. uvs.push( 0.5, 0.5 );
  18003. // increase index
  18004. index ++;
  18005. }
  18006. // save the index of the last center vertex
  18007. const centerIndexEnd = index;
  18008. // now we generate the surrounding vertices, normals and uvs
  18009. for ( let x = 0; x <= radialSegments; x ++ ) {
  18010. const u = x / radialSegments;
  18011. const theta = u * thetaLength + thetaStart;
  18012. const cosTheta = Math.cos( theta );
  18013. const sinTheta = Math.sin( theta );
  18014. // vertex
  18015. vertex.x = radius * sinTheta;
  18016. vertex.y = halfHeight * sign;
  18017. vertex.z = radius * cosTheta;
  18018. vertices.push( vertex.x, vertex.y, vertex.z );
  18019. // normal
  18020. normals.push( 0, sign, 0 );
  18021. // uv
  18022. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18023. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18024. uvs.push( uv.x, uv.y );
  18025. // increase index
  18026. index ++;
  18027. }
  18028. // generate indices
  18029. for ( let x = 0; x < radialSegments; x ++ ) {
  18030. const c = centerIndexStart + x;
  18031. const i = centerIndexEnd + x;
  18032. if ( top === true ) {
  18033. // face top
  18034. indices.push( i, i + 1, c );
  18035. } else {
  18036. // face bottom
  18037. indices.push( i + 1, i, c );
  18038. }
  18039. groupCount += 3;
  18040. }
  18041. // add a group to the geometry. this will ensure multi material support
  18042. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18043. // calculate new start value for groups
  18044. groupStart += groupCount;
  18045. }
  18046. }
  18047. }
  18048. class CylinderGeometry extends Geometry {
  18049. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18050. super();
  18051. this.type = 'CylinderGeometry';
  18052. this.parameters = {
  18053. radiusTop: radiusTop,
  18054. radiusBottom: radiusBottom,
  18055. height: height,
  18056. radialSegments: radialSegments,
  18057. heightSegments: heightSegments,
  18058. openEnded: openEnded,
  18059. thetaStart: thetaStart,
  18060. thetaLength: thetaLength
  18061. };
  18062. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  18063. this.mergeVertices();
  18064. }
  18065. }
  18066. class ConeGeometry extends CylinderGeometry {
  18067. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18068. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18069. this.type = 'ConeGeometry';
  18070. this.parameters = {
  18071. radius: radius,
  18072. height: height,
  18073. radialSegments: radialSegments,
  18074. heightSegments: heightSegments,
  18075. openEnded: openEnded,
  18076. thetaStart: thetaStart,
  18077. thetaLength: thetaLength
  18078. };
  18079. }
  18080. }
  18081. class ConeBufferGeometry extends CylinderBufferGeometry {
  18082. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18083. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18084. this.type = 'ConeBufferGeometry';
  18085. this.parameters = {
  18086. radius: radius,
  18087. height: height,
  18088. radialSegments: radialSegments,
  18089. heightSegments: heightSegments,
  18090. openEnded: openEnded,
  18091. thetaStart: thetaStart,
  18092. thetaLength: thetaLength
  18093. };
  18094. }
  18095. }
  18096. class PolyhedronBufferGeometry extends BufferGeometry {
  18097. constructor( vertices, indices, radius = 1, detail = 0 ) {
  18098. super();
  18099. this.type = 'PolyhedronBufferGeometry';
  18100. this.parameters = {
  18101. vertices: vertices,
  18102. indices: indices,
  18103. radius: radius,
  18104. detail: detail
  18105. };
  18106. // default buffer data
  18107. const vertexBuffer = [];
  18108. const uvBuffer = [];
  18109. // the subdivision creates the vertex buffer data
  18110. subdivide( detail );
  18111. // all vertices should lie on a conceptual sphere with a given radius
  18112. applyRadius( radius );
  18113. // finally, create the uv data
  18114. generateUVs();
  18115. // build non-indexed geometry
  18116. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18117. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18118. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18119. if ( detail === 0 ) {
  18120. this.computeVertexNormals(); // flat normals
  18121. } else {
  18122. this.normalizeNormals(); // smooth normals
  18123. }
  18124. // helper functions
  18125. function subdivide( detail ) {
  18126. const a = new Vector3();
  18127. const b = new Vector3();
  18128. const c = new Vector3();
  18129. // iterate over all faces and apply a subdivison with the given detail value
  18130. for ( let i = 0; i < indices.length; i += 3 ) {
  18131. // get the vertices of the face
  18132. getVertexByIndex( indices[ i + 0 ], a );
  18133. getVertexByIndex( indices[ i + 1 ], b );
  18134. getVertexByIndex( indices[ i + 2 ], c );
  18135. // perform subdivision
  18136. subdivideFace( a, b, c, detail );
  18137. }
  18138. }
  18139. function subdivideFace( a, b, c, detail ) {
  18140. const cols = detail + 1;
  18141. // we use this multidimensional array as a data structure for creating the subdivision
  18142. const v = [];
  18143. // construct all of the vertices for this subdivision
  18144. for ( let i = 0; i <= cols; i ++ ) {
  18145. v[ i ] = [];
  18146. const aj = a.clone().lerp( c, i / cols );
  18147. const bj = b.clone().lerp( c, i / cols );
  18148. const rows = cols - i;
  18149. for ( let j = 0; j <= rows; j ++ ) {
  18150. if ( j === 0 && i === cols ) {
  18151. v[ i ][ j ] = aj;
  18152. } else {
  18153. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18154. }
  18155. }
  18156. }
  18157. // construct all of the faces
  18158. for ( let i = 0; i < cols; i ++ ) {
  18159. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18160. const k = Math.floor( j / 2 );
  18161. if ( j % 2 === 0 ) {
  18162. pushVertex( v[ i ][ k + 1 ] );
  18163. pushVertex( v[ i + 1 ][ k ] );
  18164. pushVertex( v[ i ][ k ] );
  18165. } else {
  18166. pushVertex( v[ i ][ k + 1 ] );
  18167. pushVertex( v[ i + 1 ][ k + 1 ] );
  18168. pushVertex( v[ i + 1 ][ k ] );
  18169. }
  18170. }
  18171. }
  18172. }
  18173. function applyRadius( radius ) {
  18174. const vertex = new Vector3();
  18175. // iterate over the entire buffer and apply the radius to each vertex
  18176. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18177. vertex.x = vertexBuffer[ i + 0 ];
  18178. vertex.y = vertexBuffer[ i + 1 ];
  18179. vertex.z = vertexBuffer[ i + 2 ];
  18180. vertex.normalize().multiplyScalar( radius );
  18181. vertexBuffer[ i + 0 ] = vertex.x;
  18182. vertexBuffer[ i + 1 ] = vertex.y;
  18183. vertexBuffer[ i + 2 ] = vertex.z;
  18184. }
  18185. }
  18186. function generateUVs() {
  18187. const vertex = new Vector3();
  18188. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18189. vertex.x = vertexBuffer[ i + 0 ];
  18190. vertex.y = vertexBuffer[ i + 1 ];
  18191. vertex.z = vertexBuffer[ i + 2 ];
  18192. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18193. const v = inclination( vertex ) / Math.PI + 0.5;
  18194. uvBuffer.push( u, 1 - v );
  18195. }
  18196. correctUVs();
  18197. correctSeam();
  18198. }
  18199. function correctSeam() {
  18200. // handle case when face straddles the seam, see #3269
  18201. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18202. // uv data of a single face
  18203. const x0 = uvBuffer[ i + 0 ];
  18204. const x1 = uvBuffer[ i + 2 ];
  18205. const x2 = uvBuffer[ i + 4 ];
  18206. const max = Math.max( x0, x1, x2 );
  18207. const min = Math.min( x0, x1, x2 );
  18208. // 0.9 is somewhat arbitrary
  18209. if ( max > 0.9 && min < 0.1 ) {
  18210. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18211. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18212. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18213. }
  18214. }
  18215. }
  18216. function pushVertex( vertex ) {
  18217. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18218. }
  18219. function getVertexByIndex( index, vertex ) {
  18220. const stride = index * 3;
  18221. vertex.x = vertices[ stride + 0 ];
  18222. vertex.y = vertices[ stride + 1 ];
  18223. vertex.z = vertices[ stride + 2 ];
  18224. }
  18225. function correctUVs() {
  18226. const a = new Vector3();
  18227. const b = new Vector3();
  18228. const c = new Vector3();
  18229. const centroid = new Vector3();
  18230. const uvA = new Vector2$1();
  18231. const uvB = new Vector2$1();
  18232. const uvC = new Vector2$1();
  18233. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18234. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18235. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18236. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18237. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18238. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18239. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18240. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18241. const azi = azimuth( centroid );
  18242. correctUV( uvA, j + 0, a, azi );
  18243. correctUV( uvB, j + 2, b, azi );
  18244. correctUV( uvC, j + 4, c, azi );
  18245. }
  18246. }
  18247. function correctUV( uv, stride, vector, azimuth ) {
  18248. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18249. uvBuffer[ stride ] = uv.x - 1;
  18250. }
  18251. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18252. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18253. }
  18254. }
  18255. // Angle around the Y axis, counter-clockwise when looking from above.
  18256. function azimuth( vector ) {
  18257. return Math.atan2( vector.z, - vector.x );
  18258. }
  18259. // Angle above the XZ plane.
  18260. function inclination( vector ) {
  18261. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18262. }
  18263. }
  18264. }
  18265. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  18266. constructor( radius = 1, detail = 0 ) {
  18267. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18268. const r = 1 / t;
  18269. const vertices = [
  18270. // (±1, ±1, ±1)
  18271. - 1, - 1, - 1, - 1, - 1, 1,
  18272. - 1, 1, - 1, - 1, 1, 1,
  18273. 1, - 1, - 1, 1, - 1, 1,
  18274. 1, 1, - 1, 1, 1, 1,
  18275. // (0, ±1/φ, ±φ)
  18276. 0, - r, - t, 0, - r, t,
  18277. 0, r, - t, 0, r, t,
  18278. // (±1/φ, ±φ, 0)
  18279. - r, - t, 0, - r, t, 0,
  18280. r, - t, 0, r, t, 0,
  18281. // (±φ, 0, ±1/φ)
  18282. - t, 0, - r, t, 0, - r,
  18283. - t, 0, r, t, 0, r
  18284. ];
  18285. const indices = [
  18286. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18287. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18288. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18289. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18290. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18291. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18292. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18293. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18294. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18295. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18296. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18297. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18298. ];
  18299. super( vertices, indices, radius, detail );
  18300. this.type = 'DodecahedronBufferGeometry';
  18301. this.parameters = {
  18302. radius: radius,
  18303. detail: detail
  18304. };
  18305. }
  18306. }
  18307. class DodecahedronGeometry extends Geometry {
  18308. constructor( radius, detail ) {
  18309. super();
  18310. this.type = 'DodecahedronGeometry';
  18311. this.parameters = {
  18312. radius: radius,
  18313. detail: detail
  18314. };
  18315. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  18316. this.mergeVertices();
  18317. }
  18318. }
  18319. const _v0$2 = new Vector3();
  18320. const _v1$5 = new Vector3();
  18321. const _normal$1 = new Vector3();
  18322. const _triangle = new Triangle();
  18323. class EdgesGeometry extends BufferGeometry {
  18324. constructor( geometry, thresholdAngle ) {
  18325. super();
  18326. this.type = 'EdgesGeometry';
  18327. this.parameters = {
  18328. thresholdAngle: thresholdAngle
  18329. };
  18330. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  18331. if ( geometry.isGeometry ) {
  18332. geometry = new BufferGeometry().fromGeometry( geometry );
  18333. }
  18334. const precisionPoints = 4;
  18335. const precision = Math.pow( 10, precisionPoints );
  18336. const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  18337. const indexAttr = geometry.getIndex();
  18338. const positionAttr = geometry.getAttribute( 'position' );
  18339. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18340. const indexArr = [ 0, 0, 0 ];
  18341. const vertKeys = [ 'a', 'b', 'c' ];
  18342. const hashes = new Array( 3 );
  18343. const edgeData = {};
  18344. const vertices = [];
  18345. for ( let i = 0; i < indexCount; i += 3 ) {
  18346. if ( indexAttr ) {
  18347. indexArr[ 0 ] = indexAttr.getX( i );
  18348. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18349. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18350. } else {
  18351. indexArr[ 0 ] = i;
  18352. indexArr[ 1 ] = i + 1;
  18353. indexArr[ 2 ] = i + 2;
  18354. }
  18355. const { a, b, c } = _triangle;
  18356. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18357. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18358. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18359. _triangle.getNormal( _normal$1 );
  18360. // create hashes for the edge from the vertices
  18361. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18362. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18363. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18364. // skip degenerate triangles
  18365. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18366. continue;
  18367. }
  18368. // iterate over every edge
  18369. for ( let j = 0; j < 3; j ++ ) {
  18370. // get the first and next vertex making up the edge
  18371. const jNext = ( j + 1 ) % 3;
  18372. const vecHash0 = hashes[ j ];
  18373. const vecHash1 = hashes[ jNext ];
  18374. const v0 = _triangle[ vertKeys[ j ] ];
  18375. const v1 = _triangle[ vertKeys[ jNext ] ];
  18376. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18377. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18378. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18379. // if we found a sibling edge add it into the vertex array if
  18380. // it meets the angle threshold and delete the edge from the map.
  18381. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18382. vertices.push( v0.x, v0.y, v0.z );
  18383. vertices.push( v1.x, v1.y, v1.z );
  18384. }
  18385. edgeData[ reverseHash ] = null;
  18386. } else if ( ! ( hash in edgeData ) ) {
  18387. // if we've already got an edge here then skip adding a new one
  18388. edgeData[ hash ] = {
  18389. index0: indexArr[ j ],
  18390. index1: indexArr[ jNext ],
  18391. normal: _normal$1.clone(),
  18392. };
  18393. }
  18394. }
  18395. }
  18396. // iterate over all remaining, unmatched edges and add them to the vertex array
  18397. for ( const key in edgeData ) {
  18398. if ( edgeData[ key ] ) {
  18399. const { index0, index1 } = edgeData[ key ];
  18400. _v0$2.fromBufferAttribute( positionAttr, index0 );
  18401. _v1$5.fromBufferAttribute( positionAttr, index1 );
  18402. vertices.push( _v0$2.x, _v0$2.y, _v0$2.z );
  18403. vertices.push( _v1$5.x, _v1$5.y, _v1$5.z );
  18404. }
  18405. }
  18406. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18407. }
  18408. }
  18409. /**
  18410. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18411. */
  18412. const Earcut = {
  18413. triangulate: function ( data, holeIndices, dim ) {
  18414. dim = dim || 2;
  18415. const hasHoles = holeIndices && holeIndices.length;
  18416. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  18417. let outerNode = linkedList( data, 0, outerLen, dim, true );
  18418. const triangles = [];
  18419. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  18420. let minX, minY, maxX, maxY, x, y, invSize;
  18421. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  18422. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18423. if ( data.length > 80 * dim ) {
  18424. minX = maxX = data[ 0 ];
  18425. minY = maxY = data[ 1 ];
  18426. for ( let i = dim; i < outerLen; i += dim ) {
  18427. x = data[ i ];
  18428. y = data[ i + 1 ];
  18429. if ( x < minX ) minX = x;
  18430. if ( y < minY ) minY = y;
  18431. if ( x > maxX ) maxX = x;
  18432. if ( y > maxY ) maxY = y;
  18433. }
  18434. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18435. invSize = Math.max( maxX - minX, maxY - minY );
  18436. invSize = invSize !== 0 ? 1 / invSize : 0;
  18437. }
  18438. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  18439. return triangles;
  18440. }
  18441. };
  18442. // create a circular doubly linked list from polygon points in the specified winding order
  18443. function linkedList( data, start, end, dim, clockwise ) {
  18444. let i, last;
  18445. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  18446. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18447. } else {
  18448. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18449. }
  18450. if ( last && equals( last, last.next ) ) {
  18451. removeNode( last );
  18452. last = last.next;
  18453. }
  18454. return last;
  18455. }
  18456. // eliminate colinear or duplicate points
  18457. function filterPoints( start, end ) {
  18458. if ( ! start ) return start;
  18459. if ( ! end ) end = start;
  18460. let p = start,
  18461. again;
  18462. do {
  18463. again = false;
  18464. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  18465. removeNode( p );
  18466. p = end = p.prev;
  18467. if ( p === p.next ) break;
  18468. again = true;
  18469. } else {
  18470. p = p.next;
  18471. }
  18472. } while ( again || p !== end );
  18473. return end;
  18474. }
  18475. // main ear slicing loop which triangulates a polygon (given as a linked list)
  18476. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  18477. if ( ! ear ) return;
  18478. // interlink polygon nodes in z-order
  18479. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  18480. let stop = ear,
  18481. prev, next;
  18482. // iterate through ears, slicing them one by one
  18483. while ( ear.prev !== ear.next ) {
  18484. prev = ear.prev;
  18485. next = ear.next;
  18486. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  18487. // cut off the triangle
  18488. triangles.push( prev.i / dim );
  18489. triangles.push( ear.i / dim );
  18490. triangles.push( next.i / dim );
  18491. removeNode( ear );
  18492. // skipping the next vertex leads to less sliver triangles
  18493. ear = next.next;
  18494. stop = next.next;
  18495. continue;
  18496. }
  18497. ear = next;
  18498. // if we looped through the whole remaining polygon and can't find any more ears
  18499. if ( ear === stop ) {
  18500. // try filtering points and slicing again
  18501. if ( ! pass ) {
  18502. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  18503. // if this didn't work, try curing all small self-intersections locally
  18504. } else if ( pass === 1 ) {
  18505. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  18506. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  18507. // as a last resort, try splitting the remaining polygon into two
  18508. } else if ( pass === 2 ) {
  18509. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  18510. }
  18511. break;
  18512. }
  18513. }
  18514. }
  18515. // check whether a polygon node forms a valid ear with adjacent nodes
  18516. function isEar( ear ) {
  18517. const a = ear.prev,
  18518. b = ear,
  18519. c = ear.next;
  18520. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18521. // now make sure we don't have other points inside the potential ear
  18522. let p = ear.next.next;
  18523. while ( p !== ear.prev ) {
  18524. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18525. area( p.prev, p, p.next ) >= 0 ) return false;
  18526. p = p.next;
  18527. }
  18528. return true;
  18529. }
  18530. function isEarHashed( ear, minX, minY, invSize ) {
  18531. const a = ear.prev,
  18532. b = ear,
  18533. c = ear.next;
  18534. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18535. // triangle bbox; min & max are calculated like this for speed
  18536. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  18537. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  18538. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  18539. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  18540. // z-order range for the current triangle bbox;
  18541. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  18542. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  18543. let p = ear.prevZ,
  18544. n = ear.nextZ;
  18545. // look for points inside the triangle in both directions
  18546. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  18547. if ( p !== ear.prev && p !== ear.next &&
  18548. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18549. area( p.prev, p, p.next ) >= 0 ) return false;
  18550. p = p.prevZ;
  18551. if ( n !== ear.prev && n !== ear.next &&
  18552. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  18553. area( n.prev, n, n.next ) >= 0 ) return false;
  18554. n = n.nextZ;
  18555. }
  18556. // look for remaining points in decreasing z-order
  18557. while ( p && p.z >= minZ ) {
  18558. if ( p !== ear.prev && p !== ear.next &&
  18559. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18560. area( p.prev, p, p.next ) >= 0 ) return false;
  18561. p = p.prevZ;
  18562. }
  18563. // look for remaining points in increasing z-order
  18564. while ( n && n.z <= maxZ ) {
  18565. if ( n !== ear.prev && n !== ear.next &&
  18566. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  18567. area( n.prev, n, n.next ) >= 0 ) return false;
  18568. n = n.nextZ;
  18569. }
  18570. return true;
  18571. }
  18572. // go through all polygon nodes and cure small local self-intersections
  18573. function cureLocalIntersections( start, triangles, dim ) {
  18574. let p = start;
  18575. do {
  18576. const a = p.prev,
  18577. b = p.next.next;
  18578. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  18579. triangles.push( a.i / dim );
  18580. triangles.push( p.i / dim );
  18581. triangles.push( b.i / dim );
  18582. // remove two nodes involved
  18583. removeNode( p );
  18584. removeNode( p.next );
  18585. p = start = b;
  18586. }
  18587. p = p.next;
  18588. } while ( p !== start );
  18589. return filterPoints( p );
  18590. }
  18591. // try splitting polygon into two and triangulate them independently
  18592. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  18593. // look for a valid diagonal that divides the polygon into two
  18594. let a = start;
  18595. do {
  18596. let b = a.next.next;
  18597. while ( b !== a.prev ) {
  18598. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  18599. // split the polygon in two by the diagonal
  18600. let c = splitPolygon( a, b );
  18601. // filter colinear points around the cuts
  18602. a = filterPoints( a, a.next );
  18603. c = filterPoints( c, c.next );
  18604. // run earcut on each half
  18605. earcutLinked( a, triangles, dim, minX, minY, invSize );
  18606. earcutLinked( c, triangles, dim, minX, minY, invSize );
  18607. return;
  18608. }
  18609. b = b.next;
  18610. }
  18611. a = a.next;
  18612. } while ( a !== start );
  18613. }
  18614. // link every hole into the outer loop, producing a single-ring polygon without holes
  18615. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  18616. const queue = [];
  18617. let i, len, start, end, list;
  18618. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  18619. start = holeIndices[ i ] * dim;
  18620. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  18621. list = linkedList( data, start, end, dim, false );
  18622. if ( list === list.next ) list.steiner = true;
  18623. queue.push( getLeftmost( list ) );
  18624. }
  18625. queue.sort( compareX );
  18626. // process holes from left to right
  18627. for ( i = 0; i < queue.length; i ++ ) {
  18628. eliminateHole( queue[ i ], outerNode );
  18629. outerNode = filterPoints( outerNode, outerNode.next );
  18630. }
  18631. return outerNode;
  18632. }
  18633. function compareX( a, b ) {
  18634. return a.x - b.x;
  18635. }
  18636. // find a bridge between vertices that connects hole with an outer ring and and link it
  18637. function eliminateHole( hole, outerNode ) {
  18638. outerNode = findHoleBridge( hole, outerNode );
  18639. if ( outerNode ) {
  18640. const b = splitPolygon( outerNode, hole );
  18641. // filter collinear points around the cuts
  18642. filterPoints( outerNode, outerNode.next );
  18643. filterPoints( b, b.next );
  18644. }
  18645. }
  18646. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18647. function findHoleBridge( hole, outerNode ) {
  18648. let p = outerNode;
  18649. const hx = hole.x;
  18650. const hy = hole.y;
  18651. let qx = - Infinity, m;
  18652. // find a segment intersected by a ray from the hole's leftmost point to the left;
  18653. // segment's endpoint with lesser x will be potential connection point
  18654. do {
  18655. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  18656. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  18657. if ( x <= hx && x > qx ) {
  18658. qx = x;
  18659. if ( x === hx ) {
  18660. if ( hy === p.y ) return p;
  18661. if ( hy === p.next.y ) return p.next;
  18662. }
  18663. m = p.x < p.next.x ? p : p.next;
  18664. }
  18665. }
  18666. p = p.next;
  18667. } while ( p !== outerNode );
  18668. if ( ! m ) return null;
  18669. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  18670. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18671. // if there are no points found, we have a valid connection;
  18672. // otherwise choose the point of the minimum angle with the ray as connection point
  18673. const stop = m,
  18674. mx = m.x,
  18675. my = m.y;
  18676. let tanMin = Infinity, tan;
  18677. p = m;
  18678. do {
  18679. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  18680. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  18681. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  18682. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  18683. m = p;
  18684. tanMin = tan;
  18685. }
  18686. }
  18687. p = p.next;
  18688. } while ( p !== stop );
  18689. return m;
  18690. }
  18691. // whether sector in vertex m contains sector in vertex p in the same coordinates
  18692. function sectorContainsSector( m, p ) {
  18693. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  18694. }
  18695. // interlink polygon nodes in z-order
  18696. function indexCurve( start, minX, minY, invSize ) {
  18697. let p = start;
  18698. do {
  18699. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  18700. p.prevZ = p.prev;
  18701. p.nextZ = p.next;
  18702. p = p.next;
  18703. } while ( p !== start );
  18704. p.prevZ.nextZ = null;
  18705. p.prevZ = null;
  18706. sortLinked( p );
  18707. }
  18708. // Simon Tatham's linked list merge sort algorithm
  18709. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18710. function sortLinked( list ) {
  18711. let i, p, q, e, tail, numMerges, pSize, qSize,
  18712. inSize = 1;
  18713. do {
  18714. p = list;
  18715. list = null;
  18716. tail = null;
  18717. numMerges = 0;
  18718. while ( p ) {
  18719. numMerges ++;
  18720. q = p;
  18721. pSize = 0;
  18722. for ( i = 0; i < inSize; i ++ ) {
  18723. pSize ++;
  18724. q = q.nextZ;
  18725. if ( ! q ) break;
  18726. }
  18727. qSize = inSize;
  18728. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  18729. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  18730. e = p;
  18731. p = p.nextZ;
  18732. pSize --;
  18733. } else {
  18734. e = q;
  18735. q = q.nextZ;
  18736. qSize --;
  18737. }
  18738. if ( tail ) tail.nextZ = e;
  18739. else list = e;
  18740. e.prevZ = tail;
  18741. tail = e;
  18742. }
  18743. p = q;
  18744. }
  18745. tail.nextZ = null;
  18746. inSize *= 2;
  18747. } while ( numMerges > 1 );
  18748. return list;
  18749. }
  18750. // z-order of a point given coords and inverse of the longer side of data bbox
  18751. function zOrder( x, y, minX, minY, invSize ) {
  18752. // coords are transformed into non-negative 15-bit integer range
  18753. x = 32767 * ( x - minX ) * invSize;
  18754. y = 32767 * ( y - minY ) * invSize;
  18755. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  18756. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  18757. x = ( x | ( x << 2 ) ) & 0x33333333;
  18758. x = ( x | ( x << 1 ) ) & 0x55555555;
  18759. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  18760. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  18761. y = ( y | ( y << 2 ) ) & 0x33333333;
  18762. y = ( y | ( y << 1 ) ) & 0x55555555;
  18763. return x | ( y << 1 );
  18764. }
  18765. // find the leftmost node of a polygon ring
  18766. function getLeftmost( start ) {
  18767. let p = start,
  18768. leftmost = start;
  18769. do {
  18770. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  18771. p = p.next;
  18772. } while ( p !== start );
  18773. return leftmost;
  18774. }
  18775. // check if a point lies within a convex triangle
  18776. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  18777. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  18778. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  18779. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  18780. }
  18781. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18782. function isValidDiagonal( a, b ) {
  18783. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  18784. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  18785. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  18786. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  18787. }
  18788. // signed area of a triangle
  18789. function area( p, q, r ) {
  18790. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  18791. }
  18792. // check if two points are equal
  18793. function equals( p1, p2 ) {
  18794. return p1.x === p2.x && p1.y === p2.y;
  18795. }
  18796. // check if two segments intersect
  18797. function intersects( p1, q1, p2, q2 ) {
  18798. const o1 = sign( area( p1, q1, p2 ) );
  18799. const o2 = sign( area( p1, q1, q2 ) );
  18800. const o3 = sign( area( p2, q2, p1 ) );
  18801. const o4 = sign( area( p2, q2, q1 ) );
  18802. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  18803. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18804. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18805. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18806. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18807. return false;
  18808. }
  18809. // for collinear points p, q, r, check if point q lies on segment pr
  18810. function onSegment( p, q, r ) {
  18811. 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 );
  18812. }
  18813. function sign( num ) {
  18814. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  18815. }
  18816. // check if a polygon diagonal intersects any polygon segments
  18817. function intersectsPolygon( a, b ) {
  18818. let p = a;
  18819. do {
  18820. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  18821. intersects( p, p.next, a, b ) ) return true;
  18822. p = p.next;
  18823. } while ( p !== a );
  18824. return false;
  18825. }
  18826. // check if a polygon diagonal is locally inside the polygon
  18827. function locallyInside( a, b ) {
  18828. return area( a.prev, a, a.next ) < 0 ?
  18829. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  18830. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  18831. }
  18832. // check if the middle point of a polygon diagonal is inside the polygon
  18833. function middleInside( a, b ) {
  18834. let p = a,
  18835. inside = false;
  18836. const px = ( a.x + b.x ) / 2,
  18837. py = ( a.y + b.y ) / 2;
  18838. do {
  18839. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  18840. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  18841. inside = ! inside;
  18842. p = p.next;
  18843. } while ( p !== a );
  18844. return inside;
  18845. }
  18846. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18847. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18848. function splitPolygon( a, b ) {
  18849. const a2 = new Node( a.i, a.x, a.y ),
  18850. b2 = new Node( b.i, b.x, b.y ),
  18851. an = a.next,
  18852. bp = b.prev;
  18853. a.next = b;
  18854. b.prev = a;
  18855. a2.next = an;
  18856. an.prev = a2;
  18857. b2.next = a2;
  18858. a2.prev = b2;
  18859. bp.next = b2;
  18860. b2.prev = bp;
  18861. return b2;
  18862. }
  18863. // create a node and optionally link it with previous one (in a circular doubly linked list)
  18864. function insertNode( i, x, y, last ) {
  18865. const p = new Node( i, x, y );
  18866. if ( ! last ) {
  18867. p.prev = p;
  18868. p.next = p;
  18869. } else {
  18870. p.next = last.next;
  18871. p.prev = last;
  18872. last.next.prev = p;
  18873. last.next = p;
  18874. }
  18875. return p;
  18876. }
  18877. function removeNode( p ) {
  18878. p.next.prev = p.prev;
  18879. p.prev.next = p.next;
  18880. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  18881. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  18882. }
  18883. function Node( i, x, y ) {
  18884. // vertex index in coordinates array
  18885. this.i = i;
  18886. // vertex coordinates
  18887. this.x = x;
  18888. this.y = y;
  18889. // previous and next vertex nodes in a polygon ring
  18890. this.prev = null;
  18891. this.next = null;
  18892. // z-order curve value
  18893. this.z = null;
  18894. // previous and next nodes in z-order
  18895. this.prevZ = null;
  18896. this.nextZ = null;
  18897. // indicates whether this is a steiner point
  18898. this.steiner = false;
  18899. }
  18900. function signedArea( data, start, end, dim ) {
  18901. let sum = 0;
  18902. for ( let i = start, j = end - dim; i < end; i += dim ) {
  18903. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  18904. j = i;
  18905. }
  18906. return sum;
  18907. }
  18908. const ShapeUtils = {
  18909. // calculate area of the contour polygon
  18910. area: function ( contour ) {
  18911. const n = contour.length;
  18912. let a = 0.0;
  18913. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  18914. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  18915. }
  18916. return a * 0.5;
  18917. },
  18918. isClockWise: function ( pts ) {
  18919. return ShapeUtils.area( pts ) < 0;
  18920. },
  18921. triangulateShape: function ( contour, holes ) {
  18922. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18923. const holeIndices = []; // array of hole indices
  18924. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18925. removeDupEndPts( contour );
  18926. addContour( vertices, contour );
  18927. //
  18928. let holeIndex = contour.length;
  18929. holes.forEach( removeDupEndPts );
  18930. for ( let i = 0; i < holes.length; i ++ ) {
  18931. holeIndices.push( holeIndex );
  18932. holeIndex += holes[ i ].length;
  18933. addContour( vertices, holes[ i ] );
  18934. }
  18935. //
  18936. const triangles = Earcut.triangulate( vertices, holeIndices );
  18937. //
  18938. for ( let i = 0; i < triangles.length; i += 3 ) {
  18939. faces.push( triangles.slice( i, i + 3 ) );
  18940. }
  18941. return faces;
  18942. }
  18943. };
  18944. function removeDupEndPts( points ) {
  18945. const l = points.length;
  18946. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  18947. points.pop();
  18948. }
  18949. }
  18950. function addContour( vertices, contour ) {
  18951. for ( let i = 0; i < contour.length; i ++ ) {
  18952. vertices.push( contour[ i ].x );
  18953. vertices.push( contour[ i ].y );
  18954. }
  18955. }
  18956. /**
  18957. * Creates extruded geometry from a path shape.
  18958. *
  18959. * parameters = {
  18960. *
  18961. * curveSegments: <int>, // number of points on the curves
  18962. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18963. * depth: <float>, // Depth to extrude the shape
  18964. *
  18965. * bevelEnabled: <bool>, // turn on bevel
  18966. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18967. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18968. * bevelOffset: <float>, // how far from shape outline does bevel start
  18969. * bevelSegments: <int>, // number of bevel layers
  18970. *
  18971. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18972. *
  18973. * UVGenerator: <Object> // object that provides UV generator functions
  18974. *
  18975. * }
  18976. */
  18977. class ExtrudeBufferGeometry extends BufferGeometry {
  18978. constructor( shapes, options ) {
  18979. super();
  18980. this.type = 'ExtrudeBufferGeometry';
  18981. this.parameters = {
  18982. shapes: shapes,
  18983. options: options
  18984. };
  18985. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18986. const scope = this;
  18987. const verticesArray = [];
  18988. const uvArray = [];
  18989. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18990. const shape = shapes[ i ];
  18991. addShape( shape );
  18992. }
  18993. // build geometry
  18994. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  18995. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  18996. this.computeVertexNormals();
  18997. // functions
  18998. function addShape( shape ) {
  18999. const placeholder = [];
  19000. // options
  19001. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19002. const steps = options.steps !== undefined ? options.steps : 1;
  19003. let depth = options.depth !== undefined ? options.depth : 100;
  19004. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19005. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19006. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19007. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19008. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19009. const extrudePath = options.extrudePath;
  19010. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19011. // deprecated options
  19012. if ( options.amount !== undefined ) {
  19013. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  19014. depth = options.amount;
  19015. }
  19016. //
  19017. let extrudePts, extrudeByPath = false;
  19018. let splineTube, binormal, normal, position2;
  19019. if ( extrudePath ) {
  19020. extrudePts = extrudePath.getSpacedPoints( steps );
  19021. extrudeByPath = true;
  19022. bevelEnabled = false; // bevels not supported for path extrusion
  19023. // SETUP TNB variables
  19024. // TODO1 - have a .isClosed in spline?
  19025. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19026. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19027. binormal = new Vector3();
  19028. normal = new Vector3();
  19029. position2 = new Vector3();
  19030. }
  19031. // Safeguards if bevels are not enabled
  19032. if ( ! bevelEnabled ) {
  19033. bevelSegments = 0;
  19034. bevelThickness = 0;
  19035. bevelSize = 0;
  19036. bevelOffset = 0;
  19037. }
  19038. // Variables initialization
  19039. const shapePoints = shape.extractPoints( curveSegments );
  19040. let vertices = shapePoints.shape;
  19041. const holes = shapePoints.holes;
  19042. const reverse = ! ShapeUtils.isClockWise( vertices );
  19043. if ( reverse ) {
  19044. vertices = vertices.reverse();
  19045. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19046. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19047. const ahole = holes[ h ];
  19048. if ( ShapeUtils.isClockWise( ahole ) ) {
  19049. holes[ h ] = ahole.reverse();
  19050. }
  19051. }
  19052. }
  19053. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19054. /* Vertices */
  19055. const contour = vertices; // vertices has all points but contour has only points of circumference
  19056. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19057. const ahole = holes[ h ];
  19058. vertices = vertices.concat( ahole );
  19059. }
  19060. function scalePt2( pt, vec, size ) {
  19061. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19062. return vec.clone().multiplyScalar( size ).add( pt );
  19063. }
  19064. const vlen = vertices.length, flen = faces.length;
  19065. // Find directions for point movement
  19066. function getBevelVec( inPt, inPrev, inNext ) {
  19067. // computes for inPt the corresponding point inPt' on a new contour
  19068. // shifted by 1 unit (length of normalized vector) to the left
  19069. // if we walk along contour clockwise, this new contour is outside the old one
  19070. //
  19071. // inPt' is the intersection of the two lines parallel to the two
  19072. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19073. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19074. // good reading for geometry algorithms (here: line-line intersection)
  19075. // http://geomalgorithms.com/a05-_intersect-1.html
  19076. const v_prev_x = inPt.x - inPrev.x,
  19077. v_prev_y = inPt.y - inPrev.y;
  19078. const v_next_x = inNext.x - inPt.x,
  19079. v_next_y = inNext.y - inPt.y;
  19080. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19081. // check for collinear edges
  19082. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19083. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19084. // not collinear
  19085. // length of vectors for normalizing
  19086. const v_prev_len = Math.sqrt( v_prev_lensq );
  19087. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19088. // shift adjacent points by unit vectors to the left
  19089. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19090. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19091. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19092. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19093. // scaling factor for v_prev to intersection point
  19094. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19095. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19096. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19097. // vector from inPt to intersection point
  19098. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19099. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19100. // Don't normalize!, otherwise sharp corners become ugly
  19101. // but prevent crazy spikes
  19102. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19103. if ( v_trans_lensq <= 2 ) {
  19104. return new Vector2$1( v_trans_x, v_trans_y );
  19105. } else {
  19106. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19107. }
  19108. } else {
  19109. // handle special case of collinear edges
  19110. let direction_eq = false; // assumes: opposite
  19111. if ( v_prev_x > Number.EPSILON ) {
  19112. if ( v_next_x > Number.EPSILON ) {
  19113. direction_eq = true;
  19114. }
  19115. } else {
  19116. if ( v_prev_x < - Number.EPSILON ) {
  19117. if ( v_next_x < - Number.EPSILON ) {
  19118. direction_eq = true;
  19119. }
  19120. } else {
  19121. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19122. direction_eq = true;
  19123. }
  19124. }
  19125. }
  19126. if ( direction_eq ) {
  19127. // console.log("Warning: lines are a straight sequence");
  19128. v_trans_x = - v_prev_y;
  19129. v_trans_y = v_prev_x;
  19130. shrink_by = Math.sqrt( v_prev_lensq );
  19131. } else {
  19132. // console.log("Warning: lines are a straight spike");
  19133. v_trans_x = v_prev_x;
  19134. v_trans_y = v_prev_y;
  19135. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19136. }
  19137. }
  19138. return new Vector2$1( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19139. }
  19140. const contourMovements = [];
  19141. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19142. if ( j === il ) j = 0;
  19143. if ( k === il ) k = 0;
  19144. // (j)---(i)---(k)
  19145. // console.log('i,j,k', i, j , k)
  19146. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19147. }
  19148. const holesMovements = [];
  19149. let oneHoleMovements, verticesMovements = contourMovements.concat();
  19150. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19151. const ahole = holes[ h ];
  19152. oneHoleMovements = [];
  19153. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19154. if ( j === il ) j = 0;
  19155. if ( k === il ) k = 0;
  19156. // (j)---(i)---(k)
  19157. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19158. }
  19159. holesMovements.push( oneHoleMovements );
  19160. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19161. }
  19162. // Loop bevelSegments, 1 for the front, 1 for the back
  19163. for ( let b = 0; b < bevelSegments; b ++ ) {
  19164. //for ( b = bevelSegments; b > 0; b -- ) {
  19165. const t = b / bevelSegments;
  19166. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19167. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19168. // contract shape
  19169. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19170. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19171. v( vert.x, vert.y, - z );
  19172. }
  19173. // expand holes
  19174. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19175. const ahole = holes[ h ];
  19176. oneHoleMovements = holesMovements[ h ];
  19177. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19178. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19179. v( vert.x, vert.y, - z );
  19180. }
  19181. }
  19182. }
  19183. const bs = bevelSize + bevelOffset;
  19184. // Back facing vertices
  19185. for ( let i = 0; i < vlen; i ++ ) {
  19186. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19187. if ( ! extrudeByPath ) {
  19188. v( vert.x, vert.y, 0 );
  19189. } else {
  19190. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19191. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19192. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19193. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19194. v( position2.x, position2.y, position2.z );
  19195. }
  19196. }
  19197. // Add stepped vertices...
  19198. // Including front facing vertices
  19199. for ( let s = 1; s <= steps; s ++ ) {
  19200. for ( let i = 0; i < vlen; i ++ ) {
  19201. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19202. if ( ! extrudeByPath ) {
  19203. v( vert.x, vert.y, depth / steps * s );
  19204. } else {
  19205. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19206. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19207. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19208. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19209. v( position2.x, position2.y, position2.z );
  19210. }
  19211. }
  19212. }
  19213. // Add bevel segments planes
  19214. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19215. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  19216. const t = b / bevelSegments;
  19217. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19218. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19219. // contract shape
  19220. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19221. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19222. v( vert.x, vert.y, depth + z );
  19223. }
  19224. // expand holes
  19225. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19226. const ahole = holes[ h ];
  19227. oneHoleMovements = holesMovements[ h ];
  19228. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19229. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19230. if ( ! extrudeByPath ) {
  19231. v( vert.x, vert.y, depth + z );
  19232. } else {
  19233. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19234. }
  19235. }
  19236. }
  19237. }
  19238. /* Faces */
  19239. // Top and bottom faces
  19240. buildLidFaces();
  19241. // Sides faces
  19242. buildSideFaces();
  19243. ///// Internal functions
  19244. function buildLidFaces() {
  19245. const start = verticesArray.length / 3;
  19246. if ( bevelEnabled ) {
  19247. let layer = 0; // steps + 1
  19248. let offset = vlen * layer;
  19249. // Bottom faces
  19250. for ( let i = 0; i < flen; i ++ ) {
  19251. const face = faces[ i ];
  19252. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19253. }
  19254. layer = steps + bevelSegments * 2;
  19255. offset = vlen * layer;
  19256. // Top faces
  19257. for ( let i = 0; i < flen; i ++ ) {
  19258. const face = faces[ i ];
  19259. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19260. }
  19261. } else {
  19262. // Bottom faces
  19263. for ( let i = 0; i < flen; i ++ ) {
  19264. const face = faces[ i ];
  19265. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19266. }
  19267. // Top faces
  19268. for ( let i = 0; i < flen; i ++ ) {
  19269. const face = faces[ i ];
  19270. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19271. }
  19272. }
  19273. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  19274. }
  19275. // Create faces for the z-sides of the shape
  19276. function buildSideFaces() {
  19277. const start = verticesArray.length / 3;
  19278. let layeroffset = 0;
  19279. sidewalls( contour, layeroffset );
  19280. layeroffset += contour.length;
  19281. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19282. const ahole = holes[ h ];
  19283. sidewalls( ahole, layeroffset );
  19284. //, true
  19285. layeroffset += ahole.length;
  19286. }
  19287. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  19288. }
  19289. function sidewalls( contour, layeroffset ) {
  19290. let i = contour.length;
  19291. while ( -- i >= 0 ) {
  19292. const j = i;
  19293. let k = i - 1;
  19294. if ( k < 0 ) k = contour.length - 1;
  19295. //console.log('b', i,j, i-1, k,vertices.length);
  19296. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  19297. const slen1 = vlen * s;
  19298. const slen2 = vlen * ( s + 1 );
  19299. const a = layeroffset + j + slen1,
  19300. b = layeroffset + k + slen1,
  19301. c = layeroffset + k + slen2,
  19302. d = layeroffset + j + slen2;
  19303. f4( a, b, c, d );
  19304. }
  19305. }
  19306. }
  19307. function v( x, y, z ) {
  19308. placeholder.push( x );
  19309. placeholder.push( y );
  19310. placeholder.push( z );
  19311. }
  19312. function f3( a, b, c ) {
  19313. addVertex( a );
  19314. addVertex( b );
  19315. addVertex( c );
  19316. const nextIndex = verticesArray.length / 3;
  19317. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19318. addUV( uvs[ 0 ] );
  19319. addUV( uvs[ 1 ] );
  19320. addUV( uvs[ 2 ] );
  19321. }
  19322. function f4( a, b, c, d ) {
  19323. addVertex( a );
  19324. addVertex( b );
  19325. addVertex( d );
  19326. addVertex( b );
  19327. addVertex( c );
  19328. addVertex( d );
  19329. const nextIndex = verticesArray.length / 3;
  19330. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19331. addUV( uvs[ 0 ] );
  19332. addUV( uvs[ 1 ] );
  19333. addUV( uvs[ 3 ] );
  19334. addUV( uvs[ 1 ] );
  19335. addUV( uvs[ 2 ] );
  19336. addUV( uvs[ 3 ] );
  19337. }
  19338. function addVertex( index ) {
  19339. verticesArray.push( placeholder[ index * 3 + 0 ] );
  19340. verticesArray.push( placeholder[ index * 3 + 1 ] );
  19341. verticesArray.push( placeholder[ index * 3 + 2 ] );
  19342. }
  19343. function addUV( vector2 ) {
  19344. uvArray.push( vector2.x );
  19345. uvArray.push( vector2.y );
  19346. }
  19347. }
  19348. }
  19349. toJSON() {
  19350. const data = BufferGeometry.prototype.toJSON.call( this );
  19351. const shapes = this.parameters.shapes;
  19352. const options = this.parameters.options;
  19353. return toJSON( shapes, options, data );
  19354. }
  19355. }
  19356. const WorldUVGenerator = {
  19357. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  19358. const a_x = vertices[ indexA * 3 ];
  19359. const a_y = vertices[ indexA * 3 + 1 ];
  19360. const b_x = vertices[ indexB * 3 ];
  19361. const b_y = vertices[ indexB * 3 + 1 ];
  19362. const c_x = vertices[ indexC * 3 ];
  19363. const c_y = vertices[ indexC * 3 + 1 ];
  19364. return [
  19365. new Vector2$1( a_x, a_y ),
  19366. new Vector2$1( b_x, b_y ),
  19367. new Vector2$1( c_x, c_y )
  19368. ];
  19369. },
  19370. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  19371. const a_x = vertices[ indexA * 3 ];
  19372. const a_y = vertices[ indexA * 3 + 1 ];
  19373. const a_z = vertices[ indexA * 3 + 2 ];
  19374. const b_x = vertices[ indexB * 3 ];
  19375. const b_y = vertices[ indexB * 3 + 1 ];
  19376. const b_z = vertices[ indexB * 3 + 2 ];
  19377. const c_x = vertices[ indexC * 3 ];
  19378. const c_y = vertices[ indexC * 3 + 1 ];
  19379. const c_z = vertices[ indexC * 3 + 2 ];
  19380. const d_x = vertices[ indexD * 3 ];
  19381. const d_y = vertices[ indexD * 3 + 1 ];
  19382. const d_z = vertices[ indexD * 3 + 2 ];
  19383. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  19384. return [
  19385. new Vector2$1( a_x, 1 - a_z ),
  19386. new Vector2$1( b_x, 1 - b_z ),
  19387. new Vector2$1( c_x, 1 - c_z ),
  19388. new Vector2$1( d_x, 1 - d_z )
  19389. ];
  19390. } else {
  19391. return [
  19392. new Vector2$1( a_y, 1 - a_z ),
  19393. new Vector2$1( b_y, 1 - b_z ),
  19394. new Vector2$1( c_y, 1 - c_z ),
  19395. new Vector2$1( d_y, 1 - d_z )
  19396. ];
  19397. }
  19398. }
  19399. };
  19400. function toJSON( shapes, options, data ) {
  19401. data.shapes = [];
  19402. if ( Array.isArray( shapes ) ) {
  19403. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19404. const shape = shapes[ i ];
  19405. data.shapes.push( shape.uuid );
  19406. }
  19407. } else {
  19408. data.shapes.push( shapes.uuid );
  19409. }
  19410. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19411. return data;
  19412. }
  19413. /**
  19414. * Creates extruded geometry from a path shape.
  19415. *
  19416. * parameters = {
  19417. *
  19418. * curveSegments: <int>, // number of points on the curves
  19419. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19420. * depth: <float>, // Depth to extrude the shape
  19421. *
  19422. * bevelEnabled: <bool>, // turn on bevel
  19423. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19424. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19425. * bevelOffset: <float>, // how far from shape outline does bevel start
  19426. * bevelSegments: <int>, // number of bevel layers
  19427. *
  19428. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19429. *
  19430. * UVGenerator: <Object> // object that provides UV generator functions
  19431. *
  19432. * }
  19433. */
  19434. class ExtrudeGeometry extends Geometry {
  19435. constructor( shapes, options ) {
  19436. super();
  19437. this.type = 'ExtrudeGeometry';
  19438. this.parameters = {
  19439. shapes: shapes,
  19440. options: options
  19441. };
  19442. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  19443. this.mergeVertices();
  19444. }
  19445. toJSON() {
  19446. const data = super.toJSON();
  19447. const shapes = this.parameters.shapes;
  19448. const options = this.parameters.options;
  19449. return toJSON$1( shapes, options, data );
  19450. }
  19451. }
  19452. function toJSON$1( shapes, options, data ) {
  19453. data.shapes = [];
  19454. if ( Array.isArray( shapes ) ) {
  19455. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19456. const shape = shapes[ i ];
  19457. data.shapes.push( shape.uuid );
  19458. }
  19459. } else {
  19460. data.shapes.push( shapes.uuid );
  19461. }
  19462. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19463. return data;
  19464. }
  19465. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  19466. constructor( radius = 1, detail = 0 ) {
  19467. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19468. const vertices = [
  19469. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19470. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19471. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19472. ];
  19473. const indices = [
  19474. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19475. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19476. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19477. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19478. ];
  19479. super( vertices, indices, radius, detail );
  19480. this.type = 'IcosahedronBufferGeometry';
  19481. this.parameters = {
  19482. radius: radius,
  19483. detail: detail
  19484. };
  19485. }
  19486. }
  19487. class IcosahedronGeometry extends Geometry {
  19488. constructor( radius, detail ) {
  19489. super();
  19490. this.type = 'IcosahedronGeometry';
  19491. this.parameters = {
  19492. radius: radius,
  19493. detail: detail
  19494. };
  19495. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19496. this.mergeVertices();
  19497. }
  19498. }
  19499. class LatheBufferGeometry extends BufferGeometry {
  19500. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  19501. super();
  19502. this.type = 'LatheBufferGeometry';
  19503. this.parameters = {
  19504. points: points,
  19505. segments: segments,
  19506. phiStart: phiStart,
  19507. phiLength: phiLength
  19508. };
  19509. segments = Math.floor( segments );
  19510. // clamp phiLength so it's in range of [ 0, 2PI ]
  19511. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  19512. // buffers
  19513. const indices = [];
  19514. const vertices = [];
  19515. const uvs = [];
  19516. // helper variables
  19517. const inverseSegments = 1.0 / segments;
  19518. const vertex = new Vector3();
  19519. const uv = new Vector2$1();
  19520. // generate vertices and uvs
  19521. for ( let i = 0; i <= segments; i ++ ) {
  19522. const phi = phiStart + i * inverseSegments * phiLength;
  19523. const sin = Math.sin( phi );
  19524. const cos = Math.cos( phi );
  19525. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19526. // vertex
  19527. vertex.x = points[ j ].x * sin;
  19528. vertex.y = points[ j ].y;
  19529. vertex.z = points[ j ].x * cos;
  19530. vertices.push( vertex.x, vertex.y, vertex.z );
  19531. // uv
  19532. uv.x = i / segments;
  19533. uv.y = j / ( points.length - 1 );
  19534. uvs.push( uv.x, uv.y );
  19535. }
  19536. }
  19537. // indices
  19538. for ( let i = 0; i < segments; i ++ ) {
  19539. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19540. const base = j + i * points.length;
  19541. const a = base;
  19542. const b = base + points.length;
  19543. const c = base + points.length + 1;
  19544. const d = base + 1;
  19545. // faces
  19546. indices.push( a, b, d );
  19547. indices.push( b, c, d );
  19548. }
  19549. }
  19550. // build geometry
  19551. this.setIndex( indices );
  19552. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19553. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19554. // generate normals
  19555. this.computeVertexNormals();
  19556. // if the geometry is closed, we need to average the normals along the seam.
  19557. // because the corresponding vertices are identical (but still have different UVs).
  19558. if ( phiLength === Math.PI * 2 ) {
  19559. const normals = this.attributes.normal.array;
  19560. const n1 = new Vector3();
  19561. const n2 = new Vector3();
  19562. const n = new Vector3();
  19563. // this is the buffer offset for the last line of vertices
  19564. const base = segments * points.length * 3;
  19565. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  19566. // select the normal of the vertex in the first line
  19567. n1.x = normals[ j + 0 ];
  19568. n1.y = normals[ j + 1 ];
  19569. n1.z = normals[ j + 2 ];
  19570. // select the normal of the vertex in the last line
  19571. n2.x = normals[ base + j + 0 ];
  19572. n2.y = normals[ base + j + 1 ];
  19573. n2.z = normals[ base + j + 2 ];
  19574. // average normals
  19575. n.addVectors( n1, n2 ).normalize();
  19576. // assign the new values to both normals
  19577. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  19578. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  19579. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  19580. }
  19581. }
  19582. }
  19583. }
  19584. class LatheGeometry extends Geometry {
  19585. constructor( points, segments, phiStart, phiLength ) {
  19586. super();
  19587. this.type = 'LatheGeometry';
  19588. this.parameters = {
  19589. points: points,
  19590. segments: segments,
  19591. phiStart: phiStart,
  19592. phiLength: phiLength
  19593. };
  19594. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  19595. this.mergeVertices();
  19596. }
  19597. }
  19598. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  19599. constructor( radius = 1, detail = 0 ) {
  19600. const vertices = [
  19601. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  19602. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19603. ];
  19604. const indices = [
  19605. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  19606. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  19607. 1, 3, 4, 1, 4, 2
  19608. ];
  19609. super( vertices, indices, radius, detail );
  19610. this.type = 'OctahedronBufferGeometry';
  19611. this.parameters = {
  19612. radius: radius,
  19613. detail: detail
  19614. };
  19615. }
  19616. }
  19617. class OctahedronGeometry extends Geometry {
  19618. constructor( radius, detail ) {
  19619. super();
  19620. this.type = 'OctahedronGeometry';
  19621. this.parameters = {
  19622. radius: radius,
  19623. detail: detail
  19624. };
  19625. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19626. this.mergeVertices();
  19627. }
  19628. }
  19629. /**
  19630. * Parametric Surfaces Geometry
  19631. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19632. */
  19633. function ParametricBufferGeometry( func, slices, stacks ) {
  19634. BufferGeometry.call( this );
  19635. this.type = 'ParametricBufferGeometry';
  19636. this.parameters = {
  19637. func: func,
  19638. slices: slices,
  19639. stacks: stacks
  19640. };
  19641. // buffers
  19642. const indices = [];
  19643. const vertices = [];
  19644. const normals = [];
  19645. const uvs = [];
  19646. const EPS = 0.00001;
  19647. const normal = new Vector3();
  19648. const p0 = new Vector3(), p1 = new Vector3();
  19649. const pu = new Vector3(), pv = new Vector3();
  19650. if ( func.length < 3 ) {
  19651. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  19652. }
  19653. // generate vertices, normals and uvs
  19654. const sliceCount = slices + 1;
  19655. for ( let i = 0; i <= stacks; i ++ ) {
  19656. const v = i / stacks;
  19657. for ( let j = 0; j <= slices; j ++ ) {
  19658. const u = j / slices;
  19659. // vertex
  19660. func( u, v, p0 );
  19661. vertices.push( p0.x, p0.y, p0.z );
  19662. // normal
  19663. // approximate tangent vectors via finite differences
  19664. if ( u - EPS >= 0 ) {
  19665. func( u - EPS, v, p1 );
  19666. pu.subVectors( p0, p1 );
  19667. } else {
  19668. func( u + EPS, v, p1 );
  19669. pu.subVectors( p1, p0 );
  19670. }
  19671. if ( v - EPS >= 0 ) {
  19672. func( u, v - EPS, p1 );
  19673. pv.subVectors( p0, p1 );
  19674. } else {
  19675. func( u, v + EPS, p1 );
  19676. pv.subVectors( p1, p0 );
  19677. }
  19678. // cross product of tangent vectors returns surface normal
  19679. normal.crossVectors( pu, pv ).normalize();
  19680. normals.push( normal.x, normal.y, normal.z );
  19681. // uv
  19682. uvs.push( u, v );
  19683. }
  19684. }
  19685. // generate indices
  19686. for ( let i = 0; i < stacks; i ++ ) {
  19687. for ( let j = 0; j < slices; j ++ ) {
  19688. const a = i * sliceCount + j;
  19689. const b = i * sliceCount + j + 1;
  19690. const c = ( i + 1 ) * sliceCount + j + 1;
  19691. const d = ( i + 1 ) * sliceCount + j;
  19692. // faces one and two
  19693. indices.push( a, b, d );
  19694. indices.push( b, c, d );
  19695. }
  19696. }
  19697. // build geometry
  19698. this.setIndex( indices );
  19699. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19700. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19701. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19702. }
  19703. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19704. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19705. /**
  19706. * Parametric Surfaces Geometry
  19707. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19708. */
  19709. function ParametricGeometry( func, slices, stacks ) {
  19710. Geometry.call( this );
  19711. this.type = 'ParametricGeometry';
  19712. this.parameters = {
  19713. func: func,
  19714. slices: slices,
  19715. stacks: stacks
  19716. };
  19717. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19718. this.mergeVertices();
  19719. }
  19720. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19721. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19722. class PlaneGeometry extends Geometry {
  19723. constructor( width, height, widthSegments, heightSegments ) {
  19724. super();
  19725. this.type = 'PlaneGeometry';
  19726. this.parameters = {
  19727. width: width,
  19728. height: height,
  19729. widthSegments: widthSegments,
  19730. heightSegments: heightSegments
  19731. };
  19732. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19733. this.mergeVertices();
  19734. }
  19735. }
  19736. class PolyhedronGeometry extends Geometry {
  19737. constructor( vertices, indices, radius, detail ) {
  19738. super();
  19739. this.type = 'PolyhedronGeometry';
  19740. this.parameters = {
  19741. vertices: vertices,
  19742. indices: indices,
  19743. radius: radius,
  19744. detail: detail
  19745. };
  19746. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19747. this.mergeVertices();
  19748. }
  19749. }
  19750. class RingBufferGeometry extends BufferGeometry {
  19751. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19752. super();
  19753. this.type = 'RingBufferGeometry';
  19754. this.parameters = {
  19755. innerRadius: innerRadius,
  19756. outerRadius: outerRadius,
  19757. thetaSegments: thetaSegments,
  19758. phiSegments: phiSegments,
  19759. thetaStart: thetaStart,
  19760. thetaLength: thetaLength
  19761. };
  19762. thetaSegments = Math.max( 3, thetaSegments );
  19763. phiSegments = Math.max( 1, phiSegments );
  19764. // buffers
  19765. const indices = [];
  19766. const vertices = [];
  19767. const normals = [];
  19768. const uvs = [];
  19769. // some helper variables
  19770. let radius = innerRadius;
  19771. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19772. const vertex = new Vector3();
  19773. const uv = new Vector2$1();
  19774. // generate vertices, normals and uvs
  19775. for ( let j = 0; j <= phiSegments; j ++ ) {
  19776. for ( let i = 0; i <= thetaSegments; i ++ ) {
  19777. // values are generate from the inside of the ring to the outside
  19778. const segment = thetaStart + i / thetaSegments * thetaLength;
  19779. // vertex
  19780. vertex.x = radius * Math.cos( segment );
  19781. vertex.y = radius * Math.sin( segment );
  19782. vertices.push( vertex.x, vertex.y, vertex.z );
  19783. // normal
  19784. normals.push( 0, 0, 1 );
  19785. // uv
  19786. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  19787. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  19788. uvs.push( uv.x, uv.y );
  19789. }
  19790. // increase the radius for next row of vertices
  19791. radius += radiusStep;
  19792. }
  19793. // indices
  19794. for ( let j = 0; j < phiSegments; j ++ ) {
  19795. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  19796. for ( let i = 0; i < thetaSegments; i ++ ) {
  19797. const segment = i + thetaSegmentLevel;
  19798. const a = segment;
  19799. const b = segment + thetaSegments + 1;
  19800. const c = segment + thetaSegments + 2;
  19801. const d = segment + 1;
  19802. // faces
  19803. indices.push( a, b, d );
  19804. indices.push( b, c, d );
  19805. }
  19806. }
  19807. // build geometry
  19808. this.setIndex( indices );
  19809. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19810. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19811. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19812. }
  19813. }
  19814. class RingGeometry extends Geometry {
  19815. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19816. super();
  19817. this.type = 'RingGeometry';
  19818. this.parameters = {
  19819. innerRadius: innerRadius,
  19820. outerRadius: outerRadius,
  19821. thetaSegments: thetaSegments,
  19822. phiSegments: phiSegments,
  19823. thetaStart: thetaStart,
  19824. thetaLength: thetaLength
  19825. };
  19826. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  19827. this.mergeVertices();
  19828. }
  19829. }
  19830. class ShapeBufferGeometry extends BufferGeometry {
  19831. constructor( shapes, curveSegments = 12 ) {
  19832. super();
  19833. this.type = 'ShapeBufferGeometry';
  19834. this.parameters = {
  19835. shapes: shapes,
  19836. curveSegments: curveSegments
  19837. };
  19838. // buffers
  19839. const indices = [];
  19840. const vertices = [];
  19841. const normals = [];
  19842. const uvs = [];
  19843. // helper variables
  19844. let groupStart = 0;
  19845. let groupCount = 0;
  19846. // allow single and array values for "shapes" parameter
  19847. if ( Array.isArray( shapes ) === false ) {
  19848. addShape( shapes );
  19849. } else {
  19850. for ( let i = 0; i < shapes.length; i ++ ) {
  19851. addShape( shapes[ i ] );
  19852. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  19853. groupStart += groupCount;
  19854. groupCount = 0;
  19855. }
  19856. }
  19857. // build geometry
  19858. this.setIndex( indices );
  19859. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19860. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19861. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19862. // helper functions
  19863. function addShape( shape ) {
  19864. const indexOffset = vertices.length / 3;
  19865. const points = shape.extractPoints( curveSegments );
  19866. let shapeVertices = points.shape;
  19867. const shapeHoles = points.holes;
  19868. // check direction of vertices
  19869. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  19870. shapeVertices = shapeVertices.reverse();
  19871. }
  19872. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19873. const shapeHole = shapeHoles[ i ];
  19874. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  19875. shapeHoles[ i ] = shapeHole.reverse();
  19876. }
  19877. }
  19878. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  19879. // join vertices of inner and outer paths to a single array
  19880. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19881. const shapeHole = shapeHoles[ i ];
  19882. shapeVertices = shapeVertices.concat( shapeHole );
  19883. }
  19884. // vertices, normals, uvs
  19885. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  19886. const vertex = shapeVertices[ i ];
  19887. vertices.push( vertex.x, vertex.y, 0 );
  19888. normals.push( 0, 0, 1 );
  19889. uvs.push( vertex.x, vertex.y ); // world uvs
  19890. }
  19891. // incides
  19892. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  19893. const face = faces[ i ];
  19894. const a = face[ 0 ] + indexOffset;
  19895. const b = face[ 1 ] + indexOffset;
  19896. const c = face[ 2 ] + indexOffset;
  19897. indices.push( a, b, c );
  19898. groupCount += 3;
  19899. }
  19900. }
  19901. }
  19902. toJSON() {
  19903. const data = BufferGeometry.prototype.toJSON.call( this );
  19904. const shapes = this.parameters.shapes;
  19905. return toJSON$2( shapes, data );
  19906. }
  19907. }
  19908. function toJSON$2( shapes, data ) {
  19909. data.shapes = [];
  19910. if ( Array.isArray( shapes ) ) {
  19911. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19912. const shape = shapes[ i ];
  19913. data.shapes.push( shape.uuid );
  19914. }
  19915. } else {
  19916. data.shapes.push( shapes.uuid );
  19917. }
  19918. return data;
  19919. }
  19920. class ShapeGeometry extends Geometry {
  19921. constructor( shapes, curveSegments ) {
  19922. super();
  19923. this.type = 'ShapeGeometry';
  19924. if ( typeof curveSegments === 'object' ) {
  19925. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  19926. curveSegments = curveSegments.curveSegments;
  19927. }
  19928. this.parameters = {
  19929. shapes: shapes,
  19930. curveSegments: curveSegments
  19931. };
  19932. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  19933. this.mergeVertices();
  19934. }
  19935. toJSON() {
  19936. const data = Geometry.prototype.toJSON.call( this );
  19937. const shapes = this.parameters.shapes;
  19938. return toJSON$3( shapes, data );
  19939. }
  19940. }
  19941. function toJSON$3( shapes, data ) {
  19942. data.shapes = [];
  19943. if ( Array.isArray( shapes ) ) {
  19944. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19945. const shape = shapes[ i ];
  19946. data.shapes.push( shape.uuid );
  19947. }
  19948. } else {
  19949. data.shapes.push( shapes.uuid );
  19950. }
  19951. return data;
  19952. }
  19953. class SphereBufferGeometry extends BufferGeometry {
  19954. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  19955. super();
  19956. this.type = 'SphereBufferGeometry';
  19957. this.parameters = {
  19958. radius: radius,
  19959. widthSegments: widthSegments,
  19960. heightSegments: heightSegments,
  19961. phiStart: phiStart,
  19962. phiLength: phiLength,
  19963. thetaStart: thetaStart,
  19964. thetaLength: thetaLength
  19965. };
  19966. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  19967. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  19968. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  19969. let index = 0;
  19970. const grid = [];
  19971. const vertex = new Vector3();
  19972. const normal = new Vector3();
  19973. // buffers
  19974. const indices = [];
  19975. const vertices = [];
  19976. const normals = [];
  19977. const uvs = [];
  19978. // generate vertices, normals and uvs
  19979. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  19980. const verticesRow = [];
  19981. const v = iy / heightSegments;
  19982. // special case for the poles
  19983. let uOffset = 0;
  19984. if ( iy == 0 && thetaStart == 0 ) {
  19985. uOffset = 0.5 / widthSegments;
  19986. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  19987. uOffset = - 0.5 / widthSegments;
  19988. }
  19989. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  19990. const u = ix / widthSegments;
  19991. // vertex
  19992. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19993. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19994. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19995. vertices.push( vertex.x, vertex.y, vertex.z );
  19996. // normal
  19997. normal.copy( vertex ).normalize();
  19998. normals.push( normal.x, normal.y, normal.z );
  19999. // uv
  20000. uvs.push( u + uOffset, 1 - v );
  20001. verticesRow.push( index ++ );
  20002. }
  20003. grid.push( verticesRow );
  20004. }
  20005. // indices
  20006. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20007. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20008. const a = grid[ iy ][ ix + 1 ];
  20009. const b = grid[ iy ][ ix ];
  20010. const c = grid[ iy + 1 ][ ix ];
  20011. const d = grid[ iy + 1 ][ ix + 1 ];
  20012. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20013. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20014. }
  20015. }
  20016. // build geometry
  20017. this.setIndex( indices );
  20018. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20019. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20020. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20021. }
  20022. }
  20023. class SphereGeometry extends Geometry {
  20024. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20025. super();
  20026. this.type = 'SphereGeometry';
  20027. this.parameters = {
  20028. radius: radius,
  20029. widthSegments: widthSegments,
  20030. heightSegments: heightSegments,
  20031. phiStart: phiStart,
  20032. phiLength: phiLength,
  20033. thetaStart: thetaStart,
  20034. thetaLength: thetaLength
  20035. };
  20036. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  20037. this.mergeVertices();
  20038. }
  20039. }
  20040. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  20041. constructor( radius = 1, detail = 0 ) {
  20042. const vertices = [
  20043. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20044. ];
  20045. const indices = [
  20046. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20047. ];
  20048. super( vertices, indices, radius, detail );
  20049. this.type = 'TetrahedronBufferGeometry';
  20050. this.parameters = {
  20051. radius: radius,
  20052. detail: detail
  20053. };
  20054. }
  20055. }
  20056. class TetrahedronGeometry extends Geometry {
  20057. constructor( radius, detail ) {
  20058. super();
  20059. this.type = 'TetrahedronGeometry';
  20060. this.parameters = {
  20061. radius: radius,
  20062. detail: detail
  20063. };
  20064. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  20065. this.mergeVertices();
  20066. }
  20067. }
  20068. /**
  20069. * Text = 3D Text
  20070. *
  20071. * parameters = {
  20072. * font: <THREE.Font>, // font
  20073. *
  20074. * size: <float>, // size of the text
  20075. * height: <float>, // thickness to extrude text
  20076. * curveSegments: <int>, // number of points on the curves
  20077. *
  20078. * bevelEnabled: <bool>, // turn on bevel
  20079. * bevelThickness: <float>, // how deep into text bevel goes
  20080. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20081. * bevelOffset: <float> // how far from text outline does bevel start
  20082. * }
  20083. */
  20084. class TextBufferGeometry extends ExtrudeBufferGeometry {
  20085. constructor( text, parameters = {} ) {
  20086. const font = parameters.font;
  20087. if ( ! ( font && font.isFont ) ) {
  20088. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20089. return new BufferGeometry();
  20090. }
  20091. const shapes = font.generateShapes( text, parameters.size );
  20092. // translate parameters to ExtrudeGeometry API
  20093. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  20094. // defaults
  20095. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20096. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20097. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20098. super( shapes, parameters );
  20099. this.type = 'TextBufferGeometry';
  20100. }
  20101. }
  20102. /**
  20103. * Text = 3D Text
  20104. *
  20105. * parameters = {
  20106. * font: <THREE.Font>, // font
  20107. *
  20108. * size: <float>, // size of the text
  20109. * height: <float>, // thickness to extrude text
  20110. * curveSegments: <int>, // number of points on the curves
  20111. *
  20112. * bevelEnabled: <bool>, // turn on bevel
  20113. * bevelThickness: <float>, // how deep into text bevel goes
  20114. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20115. * bevelOffset: <float> // how far from text outline does bevel start
  20116. * }
  20117. */
  20118. class TextGeometry extends Geometry {
  20119. constructor( text, parameters ) {
  20120. super();
  20121. this.type = 'TextGeometry';
  20122. this.parameters = {
  20123. text: text,
  20124. parameters: parameters
  20125. };
  20126. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  20127. this.mergeVertices();
  20128. }
  20129. }
  20130. class TorusBufferGeometry extends BufferGeometry {
  20131. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  20132. super();
  20133. this.type = 'TorusBufferGeometry';
  20134. this.parameters = {
  20135. radius: radius,
  20136. tube: tube,
  20137. radialSegments: radialSegments,
  20138. tubularSegments: tubularSegments,
  20139. arc: arc
  20140. };
  20141. radialSegments = Math.floor( radialSegments );
  20142. tubularSegments = Math.floor( tubularSegments );
  20143. // buffers
  20144. const indices = [];
  20145. const vertices = [];
  20146. const normals = [];
  20147. const uvs = [];
  20148. // helper variables
  20149. const center = new Vector3();
  20150. const vertex = new Vector3();
  20151. const normal = new Vector3();
  20152. // generate vertices, normals and uvs
  20153. for ( let j = 0; j <= radialSegments; j ++ ) {
  20154. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20155. const u = i / tubularSegments * arc;
  20156. const v = j / radialSegments * Math.PI * 2;
  20157. // vertex
  20158. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20159. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20160. vertex.z = tube * Math.sin( v );
  20161. vertices.push( vertex.x, vertex.y, vertex.z );
  20162. // normal
  20163. center.x = radius * Math.cos( u );
  20164. center.y = radius * Math.sin( u );
  20165. normal.subVectors( vertex, center ).normalize();
  20166. normals.push( normal.x, normal.y, normal.z );
  20167. // uv
  20168. uvs.push( i / tubularSegments );
  20169. uvs.push( j / radialSegments );
  20170. }
  20171. }
  20172. // generate indices
  20173. for ( let j = 1; j <= radialSegments; j ++ ) {
  20174. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20175. // indices
  20176. const a = ( tubularSegments + 1 ) * j + i - 1;
  20177. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20178. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20179. const d = ( tubularSegments + 1 ) * j + i;
  20180. // faces
  20181. indices.push( a, b, d );
  20182. indices.push( b, c, d );
  20183. }
  20184. }
  20185. // build geometry
  20186. this.setIndex( indices );
  20187. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20188. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20189. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20190. }
  20191. }
  20192. class TorusGeometry extends Geometry {
  20193. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  20194. super();
  20195. this.type = 'TorusGeometry';
  20196. this.parameters = {
  20197. radius: radius,
  20198. tube: tube,
  20199. radialSegments: radialSegments,
  20200. tubularSegments: tubularSegments,
  20201. arc: arc
  20202. };
  20203. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20204. this.mergeVertices();
  20205. }
  20206. }
  20207. class TorusKnotBufferGeometry extends BufferGeometry {
  20208. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20209. super();
  20210. this.type = 'TorusKnotBufferGeometry';
  20211. this.parameters = {
  20212. radius: radius,
  20213. tube: tube,
  20214. tubularSegments: tubularSegments,
  20215. radialSegments: radialSegments,
  20216. p: p,
  20217. q: q
  20218. };
  20219. tubularSegments = Math.floor( tubularSegments );
  20220. radialSegments = Math.floor( radialSegments );
  20221. // buffers
  20222. const indices = [];
  20223. const vertices = [];
  20224. const normals = [];
  20225. const uvs = [];
  20226. // helper variables
  20227. const vertex = new Vector3();
  20228. const normal = new Vector3();
  20229. const P1 = new Vector3();
  20230. const P2 = new Vector3();
  20231. const B = new Vector3();
  20232. const T = new Vector3();
  20233. const N = new Vector3();
  20234. // generate vertices, normals and uvs
  20235. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20236. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20237. const u = i / tubularSegments * p * Math.PI * 2;
  20238. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20239. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20240. calculatePositionOnCurve( u, p, q, radius, P1 );
  20241. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20242. // calculate orthonormal basis
  20243. T.subVectors( P2, P1 );
  20244. N.addVectors( P2, P1 );
  20245. B.crossVectors( T, N );
  20246. N.crossVectors( B, T );
  20247. // normalize B, N. T can be ignored, we don't use it
  20248. B.normalize();
  20249. N.normalize();
  20250. for ( let j = 0; j <= radialSegments; ++ j ) {
  20251. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20252. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20253. const v = j / radialSegments * Math.PI * 2;
  20254. const cx = - tube * Math.cos( v );
  20255. const cy = tube * Math.sin( v );
  20256. // now calculate the final vertex position.
  20257. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20258. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20259. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20260. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20261. vertices.push( vertex.x, vertex.y, vertex.z );
  20262. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20263. normal.subVectors( vertex, P1 ).normalize();
  20264. normals.push( normal.x, normal.y, normal.z );
  20265. // uv
  20266. uvs.push( i / tubularSegments );
  20267. uvs.push( j / radialSegments );
  20268. }
  20269. }
  20270. // generate indices
  20271. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20272. for ( let i = 1; i <= radialSegments; i ++ ) {
  20273. // indices
  20274. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20275. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20276. const c = ( radialSegments + 1 ) * j + i;
  20277. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20278. // faces
  20279. indices.push( a, b, d );
  20280. indices.push( b, c, d );
  20281. }
  20282. }
  20283. // build geometry
  20284. this.setIndex( indices );
  20285. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20286. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20287. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20288. // this function calculates the current position on the torus curve
  20289. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20290. const cu = Math.cos( u );
  20291. const su = Math.sin( u );
  20292. const quOverP = q / p * u;
  20293. const cs = Math.cos( quOverP );
  20294. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20295. position.y = radius * ( 2 + cs ) * su * 0.5;
  20296. position.z = radius * Math.sin( quOverP ) * 0.5;
  20297. }
  20298. }
  20299. }
  20300. class TorusKnotGeometry extends Geometry {
  20301. constructor( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20302. super();
  20303. this.type = 'TorusKnotGeometry';
  20304. this.parameters = {
  20305. radius: radius,
  20306. tube: tube,
  20307. tubularSegments: tubularSegments,
  20308. radialSegments: radialSegments,
  20309. p: p,
  20310. q: q
  20311. };
  20312. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20313. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20314. this.mergeVertices();
  20315. }
  20316. }
  20317. class TubeBufferGeometry extends BufferGeometry {
  20318. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  20319. super();
  20320. this.type = 'TubeBufferGeometry';
  20321. this.parameters = {
  20322. path: path,
  20323. tubularSegments: tubularSegments,
  20324. radius: radius,
  20325. radialSegments: radialSegments,
  20326. closed: closed
  20327. };
  20328. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20329. // expose internals
  20330. this.tangents = frames.tangents;
  20331. this.normals = frames.normals;
  20332. this.binormals = frames.binormals;
  20333. // helper variables
  20334. const vertex = new Vector3();
  20335. const normal = new Vector3();
  20336. const uv = new Vector2$1();
  20337. let P = new Vector3();
  20338. // buffer
  20339. const vertices = [];
  20340. const normals = [];
  20341. const uvs = [];
  20342. const indices = [];
  20343. // create buffer data
  20344. generateBufferData();
  20345. // build geometry
  20346. this.setIndex( indices );
  20347. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20348. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20349. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20350. // functions
  20351. function generateBufferData() {
  20352. for ( let i = 0; i < tubularSegments; i ++ ) {
  20353. generateSegment( i );
  20354. }
  20355. // if the geometry is not closed, generate the last row of vertices and normals
  20356. // at the regular position on the given path
  20357. //
  20358. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20359. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20360. // uvs are generated in a separate function.
  20361. // this makes it easy compute correct values for closed geometries
  20362. generateUVs();
  20363. // finally create faces
  20364. generateIndices();
  20365. }
  20366. function generateSegment( i ) {
  20367. // we use getPointAt to sample evenly distributed points from the given path
  20368. P = path.getPointAt( i / tubularSegments, P );
  20369. // retrieve corresponding normal and binormal
  20370. const N = frames.normals[ i ];
  20371. const B = frames.binormals[ i ];
  20372. // generate normals and vertices for the current segment
  20373. for ( let j = 0; j <= radialSegments; j ++ ) {
  20374. const v = j / radialSegments * Math.PI * 2;
  20375. const sin = Math.sin( v );
  20376. const cos = - Math.cos( v );
  20377. // normal
  20378. normal.x = ( cos * N.x + sin * B.x );
  20379. normal.y = ( cos * N.y + sin * B.y );
  20380. normal.z = ( cos * N.z + sin * B.z );
  20381. normal.normalize();
  20382. normals.push( normal.x, normal.y, normal.z );
  20383. // vertex
  20384. vertex.x = P.x + radius * normal.x;
  20385. vertex.y = P.y + radius * normal.y;
  20386. vertex.z = P.z + radius * normal.z;
  20387. vertices.push( vertex.x, vertex.y, vertex.z );
  20388. }
  20389. }
  20390. function generateIndices() {
  20391. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20392. for ( let i = 1; i <= radialSegments; i ++ ) {
  20393. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20394. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20395. const c = ( radialSegments + 1 ) * j + i;
  20396. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20397. // faces
  20398. indices.push( a, b, d );
  20399. indices.push( b, c, d );
  20400. }
  20401. }
  20402. }
  20403. function generateUVs() {
  20404. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20405. for ( let j = 0; j <= radialSegments; j ++ ) {
  20406. uv.x = i / tubularSegments;
  20407. uv.y = j / radialSegments;
  20408. uvs.push( uv.x, uv.y );
  20409. }
  20410. }
  20411. }
  20412. }
  20413. toJSON() {
  20414. const data = BufferGeometry.prototype.toJSON.call( this );
  20415. data.path = this.parameters.path.toJSON();
  20416. return data;
  20417. }
  20418. }
  20419. class TubeGeometry extends Geometry {
  20420. constructor( path, tubularSegments, radius, radialSegments, closed, taper ) {
  20421. super();
  20422. this.type = 'TubeGeometry';
  20423. this.parameters = {
  20424. path: path,
  20425. tubularSegments: tubularSegments,
  20426. radius: radius,
  20427. radialSegments: radialSegments,
  20428. closed: closed
  20429. };
  20430. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  20431. const bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  20432. // expose internals
  20433. this.tangents = bufferGeometry.tangents;
  20434. this.normals = bufferGeometry.normals;
  20435. this.binormals = bufferGeometry.binormals;
  20436. // create geometry
  20437. this.fromBufferGeometry( bufferGeometry );
  20438. this.mergeVertices();
  20439. }
  20440. }
  20441. class WireframeGeometry extends BufferGeometry {
  20442. constructor( geometry ) {
  20443. super();
  20444. this.type = 'WireframeGeometry';
  20445. // buffer
  20446. const vertices = [];
  20447. // helper variables
  20448. const edge = [ 0, 0 ], edges = {};
  20449. const keys = [ 'a', 'b', 'c' ];
  20450. // different logic for Geometry and BufferGeometry
  20451. if ( geometry && geometry.isGeometry ) {
  20452. // create a data structure that contains all edges without duplicates
  20453. const faces = geometry.faces;
  20454. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20455. const face = faces[ i ];
  20456. for ( let j = 0; j < 3; j ++ ) {
  20457. const edge1 = face[ keys[ j ] ];
  20458. const edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  20459. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20460. edge[ 1 ] = Math.max( edge1, edge2 );
  20461. const key = edge[ 0 ] + ',' + edge[ 1 ];
  20462. if ( edges[ key ] === undefined ) {
  20463. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20464. }
  20465. }
  20466. }
  20467. // generate vertices
  20468. for ( const key in edges ) {
  20469. const e = edges[ key ];
  20470. let vertex = geometry.vertices[ e.index1 ];
  20471. vertices.push( vertex.x, vertex.y, vertex.z );
  20472. vertex = geometry.vertices[ e.index2 ];
  20473. vertices.push( vertex.x, vertex.y, vertex.z );
  20474. }
  20475. } else if ( geometry && geometry.isBufferGeometry ) {
  20476. const vertex = new Vector3();
  20477. if ( geometry.index !== null ) {
  20478. // indexed BufferGeometry
  20479. const position = geometry.attributes.position;
  20480. const indices = geometry.index;
  20481. let groups = geometry.groups;
  20482. if ( groups.length === 0 ) {
  20483. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20484. }
  20485. // create a data structure that contains all eges without duplicates
  20486. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  20487. const group = groups[ o ];
  20488. const start = group.start;
  20489. const count = group.count;
  20490. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  20491. for ( let j = 0; j < 3; j ++ ) {
  20492. const edge1 = indices.getX( i + j );
  20493. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  20494. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20495. edge[ 1 ] = Math.max( edge1, edge2 );
  20496. const key = edge[ 0 ] + ',' + edge[ 1 ];
  20497. if ( edges[ key ] === undefined ) {
  20498. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20499. }
  20500. }
  20501. }
  20502. }
  20503. // generate vertices
  20504. for ( const key in edges ) {
  20505. const e = edges[ key ];
  20506. vertex.fromBufferAttribute( position, e.index1 );
  20507. vertices.push( vertex.x, vertex.y, vertex.z );
  20508. vertex.fromBufferAttribute( position, e.index2 );
  20509. vertices.push( vertex.x, vertex.y, vertex.z );
  20510. }
  20511. } else {
  20512. // non-indexed BufferGeometry
  20513. const position = geometry.attributes.position;
  20514. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20515. for ( let j = 0; j < 3; j ++ ) {
  20516. // three edges per triangle, an edge is represented as (index1, index2)
  20517. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20518. const index1 = 3 * i + j;
  20519. vertex.fromBufferAttribute( position, index1 );
  20520. vertices.push( vertex.x, vertex.y, vertex.z );
  20521. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  20522. vertex.fromBufferAttribute( position, index2 );
  20523. vertices.push( vertex.x, vertex.y, vertex.z );
  20524. }
  20525. }
  20526. }
  20527. }
  20528. // build geometry
  20529. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20530. }
  20531. }
  20532. var Geometries = /*#__PURE__*/Object.freeze({
  20533. __proto__: null,
  20534. BoxGeometry: BoxGeometry,
  20535. BoxBufferGeometry: BoxBufferGeometry,
  20536. CircleGeometry: CircleGeometry,
  20537. CircleBufferGeometry: CircleBufferGeometry,
  20538. ConeGeometry: ConeGeometry,
  20539. ConeBufferGeometry: ConeBufferGeometry,
  20540. CylinderGeometry: CylinderGeometry,
  20541. CylinderBufferGeometry: CylinderBufferGeometry,
  20542. DodecahedronGeometry: DodecahedronGeometry,
  20543. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20544. EdgesGeometry: EdgesGeometry,
  20545. ExtrudeGeometry: ExtrudeGeometry,
  20546. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20547. IcosahedronGeometry: IcosahedronGeometry,
  20548. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20549. LatheGeometry: LatheGeometry,
  20550. LatheBufferGeometry: LatheBufferGeometry,
  20551. OctahedronGeometry: OctahedronGeometry,
  20552. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20553. ParametricGeometry: ParametricGeometry,
  20554. ParametricBufferGeometry: ParametricBufferGeometry,
  20555. PlaneGeometry: PlaneGeometry,
  20556. PlaneBufferGeometry: PlaneBufferGeometry,
  20557. PolyhedronGeometry: PolyhedronGeometry,
  20558. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20559. RingGeometry: RingGeometry,
  20560. RingBufferGeometry: RingBufferGeometry,
  20561. ShapeGeometry: ShapeGeometry,
  20562. ShapeBufferGeometry: ShapeBufferGeometry,
  20563. SphereGeometry: SphereGeometry,
  20564. SphereBufferGeometry: SphereBufferGeometry,
  20565. TetrahedronGeometry: TetrahedronGeometry,
  20566. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20567. TextGeometry: TextGeometry,
  20568. TextBufferGeometry: TextBufferGeometry,
  20569. TorusGeometry: TorusGeometry,
  20570. TorusBufferGeometry: TorusBufferGeometry,
  20571. TorusKnotGeometry: TorusKnotGeometry,
  20572. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20573. TubeGeometry: TubeGeometry,
  20574. TubeBufferGeometry: TubeBufferGeometry,
  20575. WireframeGeometry: WireframeGeometry
  20576. });
  20577. /**
  20578. * parameters = {
  20579. * color: <THREE.Color>
  20580. * }
  20581. */
  20582. function ShadowMaterial( parameters ) {
  20583. Material.call( this );
  20584. this.type = 'ShadowMaterial';
  20585. this.color = new Color( 0x000000 );
  20586. this.transparent = true;
  20587. this.setValues( parameters );
  20588. }
  20589. ShadowMaterial.prototype = Object.create( Material.prototype );
  20590. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20591. ShadowMaterial.prototype.isShadowMaterial = true;
  20592. ShadowMaterial.prototype.copy = function ( source ) {
  20593. Material.prototype.copy.call( this, source );
  20594. this.color.copy( source.color );
  20595. return this;
  20596. };
  20597. function RawShaderMaterial( parameters ) {
  20598. ShaderMaterial.call( this, parameters );
  20599. this.type = 'RawShaderMaterial';
  20600. }
  20601. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  20602. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20603. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20604. /**
  20605. * parameters = {
  20606. * color: <hex>,
  20607. * roughness: <float>,
  20608. * metalness: <float>,
  20609. * opacity: <float>,
  20610. *
  20611. * map: new THREE.Texture( <Image> ),
  20612. *
  20613. * lightMap: new THREE.Texture( <Image> ),
  20614. * lightMapIntensity: <float>
  20615. *
  20616. * aoMap: new THREE.Texture( <Image> ),
  20617. * aoMapIntensity: <float>
  20618. *
  20619. * emissive: <hex>,
  20620. * emissiveIntensity: <float>
  20621. * emissiveMap: new THREE.Texture( <Image> ),
  20622. *
  20623. * bumpMap: new THREE.Texture( <Image> ),
  20624. * bumpScale: <float>,
  20625. *
  20626. * normalMap: new THREE.Texture( <Image> ),
  20627. * normalMapType: THREE.TangentSpaceNormalMap,
  20628. * normalScale: <Vector2>,
  20629. *
  20630. * displacementMap: new THREE.Texture( <Image> ),
  20631. * displacementScale: <float>,
  20632. * displacementBias: <float>,
  20633. *
  20634. * roughnessMap: new THREE.Texture( <Image> ),
  20635. *
  20636. * metalnessMap: new THREE.Texture( <Image> ),
  20637. *
  20638. * alphaMap: new THREE.Texture( <Image> ),
  20639. *
  20640. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20641. * envMapIntensity: <float>
  20642. *
  20643. * refractionRatio: <float>,
  20644. *
  20645. * wireframe: <boolean>,
  20646. * wireframelineWidth: <float>,
  20647. *
  20648. * skinning: <bool>,
  20649. * morphTargets: <bool>,
  20650. * morphNormals: <bool>
  20651. * }
  20652. */
  20653. function MeshStandardMaterial( parameters ) {
  20654. Material.call( this );
  20655. this.defines = { 'STANDARD': '' };
  20656. this.type = 'MeshStandardMaterial';
  20657. this.color = new Color( 0xffffff ); // diffuse
  20658. this.roughness = 1.0;
  20659. this.metalness = 0.0;
  20660. this.map = null;
  20661. this.lightMap = null;
  20662. this.lightMapIntensity = 1.0;
  20663. this.aoMap = null;
  20664. this.aoMapIntensity = 1.0;
  20665. this.emissive = new Color( 0x000000 );
  20666. this.emissiveIntensity = 1.0;
  20667. this.emissiveMap = null;
  20668. this.bumpMap = null;
  20669. this.bumpScale = 1;
  20670. this.normalMap = null;
  20671. this.normalMapType = TangentSpaceNormalMap;
  20672. this.normalScale = new Vector2$1( 1, 1 );
  20673. this.displacementMap = null;
  20674. this.displacementScale = 1;
  20675. this.displacementBias = 0;
  20676. this.roughnessMap = null;
  20677. this.metalnessMap = null;
  20678. this.alphaMap = null;
  20679. this.envMap = null;
  20680. this.envMapIntensity = 1.0;
  20681. this.refractionRatio = 0.98;
  20682. this.wireframe = false;
  20683. this.wireframelineWidth = 1;
  20684. this.wireframeLinecap = 'round';
  20685. this.wireframeLinejoin = 'round';
  20686. this.skinning = false;
  20687. this.morphTargets = false;
  20688. this.morphNormals = false;
  20689. this.vertexTangents = false;
  20690. this.setValues( parameters );
  20691. }
  20692. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  20693. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20694. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20695. MeshStandardMaterial.prototype.copy = function ( source ) {
  20696. Material.prototype.copy.call( this, source );
  20697. this.defines = { 'STANDARD': '' };
  20698. this.color.copy( source.color );
  20699. this.roughness = source.roughness;
  20700. this.metalness = source.metalness;
  20701. this.map = source.map;
  20702. this.lightMap = source.lightMap;
  20703. this.lightMapIntensity = source.lightMapIntensity;
  20704. this.aoMap = source.aoMap;
  20705. this.aoMapIntensity = source.aoMapIntensity;
  20706. this.emissive.copy( source.emissive );
  20707. this.emissiveMap = source.emissiveMap;
  20708. this.emissiveIntensity = source.emissiveIntensity;
  20709. this.bumpMap = source.bumpMap;
  20710. this.bumpScale = source.bumpScale;
  20711. this.normalMap = source.normalMap;
  20712. this.normalMapType = source.normalMapType;
  20713. this.normalScale.copy( source.normalScale );
  20714. this.displacementMap = source.displacementMap;
  20715. this.displacementScale = source.displacementScale;
  20716. this.displacementBias = source.displacementBias;
  20717. this.roughnessMap = source.roughnessMap;
  20718. this.metalnessMap = source.metalnessMap;
  20719. this.alphaMap = source.alphaMap;
  20720. this.envMap = source.envMap;
  20721. this.envMapIntensity = source.envMapIntensity;
  20722. this.refractionRatio = source.refractionRatio;
  20723. this.wireframe = source.wireframe;
  20724. this.wireframelineWidth = source.wireframelineWidth;
  20725. this.wireframeLinecap = source.wireframeLinecap;
  20726. this.wireframeLinejoin = source.wireframeLinejoin;
  20727. this.skinning = source.skinning;
  20728. this.morphTargets = source.morphTargets;
  20729. this.morphNormals = source.morphNormals;
  20730. this.vertexTangents = source.vertexTangents;
  20731. return this;
  20732. };
  20733. /**
  20734. * parameters = {
  20735. * clearcoat: <float>,
  20736. * clearcoatMap: new THREE.Texture( <Image> ),
  20737. * clearcoatRoughness: <float>,
  20738. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20739. * clearcoatNormalScale: <Vector2>,
  20740. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20741. *
  20742. * reflectivity: <float>,
  20743. * ior: <float>,
  20744. *
  20745. * sheen: <Color>,
  20746. *
  20747. * transmission: <float>,
  20748. * transmissionMap: new THREE.Texture( <Image> )
  20749. * }
  20750. */
  20751. function MeshPhysicalMaterial( parameters ) {
  20752. MeshStandardMaterial.call( this );
  20753. this.defines = {
  20754. 'STANDARD': '',
  20755. 'PHYSICAL': ''
  20756. };
  20757. this.type = 'MeshPhysicalMaterial';
  20758. this.clearcoat = 0.0;
  20759. this.clearcoatMap = null;
  20760. this.clearcoatRoughness = 0.0;
  20761. this.clearcoatRoughnessMap = null;
  20762. this.clearcoatNormalScale = new Vector2$1( 1, 1 );
  20763. this.clearcoatNormalMap = null;
  20764. this.reflectivity = 0.5; // maps to F0 = 0.04
  20765. Object.defineProperty( this, 'ior', {
  20766. get: function () {
  20767. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  20768. },
  20769. set: function ( ior ) {
  20770. this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  20771. }
  20772. } );
  20773. this.sheen = null; // null will disable sheen bsdf
  20774. this.transmission = 0.0;
  20775. this.transmissionMap = null;
  20776. this.setValues( parameters );
  20777. }
  20778. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  20779. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20780. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20781. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  20782. MeshStandardMaterial.prototype.copy.call( this, source );
  20783. this.defines = {
  20784. 'STANDARD': '',
  20785. 'PHYSICAL': ''
  20786. };
  20787. this.clearcoat = source.clearcoat;
  20788. this.clearcoatMap = source.clearcoatMap;
  20789. this.clearcoatRoughness = source.clearcoatRoughness;
  20790. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20791. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20792. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  20793. this.reflectivity = source.reflectivity;
  20794. if ( source.sheen ) {
  20795. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  20796. } else {
  20797. this.sheen = null;
  20798. }
  20799. this.transmission = source.transmission;
  20800. this.transmissionMap = source.transmissionMap;
  20801. return this;
  20802. };
  20803. /**
  20804. * parameters = {
  20805. * color: <hex>,
  20806. * specular: <hex>,
  20807. * shininess: <float>,
  20808. * opacity: <float>,
  20809. *
  20810. * map: new THREE.Texture( <Image> ),
  20811. *
  20812. * lightMap: new THREE.Texture( <Image> ),
  20813. * lightMapIntensity: <float>
  20814. *
  20815. * aoMap: new THREE.Texture( <Image> ),
  20816. * aoMapIntensity: <float>
  20817. *
  20818. * emissive: <hex>,
  20819. * emissiveIntensity: <float>
  20820. * emissiveMap: new THREE.Texture( <Image> ),
  20821. *
  20822. * bumpMap: new THREE.Texture( <Image> ),
  20823. * bumpScale: <float>,
  20824. *
  20825. * normalMap: new THREE.Texture( <Image> ),
  20826. * normalMapType: THREE.TangentSpaceNormalMap,
  20827. * normalScale: <Vector2>,
  20828. *
  20829. * displacementMap: new THREE.Texture( <Image> ),
  20830. * displacementScale: <float>,
  20831. * displacementBias: <float>,
  20832. *
  20833. * specularMap: new THREE.Texture( <Image> ),
  20834. *
  20835. * alphaMap: new THREE.Texture( <Image> ),
  20836. *
  20837. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20838. * combine: THREE.MultiplyOperation,
  20839. * reflectivity: <float>,
  20840. * refractionRatio: <float>,
  20841. *
  20842. * wireframe: <boolean>,
  20843. * wireframelineWidth: <float>,
  20844. *
  20845. * skinning: <bool>,
  20846. * morphTargets: <bool>,
  20847. * morphNormals: <bool>
  20848. * }
  20849. */
  20850. function MeshPhongMaterial( parameters ) {
  20851. Material.call( this );
  20852. this.type = 'MeshPhongMaterial';
  20853. this.color = new Color( 0xffffff ); // diffuse
  20854. this.specular = new Color( 0x111111 );
  20855. this.shininess = 30;
  20856. this.map = null;
  20857. this.lightMap = null;
  20858. this.lightMapIntensity = 1.0;
  20859. this.aoMap = null;
  20860. this.aoMapIntensity = 1.0;
  20861. this.emissive = new Color( 0x000000 );
  20862. this.emissiveIntensity = 1.0;
  20863. this.emissiveMap = null;
  20864. this.bumpMap = null;
  20865. this.bumpScale = 1;
  20866. this.normalMap = null;
  20867. this.normalMapType = TangentSpaceNormalMap;
  20868. this.normalScale = new Vector2$1( 1, 1 );
  20869. this.displacementMap = null;
  20870. this.displacementScale = 1;
  20871. this.displacementBias = 0;
  20872. this.specularMap = null;
  20873. this.alphaMap = null;
  20874. this.envMap = null;
  20875. this.combine = MultiplyOperation;
  20876. this.reflectivity = 1;
  20877. this.refractionRatio = 0.98;
  20878. this.wireframe = false;
  20879. this.wireframelineWidth = 1;
  20880. this.wireframeLinecap = 'round';
  20881. this.wireframeLinejoin = 'round';
  20882. this.skinning = false;
  20883. this.morphTargets = false;
  20884. this.morphNormals = false;
  20885. this.setValues( parameters );
  20886. }
  20887. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  20888. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20889. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20890. MeshPhongMaterial.prototype.copy = function ( source ) {
  20891. Material.prototype.copy.call( this, source );
  20892. this.color.copy( source.color );
  20893. this.specular.copy( source.specular );
  20894. this.shininess = source.shininess;
  20895. this.map = source.map;
  20896. this.lightMap = source.lightMap;
  20897. this.lightMapIntensity = source.lightMapIntensity;
  20898. this.aoMap = source.aoMap;
  20899. this.aoMapIntensity = source.aoMapIntensity;
  20900. this.emissive.copy( source.emissive );
  20901. this.emissiveMap = source.emissiveMap;
  20902. this.emissiveIntensity = source.emissiveIntensity;
  20903. this.bumpMap = source.bumpMap;
  20904. this.bumpScale = source.bumpScale;
  20905. this.normalMap = source.normalMap;
  20906. this.normalMapType = source.normalMapType;
  20907. this.normalScale.copy( source.normalScale );
  20908. this.displacementMap = source.displacementMap;
  20909. this.displacementScale = source.displacementScale;
  20910. this.displacementBias = source.displacementBias;
  20911. this.specularMap = source.specularMap;
  20912. this.alphaMap = source.alphaMap;
  20913. this.envMap = source.envMap;
  20914. this.combine = source.combine;
  20915. this.reflectivity = source.reflectivity;
  20916. this.refractionRatio = source.refractionRatio;
  20917. this.wireframe = source.wireframe;
  20918. this.wireframelineWidth = source.wireframelineWidth;
  20919. this.wireframeLinecap = source.wireframeLinecap;
  20920. this.wireframeLinejoin = source.wireframeLinejoin;
  20921. this.skinning = source.skinning;
  20922. this.morphTargets = source.morphTargets;
  20923. this.morphNormals = source.morphNormals;
  20924. return this;
  20925. };
  20926. /**
  20927. * parameters = {
  20928. * color: <hex>,
  20929. *
  20930. * map: new THREE.Texture( <Image> ),
  20931. * gradientMap: new THREE.Texture( <Image> ),
  20932. *
  20933. * lightMap: new THREE.Texture( <Image> ),
  20934. * lightMapIntensity: <float>
  20935. *
  20936. * aoMap: new THREE.Texture( <Image> ),
  20937. * aoMapIntensity: <float>
  20938. *
  20939. * emissive: <hex>,
  20940. * emissiveIntensity: <float>
  20941. * emissiveMap: new THREE.Texture( <Image> ),
  20942. *
  20943. * bumpMap: new THREE.Texture( <Image> ),
  20944. * bumpScale: <float>,
  20945. *
  20946. * normalMap: new THREE.Texture( <Image> ),
  20947. * normalMapType: THREE.TangentSpaceNormalMap,
  20948. * normalScale: <Vector2>,
  20949. *
  20950. * displacementMap: new THREE.Texture( <Image> ),
  20951. * displacementScale: <float>,
  20952. * displacementBias: <float>,
  20953. *
  20954. * alphaMap: new THREE.Texture( <Image> ),
  20955. *
  20956. * wireframe: <boolean>,
  20957. * wireframelineWidth: <float>,
  20958. *
  20959. * skinning: <bool>,
  20960. * morphTargets: <bool>,
  20961. * morphNormals: <bool>
  20962. * }
  20963. */
  20964. function MeshToonMaterial( parameters ) {
  20965. Material.call( this );
  20966. this.defines = { 'TOON': '' };
  20967. this.type = 'MeshToonMaterial';
  20968. this.color = new Color( 0xffffff );
  20969. this.map = null;
  20970. this.gradientMap = null;
  20971. this.lightMap = null;
  20972. this.lightMapIntensity = 1.0;
  20973. this.aoMap = null;
  20974. this.aoMapIntensity = 1.0;
  20975. this.emissive = new Color( 0x000000 );
  20976. this.emissiveIntensity = 1.0;
  20977. this.emissiveMap = null;
  20978. this.bumpMap = null;
  20979. this.bumpScale = 1;
  20980. this.normalMap = null;
  20981. this.normalMapType = TangentSpaceNormalMap;
  20982. this.normalScale = new Vector2$1( 1, 1 );
  20983. this.displacementMap = null;
  20984. this.displacementScale = 1;
  20985. this.displacementBias = 0;
  20986. this.alphaMap = null;
  20987. this.wireframe = false;
  20988. this.wireframelineWidth = 1;
  20989. this.wireframeLinecap = 'round';
  20990. this.wireframeLinejoin = 'round';
  20991. this.skinning = false;
  20992. this.morphTargets = false;
  20993. this.morphNormals = false;
  20994. this.setValues( parameters );
  20995. }
  20996. MeshToonMaterial.prototype = Object.create( Material.prototype );
  20997. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20998. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20999. MeshToonMaterial.prototype.copy = function ( source ) {
  21000. Material.prototype.copy.call( this, source );
  21001. this.color.copy( source.color );
  21002. this.map = source.map;
  21003. this.gradientMap = source.gradientMap;
  21004. this.lightMap = source.lightMap;
  21005. this.lightMapIntensity = source.lightMapIntensity;
  21006. this.aoMap = source.aoMap;
  21007. this.aoMapIntensity = source.aoMapIntensity;
  21008. this.emissive.copy( source.emissive );
  21009. this.emissiveMap = source.emissiveMap;
  21010. this.emissiveIntensity = source.emissiveIntensity;
  21011. this.bumpMap = source.bumpMap;
  21012. this.bumpScale = source.bumpScale;
  21013. this.normalMap = source.normalMap;
  21014. this.normalMapType = source.normalMapType;
  21015. this.normalScale.copy( source.normalScale );
  21016. this.displacementMap = source.displacementMap;
  21017. this.displacementScale = source.displacementScale;
  21018. this.displacementBias = source.displacementBias;
  21019. this.alphaMap = source.alphaMap;
  21020. this.wireframe = source.wireframe;
  21021. this.wireframelineWidth = source.wireframelineWidth;
  21022. this.wireframeLinecap = source.wireframeLinecap;
  21023. this.wireframeLinejoin = source.wireframeLinejoin;
  21024. this.skinning = source.skinning;
  21025. this.morphTargets = source.morphTargets;
  21026. this.morphNormals = source.morphNormals;
  21027. return this;
  21028. };
  21029. /**
  21030. * parameters = {
  21031. * opacity: <float>,
  21032. *
  21033. * bumpMap: new THREE.Texture( <Image> ),
  21034. * bumpScale: <float>,
  21035. *
  21036. * normalMap: new THREE.Texture( <Image> ),
  21037. * normalMapType: THREE.TangentSpaceNormalMap,
  21038. * normalScale: <Vector2>,
  21039. *
  21040. * displacementMap: new THREE.Texture( <Image> ),
  21041. * displacementScale: <float>,
  21042. * displacementBias: <float>,
  21043. *
  21044. * wireframe: <boolean>,
  21045. * wireframelineWidth: <float>
  21046. *
  21047. * skinning: <bool>,
  21048. * morphTargets: <bool>,
  21049. * morphNormals: <bool>
  21050. * }
  21051. */
  21052. function MeshNormalMaterial( parameters ) {
  21053. Material.call( this );
  21054. this.type = 'MeshNormalMaterial';
  21055. this.bumpMap = null;
  21056. this.bumpScale = 1;
  21057. this.normalMap = null;
  21058. this.normalMapType = TangentSpaceNormalMap;
  21059. this.normalScale = new Vector2$1( 1, 1 );
  21060. this.displacementMap = null;
  21061. this.displacementScale = 1;
  21062. this.displacementBias = 0;
  21063. this.wireframe = false;
  21064. this.wireframelineWidth = 1;
  21065. this.fog = false;
  21066. this.skinning = false;
  21067. this.morphTargets = false;
  21068. this.morphNormals = false;
  21069. this.setValues( parameters );
  21070. }
  21071. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  21072. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  21073. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21074. MeshNormalMaterial.prototype.copy = function ( source ) {
  21075. Material.prototype.copy.call( this, source );
  21076. this.bumpMap = source.bumpMap;
  21077. this.bumpScale = source.bumpScale;
  21078. this.normalMap = source.normalMap;
  21079. this.normalMapType = source.normalMapType;
  21080. this.normalScale.copy( source.normalScale );
  21081. this.displacementMap = source.displacementMap;
  21082. this.displacementScale = source.displacementScale;
  21083. this.displacementBias = source.displacementBias;
  21084. this.wireframe = source.wireframe;
  21085. this.wireframelineWidth = source.wireframelineWidth;
  21086. this.skinning = source.skinning;
  21087. this.morphTargets = source.morphTargets;
  21088. this.morphNormals = source.morphNormals;
  21089. return this;
  21090. };
  21091. /**
  21092. * parameters = {
  21093. * color: <hex>,
  21094. * opacity: <float>,
  21095. *
  21096. * map: new THREE.Texture( <Image> ),
  21097. *
  21098. * lightMap: new THREE.Texture( <Image> ),
  21099. * lightMapIntensity: <float>
  21100. *
  21101. * aoMap: new THREE.Texture( <Image> ),
  21102. * aoMapIntensity: <float>
  21103. *
  21104. * emissive: <hex>,
  21105. * emissiveIntensity: <float>
  21106. * emissiveMap: new THREE.Texture( <Image> ),
  21107. *
  21108. * specularMap: new THREE.Texture( <Image> ),
  21109. *
  21110. * alphaMap: new THREE.Texture( <Image> ),
  21111. *
  21112. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21113. * combine: THREE.Multiply,
  21114. * reflectivity: <float>,
  21115. * refractionRatio: <float>,
  21116. *
  21117. * wireframe: <boolean>,
  21118. * wireframelineWidth: <float>,
  21119. *
  21120. * skinning: <bool>,
  21121. * morphTargets: <bool>,
  21122. * morphNormals: <bool>
  21123. * }
  21124. */
  21125. function MeshLambertMaterial( parameters ) {
  21126. Material.call( this );
  21127. this.type = 'MeshLambertMaterial';
  21128. this.color = new Color( 0xffffff ); // diffuse
  21129. this.map = null;
  21130. this.lightMap = null;
  21131. this.lightMapIntensity = 1.0;
  21132. this.aoMap = null;
  21133. this.aoMapIntensity = 1.0;
  21134. this.emissive = new Color( 0x000000 );
  21135. this.emissiveIntensity = 1.0;
  21136. this.emissiveMap = null;
  21137. this.specularMap = null;
  21138. this.alphaMap = null;
  21139. this.envMap = null;
  21140. this.combine = MultiplyOperation;
  21141. this.reflectivity = 1;
  21142. this.refractionRatio = 0.98;
  21143. this.wireframe = false;
  21144. this.wireframelineWidth = 1;
  21145. this.wireframeLinecap = 'round';
  21146. this.wireframeLinejoin = 'round';
  21147. this.skinning = false;
  21148. this.morphTargets = false;
  21149. this.morphNormals = false;
  21150. this.setValues( parameters );
  21151. }
  21152. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  21153. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21154. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21155. MeshLambertMaterial.prototype.copy = function ( source ) {
  21156. Material.prototype.copy.call( this, source );
  21157. this.color.copy( source.color );
  21158. this.map = source.map;
  21159. this.lightMap = source.lightMap;
  21160. this.lightMapIntensity = source.lightMapIntensity;
  21161. this.aoMap = source.aoMap;
  21162. this.aoMapIntensity = source.aoMapIntensity;
  21163. this.emissive.copy( source.emissive );
  21164. this.emissiveMap = source.emissiveMap;
  21165. this.emissiveIntensity = source.emissiveIntensity;
  21166. this.specularMap = source.specularMap;
  21167. this.alphaMap = source.alphaMap;
  21168. this.envMap = source.envMap;
  21169. this.combine = source.combine;
  21170. this.reflectivity = source.reflectivity;
  21171. this.refractionRatio = source.refractionRatio;
  21172. this.wireframe = source.wireframe;
  21173. this.wireframelineWidth = source.wireframelineWidth;
  21174. this.wireframeLinecap = source.wireframeLinecap;
  21175. this.wireframeLinejoin = source.wireframeLinejoin;
  21176. this.skinning = source.skinning;
  21177. this.morphTargets = source.morphTargets;
  21178. this.morphNormals = source.morphNormals;
  21179. return this;
  21180. };
  21181. /**
  21182. * parameters = {
  21183. * color: <hex>,
  21184. * opacity: <float>,
  21185. *
  21186. * matcap: new THREE.Texture( <Image> ),
  21187. *
  21188. * map: new THREE.Texture( <Image> ),
  21189. *
  21190. * bumpMap: new THREE.Texture( <Image> ),
  21191. * bumpScale: <float>,
  21192. *
  21193. * normalMap: new THREE.Texture( <Image> ),
  21194. * normalMapType: THREE.TangentSpaceNormalMap,
  21195. * normalScale: <Vector2>,
  21196. *
  21197. * displacementMap: new THREE.Texture( <Image> ),
  21198. * displacementScale: <float>,
  21199. * displacementBias: <float>,
  21200. *
  21201. * alphaMap: new THREE.Texture( <Image> ),
  21202. *
  21203. * skinning: <bool>,
  21204. * morphTargets: <bool>,
  21205. * morphNormals: <bool>
  21206. * }
  21207. */
  21208. function MeshMatcapMaterial( parameters ) {
  21209. Material.call( this );
  21210. this.defines = { 'MATCAP': '' };
  21211. this.type = 'MeshMatcapMaterial';
  21212. this.color = new Color( 0xffffff ); // diffuse
  21213. this.matcap = null;
  21214. this.map = null;
  21215. this.bumpMap = null;
  21216. this.bumpScale = 1;
  21217. this.normalMap = null;
  21218. this.normalMapType = TangentSpaceNormalMap;
  21219. this.normalScale = new Vector2$1( 1, 1 );
  21220. this.displacementMap = null;
  21221. this.displacementScale = 1;
  21222. this.displacementBias = 0;
  21223. this.alphaMap = null;
  21224. this.skinning = false;
  21225. this.morphTargets = false;
  21226. this.morphNormals = false;
  21227. this.setValues( parameters );
  21228. }
  21229. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  21230. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21231. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21232. MeshMatcapMaterial.prototype.copy = function ( source ) {
  21233. Material.prototype.copy.call( this, source );
  21234. this.defines = { 'MATCAP': '' };
  21235. this.color.copy( source.color );
  21236. this.matcap = source.matcap;
  21237. this.map = source.map;
  21238. this.bumpMap = source.bumpMap;
  21239. this.bumpScale = source.bumpScale;
  21240. this.normalMap = source.normalMap;
  21241. this.normalMapType = source.normalMapType;
  21242. this.normalScale.copy( source.normalScale );
  21243. this.displacementMap = source.displacementMap;
  21244. this.displacementScale = source.displacementScale;
  21245. this.displacementBias = source.displacementBias;
  21246. this.alphaMap = source.alphaMap;
  21247. this.skinning = source.skinning;
  21248. this.morphTargets = source.morphTargets;
  21249. this.morphNormals = source.morphNormals;
  21250. return this;
  21251. };
  21252. /**
  21253. * parameters = {
  21254. * color: <hex>,
  21255. * opacity: <float>,
  21256. *
  21257. * lineWidth: <float>,
  21258. *
  21259. * scale: <float>,
  21260. * dashSize: <float>,
  21261. * gapSize: <float>
  21262. * }
  21263. */
  21264. function LineDashedMaterial( parameters ) {
  21265. LineBasicMaterial.call( this );
  21266. this.type = 'LineDashedMaterial';
  21267. this.scale = 1;
  21268. this.dashSize = 3;
  21269. this.gapSize = 1;
  21270. this.setValues( parameters );
  21271. }
  21272. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  21273. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21274. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21275. LineDashedMaterial.prototype.copy = function ( source ) {
  21276. LineBasicMaterial.prototype.copy.call( this, source );
  21277. this.scale = source.scale;
  21278. this.dashSize = source.dashSize;
  21279. this.gapSize = source.gapSize;
  21280. return this;
  21281. };
  21282. var Materials = /*#__PURE__*/Object.freeze({
  21283. __proto__: null,
  21284. ShadowMaterial: ShadowMaterial,
  21285. SpriteMaterial: SpriteMaterial,
  21286. RawShaderMaterial: RawShaderMaterial,
  21287. ShaderMaterial: ShaderMaterial,
  21288. PointsMaterial: PointsMaterial,
  21289. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21290. MeshStandardMaterial: MeshStandardMaterial,
  21291. MeshPhongMaterial: MeshPhongMaterial,
  21292. MeshToonMaterial: MeshToonMaterial,
  21293. MeshNormalMaterial: MeshNormalMaterial,
  21294. MeshLambertMaterial: MeshLambertMaterial,
  21295. MeshDepthMaterial: MeshDepthMaterial,
  21296. MeshDistanceMaterial: MeshDistanceMaterial,
  21297. MeshBasicMaterial: MeshBasicMaterial,
  21298. MeshMatcapMaterial: MeshMatcapMaterial,
  21299. LineDashedMaterial: LineDashedMaterial,
  21300. LineBasicMaterial: LineBasicMaterial,
  21301. Material: Material
  21302. });
  21303. const AnimationUtils = {
  21304. // same as Array.prototype.slice, but also works on typed arrays
  21305. arraySlice: function ( array, from, to ) {
  21306. if ( AnimationUtils.isTypedArray( array ) ) {
  21307. // in ios9 array.subarray(from, undefined) will return empty array
  21308. // but array.subarray(from) or array.subarray(from, len) is correct
  21309. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  21310. }
  21311. return array.slice( from, to );
  21312. },
  21313. // converts an array to a specific type
  21314. convertArray: function ( array, type, forceClone ) {
  21315. if ( ! array || // let 'undefined' and 'null' pass
  21316. ! forceClone && array.constructor === type ) return array;
  21317. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21318. return new type( array ); // create typed array
  21319. }
  21320. return Array.prototype.slice.call( array ); // create Array
  21321. },
  21322. isTypedArray: function ( object ) {
  21323. return ArrayBuffer.isView( object ) &&
  21324. ! ( object instanceof DataView );
  21325. },
  21326. // returns an array by which times and values can be sorted
  21327. getKeyframeOrder: function ( times ) {
  21328. function compareTime( i, j ) {
  21329. return times[ i ] - times[ j ];
  21330. }
  21331. const n = times.length;
  21332. const result = new Array( n );
  21333. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21334. result.sort( compareTime );
  21335. return result;
  21336. },
  21337. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21338. sortedArray: function ( values, stride, order ) {
  21339. const nValues = values.length;
  21340. const result = new values.constructor( nValues );
  21341. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21342. const srcOffset = order[ i ] * stride;
  21343. for ( let j = 0; j !== stride; ++ j ) {
  21344. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21345. }
  21346. }
  21347. return result;
  21348. },
  21349. // function for parsing AOS keyframe formats
  21350. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  21351. let i = 1, key = jsonKeys[ 0 ];
  21352. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21353. key = jsonKeys[ i ++ ];
  21354. }
  21355. if ( key === undefined ) return; // no data
  21356. let value = key[ valuePropertyName ];
  21357. if ( value === undefined ) return; // no data
  21358. if ( Array.isArray( value ) ) {
  21359. do {
  21360. value = key[ valuePropertyName ];
  21361. if ( value !== undefined ) {
  21362. times.push( key.time );
  21363. values.push.apply( values, value ); // push all elements
  21364. }
  21365. key = jsonKeys[ i ++ ];
  21366. } while ( key !== undefined );
  21367. } else if ( value.toArray !== undefined ) {
  21368. // ...assume THREE.Math-ish
  21369. do {
  21370. value = key[ valuePropertyName ];
  21371. if ( value !== undefined ) {
  21372. times.push( key.time );
  21373. value.toArray( values, values.length );
  21374. }
  21375. key = jsonKeys[ i ++ ];
  21376. } while ( key !== undefined );
  21377. } else {
  21378. // otherwise push as-is
  21379. do {
  21380. value = key[ valuePropertyName ];
  21381. if ( value !== undefined ) {
  21382. times.push( key.time );
  21383. values.push( value );
  21384. }
  21385. key = jsonKeys[ i ++ ];
  21386. } while ( key !== undefined );
  21387. }
  21388. },
  21389. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21390. const clip = sourceClip.clone();
  21391. clip.name = name;
  21392. const tracks = [];
  21393. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21394. const track = clip.tracks[ i ];
  21395. const valueSize = track.getValueSize();
  21396. const times = [];
  21397. const values = [];
  21398. for ( let j = 0; j < track.times.length; ++ j ) {
  21399. const frame = track.times[ j ] * fps;
  21400. if ( frame < startFrame || frame >= endFrame ) continue;
  21401. times.push( track.times[ j ] );
  21402. for ( let k = 0; k < valueSize; ++ k ) {
  21403. values.push( track.values[ j * valueSize + k ] );
  21404. }
  21405. }
  21406. if ( times.length === 0 ) continue;
  21407. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  21408. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  21409. tracks.push( track );
  21410. }
  21411. clip.tracks = tracks;
  21412. // find minimum .times value across all tracks in the trimmed clip
  21413. let minStartTime = Infinity;
  21414. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21415. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21416. minStartTime = clip.tracks[ i ].times[ 0 ];
  21417. }
  21418. }
  21419. // shift all tracks such that clip begins at t=0
  21420. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21421. clip.tracks[ i ].shift( - 1 * minStartTime );
  21422. }
  21423. clip.resetDuration();
  21424. return clip;
  21425. },
  21426. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21427. if ( fps <= 0 ) fps = 30;
  21428. const numTracks = referenceClip.tracks.length;
  21429. const referenceTime = referenceFrame / fps;
  21430. // Make each track's values relative to the values at the reference frame
  21431. for ( let i = 0; i < numTracks; ++ i ) {
  21432. const referenceTrack = referenceClip.tracks[ i ];
  21433. const referenceTrackType = referenceTrack.ValueTypeName;
  21434. // Skip this track if it's non-numeric
  21435. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21436. // Find the track in the target clip whose name and type matches the reference track
  21437. const targetTrack = targetClip.tracks.find( function ( track ) {
  21438. return track.name === referenceTrack.name
  21439. && track.ValueTypeName === referenceTrackType;
  21440. } );
  21441. if ( targetTrack === undefined ) continue;
  21442. let referenceOffset = 0;
  21443. const referenceValueSize = referenceTrack.getValueSize();
  21444. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21445. referenceOffset = referenceValueSize / 3;
  21446. }
  21447. let targetOffset = 0;
  21448. const targetValueSize = targetTrack.getValueSize();
  21449. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21450. targetOffset = targetValueSize / 3;
  21451. }
  21452. const lastIndex = referenceTrack.times.length - 1;
  21453. let referenceValue;
  21454. // Find the value to subtract out of the track
  21455. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21456. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21457. const startIndex = referenceOffset;
  21458. const endIndex = referenceValueSize - referenceOffset;
  21459. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21460. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21461. // Reference frame is after the last keyframe, so just use the last keyframe
  21462. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21463. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21464. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21465. } else {
  21466. // Interpolate to the reference value
  21467. const interpolant = referenceTrack.createInterpolant();
  21468. const startIndex = referenceOffset;
  21469. const endIndex = referenceValueSize - referenceOffset;
  21470. interpolant.evaluate( referenceTime );
  21471. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  21472. }
  21473. // Conjugate the quaternion
  21474. if ( referenceTrackType === 'quaternion' ) {
  21475. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21476. referenceQuat.toArray( referenceValue );
  21477. }
  21478. // Subtract the reference value from all of the track values
  21479. const numTimes = targetTrack.times.length;
  21480. for ( let j = 0; j < numTimes; ++ j ) {
  21481. const valueStart = j * targetValueSize + targetOffset;
  21482. if ( referenceTrackType === 'quaternion' ) {
  21483. // Multiply the conjugate for quaternion track types
  21484. Quaternion.multiplyQuaternionsFlat(
  21485. targetTrack.values,
  21486. valueStart,
  21487. referenceValue,
  21488. 0,
  21489. targetTrack.values,
  21490. valueStart
  21491. );
  21492. } else {
  21493. const valueEnd = targetValueSize - targetOffset * 2;
  21494. // Subtract each value for all other numeric track types
  21495. for ( let k = 0; k < valueEnd; ++ k ) {
  21496. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  21497. }
  21498. }
  21499. }
  21500. }
  21501. targetClip.blendMode = AdditiveAnimationBlendMode;
  21502. return targetClip;
  21503. }
  21504. };
  21505. /**
  21506. * Abstract base class of interpolants over parametric samples.
  21507. *
  21508. * The parameter domain is one dimensional, typically the time or a path
  21509. * along a curve defined by the data.
  21510. *
  21511. * The sample values can have any dimensionality and derived classes may
  21512. * apply special interpretations to the data.
  21513. *
  21514. * This class provides the interval seek in a Template Method, deferring
  21515. * the actual interpolation to derived classes.
  21516. *
  21517. * Time complexity is O(1) for linear access crossing at most two points
  21518. * and O(log N) for random access, where N is the number of positions.
  21519. *
  21520. * References:
  21521. *
  21522. * http://www.oodesign.com/template-method-pattern.html
  21523. *
  21524. */
  21525. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21526. this.parameterPositions = parameterPositions;
  21527. this._cachedIndex = 0;
  21528. this.resultBuffer = resultBuffer !== undefined ?
  21529. resultBuffer : new sampleValues.constructor( sampleSize );
  21530. this.sampleValues = sampleValues;
  21531. this.valueSize = sampleSize;
  21532. }
  21533. Object.assign( Interpolant.prototype, {
  21534. evaluate: function ( t ) {
  21535. const pp = this.parameterPositions;
  21536. let i1 = this._cachedIndex,
  21537. t1 = pp[ i1 ],
  21538. t0 = pp[ i1 - 1 ];
  21539. validate_interval: {
  21540. seek: {
  21541. let right;
  21542. linear_scan: {
  21543. //- See http://jsperf.com/comparison-to-undefined/3
  21544. //- slower code:
  21545. //-
  21546. //- if ( t >= t1 || t1 === undefined ) {
  21547. forward_scan: if ( ! ( t < t1 ) ) {
  21548. for ( let giveUpAt = i1 + 2; ; ) {
  21549. if ( t1 === undefined ) {
  21550. if ( t < t0 ) break forward_scan;
  21551. // after end
  21552. i1 = pp.length;
  21553. this._cachedIndex = i1;
  21554. return this.afterEnd_( i1 - 1, t, t0 );
  21555. }
  21556. if ( i1 === giveUpAt ) break; // this loop
  21557. t0 = t1;
  21558. t1 = pp[ ++ i1 ];
  21559. if ( t < t1 ) {
  21560. // we have arrived at the sought interval
  21561. break seek;
  21562. }
  21563. }
  21564. // prepare binary search on the right side of the index
  21565. right = pp.length;
  21566. break linear_scan;
  21567. }
  21568. //- slower code:
  21569. //- if ( t < t0 || t0 === undefined ) {
  21570. if ( ! ( t >= t0 ) ) {
  21571. // looping?
  21572. const t1global = pp[ 1 ];
  21573. if ( t < t1global ) {
  21574. i1 = 2; // + 1, using the scan for the details
  21575. t0 = t1global;
  21576. }
  21577. // linear reverse scan
  21578. for ( let giveUpAt = i1 - 2; ; ) {
  21579. if ( t0 === undefined ) {
  21580. // before start
  21581. this._cachedIndex = 0;
  21582. return this.beforeStart_( 0, t, t1 );
  21583. }
  21584. if ( i1 === giveUpAt ) break; // this loop
  21585. t1 = t0;
  21586. t0 = pp[ -- i1 - 1 ];
  21587. if ( t >= t0 ) {
  21588. // we have arrived at the sought interval
  21589. break seek;
  21590. }
  21591. }
  21592. // prepare binary search on the left side of the index
  21593. right = i1;
  21594. i1 = 0;
  21595. break linear_scan;
  21596. }
  21597. // the interval is valid
  21598. break validate_interval;
  21599. } // linear scan
  21600. // binary search
  21601. while ( i1 < right ) {
  21602. const mid = ( i1 + right ) >>> 1;
  21603. if ( t < pp[ mid ] ) {
  21604. right = mid;
  21605. } else {
  21606. i1 = mid + 1;
  21607. }
  21608. }
  21609. t1 = pp[ i1 ];
  21610. t0 = pp[ i1 - 1 ];
  21611. // check boundary cases, again
  21612. if ( t0 === undefined ) {
  21613. this._cachedIndex = 0;
  21614. return this.beforeStart_( 0, t, t1 );
  21615. }
  21616. if ( t1 === undefined ) {
  21617. i1 = pp.length;
  21618. this._cachedIndex = i1;
  21619. return this.afterEnd_( i1 - 1, t0, t );
  21620. }
  21621. } // seek
  21622. this._cachedIndex = i1;
  21623. this.intervalChanged_( i1, t0, t1 );
  21624. } // validate_interval
  21625. return this.interpolate_( i1, t0, t, t1 );
  21626. },
  21627. settings: null, // optional, subclass-specific settings structure
  21628. // Note: The indirection allows central control of many interpolants.
  21629. // --- Protected interface
  21630. DefaultSettings_: {},
  21631. getSettings_: function () {
  21632. return this.settings || this.DefaultSettings_;
  21633. },
  21634. copySampleValue_: function ( index ) {
  21635. // copies a sample value to the result buffer
  21636. const result = this.resultBuffer,
  21637. values = this.sampleValues,
  21638. stride = this.valueSize,
  21639. offset = index * stride;
  21640. for ( let i = 0; i !== stride; ++ i ) {
  21641. result[ i ] = values[ offset + i ];
  21642. }
  21643. return result;
  21644. },
  21645. // Template methods for derived classes:
  21646. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  21647. throw new Error( 'call to abstract method' );
  21648. // implementations shall return this.resultBuffer
  21649. },
  21650. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  21651. // empty
  21652. }
  21653. } );
  21654. // DECLARE ALIAS AFTER assign prototype
  21655. Object.assign( Interpolant.prototype, {
  21656. //( 0, t, t0 ), returns this.resultBuffer
  21657. beforeStart_: Interpolant.prototype.copySampleValue_,
  21658. //( N-1, tN-1, t ), returns this.resultBuffer
  21659. afterEnd_: Interpolant.prototype.copySampleValue_,
  21660. } );
  21661. /**
  21662. * Fast and simple cubic spline interpolant.
  21663. *
  21664. * It was derived from a Hermitian construction setting the first derivative
  21665. * at each sample position to the linear slope between neighboring positions
  21666. * over their parameter interval.
  21667. */
  21668. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21669. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21670. this._weightPrev = - 0;
  21671. this._offsetPrev = - 0;
  21672. this._weightNext = - 0;
  21673. this._offsetNext = - 0;
  21674. }
  21675. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21676. constructor: CubicInterpolant,
  21677. DefaultSettings_: {
  21678. endingStart: ZeroCurvatureEnding,
  21679. endingEnd: ZeroCurvatureEnding
  21680. },
  21681. intervalChanged_: function ( i1, t0, t1 ) {
  21682. const pp = this.parameterPositions;
  21683. let iPrev = i1 - 2,
  21684. iNext = i1 + 1,
  21685. tPrev = pp[ iPrev ],
  21686. tNext = pp[ iNext ];
  21687. if ( tPrev === undefined ) {
  21688. switch ( this.getSettings_().endingStart ) {
  21689. case ZeroSlopeEnding:
  21690. // f'(t0) = 0
  21691. iPrev = i1;
  21692. tPrev = 2 * t0 - t1;
  21693. break;
  21694. case WrapAroundEnding:
  21695. // use the other end of the curve
  21696. iPrev = pp.length - 2;
  21697. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  21698. break;
  21699. default: // ZeroCurvatureEnding
  21700. // f''(t0) = 0 a.k.a. Natural Spline
  21701. iPrev = i1;
  21702. tPrev = t1;
  21703. }
  21704. }
  21705. if ( tNext === undefined ) {
  21706. switch ( this.getSettings_().endingEnd ) {
  21707. case ZeroSlopeEnding:
  21708. // f'(tN) = 0
  21709. iNext = i1;
  21710. tNext = 2 * t1 - t0;
  21711. break;
  21712. case WrapAroundEnding:
  21713. // use the other end of the curve
  21714. iNext = 1;
  21715. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  21716. break;
  21717. default: // ZeroCurvatureEnding
  21718. // f''(tN) = 0, a.k.a. Natural Spline
  21719. iNext = i1 - 1;
  21720. tNext = t0;
  21721. }
  21722. }
  21723. const halfDt = ( t1 - t0 ) * 0.5,
  21724. stride = this.valueSize;
  21725. this._weightPrev = halfDt / ( t0 - tPrev );
  21726. this._weightNext = halfDt / ( tNext - t1 );
  21727. this._offsetPrev = iPrev * stride;
  21728. this._offsetNext = iNext * stride;
  21729. },
  21730. interpolate_: function ( i1, t0, t, t1 ) {
  21731. const result = this.resultBuffer,
  21732. values = this.sampleValues,
  21733. stride = this.valueSize,
  21734. o1 = i1 * stride, o0 = o1 - stride,
  21735. oP = this._offsetPrev, oN = this._offsetNext,
  21736. wP = this._weightPrev, wN = this._weightNext,
  21737. p = ( t - t0 ) / ( t1 - t0 ),
  21738. pp = p * p,
  21739. ppp = pp * p;
  21740. // evaluate polynomials
  21741. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  21742. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  21743. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  21744. const sN = wN * ppp - wN * pp;
  21745. // combine data linearly
  21746. for ( let i = 0; i !== stride; ++ i ) {
  21747. result[ i ] =
  21748. sP * values[ oP + i ] +
  21749. s0 * values[ o0 + i ] +
  21750. s1 * values[ o1 + i ] +
  21751. sN * values[ oN + i ];
  21752. }
  21753. return result;
  21754. }
  21755. } );
  21756. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21757. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21758. }
  21759. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21760. constructor: LinearInterpolant,
  21761. interpolate_: function ( i1, t0, t, t1 ) {
  21762. const result = this.resultBuffer,
  21763. values = this.sampleValues,
  21764. stride = this.valueSize,
  21765. offset1 = i1 * stride,
  21766. offset0 = offset1 - stride,
  21767. weight1 = ( t - t0 ) / ( t1 - t0 ),
  21768. weight0 = 1 - weight1;
  21769. for ( let i = 0; i !== stride; ++ i ) {
  21770. result[ i ] =
  21771. values[ offset0 + i ] * weight0 +
  21772. values[ offset1 + i ] * weight1;
  21773. }
  21774. return result;
  21775. }
  21776. } );
  21777. /**
  21778. *
  21779. * Interpolant that evaluates to the sample value at the position preceeding
  21780. * the parameter.
  21781. */
  21782. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21783. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21784. }
  21785. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21786. constructor: DiscreteInterpolant,
  21787. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  21788. return this.copySampleValue_( i1 - 1 );
  21789. }
  21790. } );
  21791. function KeyframeTrack( name, times, values, interpolation ) {
  21792. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  21793. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  21794. this.name = name;
  21795. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  21796. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  21797. this.setInterpolation( interpolation || this.DefaultInterpolation );
  21798. }
  21799. // Static methods
  21800. Object.assign( KeyframeTrack, {
  21801. // Serialization (in static context, because of constructor invocation
  21802. // and automatic invocation of .toJSON):
  21803. toJSON: function ( track ) {
  21804. const trackType = track.constructor;
  21805. let json;
  21806. // derived classes can define a static toJSON method
  21807. if ( trackType.toJSON !== undefined ) {
  21808. json = trackType.toJSON( track );
  21809. } else {
  21810. // by default, we assume the data can be serialized as-is
  21811. json = {
  21812. 'name': track.name,
  21813. 'times': AnimationUtils.convertArray( track.times, Array ),
  21814. 'values': AnimationUtils.convertArray( track.values, Array )
  21815. };
  21816. const interpolation = track.getInterpolation();
  21817. if ( interpolation !== track.DefaultInterpolation ) {
  21818. json.interpolation = interpolation;
  21819. }
  21820. }
  21821. json.type = track.ValueTypeName; // mandatory
  21822. return json;
  21823. }
  21824. } );
  21825. Object.assign( KeyframeTrack.prototype, {
  21826. constructor: KeyframeTrack,
  21827. TimeBufferType: Float32Array,
  21828. ValueBufferType: Float32Array,
  21829. DefaultInterpolation: InterpolateLinear,
  21830. InterpolantFactoryMethodDiscrete: function ( result ) {
  21831. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  21832. },
  21833. InterpolantFactoryMethodLinear: function ( result ) {
  21834. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  21835. },
  21836. InterpolantFactoryMethodSmooth: function ( result ) {
  21837. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  21838. },
  21839. setInterpolation: function ( interpolation ) {
  21840. let factoryMethod;
  21841. switch ( interpolation ) {
  21842. case InterpolateDiscrete:
  21843. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21844. break;
  21845. case InterpolateLinear:
  21846. factoryMethod = this.InterpolantFactoryMethodLinear;
  21847. break;
  21848. case InterpolateSmooth:
  21849. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21850. break;
  21851. }
  21852. if ( factoryMethod === undefined ) {
  21853. const message = 'unsupported interpolation for ' +
  21854. this.ValueTypeName + ' keyframe track named ' + this.name;
  21855. if ( this.createInterpolant === undefined ) {
  21856. // fall back to default, unless the default itself is messed up
  21857. if ( interpolation !== this.DefaultInterpolation ) {
  21858. this.setInterpolation( this.DefaultInterpolation );
  21859. } else {
  21860. throw new Error( message ); // fatal, in this case
  21861. }
  21862. }
  21863. console.warn( 'THREE.KeyframeTrack:', message );
  21864. return this;
  21865. }
  21866. this.createInterpolant = factoryMethod;
  21867. return this;
  21868. },
  21869. getInterpolation: function () {
  21870. switch ( this.createInterpolant ) {
  21871. case this.InterpolantFactoryMethodDiscrete:
  21872. return InterpolateDiscrete;
  21873. case this.InterpolantFactoryMethodLinear:
  21874. return InterpolateLinear;
  21875. case this.InterpolantFactoryMethodSmooth:
  21876. return InterpolateSmooth;
  21877. }
  21878. },
  21879. getValueSize: function () {
  21880. return this.values.length / this.times.length;
  21881. },
  21882. // move all keyframes either forwards or backwards in time
  21883. shift: function ( timeOffset ) {
  21884. if ( timeOffset !== 0.0 ) {
  21885. const times = this.times;
  21886. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21887. times[ i ] += timeOffset;
  21888. }
  21889. }
  21890. return this;
  21891. },
  21892. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21893. scale: function ( timeScale ) {
  21894. if ( timeScale !== 1.0 ) {
  21895. const times = this.times;
  21896. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21897. times[ i ] *= timeScale;
  21898. }
  21899. }
  21900. return this;
  21901. },
  21902. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21903. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21904. trim: function ( startTime, endTime ) {
  21905. const times = this.times,
  21906. nKeys = times.length;
  21907. let from = 0,
  21908. to = nKeys - 1;
  21909. while ( from !== nKeys && times[ from ] < startTime ) {
  21910. ++ from;
  21911. }
  21912. while ( to !== - 1 && times[ to ] > endTime ) {
  21913. -- to;
  21914. }
  21915. ++ to; // inclusive -> exclusive bound
  21916. if ( from !== 0 || to !== nKeys ) {
  21917. // empty tracks are forbidden, so keep at least one keyframe
  21918. if ( from >= to ) {
  21919. to = Math.max( to, 1 );
  21920. from = to - 1;
  21921. }
  21922. const stride = this.getValueSize();
  21923. this.times = AnimationUtils.arraySlice( times, from, to );
  21924. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  21925. }
  21926. return this;
  21927. },
  21928. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21929. validate: function () {
  21930. let valid = true;
  21931. const valueSize = this.getValueSize();
  21932. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  21933. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  21934. valid = false;
  21935. }
  21936. const times = this.times,
  21937. values = this.values,
  21938. nKeys = times.length;
  21939. if ( nKeys === 0 ) {
  21940. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  21941. valid = false;
  21942. }
  21943. let prevTime = null;
  21944. for ( let i = 0; i !== nKeys; i ++ ) {
  21945. const currTime = times[ i ];
  21946. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  21947. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  21948. valid = false;
  21949. break;
  21950. }
  21951. if ( prevTime !== null && prevTime > currTime ) {
  21952. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  21953. valid = false;
  21954. break;
  21955. }
  21956. prevTime = currTime;
  21957. }
  21958. if ( values !== undefined ) {
  21959. if ( AnimationUtils.isTypedArray( values ) ) {
  21960. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  21961. const value = values[ i ];
  21962. if ( isNaN( value ) ) {
  21963. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  21964. valid = false;
  21965. break;
  21966. }
  21967. }
  21968. }
  21969. }
  21970. return valid;
  21971. },
  21972. // removes equivalent sequential keys as common in morph target sequences
  21973. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21974. optimize: function () {
  21975. // times or values may be shared with other tracks, so overwriting is unsafe
  21976. const times = AnimationUtils.arraySlice( this.times ),
  21977. values = AnimationUtils.arraySlice( this.values ),
  21978. stride = this.getValueSize(),
  21979. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21980. lastIndex = times.length - 1;
  21981. let writeIndex = 1;
  21982. for ( let i = 1; i < lastIndex; ++ i ) {
  21983. let keep = false;
  21984. const time = times[ i ];
  21985. const timeNext = times[ i + 1 ];
  21986. // remove adjacent keyframes scheduled at the same time
  21987. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  21988. if ( ! smoothInterpolation ) {
  21989. // remove unnecessary keyframes same as their neighbors
  21990. const offset = i * stride,
  21991. offsetP = offset - stride,
  21992. offsetN = offset + stride;
  21993. for ( let j = 0; j !== stride; ++ j ) {
  21994. const value = values[ offset + j ];
  21995. if ( value !== values[ offsetP + j ] ||
  21996. value !== values[ offsetN + j ] ) {
  21997. keep = true;
  21998. break;
  21999. }
  22000. }
  22001. } else {
  22002. keep = true;
  22003. }
  22004. }
  22005. // in-place compaction
  22006. if ( keep ) {
  22007. if ( i !== writeIndex ) {
  22008. times[ writeIndex ] = times[ i ];
  22009. const readOffset = i * stride,
  22010. writeOffset = writeIndex * stride;
  22011. for ( let j = 0; j !== stride; ++ j ) {
  22012. values[ writeOffset + j ] = values[ readOffset + j ];
  22013. }
  22014. }
  22015. ++ writeIndex;
  22016. }
  22017. }
  22018. // flush last keyframe (compaction looks ahead)
  22019. if ( lastIndex > 0 ) {
  22020. times[ writeIndex ] = times[ lastIndex ];
  22021. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22022. values[ writeOffset + j ] = values[ readOffset + j ];
  22023. }
  22024. ++ writeIndex;
  22025. }
  22026. if ( writeIndex !== times.length ) {
  22027. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22028. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22029. } else {
  22030. this.times = times;
  22031. this.values = values;
  22032. }
  22033. return this;
  22034. },
  22035. clone: function () {
  22036. const times = AnimationUtils.arraySlice( this.times, 0 );
  22037. const values = AnimationUtils.arraySlice( this.values, 0 );
  22038. const TypedKeyframeTrack = this.constructor;
  22039. const track = new TypedKeyframeTrack( this.name, times, values );
  22040. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22041. track.createInterpolant = this.createInterpolant;
  22042. return track;
  22043. }
  22044. } );
  22045. /**
  22046. * A Track of Boolean keyframe values.
  22047. */
  22048. function BooleanKeyframeTrack( name, times, values ) {
  22049. KeyframeTrack.call( this, name, times, values );
  22050. }
  22051. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22052. constructor: BooleanKeyframeTrack,
  22053. ValueTypeName: 'bool',
  22054. ValueBufferType: Array,
  22055. DefaultInterpolation: InterpolateDiscrete,
  22056. InterpolantFactoryMethodLinear: undefined,
  22057. InterpolantFactoryMethodSmooth: undefined
  22058. // Note: Actually this track could have a optimized / compressed
  22059. // representation of a single value and a custom interpolant that
  22060. // computes "firstValue ^ isOdd( index )".
  22061. } );
  22062. /**
  22063. * A Track of keyframe values that represent color.
  22064. */
  22065. function ColorKeyframeTrack( name, times, values, interpolation ) {
  22066. KeyframeTrack.call( this, name, times, values, interpolation );
  22067. }
  22068. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22069. constructor: ColorKeyframeTrack,
  22070. ValueTypeName: 'color'
  22071. // ValueBufferType is inherited
  22072. // DefaultInterpolation is inherited
  22073. // Note: Very basic implementation and nothing special yet.
  22074. // However, this is the place for color space parameterization.
  22075. } );
  22076. /**
  22077. * A Track of numeric keyframe values.
  22078. */
  22079. function NumberKeyframeTrack( name, times, values, interpolation ) {
  22080. KeyframeTrack.call( this, name, times, values, interpolation );
  22081. }
  22082. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22083. constructor: NumberKeyframeTrack,
  22084. ValueTypeName: 'number'
  22085. // ValueBufferType is inherited
  22086. // DefaultInterpolation is inherited
  22087. } );
  22088. /**
  22089. * Spherical linear unit quaternion interpolant.
  22090. */
  22091. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22092. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22093. }
  22094. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  22095. constructor: QuaternionLinearInterpolant,
  22096. interpolate_: function ( i1, t0, t, t1 ) {
  22097. const result = this.resultBuffer,
  22098. values = this.sampleValues,
  22099. stride = this.valueSize,
  22100. alpha = ( t - t0 ) / ( t1 - t0 );
  22101. let offset = i1 * stride;
  22102. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22103. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22104. }
  22105. return result;
  22106. }
  22107. } );
  22108. /**
  22109. * A Track of quaternion keyframe values.
  22110. */
  22111. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  22112. KeyframeTrack.call( this, name, times, values, interpolation );
  22113. }
  22114. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22115. constructor: QuaternionKeyframeTrack,
  22116. ValueTypeName: 'quaternion',
  22117. // ValueBufferType is inherited
  22118. DefaultInterpolation: InterpolateLinear,
  22119. InterpolantFactoryMethodLinear: function ( result ) {
  22120. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22121. },
  22122. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  22123. } );
  22124. /**
  22125. * A Track that interpolates Strings
  22126. */
  22127. function StringKeyframeTrack( name, times, values, interpolation ) {
  22128. KeyframeTrack.call( this, name, times, values, interpolation );
  22129. }
  22130. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22131. constructor: StringKeyframeTrack,
  22132. ValueTypeName: 'string',
  22133. ValueBufferType: Array,
  22134. DefaultInterpolation: InterpolateDiscrete,
  22135. InterpolantFactoryMethodLinear: undefined,
  22136. InterpolantFactoryMethodSmooth: undefined
  22137. } );
  22138. /**
  22139. * A Track of vectored keyframe values.
  22140. */
  22141. function VectorKeyframeTrack( name, times, values, interpolation ) {
  22142. KeyframeTrack.call( this, name, times, values, interpolation );
  22143. }
  22144. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22145. constructor: VectorKeyframeTrack,
  22146. ValueTypeName: 'vector'
  22147. // ValueBufferType is inherited
  22148. // DefaultInterpolation is inherited
  22149. } );
  22150. function AnimationClip( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22151. this.name = name;
  22152. this.tracks = tracks;
  22153. this.duration = duration;
  22154. this.blendMode = blendMode;
  22155. this.uuid = MathUtils.generateUUID();
  22156. // this means it should figure out its duration by scanning the tracks
  22157. if ( this.duration < 0 ) {
  22158. this.resetDuration();
  22159. }
  22160. }
  22161. function getTrackTypeForValueTypeName( typeName ) {
  22162. switch ( typeName.toLowerCase() ) {
  22163. case 'scalar':
  22164. case 'double':
  22165. case 'float':
  22166. case 'number':
  22167. case 'integer':
  22168. return NumberKeyframeTrack;
  22169. case 'vector':
  22170. case 'vector2':
  22171. case 'vector3':
  22172. case 'vector4':
  22173. return VectorKeyframeTrack;
  22174. case 'color':
  22175. return ColorKeyframeTrack;
  22176. case 'quaternion':
  22177. return QuaternionKeyframeTrack;
  22178. case 'bool':
  22179. case 'boolean':
  22180. return BooleanKeyframeTrack;
  22181. case 'string':
  22182. return StringKeyframeTrack;
  22183. }
  22184. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22185. }
  22186. function parseKeyframeTrack( json ) {
  22187. if ( json.type === undefined ) {
  22188. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22189. }
  22190. const trackType = getTrackTypeForValueTypeName( json.type );
  22191. if ( json.times === undefined ) {
  22192. const times = [], values = [];
  22193. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  22194. json.times = times;
  22195. json.values = values;
  22196. }
  22197. // derived classes can define a static parse method
  22198. if ( trackType.parse !== undefined ) {
  22199. return trackType.parse( json );
  22200. } else {
  22201. // by default, we assume a constructor compatible with the base
  22202. return new trackType( json.name, json.times, json.values, json.interpolation );
  22203. }
  22204. }
  22205. Object.assign( AnimationClip, {
  22206. parse: function ( json ) {
  22207. const tracks = [],
  22208. jsonTracks = json.tracks,
  22209. frameTime = 1.0 / ( json.fps || 1.0 );
  22210. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22211. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22212. }
  22213. const clip = new AnimationClip( json.name, json.duration, tracks, json.blendMode );
  22214. clip.uuid = json.uuid;
  22215. return clip;
  22216. },
  22217. toJSON: function ( clip ) {
  22218. const tracks = [],
  22219. clipTracks = clip.tracks;
  22220. const json = {
  22221. 'name': clip.name,
  22222. 'duration': clip.duration,
  22223. 'tracks': tracks,
  22224. 'uuid': clip.uuid,
  22225. 'blendMode': clip.blendMode
  22226. };
  22227. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22228. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22229. }
  22230. return json;
  22231. },
  22232. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  22233. const numMorphTargets = morphTargetSequence.length;
  22234. const tracks = [];
  22235. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22236. let times = [];
  22237. let values = [];
  22238. times.push(
  22239. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22240. i,
  22241. ( i + 1 ) % numMorphTargets );
  22242. values.push( 0, 1, 0 );
  22243. const order = AnimationUtils.getKeyframeOrder( times );
  22244. times = AnimationUtils.sortedArray( times, 1, order );
  22245. values = AnimationUtils.sortedArray( values, 1, order );
  22246. // if there is a key at the first frame, duplicate it as the
  22247. // last frame as well for perfect loop.
  22248. if ( ! noLoop && times[ 0 ] === 0 ) {
  22249. times.push( numMorphTargets );
  22250. values.push( values[ 0 ] );
  22251. }
  22252. tracks.push(
  22253. new NumberKeyframeTrack(
  22254. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22255. times, values
  22256. ).scale( 1.0 / fps ) );
  22257. }
  22258. return new AnimationClip( name, - 1, tracks );
  22259. },
  22260. findByName: function ( objectOrClipArray, name ) {
  22261. let clipArray = objectOrClipArray;
  22262. if ( ! Array.isArray( objectOrClipArray ) ) {
  22263. const o = objectOrClipArray;
  22264. clipArray = o.geometry && o.geometry.animations || o.animations;
  22265. }
  22266. for ( let i = 0; i < clipArray.length; i ++ ) {
  22267. if ( clipArray[ i ].name === name ) {
  22268. return clipArray[ i ];
  22269. }
  22270. }
  22271. return null;
  22272. },
  22273. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  22274. const animationToMorphTargets = {};
  22275. // tested with https://regex101.com/ on trick sequences
  22276. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22277. const pattern = /^([\w-]*?)([\d]+)$/;
  22278. // sort morph target names into animation groups based
  22279. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22280. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22281. const morphTarget = morphTargets[ i ];
  22282. const parts = morphTarget.name.match( pattern );
  22283. if ( parts && parts.length > 1 ) {
  22284. const name = parts[ 1 ];
  22285. let animationMorphTargets = animationToMorphTargets[ name ];
  22286. if ( ! animationMorphTargets ) {
  22287. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22288. }
  22289. animationMorphTargets.push( morphTarget );
  22290. }
  22291. }
  22292. const clips = [];
  22293. for ( const name in animationToMorphTargets ) {
  22294. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22295. }
  22296. return clips;
  22297. },
  22298. // parse the animation.hierarchy format
  22299. parseAnimation: function ( animation, bones ) {
  22300. if ( ! animation ) {
  22301. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22302. return null;
  22303. }
  22304. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22305. // only return track if there are actually keys.
  22306. if ( animationKeys.length !== 0 ) {
  22307. const times = [];
  22308. const values = [];
  22309. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22310. // empty keys are filtered out, so check again
  22311. if ( times.length !== 0 ) {
  22312. destTracks.push( new trackType( trackName, times, values ) );
  22313. }
  22314. }
  22315. };
  22316. const tracks = [];
  22317. const clipName = animation.name || 'default';
  22318. const fps = animation.fps || 30;
  22319. const blendMode = animation.blendMode;
  22320. // automatic length determination in AnimationClip.
  22321. let duration = animation.length || - 1;
  22322. const hierarchyTracks = animation.hierarchy || [];
  22323. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22324. const animationKeys = hierarchyTracks[ h ].keys;
  22325. // skip empty tracks
  22326. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22327. // process morph targets
  22328. if ( animationKeys[ 0 ].morphTargets ) {
  22329. // figure out all morph targets used in this track
  22330. const morphTargetNames = {};
  22331. let k;
  22332. for ( k = 0; k < animationKeys.length; k ++ ) {
  22333. if ( animationKeys[ k ].morphTargets ) {
  22334. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22335. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  22336. }
  22337. }
  22338. }
  22339. // create a track for each morph target with all zero
  22340. // morphTargetInfluences except for the keys in which
  22341. // the morphTarget is named.
  22342. for ( const morphTargetName in morphTargetNames ) {
  22343. const times = [];
  22344. const values = [];
  22345. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22346. const animationKey = animationKeys[ k ];
  22347. times.push( animationKey.time );
  22348. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22349. }
  22350. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22351. }
  22352. duration = morphTargetNames.length * ( fps || 1.0 );
  22353. } else {
  22354. // ...assume skeletal animation
  22355. const boneName = '.bones[' + bones[ h ].name + ']';
  22356. addNonemptyTrack(
  22357. VectorKeyframeTrack, boneName + '.position',
  22358. animationKeys, 'pos', tracks );
  22359. addNonemptyTrack(
  22360. QuaternionKeyframeTrack, boneName + '.quaternion',
  22361. animationKeys, 'rot', tracks );
  22362. addNonemptyTrack(
  22363. VectorKeyframeTrack, boneName + '.scale',
  22364. animationKeys, 'scl', tracks );
  22365. }
  22366. }
  22367. if ( tracks.length === 0 ) {
  22368. return null;
  22369. }
  22370. const clip = new AnimationClip( clipName, duration, tracks, blendMode );
  22371. return clip;
  22372. }
  22373. } );
  22374. Object.assign( AnimationClip.prototype, {
  22375. resetDuration: function () {
  22376. const tracks = this.tracks;
  22377. let duration = 0;
  22378. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22379. const track = this.tracks[ i ];
  22380. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22381. }
  22382. this.duration = duration;
  22383. return this;
  22384. },
  22385. trim: function () {
  22386. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22387. this.tracks[ i ].trim( 0, this.duration );
  22388. }
  22389. return this;
  22390. },
  22391. validate: function () {
  22392. let valid = true;
  22393. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22394. valid = valid && this.tracks[ i ].validate();
  22395. }
  22396. return valid;
  22397. },
  22398. optimize: function () {
  22399. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22400. this.tracks[ i ].optimize();
  22401. }
  22402. return this;
  22403. },
  22404. clone: function () {
  22405. const tracks = [];
  22406. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22407. tracks.push( this.tracks[ i ].clone() );
  22408. }
  22409. return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
  22410. },
  22411. toJSON: function () {
  22412. return AnimationClip.toJSON( this );
  22413. }
  22414. } );
  22415. const Cache = {
  22416. enabled: false,
  22417. files: {},
  22418. add: function ( key, file ) {
  22419. if ( this.enabled === false ) return;
  22420. // console.log( 'THREE.Cache', 'Adding key:', key );
  22421. this.files[ key ] = file;
  22422. },
  22423. get: function ( key ) {
  22424. if ( this.enabled === false ) return;
  22425. // console.log( 'THREE.Cache', 'Checking key:', key );
  22426. return this.files[ key ];
  22427. },
  22428. remove: function ( key ) {
  22429. delete this.files[ key ];
  22430. },
  22431. clear: function () {
  22432. this.files = {};
  22433. }
  22434. };
  22435. function LoadingManager( onLoad, onProgress, onError ) {
  22436. const scope = this;
  22437. let isLoading = false;
  22438. let itemsLoaded = 0;
  22439. let itemsTotal = 0;
  22440. let urlModifier = undefined;
  22441. const handlers = [];
  22442. // Refer to #5689 for the reason why we don't set .onStart
  22443. // in the constructor
  22444. this.onStart = undefined;
  22445. this.onLoad = onLoad;
  22446. this.onProgress = onProgress;
  22447. this.onError = onError;
  22448. this.itemStart = function ( url ) {
  22449. itemsTotal ++;
  22450. if ( isLoading === false ) {
  22451. if ( scope.onStart !== undefined ) {
  22452. scope.onStart( url, itemsLoaded, itemsTotal );
  22453. }
  22454. }
  22455. isLoading = true;
  22456. };
  22457. this.itemEnd = function ( url ) {
  22458. itemsLoaded ++;
  22459. if ( scope.onProgress !== undefined ) {
  22460. scope.onProgress( url, itemsLoaded, itemsTotal );
  22461. }
  22462. if ( itemsLoaded === itemsTotal ) {
  22463. isLoading = false;
  22464. if ( scope.onLoad !== undefined ) {
  22465. scope.onLoad();
  22466. }
  22467. }
  22468. };
  22469. this.itemError = function ( url ) {
  22470. if ( scope.onError !== undefined ) {
  22471. scope.onError( url );
  22472. }
  22473. };
  22474. this.resolveURL = function ( url ) {
  22475. if ( urlModifier ) {
  22476. return urlModifier( url );
  22477. }
  22478. return url;
  22479. };
  22480. this.setURLModifier = function ( transform ) {
  22481. urlModifier = transform;
  22482. return this;
  22483. };
  22484. this.addHandler = function ( regex, loader ) {
  22485. handlers.push( regex, loader );
  22486. return this;
  22487. };
  22488. this.removeHandler = function ( regex ) {
  22489. const index = handlers.indexOf( regex );
  22490. if ( index !== - 1 ) {
  22491. handlers.splice( index, 2 );
  22492. }
  22493. return this;
  22494. };
  22495. this.getHandler = function ( file ) {
  22496. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22497. const regex = handlers[ i ];
  22498. const loader = handlers[ i + 1 ];
  22499. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22500. if ( regex.test( file ) ) {
  22501. return loader;
  22502. }
  22503. }
  22504. return null;
  22505. };
  22506. }
  22507. const DefaultLoadingManager = new LoadingManager();
  22508. function Loader( manager ) {
  22509. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22510. this.crossOrigin = 'anonymous';
  22511. this.withCredentials = false;
  22512. this.path = '';
  22513. this.resourcePath = '';
  22514. this.requestHeader = {};
  22515. }
  22516. Object.assign( Loader.prototype, {
  22517. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  22518. loadAsync: function ( url, onProgress ) {
  22519. const scope = this;
  22520. return new Promise( function ( resolve, reject ) {
  22521. scope.load( url, resolve, onProgress, reject );
  22522. } );
  22523. },
  22524. parse: function ( /* data */ ) {},
  22525. setCrossOrigin: function ( crossOrigin ) {
  22526. this.crossOrigin = crossOrigin;
  22527. return this;
  22528. },
  22529. setWithCredentials: function ( value ) {
  22530. this.withCredentials = value;
  22531. return this;
  22532. },
  22533. setPath: function ( path ) {
  22534. this.path = path;
  22535. return this;
  22536. },
  22537. setResourcePath: function ( resourcePath ) {
  22538. this.resourcePath = resourcePath;
  22539. return this;
  22540. },
  22541. setRequestHeader: function ( requestHeader ) {
  22542. this.requestHeader = requestHeader;
  22543. return this;
  22544. }
  22545. } );
  22546. const loading = {};
  22547. function FileLoader( manager ) {
  22548. Loader.call( this, manager );
  22549. }
  22550. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22551. constructor: FileLoader,
  22552. load: function ( url, onLoad, onProgress, onError ) {
  22553. if ( url === undefined ) url = '';
  22554. if ( this.path !== undefined ) url = this.path + url;
  22555. url = this.manager.resolveURL( url );
  22556. const scope = this;
  22557. const cached = Cache.get( url );
  22558. if ( cached !== undefined ) {
  22559. scope.manager.itemStart( url );
  22560. setTimeout( function () {
  22561. if ( onLoad ) onLoad( cached );
  22562. scope.manager.itemEnd( url );
  22563. }, 0 );
  22564. return cached;
  22565. }
  22566. // Check if request is duplicate
  22567. if ( loading[ url ] !== undefined ) {
  22568. loading[ url ].push( {
  22569. onLoad: onLoad,
  22570. onProgress: onProgress,
  22571. onError: onError
  22572. } );
  22573. return;
  22574. }
  22575. // Check for data: URI
  22576. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22577. const dataUriRegexResult = url.match( dataUriRegex );
  22578. let request;
  22579. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22580. if ( dataUriRegexResult ) {
  22581. const mimeType = dataUriRegexResult[ 1 ];
  22582. const isBase64 = !! dataUriRegexResult[ 2 ];
  22583. let data = dataUriRegexResult[ 3 ];
  22584. data = decodeURIComponent( data );
  22585. if ( isBase64 ) data = atob( data );
  22586. try {
  22587. let response;
  22588. const responseType = ( this.responseType || '' ).toLowerCase();
  22589. switch ( responseType ) {
  22590. case 'arraybuffer':
  22591. case 'blob':
  22592. const view = new Uint8Array( data.length );
  22593. for ( let i = 0; i < data.length; i ++ ) {
  22594. view[ i ] = data.charCodeAt( i );
  22595. }
  22596. if ( responseType === 'blob' ) {
  22597. response = new Blob( [ view.buffer ], { type: mimeType } );
  22598. } else {
  22599. response = view.buffer;
  22600. }
  22601. break;
  22602. case 'document':
  22603. const parser = new DOMParser();
  22604. response = parser.parseFromString( data, mimeType );
  22605. break;
  22606. case 'json':
  22607. response = JSON.parse( data );
  22608. break;
  22609. default: // 'text' or other
  22610. response = data;
  22611. break;
  22612. }
  22613. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22614. setTimeout( function () {
  22615. if ( onLoad ) onLoad( response );
  22616. scope.manager.itemEnd( url );
  22617. }, 0 );
  22618. } catch ( error ) {
  22619. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22620. setTimeout( function () {
  22621. if ( onError ) onError( error );
  22622. scope.manager.itemError( url );
  22623. scope.manager.itemEnd( url );
  22624. }, 0 );
  22625. }
  22626. } else {
  22627. // Initialise array for duplicate requests
  22628. loading[ url ] = [];
  22629. loading[ url ].push( {
  22630. onLoad: onLoad,
  22631. onProgress: onProgress,
  22632. onError: onError
  22633. } );
  22634. request = new XMLHttpRequest();
  22635. request.open( 'GET', url, true );
  22636. request.addEventListener( 'load', function ( event ) {
  22637. const response = this.response;
  22638. const callbacks = loading[ url ];
  22639. delete loading[ url ];
  22640. if ( this.status === 200 || this.status === 0 ) {
  22641. // Some browsers return HTTP Status 0 when using non-http protocol
  22642. // e.g. 'file://' or 'data://'. Handle as success.
  22643. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22644. // Add to cache only on HTTP success, so that we do not cache
  22645. // error response bodies as proper responses to requests.
  22646. Cache.add( url, response );
  22647. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22648. const callback = callbacks[ i ];
  22649. if ( callback.onLoad ) callback.onLoad( response, event.total); //xzw add event.total
  22650. }
  22651. scope.manager.itemEnd( url );
  22652. } else {
  22653. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22654. const callback = callbacks[ i ];
  22655. if ( callback.onError ) callback.onError( event );
  22656. }
  22657. scope.manager.itemError( url );
  22658. scope.manager.itemEnd( url );
  22659. }
  22660. }, false );
  22661. request.addEventListener( 'progress', function ( event ) {
  22662. const callbacks = loading[ url ];
  22663. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22664. const callback = callbacks[ i ];
  22665. if ( callback.onProgress ) callback.onProgress( event );
  22666. }
  22667. }, false );
  22668. request.addEventListener( 'error', function ( event ) {
  22669. const callbacks = loading[ url ];
  22670. delete loading[ url ];
  22671. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22672. const callback = callbacks[ i ];
  22673. if ( callback.onError ) callback.onError( event );
  22674. }
  22675. scope.manager.itemError( url );
  22676. scope.manager.itemEnd( url );
  22677. }, false );
  22678. request.addEventListener( 'abort', function ( event ) {
  22679. const callbacks = loading[ url ];
  22680. delete loading[ url ];
  22681. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22682. const callback = callbacks[ i ];
  22683. if ( callback.onError ) callback.onError( event );
  22684. }
  22685. scope.manager.itemError( url );
  22686. scope.manager.itemEnd( url );
  22687. }, false );
  22688. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22689. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22690. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22691. for ( const header in this.requestHeader ) {
  22692. request.setRequestHeader( header, this.requestHeader[ header ] );
  22693. }
  22694. request.send( null );
  22695. }
  22696. scope.manager.itemStart( url );
  22697. return request;
  22698. },
  22699. setResponseType: function ( value ) {
  22700. this.responseType = value;
  22701. return this;
  22702. },
  22703. setMimeType: function ( value ) {
  22704. this.mimeType = value;
  22705. return this;
  22706. }
  22707. } );
  22708. function AnimationLoader( manager ) {
  22709. Loader.call( this, manager );
  22710. }
  22711. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22712. constructor: AnimationLoader,
  22713. load: function ( url, onLoad, onProgress, onError ) {
  22714. const scope = this;
  22715. const loader = new FileLoader( scope.manager );
  22716. loader.setPath( scope.path );
  22717. loader.setRequestHeader( scope.requestHeader );
  22718. loader.setWithCredentials( scope.withCredentials );
  22719. loader.load( url, function ( text ) {
  22720. try {
  22721. onLoad( scope.parse( JSON.parse( text ) ) );
  22722. } catch ( e ) {
  22723. if ( onError ) {
  22724. onError( e );
  22725. } else {
  22726. console.error( e );
  22727. }
  22728. scope.manager.itemError( url );
  22729. }
  22730. }, onProgress, onError );
  22731. },
  22732. parse: function ( json ) {
  22733. const animations = [];
  22734. for ( let i = 0; i < json.length; i ++ ) {
  22735. const clip = AnimationClip.parse( json[ i ] );
  22736. animations.push( clip );
  22737. }
  22738. return animations;
  22739. }
  22740. } );
  22741. /**
  22742. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22743. *
  22744. * Sub classes have to implement the parse() method which will be used in load().
  22745. */
  22746. function CompressedTextureLoader( manager ) {
  22747. Loader.call( this, manager );
  22748. }
  22749. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22750. constructor: CompressedTextureLoader,
  22751. load: function ( url, onLoad, onProgress, onError ) {
  22752. const scope = this;
  22753. const images = [];
  22754. const texture = new CompressedTexture();
  22755. const loader = new FileLoader( this.manager );
  22756. loader.setPath( this.path );
  22757. loader.setResponseType( 'arraybuffer' );
  22758. loader.setRequestHeader( this.requestHeader );
  22759. loader.setWithCredentials( scope.withCredentials );
  22760. let loaded = 0;
  22761. function loadTexture( i ) {
  22762. loader.load( url[ i ], function ( buffer ) {
  22763. const texDatas = scope.parse( buffer, true );
  22764. images[ i ] = {
  22765. width: texDatas.width,
  22766. height: texDatas.height,
  22767. format: texDatas.format,
  22768. mipmaps: texDatas.mipmaps
  22769. };
  22770. loaded += 1;
  22771. if ( loaded === 6 ) {
  22772. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  22773. texture.image = images;
  22774. texture.format = texDatas.format;
  22775. texture.needsUpdate = true;
  22776. if ( onLoad ) onLoad( texture );
  22777. }
  22778. }, onProgress, onError );
  22779. }
  22780. if ( Array.isArray( url ) ) {
  22781. for ( let i = 0, il = url.length; i < il; ++ i ) {
  22782. loadTexture( i );
  22783. }
  22784. } else {
  22785. // compressed cubemap texture stored in a single DDS file
  22786. loader.load( url, function ( buffer ) {
  22787. const texDatas = scope.parse( buffer, true );
  22788. if ( texDatas.isCubemap ) {
  22789. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22790. for ( let f = 0; f < faces; f ++ ) {
  22791. images[ f ] = { mipmaps: [] };
  22792. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  22793. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22794. images[ f ].format = texDatas.format;
  22795. images[ f ].width = texDatas.width;
  22796. images[ f ].height = texDatas.height;
  22797. }
  22798. }
  22799. texture.image = images;
  22800. } else {
  22801. texture.image.width = texDatas.width;
  22802. texture.image.height = texDatas.height;
  22803. texture.mipmaps = texDatas.mipmaps;
  22804. }
  22805. if ( texDatas.mipmapCount === 1 ) {
  22806. texture.minFilter = LinearFilter;
  22807. }
  22808. texture.format = texDatas.format;
  22809. texture.needsUpdate = true;
  22810. if ( onLoad ) onLoad( texture );
  22811. }, onProgress, onError );
  22812. }
  22813. return texture;
  22814. }
  22815. } );
  22816. function ImageLoader( manager ) {
  22817. Loader.call( this, manager );
  22818. }
  22819. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22820. constructor: ImageLoader,
  22821. load: function ( url, onLoad, onProgress, onError ) {
  22822. if ( this.path !== undefined ) url = this.path + url;
  22823. url = this.manager.resolveURL( url );
  22824. const scope = this;
  22825. const cached = Cache.get( url );
  22826. if ( cached !== undefined ) {
  22827. scope.manager.itemStart( url );
  22828. setTimeout( function () {
  22829. if ( onLoad ) onLoad( cached );
  22830. scope.manager.itemEnd( url );
  22831. }, 0 );
  22832. return cached;
  22833. }
  22834. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22835. function onImageLoad() {
  22836. image.removeEventListener( 'load', onImageLoad, false );
  22837. image.removeEventListener( 'error', onImageError, false );
  22838. Cache.add( url, this );
  22839. if ( onLoad ) onLoad( this );
  22840. scope.manager.itemEnd( url );
  22841. }
  22842. function onImageError( event ) {
  22843. image.removeEventListener( 'load', onImageLoad, false );
  22844. image.removeEventListener( 'error', onImageError, false );
  22845. if ( onError ) onError( event );
  22846. scope.manager.itemError( url );
  22847. scope.manager.itemEnd( url );
  22848. }
  22849. image.addEventListener( 'load', onImageLoad, false );
  22850. image.addEventListener( 'error', onImageError, false );
  22851. if ( url.substr( 0, 5 ) !== 'data:' ) {
  22852. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  22853. }
  22854. scope.manager.itemStart( url );
  22855. image.src = url;
  22856. return image;
  22857. }
  22858. } );
  22859. function CubeTextureLoader( manager ) {
  22860. Loader.call( this, manager );
  22861. }
  22862. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22863. constructor: CubeTextureLoader,
  22864. load: function ( urls, onLoad, onProgress, onError ) {
  22865. const texture = new CubeTexture();
  22866. const loader = new ImageLoader( this.manager );
  22867. loader.setCrossOrigin( this.crossOrigin );
  22868. loader.setPath( this.path );
  22869. let loaded = 0;
  22870. function loadTexture( i ) {
  22871. loader.load( urls[ i ], function ( image ) {
  22872. texture.images[ i ] = image;
  22873. loaded ++;
  22874. if ( loaded === 6 ) {
  22875. texture.needsUpdate = true;
  22876. if ( onLoad ) onLoad( texture );
  22877. }
  22878. }, undefined, onError );
  22879. }
  22880. for ( let i = 0; i < urls.length; ++ i ) {
  22881. loadTexture( i );
  22882. }
  22883. return texture;
  22884. }
  22885. } );
  22886. /**
  22887. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22888. *
  22889. * Sub classes have to implement the parse() method which will be used in load().
  22890. */
  22891. function DataTextureLoader( manager ) {
  22892. Loader.call( this, manager );
  22893. }
  22894. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22895. constructor: DataTextureLoader,
  22896. load: function ( url, onLoad, onProgress, onError ) {
  22897. const scope = this;
  22898. const texture = new DataTexture();
  22899. const loader = new FileLoader( this.manager );
  22900. loader.setResponseType( 'arraybuffer' );
  22901. loader.setRequestHeader( this.requestHeader );
  22902. loader.setPath( this.path );
  22903. loader.setWithCredentials( scope.withCredentials );
  22904. loader.load( url, function ( buffer ) {
  22905. const texData = scope.parse( buffer );
  22906. if ( ! texData ) return;
  22907. if ( texData.image !== undefined ) {
  22908. texture.image = texData.image;
  22909. } else if ( texData.data !== undefined ) {
  22910. texture.image.width = texData.width;
  22911. texture.image.height = texData.height;
  22912. texture.image.data = texData.data;
  22913. }
  22914. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22915. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22916. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22917. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22918. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22919. if ( texData.format !== undefined ) {
  22920. texture.format = texData.format;
  22921. }
  22922. if ( texData.type !== undefined ) {
  22923. texture.type = texData.type;
  22924. }
  22925. if ( texData.mipmaps !== undefined ) {
  22926. texture.mipmaps = texData.mipmaps;
  22927. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22928. }
  22929. if ( texData.mipmapCount === 1 ) {
  22930. texture.minFilter = LinearFilter;
  22931. }
  22932. texture.needsUpdate = true;
  22933. if ( onLoad ) onLoad( texture, texData );
  22934. }, onProgress, onError );
  22935. return texture;
  22936. }
  22937. } );
  22938. function TextureLoader( manager ) {
  22939. Loader.call( this, manager );
  22940. }
  22941. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22942. constructor: TextureLoader,
  22943. load: function ( url, onLoad, onProgress, onError ) {
  22944. const texture = new Texture();
  22945. const loader = new ImageLoader( this.manager );
  22946. loader.setCrossOrigin( this.crossOrigin );
  22947. loader.setPath( this.path );
  22948. loader.load( url, function ( image ) {
  22949. texture.image = image;
  22950. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22951. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22952. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22953. texture.needsUpdate = true;
  22954. if ( onLoad !== undefined ) {
  22955. onLoad( texture );
  22956. }
  22957. }, onProgress, onError );
  22958. return texture;
  22959. }
  22960. } );
  22961. /**
  22962. * Extensible curve object.
  22963. *
  22964. * Some common of curve methods:
  22965. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22966. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22967. * .getPoints(), .getSpacedPoints()
  22968. * .getLength()
  22969. * .updateArcLengths()
  22970. *
  22971. * This following curves inherit from THREE.Curve:
  22972. *
  22973. * -- 2D curves --
  22974. * THREE.ArcCurve
  22975. * THREE.CubicBezierCurve
  22976. * THREE.EllipseCurve
  22977. * THREE.LineCurve
  22978. * THREE.QuadraticBezierCurve
  22979. * THREE.SplineCurve
  22980. *
  22981. * -- 3D curves --
  22982. * THREE.CatmullRomCurve3
  22983. * THREE.CubicBezierCurve3
  22984. * THREE.LineCurve3
  22985. * THREE.QuadraticBezierCurve3
  22986. *
  22987. * A series of curves can be represented as a THREE.CurvePath.
  22988. *
  22989. **/
  22990. function Curve() {
  22991. this.type = 'Curve';
  22992. this.arcLengthDivisions = 200;
  22993. }
  22994. Object.assign( Curve.prototype, {
  22995. // Virtual base class method to overwrite and implement in subclasses
  22996. // - t [0 .. 1]
  22997. getPoint: function ( /* t, optionalTarget */ ) {
  22998. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  22999. return null;
  23000. },
  23001. // Get point at relative position in curve according to arc length
  23002. // - u [0 .. 1]
  23003. getPointAt: function ( u, optionalTarget ) {
  23004. const t = this.getUtoTmapping( u );
  23005. return this.getPoint( t, optionalTarget );
  23006. },
  23007. // Get sequence of points using getPoint( t )
  23008. getPoints: function ( divisions = 5 ) {
  23009. const points = [];
  23010. for ( let d = 0; d <= divisions; d ++ ) {
  23011. points.push( this.getPoint( d / divisions ) );
  23012. }
  23013. return points;
  23014. },
  23015. // Get sequence of points using getPointAt( u )
  23016. getSpacedPoints: function ( divisions = 5 ) {
  23017. const points = [];
  23018. for ( let d = 0; d <= divisions; d ++ ) {
  23019. points.push( this.getPointAt( d / divisions ) );
  23020. }
  23021. return points;
  23022. },
  23023. // Get total curve arc length
  23024. getLength: function () {
  23025. const lengths = this.getLengths();
  23026. return lengths[ lengths.length - 1 ];
  23027. },
  23028. // Get list of cumulative segment lengths
  23029. getLengths: function ( divisions ) {
  23030. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  23031. if ( this.cacheArcLengths &&
  23032. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23033. ! this.needsUpdate ) {
  23034. return this.cacheArcLengths;
  23035. }
  23036. this.needsUpdate = false;
  23037. const cache = [];
  23038. let current, last = this.getPoint( 0 );
  23039. let sum = 0;
  23040. cache.push( 0 );
  23041. for ( let p = 1; p <= divisions; p ++ ) {
  23042. current = this.getPoint( p / divisions );
  23043. sum += current.distanceTo( last );
  23044. cache.push( sum );
  23045. last = current;
  23046. }
  23047. this.cacheArcLengths = cache;
  23048. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23049. },
  23050. updateArcLengths: function () {
  23051. this.needsUpdate = true;
  23052. this.getLengths();
  23053. },
  23054. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  23055. getUtoTmapping: function ( u, distance ) {
  23056. const arcLengths = this.getLengths();
  23057. let i = 0;
  23058. const il = arcLengths.length;
  23059. let targetArcLength; // The targeted u distance value to get
  23060. if ( distance ) {
  23061. targetArcLength = distance;
  23062. } else {
  23063. targetArcLength = u * arcLengths[ il - 1 ];
  23064. }
  23065. // binary search for the index with largest value smaller than target u distance
  23066. let low = 0, high = il - 1, comparison;
  23067. while ( low <= high ) {
  23068. 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
  23069. comparison = arcLengths[ i ] - targetArcLength;
  23070. if ( comparison < 0 ) {
  23071. low = i + 1;
  23072. } else if ( comparison > 0 ) {
  23073. high = i - 1;
  23074. } else {
  23075. high = i;
  23076. break;
  23077. // DONE
  23078. }
  23079. }
  23080. i = high;
  23081. if ( arcLengths[ i ] === targetArcLength ) {
  23082. return i / ( il - 1 );
  23083. }
  23084. // we could get finer grain at lengths, or use simple interpolation between two points
  23085. const lengthBefore = arcLengths[ i ];
  23086. const lengthAfter = arcLengths[ i + 1 ];
  23087. const segmentLength = lengthAfter - lengthBefore;
  23088. // determine where we are between the 'before' and 'after' points
  23089. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23090. // add that fractional amount to t
  23091. const t = ( i + segmentFraction ) / ( il - 1 );
  23092. return t;
  23093. },
  23094. // Returns a unit vector tangent at t
  23095. // In case any sub curve does not implement its tangent derivation,
  23096. // 2 points a small delta apart will be used to find its gradient
  23097. // which seems to give a reasonable approximation
  23098. getTangent: function ( t, optionalTarget ) {
  23099. const delta = 0.0001;
  23100. let t1 = t - delta;
  23101. let t2 = t + delta;
  23102. // Capping in case of danger
  23103. if ( t1 < 0 ) t1 = 0;
  23104. if ( t2 > 1 ) t2 = 1;
  23105. const pt1 = this.getPoint( t1 );
  23106. const pt2 = this.getPoint( t2 );
  23107. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2$1() : new Vector3() );
  23108. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23109. return tangent;
  23110. },
  23111. getTangentAt: function ( u, optionalTarget ) {
  23112. const t = this.getUtoTmapping( u );
  23113. return this.getTangent( t, optionalTarget );
  23114. },
  23115. computeFrenetFrames: function ( segments, closed ) {
  23116. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23117. const normal = new Vector3();
  23118. const tangents = [];
  23119. const normals = [];
  23120. const binormals = [];
  23121. const vec = new Vector3();
  23122. const mat = new Matrix4();
  23123. // compute the tangent vectors for each segment on the curve
  23124. for ( let i = 0; i <= segments; i ++ ) {
  23125. const u = i / segments;
  23126. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23127. tangents[ i ].normalize();
  23128. }
  23129. // select an initial normal vector perpendicular to the first tangent vector,
  23130. // and in the direction of the minimum tangent xyz component
  23131. normals[ 0 ] = new Vector3();
  23132. binormals[ 0 ] = new Vector3();
  23133. let min = Number.MAX_VALUE;
  23134. const tx = Math.abs( tangents[ 0 ].x );
  23135. const ty = Math.abs( tangents[ 0 ].y );
  23136. const tz = Math.abs( tangents[ 0 ].z );
  23137. if ( tx <= min ) {
  23138. min = tx;
  23139. normal.set( 1, 0, 0 );
  23140. }
  23141. if ( ty <= min ) {
  23142. min = ty;
  23143. normal.set( 0, 1, 0 );
  23144. }
  23145. if ( tz <= min ) {
  23146. normal.set( 0, 0, 1 );
  23147. }
  23148. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23149. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23150. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23151. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23152. for ( let i = 1; i <= segments; i ++ ) {
  23153. normals[ i ] = normals[ i - 1 ].clone();
  23154. binormals[ i ] = binormals[ i - 1 ].clone();
  23155. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23156. if ( vec.length() > Number.EPSILON ) {
  23157. vec.normalize();
  23158. const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23159. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23160. }
  23161. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23162. }
  23163. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23164. if ( closed === true ) {
  23165. let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  23166. theta /= segments;
  23167. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23168. theta = - theta;
  23169. }
  23170. for ( let i = 1; i <= segments; i ++ ) {
  23171. // twist a little...
  23172. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23173. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23174. }
  23175. }
  23176. return {
  23177. tangents: tangents,
  23178. normals: normals,
  23179. binormals: binormals
  23180. };
  23181. },
  23182. clone: function () {
  23183. return new this.constructor().copy( this );
  23184. },
  23185. copy: function ( source ) {
  23186. this.arcLengthDivisions = source.arcLengthDivisions;
  23187. return this;
  23188. },
  23189. toJSON: function () {
  23190. const data = {
  23191. metadata: {
  23192. version: 4.5,
  23193. type: 'Curve',
  23194. generator: 'Curve.toJSON'
  23195. }
  23196. };
  23197. data.arcLengthDivisions = this.arcLengthDivisions;
  23198. data.type = this.type;
  23199. return data;
  23200. },
  23201. fromJSON: function ( json ) {
  23202. this.arcLengthDivisions = json.arcLengthDivisions;
  23203. return this;
  23204. }
  23205. } );
  23206. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23207. Curve.call( this );
  23208. this.type = 'EllipseCurve';
  23209. this.aX = aX || 0;
  23210. this.aY = aY || 0;
  23211. this.xRadius = xRadius || 1;
  23212. this.yRadius = yRadius || 1;
  23213. this.aStartAngle = aStartAngle || 0;
  23214. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23215. this.aClockwise = aClockwise || false;
  23216. this.aRotation = aRotation || 0;
  23217. }
  23218. EllipseCurve.prototype = Object.create( Curve.prototype );
  23219. EllipseCurve.prototype.constructor = EllipseCurve;
  23220. EllipseCurve.prototype.isEllipseCurve = true;
  23221. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23222. const point = optionalTarget || new Vector2$1();
  23223. const twoPi = Math.PI * 2;
  23224. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23225. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23226. // ensures that deltaAngle is 0 .. 2 PI
  23227. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23228. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23229. if ( deltaAngle < Number.EPSILON ) {
  23230. if ( samePoints ) {
  23231. deltaAngle = 0;
  23232. } else {
  23233. deltaAngle = twoPi;
  23234. }
  23235. }
  23236. if ( this.aClockwise === true && ! samePoints ) {
  23237. if ( deltaAngle === twoPi ) {
  23238. deltaAngle = - twoPi;
  23239. } else {
  23240. deltaAngle = deltaAngle - twoPi;
  23241. }
  23242. }
  23243. const angle = this.aStartAngle + t * deltaAngle;
  23244. let x = this.aX + this.xRadius * Math.cos( angle );
  23245. let y = this.aY + this.yRadius * Math.sin( angle );
  23246. if ( this.aRotation !== 0 ) {
  23247. const cos = Math.cos( this.aRotation );
  23248. const sin = Math.sin( this.aRotation );
  23249. const tx = x - this.aX;
  23250. const ty = y - this.aY;
  23251. // Rotate the point about the center of the ellipse.
  23252. x = tx * cos - ty * sin + this.aX;
  23253. y = tx * sin + ty * cos + this.aY;
  23254. }
  23255. return point.set( x, y );
  23256. };
  23257. EllipseCurve.prototype.copy = function ( source ) {
  23258. Curve.prototype.copy.call( this, source );
  23259. this.aX = source.aX;
  23260. this.aY = source.aY;
  23261. this.xRadius = source.xRadius;
  23262. this.yRadius = source.yRadius;
  23263. this.aStartAngle = source.aStartAngle;
  23264. this.aEndAngle = source.aEndAngle;
  23265. this.aClockwise = source.aClockwise;
  23266. this.aRotation = source.aRotation;
  23267. return this;
  23268. };
  23269. EllipseCurve.prototype.toJSON = function () {
  23270. const data = Curve.prototype.toJSON.call( this );
  23271. data.aX = this.aX;
  23272. data.aY = this.aY;
  23273. data.xRadius = this.xRadius;
  23274. data.yRadius = this.yRadius;
  23275. data.aStartAngle = this.aStartAngle;
  23276. data.aEndAngle = this.aEndAngle;
  23277. data.aClockwise = this.aClockwise;
  23278. data.aRotation = this.aRotation;
  23279. return data;
  23280. };
  23281. EllipseCurve.prototype.fromJSON = function ( json ) {
  23282. Curve.prototype.fromJSON.call( this, json );
  23283. this.aX = json.aX;
  23284. this.aY = json.aY;
  23285. this.xRadius = json.xRadius;
  23286. this.yRadius = json.yRadius;
  23287. this.aStartAngle = json.aStartAngle;
  23288. this.aEndAngle = json.aEndAngle;
  23289. this.aClockwise = json.aClockwise;
  23290. this.aRotation = json.aRotation;
  23291. return this;
  23292. };
  23293. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23294. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23295. this.type = 'ArcCurve';
  23296. }
  23297. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  23298. ArcCurve.prototype.constructor = ArcCurve;
  23299. ArcCurve.prototype.isArcCurve = true;
  23300. /**
  23301. * Centripetal CatmullRom Curve - which is useful for avoiding
  23302. * cusps and self-intersections in non-uniform catmull rom curves.
  23303. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23304. *
  23305. * curve.type accepts centripetal(default), chordal and catmullrom
  23306. * curve.tension is used for catmullrom which defaults to 0.5
  23307. */
  23308. /*
  23309. Based on an optimized c++ solution in
  23310. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23311. - http://ideone.com/NoEbVM
  23312. This CubicPoly class could be used for reusing some variables and calculations,
  23313. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23314. which can be placed in CurveUtils.
  23315. */
  23316. function CubicPoly() {
  23317. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23318. /*
  23319. * Compute coefficients for a cubic polynomial
  23320. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23321. * such that
  23322. * p(0) = x0, p(1) = x1
  23323. * and
  23324. * p'(0) = t0, p'(1) = t1.
  23325. */
  23326. function init( x0, x1, t0, t1 ) {
  23327. c0 = x0;
  23328. c1 = t0;
  23329. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  23330. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23331. }
  23332. return {
  23333. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23334. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23335. },
  23336. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23337. // compute tangents when parameterized in [t1,t2]
  23338. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23339. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23340. // rescale tangents for parametrization in [0,1]
  23341. t1 *= dt1;
  23342. t2 *= dt1;
  23343. init( x1, x2, t1, t2 );
  23344. },
  23345. calc: function ( t ) {
  23346. const t2 = t * t;
  23347. const t3 = t2 * t;
  23348. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23349. }
  23350. };
  23351. }
  23352. //
  23353. const tmp = new Vector3();
  23354. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  23355. function CatmullRomCurve3( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23356. Curve.call( this );
  23357. this.type = 'CatmullRomCurve3';
  23358. this.points = points;
  23359. this.closed = closed;
  23360. this.curveType = curveType;
  23361. this.tension = tension;
  23362. }
  23363. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  23364. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23365. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23366. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23367. const point = optionalTarget;
  23368. const points = this.points;
  23369. const l = points.length;
  23370. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23371. let intPoint = Math.floor( p );
  23372. let weight = p - intPoint;
  23373. if ( this.closed ) {
  23374. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23375. } else if ( weight === 0 && intPoint === l - 1 ) {
  23376. intPoint = l - 2;
  23377. weight = 1;
  23378. }
  23379. let p0, p3; // 4 points (p1 & p2 defined below)
  23380. if ( this.closed || intPoint > 0 ) {
  23381. p0 = points[ ( intPoint - 1 ) % l ];
  23382. } else {
  23383. // extrapolate first point
  23384. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23385. p0 = tmp;
  23386. }
  23387. const p1 = points[ intPoint % l ];
  23388. const p2 = points[ ( intPoint + 1 ) % l ];
  23389. if ( this.closed || intPoint + 2 < l ) {
  23390. p3 = points[ ( intPoint + 2 ) % l ];
  23391. } else {
  23392. // extrapolate last point
  23393. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23394. p3 = tmp;
  23395. }
  23396. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23397. // init Centripetal / Chordal Catmull-Rom
  23398. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23399. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23400. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23401. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23402. // safety check for repeated points
  23403. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23404. if ( dt0 < 1e-4 ) dt0 = dt1;
  23405. if ( dt2 < 1e-4 ) dt2 = dt1;
  23406. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23407. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23408. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23409. } else if ( this.curveType === 'catmullrom' ) {
  23410. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23411. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23412. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23413. }
  23414. point.set(
  23415. px.calc( weight ),
  23416. py.calc( weight ),
  23417. pz.calc( weight )
  23418. );
  23419. return point;
  23420. };
  23421. CatmullRomCurve3.prototype.copy = function ( source ) {
  23422. Curve.prototype.copy.call( this, source );
  23423. this.points = [];
  23424. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23425. const point = source.points[ i ];
  23426. this.points.push( point.clone() );
  23427. }
  23428. this.closed = source.closed;
  23429. this.curveType = source.curveType;
  23430. this.tension = source.tension;
  23431. return this;
  23432. };
  23433. CatmullRomCurve3.prototype.toJSON = function () {
  23434. const data = Curve.prototype.toJSON.call( this );
  23435. data.points = [];
  23436. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23437. const point = this.points[ i ];
  23438. data.points.push( point.toArray() );
  23439. }
  23440. data.closed = this.closed;
  23441. data.curveType = this.curveType;
  23442. data.tension = this.tension;
  23443. return data;
  23444. };
  23445. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  23446. Curve.prototype.fromJSON.call( this, json );
  23447. this.points = [];
  23448. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23449. const point = json.points[ i ];
  23450. this.points.push( new Vector3().fromArray( point ) );
  23451. }
  23452. this.closed = json.closed;
  23453. this.curveType = json.curveType;
  23454. this.tension = json.tension;
  23455. return this;
  23456. };
  23457. /**
  23458. * Bezier Curves formulas obtained from
  23459. * http://en.wikipedia.org/wiki/Bézier_curve
  23460. */
  23461. function CatmullRom( t, p0, p1, p2, p3 ) {
  23462. const v0 = ( p2 - p0 ) * 0.5;
  23463. const v1 = ( p3 - p1 ) * 0.5;
  23464. const t2 = t * t;
  23465. const t3 = t * t2;
  23466. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23467. }
  23468. //
  23469. function QuadraticBezierP0( t, p ) {
  23470. const k = 1 - t;
  23471. return k * k * p;
  23472. }
  23473. function QuadraticBezierP1( t, p ) {
  23474. return 2 * ( 1 - t ) * t * p;
  23475. }
  23476. function QuadraticBezierP2( t, p ) {
  23477. return t * t * p;
  23478. }
  23479. function QuadraticBezier( t, p0, p1, p2 ) {
  23480. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23481. QuadraticBezierP2( t, p2 );
  23482. }
  23483. //
  23484. function CubicBezierP0( t, p ) {
  23485. const k = 1 - t;
  23486. return k * k * k * p;
  23487. }
  23488. function CubicBezierP1( t, p ) {
  23489. const k = 1 - t;
  23490. return 3 * k * k * t * p;
  23491. }
  23492. function CubicBezierP2( t, p ) {
  23493. return 3 * ( 1 - t ) * t * t * p;
  23494. }
  23495. function CubicBezierP3( t, p ) {
  23496. return t * t * t * p;
  23497. }
  23498. function CubicBezier( t, p0, p1, p2, p3 ) {
  23499. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23500. CubicBezierP3( t, p3 );
  23501. }
  23502. function CubicBezierCurve( v0 = new Vector2$1(), v1 = new Vector2$1(), v2 = new Vector2$1(), v3 = new Vector2$1() ) {
  23503. Curve.call( this );
  23504. this.type = 'CubicBezierCurve';
  23505. this.v0 = v0;
  23506. this.v1 = v1;
  23507. this.v2 = v2;
  23508. this.v3 = v3;
  23509. }
  23510. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  23511. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23512. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23513. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23514. const point = optionalTarget;
  23515. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23516. point.set(
  23517. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23518. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23519. );
  23520. return point;
  23521. };
  23522. CubicBezierCurve.prototype.copy = function ( source ) {
  23523. Curve.prototype.copy.call( this, source );
  23524. this.v0.copy( source.v0 );
  23525. this.v1.copy( source.v1 );
  23526. this.v2.copy( source.v2 );
  23527. this.v3.copy( source.v3 );
  23528. return this;
  23529. };
  23530. CubicBezierCurve.prototype.toJSON = function () {
  23531. const data = Curve.prototype.toJSON.call( this );
  23532. data.v0 = this.v0.toArray();
  23533. data.v1 = this.v1.toArray();
  23534. data.v2 = this.v2.toArray();
  23535. data.v3 = this.v3.toArray();
  23536. return data;
  23537. };
  23538. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  23539. Curve.prototype.fromJSON.call( this, json );
  23540. this.v0.fromArray( json.v0 );
  23541. this.v1.fromArray( json.v1 );
  23542. this.v2.fromArray( json.v2 );
  23543. this.v3.fromArray( json.v3 );
  23544. return this;
  23545. };
  23546. function CubicBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23547. Curve.call( this );
  23548. this.type = 'CubicBezierCurve3';
  23549. this.v0 = v0;
  23550. this.v1 = v1;
  23551. this.v2 = v2;
  23552. this.v3 = v3;
  23553. }
  23554. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  23555. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23556. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23557. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23558. const point = optionalTarget;
  23559. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23560. point.set(
  23561. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23562. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23563. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23564. );
  23565. return point;
  23566. };
  23567. CubicBezierCurve3.prototype.copy = function ( source ) {
  23568. Curve.prototype.copy.call( this, source );
  23569. this.v0.copy( source.v0 );
  23570. this.v1.copy( source.v1 );
  23571. this.v2.copy( source.v2 );
  23572. this.v3.copy( source.v3 );
  23573. return this;
  23574. };
  23575. CubicBezierCurve3.prototype.toJSON = function () {
  23576. const data = Curve.prototype.toJSON.call( this );
  23577. data.v0 = this.v0.toArray();
  23578. data.v1 = this.v1.toArray();
  23579. data.v2 = this.v2.toArray();
  23580. data.v3 = this.v3.toArray();
  23581. return data;
  23582. };
  23583. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  23584. Curve.prototype.fromJSON.call( this, json );
  23585. this.v0.fromArray( json.v0 );
  23586. this.v1.fromArray( json.v1 );
  23587. this.v2.fromArray( json.v2 );
  23588. this.v3.fromArray( json.v3 );
  23589. return this;
  23590. };
  23591. function LineCurve( v1 = new Vector2$1(), v2 = new Vector2$1() ) {
  23592. Curve.call( this );
  23593. this.type = 'LineCurve';
  23594. this.v1 = v1;
  23595. this.v2 = v2;
  23596. }
  23597. LineCurve.prototype = Object.create( Curve.prototype );
  23598. LineCurve.prototype.constructor = LineCurve;
  23599. LineCurve.prototype.isLineCurve = true;
  23600. LineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23601. const point = optionalTarget;
  23602. if ( t === 1 ) {
  23603. point.copy( this.v2 );
  23604. } else {
  23605. point.copy( this.v2 ).sub( this.v1 );
  23606. point.multiplyScalar( t ).add( this.v1 );
  23607. }
  23608. return point;
  23609. };
  23610. // Line curve is linear, so we can overwrite default getPointAt
  23611. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  23612. return this.getPoint( u, optionalTarget );
  23613. };
  23614. LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
  23615. const tangent = optionalTarget || new Vector2$1();
  23616. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  23617. return tangent;
  23618. };
  23619. LineCurve.prototype.copy = function ( source ) {
  23620. Curve.prototype.copy.call( this, source );
  23621. this.v1.copy( source.v1 );
  23622. this.v2.copy( source.v2 );
  23623. return this;
  23624. };
  23625. LineCurve.prototype.toJSON = function () {
  23626. const data = Curve.prototype.toJSON.call( this );
  23627. data.v1 = this.v1.toArray();
  23628. data.v2 = this.v2.toArray();
  23629. return data;
  23630. };
  23631. LineCurve.prototype.fromJSON = function ( json ) {
  23632. Curve.prototype.fromJSON.call( this, json );
  23633. this.v1.fromArray( json.v1 );
  23634. this.v2.fromArray( json.v2 );
  23635. return this;
  23636. };
  23637. function LineCurve3( v1 = new Vector3(), v2 = new Vector3() ) {
  23638. Curve.call( this );
  23639. this.type = 'LineCurve3';
  23640. this.v1 = v1;
  23641. this.v2 = v2;
  23642. }
  23643. LineCurve3.prototype = Object.create( Curve.prototype );
  23644. LineCurve3.prototype.constructor = LineCurve3;
  23645. LineCurve3.prototype.isLineCurve3 = true;
  23646. LineCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23647. const point = optionalTarget;
  23648. if ( t === 1 ) {
  23649. point.copy( this.v2 );
  23650. } else {
  23651. point.copy( this.v2 ).sub( this.v1 );
  23652. point.multiplyScalar( t ).add( this.v1 );
  23653. }
  23654. return point;
  23655. };
  23656. // Line curve is linear, so we can overwrite default getPointAt
  23657. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  23658. return this.getPoint( u, optionalTarget );
  23659. };
  23660. LineCurve3.prototype.copy = function ( source ) {
  23661. Curve.prototype.copy.call( this, source );
  23662. this.v1.copy( source.v1 );
  23663. this.v2.copy( source.v2 );
  23664. return this;
  23665. };
  23666. LineCurve3.prototype.toJSON = function () {
  23667. const data = Curve.prototype.toJSON.call( this );
  23668. data.v1 = this.v1.toArray();
  23669. data.v2 = this.v2.toArray();
  23670. return data;
  23671. };
  23672. LineCurve3.prototype.fromJSON = function ( json ) {
  23673. Curve.prototype.fromJSON.call( this, json );
  23674. this.v1.fromArray( json.v1 );
  23675. this.v2.fromArray( json.v2 );
  23676. return this;
  23677. };
  23678. function QuadraticBezierCurve( v0 = new Vector2$1(), v1 = new Vector2$1(), v2 = new Vector2$1() ) {
  23679. Curve.call( this );
  23680. this.type = 'QuadraticBezierCurve';
  23681. this.v0 = v0;
  23682. this.v1 = v1;
  23683. this.v2 = v2;
  23684. }
  23685. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  23686. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23687. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23688. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23689. const point = optionalTarget;
  23690. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23691. point.set(
  23692. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23693. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23694. );
  23695. return point;
  23696. };
  23697. QuadraticBezierCurve.prototype.copy = function ( source ) {
  23698. Curve.prototype.copy.call( this, source );
  23699. this.v0.copy( source.v0 );
  23700. this.v1.copy( source.v1 );
  23701. this.v2.copy( source.v2 );
  23702. return this;
  23703. };
  23704. QuadraticBezierCurve.prototype.toJSON = function () {
  23705. const data = Curve.prototype.toJSON.call( this );
  23706. data.v0 = this.v0.toArray();
  23707. data.v1 = this.v1.toArray();
  23708. data.v2 = this.v2.toArray();
  23709. return data;
  23710. };
  23711. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  23712. Curve.prototype.fromJSON.call( this, json );
  23713. this.v0.fromArray( json.v0 );
  23714. this.v1.fromArray( json.v1 );
  23715. this.v2.fromArray( json.v2 );
  23716. return this;
  23717. };
  23718. function QuadraticBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23719. Curve.call( this );
  23720. this.type = 'QuadraticBezierCurve3';
  23721. this.v0 = v0;
  23722. this.v1 = v1;
  23723. this.v2 = v2;
  23724. }
  23725. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  23726. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23727. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23728. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23729. const point = optionalTarget;
  23730. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23731. point.set(
  23732. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23733. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23734. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23735. );
  23736. return point;
  23737. };
  23738. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  23739. Curve.prototype.copy.call( this, source );
  23740. this.v0.copy( source.v0 );
  23741. this.v1.copy( source.v1 );
  23742. this.v2.copy( source.v2 );
  23743. return this;
  23744. };
  23745. QuadraticBezierCurve3.prototype.toJSON = function () {
  23746. const data = Curve.prototype.toJSON.call( this );
  23747. data.v0 = this.v0.toArray();
  23748. data.v1 = this.v1.toArray();
  23749. data.v2 = this.v2.toArray();
  23750. return data;
  23751. };
  23752. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  23753. Curve.prototype.fromJSON.call( this, json );
  23754. this.v0.fromArray( json.v0 );
  23755. this.v1.fromArray( json.v1 );
  23756. this.v2.fromArray( json.v2 );
  23757. return this;
  23758. };
  23759. function SplineCurve( points = [] ) {
  23760. Curve.call( this );
  23761. this.type = 'SplineCurve';
  23762. this.points = points;
  23763. }
  23764. SplineCurve.prototype = Object.create( Curve.prototype );
  23765. SplineCurve.prototype.constructor = SplineCurve;
  23766. SplineCurve.prototype.isSplineCurve = true;
  23767. SplineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23768. const point = optionalTarget;
  23769. const points = this.points;
  23770. const p = ( points.length - 1 ) * t;
  23771. const intPoint = Math.floor( p );
  23772. const weight = p - intPoint;
  23773. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23774. const p1 = points[ intPoint ];
  23775. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23776. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23777. point.set(
  23778. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23779. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23780. );
  23781. return point;
  23782. };
  23783. SplineCurve.prototype.copy = function ( source ) {
  23784. Curve.prototype.copy.call( this, source );
  23785. this.points = [];
  23786. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23787. const point = source.points[ i ];
  23788. this.points.push( point.clone() );
  23789. }
  23790. return this;
  23791. };
  23792. SplineCurve.prototype.toJSON = function () {
  23793. const data = Curve.prototype.toJSON.call( this );
  23794. data.points = [];
  23795. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23796. const point = this.points[ i ];
  23797. data.points.push( point.toArray() );
  23798. }
  23799. return data;
  23800. };
  23801. SplineCurve.prototype.fromJSON = function ( json ) {
  23802. Curve.prototype.fromJSON.call( this, json );
  23803. this.points = [];
  23804. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23805. const point = json.points[ i ];
  23806. this.points.push( new Vector2$1().fromArray( point ) );
  23807. }
  23808. return this;
  23809. };
  23810. var Curves = /*#__PURE__*/Object.freeze({
  23811. __proto__: null,
  23812. ArcCurve: ArcCurve,
  23813. CatmullRomCurve3: CatmullRomCurve3,
  23814. CubicBezierCurve: CubicBezierCurve,
  23815. CubicBezierCurve3: CubicBezierCurve3,
  23816. EllipseCurve: EllipseCurve,
  23817. LineCurve: LineCurve,
  23818. LineCurve3: LineCurve3,
  23819. QuadraticBezierCurve: QuadraticBezierCurve,
  23820. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23821. SplineCurve: SplineCurve
  23822. });
  23823. /**************************************************************
  23824. * Curved Path - a curve path is simply a array of connected
  23825. * curves, but retains the api of a curve
  23826. **************************************************************/
  23827. function CurvePath() {
  23828. Curve.call( this );
  23829. this.type = 'CurvePath';
  23830. this.curves = [];
  23831. this.autoClose = false; // Automatically closes the path
  23832. }
  23833. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  23834. constructor: CurvePath,
  23835. add: function ( curve ) {
  23836. this.curves.push( curve );
  23837. },
  23838. closePath: function () {
  23839. // Add a line curve if start and end of lines are not connected
  23840. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23841. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23842. if ( ! startPoint.equals( endPoint ) ) {
  23843. this.curves.push( new LineCurve( endPoint, startPoint ) );
  23844. }
  23845. },
  23846. // To get accurate point with reference to
  23847. // entire path distance at time t,
  23848. // following has to be done:
  23849. // 1. Length of each sub path have to be known
  23850. // 2. Locate and identify type of curve
  23851. // 3. Get t for the curve
  23852. // 4. Return curve.getPointAt(t')
  23853. getPoint: function ( t ) {
  23854. const d = t * this.getLength();
  23855. const curveLengths = this.getCurveLengths();
  23856. let i = 0;
  23857. // To think about boundaries points.
  23858. while ( i < curveLengths.length ) {
  23859. if ( curveLengths[ i ] >= d ) {
  23860. const diff = curveLengths[ i ] - d;
  23861. const curve = this.curves[ i ];
  23862. const segmentLength = curve.getLength();
  23863. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23864. return curve.getPointAt( u );
  23865. }
  23866. i ++;
  23867. }
  23868. return null;
  23869. // loop where sum != 0, sum > d , sum+1 <d
  23870. },
  23871. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23872. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23873. // getPoint() depends on getLength
  23874. getLength: function () {
  23875. const lens = this.getCurveLengths();
  23876. return lens[ lens.length - 1 ];
  23877. },
  23878. // cacheLengths must be recalculated.
  23879. updateArcLengths: function () {
  23880. this.needsUpdate = true;
  23881. this.cacheLengths = null;
  23882. this.getCurveLengths();
  23883. },
  23884. // Compute lengths and cache them
  23885. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23886. getCurveLengths: function () {
  23887. // We use cache values if curves and cache array are same length
  23888. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23889. return this.cacheLengths;
  23890. }
  23891. // Get length of sub-curve
  23892. // Push sums into cached array
  23893. const lengths = [];
  23894. let sums = 0;
  23895. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23896. sums += this.curves[ i ].getLength();
  23897. lengths.push( sums );
  23898. }
  23899. this.cacheLengths = lengths;
  23900. return lengths;
  23901. },
  23902. getSpacedPoints: function ( divisions = 40 ) {
  23903. const points = [];
  23904. for ( let i = 0; i <= divisions; i ++ ) {
  23905. points.push( this.getPoint( i / divisions ) );
  23906. }
  23907. if ( this.autoClose ) {
  23908. points.push( points[ 0 ] );
  23909. }
  23910. return points;
  23911. },
  23912. getPoints: function ( divisions = 12 ) {
  23913. const points = [];
  23914. let last;
  23915. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23916. const curve = curves[ i ];
  23917. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  23918. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  23919. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  23920. : divisions;
  23921. const pts = curve.getPoints( resolution );
  23922. for ( let j = 0; j < pts.length; j ++ ) {
  23923. const point = pts[ j ];
  23924. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23925. points.push( point );
  23926. last = point;
  23927. }
  23928. }
  23929. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23930. points.push( points[ 0 ] );
  23931. }
  23932. return points;
  23933. },
  23934. copy: function ( source ) {
  23935. Curve.prototype.copy.call( this, source );
  23936. this.curves = [];
  23937. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23938. const curve = source.curves[ i ];
  23939. this.curves.push( curve.clone() );
  23940. }
  23941. this.autoClose = source.autoClose;
  23942. return this;
  23943. },
  23944. toJSON: function () {
  23945. const data = Curve.prototype.toJSON.call( this );
  23946. data.autoClose = this.autoClose;
  23947. data.curves = [];
  23948. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23949. const curve = this.curves[ i ];
  23950. data.curves.push( curve.toJSON() );
  23951. }
  23952. return data;
  23953. },
  23954. fromJSON: function ( json ) {
  23955. Curve.prototype.fromJSON.call( this, json );
  23956. this.autoClose = json.autoClose;
  23957. this.curves = [];
  23958. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23959. const curve = json.curves[ i ];
  23960. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23961. }
  23962. return this;
  23963. }
  23964. } );
  23965. function Path( points ) {
  23966. CurvePath.call( this );
  23967. this.type = 'Path';
  23968. this.currentPoint = new Vector2$1();
  23969. if ( points ) {
  23970. this.setFromPoints( points );
  23971. }
  23972. }
  23973. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  23974. constructor: Path,
  23975. setFromPoints: function ( points ) {
  23976. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23977. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23978. this.lineTo( points[ i ].x, points[ i ].y );
  23979. }
  23980. return this;
  23981. },
  23982. moveTo: function ( x, y ) {
  23983. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23984. return this;
  23985. },
  23986. lineTo: function ( x, y ) {
  23987. const curve = new LineCurve( this.currentPoint.clone(), new Vector2$1( x, y ) );
  23988. this.curves.push( curve );
  23989. this.currentPoint.set( x, y );
  23990. return this;
  23991. },
  23992. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  23993. const curve = new QuadraticBezierCurve(
  23994. this.currentPoint.clone(),
  23995. new Vector2$1( aCPx, aCPy ),
  23996. new Vector2$1( aX, aY )
  23997. );
  23998. this.curves.push( curve );
  23999. this.currentPoint.set( aX, aY );
  24000. return this;
  24001. },
  24002. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24003. const curve = new CubicBezierCurve(
  24004. this.currentPoint.clone(),
  24005. new Vector2$1( aCP1x, aCP1y ),
  24006. new Vector2$1( aCP2x, aCP2y ),
  24007. new Vector2$1( aX, aY )
  24008. );
  24009. this.curves.push( curve );
  24010. this.currentPoint.set( aX, aY );
  24011. return this;
  24012. },
  24013. splineThru: function ( pts /*Array of Vector*/ ) {
  24014. const npts = [ this.currentPoint.clone() ].concat( pts );
  24015. const curve = new SplineCurve( npts );
  24016. this.curves.push( curve );
  24017. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24018. return this;
  24019. },
  24020. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24021. const x0 = this.currentPoint.x;
  24022. const y0 = this.currentPoint.y;
  24023. this.absarc( aX + x0, aY + y0, aRadius,
  24024. aStartAngle, aEndAngle, aClockwise );
  24025. return this;
  24026. },
  24027. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24028. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24029. return this;
  24030. },
  24031. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24032. const x0 = this.currentPoint.x;
  24033. const y0 = this.currentPoint.y;
  24034. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24035. return this;
  24036. },
  24037. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24038. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24039. if ( this.curves.length > 0 ) {
  24040. // if a previous curve is present, attempt to join
  24041. const firstPoint = curve.getPoint( 0 );
  24042. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24043. this.lineTo( firstPoint.x, firstPoint.y );
  24044. }
  24045. }
  24046. this.curves.push( curve );
  24047. const lastPoint = curve.getPoint( 1 );
  24048. this.currentPoint.copy( lastPoint );
  24049. return this;
  24050. },
  24051. copy: function ( source ) {
  24052. CurvePath.prototype.copy.call( this, source );
  24053. this.currentPoint.copy( source.currentPoint );
  24054. return this;
  24055. },
  24056. toJSON: function () {
  24057. const data = CurvePath.prototype.toJSON.call( this );
  24058. data.currentPoint = this.currentPoint.toArray();
  24059. return data;
  24060. },
  24061. fromJSON: function ( json ) {
  24062. CurvePath.prototype.fromJSON.call( this, json );
  24063. this.currentPoint.fromArray( json.currentPoint );
  24064. return this;
  24065. }
  24066. } );
  24067. function Shape( points ) {
  24068. Path.call( this, points );
  24069. this.uuid = MathUtils.generateUUID();
  24070. this.type = 'Shape';
  24071. this.holes = [];
  24072. }
  24073. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  24074. constructor: Shape,
  24075. getPointsHoles: function ( divisions ) {
  24076. const holesPts = [];
  24077. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24078. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24079. }
  24080. return holesPts;
  24081. },
  24082. // get points of shape and holes (keypoints based on segments parameter)
  24083. extractPoints: function ( divisions ) {
  24084. return {
  24085. shape: this.getPoints( divisions ),
  24086. holes: this.getPointsHoles( divisions )
  24087. };
  24088. },
  24089. copy: function ( source ) {
  24090. Path.prototype.copy.call( this, source );
  24091. this.holes = [];
  24092. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24093. const hole = source.holes[ i ];
  24094. this.holes.push( hole.clone() );
  24095. }
  24096. return this;
  24097. },
  24098. toJSON: function () {
  24099. const data = Path.prototype.toJSON.call( this );
  24100. data.uuid = this.uuid;
  24101. data.holes = [];
  24102. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24103. const hole = this.holes[ i ];
  24104. data.holes.push( hole.toJSON() );
  24105. }
  24106. return data;
  24107. },
  24108. fromJSON: function ( json ) {
  24109. Path.prototype.fromJSON.call( this, json );
  24110. this.uuid = json.uuid;
  24111. this.holes = [];
  24112. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24113. const hole = json.holes[ i ];
  24114. this.holes.push( new Path().fromJSON( hole ) );
  24115. }
  24116. return this;
  24117. }
  24118. } );
  24119. function Light( color, intensity = 1 ) {
  24120. Object3D.call( this );
  24121. this.type = 'Light';
  24122. this.color = new Color( color );
  24123. this.intensity = intensity;
  24124. }
  24125. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24126. constructor: Light,
  24127. isLight: true,
  24128. copy: function ( source ) {
  24129. Object3D.prototype.copy.call( this, source );
  24130. this.color.copy( source.color );
  24131. this.intensity = source.intensity;
  24132. return this;
  24133. },
  24134. toJSON: function ( meta ) {
  24135. const data = Object3D.prototype.toJSON.call( this, meta );
  24136. data.object.color = this.color.getHex();
  24137. data.object.intensity = this.intensity;
  24138. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24139. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24140. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24141. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24142. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24143. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24144. return data;
  24145. }
  24146. } );
  24147. function HemisphereLight( skyColor, groundColor, intensity ) {
  24148. Light.call( this, skyColor, intensity );
  24149. this.type = 'HemisphereLight';
  24150. this.position.copy( Object3D.DefaultUp );
  24151. this.updateMatrix();
  24152. this.groundColor = new Color( groundColor );
  24153. }
  24154. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24155. constructor: HemisphereLight,
  24156. isHemisphereLight: true,
  24157. copy: function ( source ) {
  24158. Light.prototype.copy.call( this, source );
  24159. this.groundColor.copy( source.groundColor );
  24160. return this;
  24161. }
  24162. } );
  24163. function LightShadow( camera ) {
  24164. this.camera = camera;
  24165. this.bias = 0;
  24166. this.normalBias = 0;
  24167. this.radius = 1;
  24168. this.mapSize = new Vector2$1( 512, 512 );
  24169. this.map = null;
  24170. this.mapPass = null;
  24171. this.matrix = new Matrix4();
  24172. this.autoUpdate = true;
  24173. this.needsUpdate = false;
  24174. this._frustum = new Frustum();
  24175. this._frameExtents = new Vector2$1( 1, 1 );
  24176. this._viewportCount = 1;
  24177. this._viewports = [
  24178. new Vector4( 0, 0, 1, 1 )
  24179. ];
  24180. }
  24181. Object.assign( LightShadow.prototype, {
  24182. _projScreenMatrix: new Matrix4(),
  24183. _lightPositionWorld: new Vector3(),
  24184. _lookTarget: new Vector3(),
  24185. getViewportCount: function () {
  24186. return this._viewportCount;
  24187. },
  24188. getFrustum: function () {
  24189. return this._frustum;
  24190. },
  24191. updateMatrices: function ( light ) {
  24192. const shadowCamera = this.camera,
  24193. shadowMatrix = this.matrix,
  24194. projScreenMatrix = this._projScreenMatrix,
  24195. lookTarget = this._lookTarget,
  24196. lightPositionWorld = this._lightPositionWorld;
  24197. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24198. shadowCamera.position.copy( lightPositionWorld );
  24199. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  24200. shadowCamera.lookAt( lookTarget );
  24201. shadowCamera.updateMatrixWorld();
  24202. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24203. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  24204. shadowMatrix.set(
  24205. 0.5, 0.0, 0.0, 0.5,
  24206. 0.0, 0.5, 0.0, 0.5,
  24207. 0.0, 0.0, 0.5, 0.5,
  24208. 0.0, 0.0, 0.0, 1.0
  24209. );
  24210. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24211. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24212. },
  24213. getViewport: function ( viewportIndex ) {
  24214. return this._viewports[ viewportIndex ];
  24215. },
  24216. getFrameExtents: function () {
  24217. return this._frameExtents;
  24218. },
  24219. copy: function ( source ) {
  24220. this.camera = source.camera.clone();
  24221. this.bias = source.bias;
  24222. this.radius = source.radius;
  24223. this.mapSize.copy( source.mapSize );
  24224. return this;
  24225. },
  24226. clone: function () {
  24227. return new this.constructor().copy( this );
  24228. },
  24229. toJSON: function () {
  24230. const object = {};
  24231. if ( this.bias !== 0 ) object.bias = this.bias;
  24232. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24233. if ( this.radius !== 1 ) object.radius = this.radius;
  24234. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24235. object.camera = this.camera.toJSON( false ).object;
  24236. delete object.camera.matrix;
  24237. return object;
  24238. }
  24239. } );
  24240. function SpotLightShadow() {
  24241. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24242. this.focus = 1;
  24243. }
  24244. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24245. constructor: SpotLightShadow,
  24246. isSpotLightShadow: true,
  24247. updateMatrices: function ( light ) {
  24248. const camera = this.camera;
  24249. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  24250. const aspect = this.mapSize.width / this.mapSize.height;
  24251. const far = light.distance || camera.far;
  24252. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24253. camera.fov = fov;
  24254. camera.aspect = aspect;
  24255. camera.far = far;
  24256. camera.updateProjectionMatrix();
  24257. }
  24258. LightShadow.prototype.updateMatrices.call( this, light );
  24259. }
  24260. } );
  24261. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  24262. Light.call( this, color, intensity );
  24263. this.type = 'SpotLight';
  24264. this.position.copy( Object3D.DefaultUp );
  24265. this.updateMatrix();
  24266. this.target = new Object3D();
  24267. Object.defineProperty( this, 'power', {
  24268. get: function () {
  24269. // intensity = power per solid angle.
  24270. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24271. return this.intensity * Math.PI;
  24272. },
  24273. set: function ( power ) {
  24274. // intensity = power per solid angle.
  24275. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24276. this.intensity = power / Math.PI;
  24277. }
  24278. } );
  24279. this.distance = ( distance !== undefined ) ? distance : 0;
  24280. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  24281. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  24282. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24283. this.shadow = new SpotLightShadow();
  24284. }
  24285. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24286. constructor: SpotLight,
  24287. isSpotLight: true,
  24288. copy: function ( source ) {
  24289. Light.prototype.copy.call( this, source );
  24290. this.distance = source.distance;
  24291. this.angle = source.angle;
  24292. this.penumbra = source.penumbra;
  24293. this.decay = source.decay;
  24294. this.target = source.target.clone();
  24295. this.shadow = source.shadow.clone();
  24296. return this;
  24297. }
  24298. } );
  24299. function PointLightShadow() {
  24300. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24301. this._frameExtents = new Vector2$1( 4, 2 );
  24302. this._viewportCount = 6;
  24303. this._viewports = [
  24304. // These viewports map a cube-map onto a 2D texture with the
  24305. // following orientation:
  24306. //
  24307. // xzXZ
  24308. // y Y
  24309. //
  24310. // X - Positive x direction
  24311. // x - Negative x direction
  24312. // Y - Positive y direction
  24313. // y - Negative y direction
  24314. // Z - Positive z direction
  24315. // z - Negative z direction
  24316. // positive X
  24317. new Vector4( 2, 1, 1, 1 ),
  24318. // negative X
  24319. new Vector4( 0, 1, 1, 1 ),
  24320. // positive Z
  24321. new Vector4( 3, 1, 1, 1 ),
  24322. // negative Z
  24323. new Vector4( 1, 1, 1, 1 ),
  24324. // positive Y
  24325. new Vector4( 3, 0, 1, 1 ),
  24326. // negative Y
  24327. new Vector4( 1, 0, 1, 1 )
  24328. ];
  24329. this._cubeDirections = [
  24330. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24331. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24332. ];
  24333. this._cubeUps = [
  24334. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24335. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24336. ];
  24337. }
  24338. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24339. constructor: PointLightShadow,
  24340. isPointLightShadow: true,
  24341. updateMatrices: function ( light, viewportIndex = 0 ) {
  24342. const camera = this.camera,
  24343. shadowMatrix = this.matrix,
  24344. lightPositionWorld = this._lightPositionWorld,
  24345. lookTarget = this._lookTarget,
  24346. projScreenMatrix = this._projScreenMatrix;
  24347. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24348. camera.position.copy( lightPositionWorld );
  24349. lookTarget.copy( camera.position );
  24350. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24351. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24352. camera.lookAt( lookTarget );
  24353. camera.updateMatrixWorld();
  24354. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  24355. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24356. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  24357. }
  24358. } );
  24359. function PointLight( color, intensity, distance, decay ) {
  24360. Light.call( this, color, intensity );
  24361. this.type = 'PointLight';
  24362. Object.defineProperty( this, 'power', {
  24363. get: function () {
  24364. // intensity = power per solid angle.
  24365. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24366. return this.intensity * 4 * Math.PI;
  24367. },
  24368. set: function ( power ) {
  24369. // intensity = power per solid angle.
  24370. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24371. this.intensity = power / ( 4 * Math.PI );
  24372. }
  24373. } );
  24374. this.distance = ( distance !== undefined ) ? distance : 0;
  24375. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24376. this.shadow = new PointLightShadow();
  24377. }
  24378. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24379. constructor: PointLight,
  24380. isPointLight: true,
  24381. copy: function ( source ) {
  24382. Light.prototype.copy.call( this, source );
  24383. this.distance = source.distance;
  24384. this.decay = source.decay;
  24385. this.shadow = source.shadow.clone();
  24386. return this;
  24387. }
  24388. } );
  24389. function OrthographicCamera( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  24390. Camera.call( this );
  24391. this.type = 'OrthographicCamera';
  24392. this.zoom = 1;
  24393. this.view = null;
  24394. this.left = left;
  24395. this.right = right;
  24396. this.top = top;
  24397. this.bottom = bottom;
  24398. this.near = near;
  24399. this.far = far;
  24400. this.updateProjectionMatrix();
  24401. }
  24402. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  24403. constructor: OrthographicCamera,
  24404. isOrthographicCamera: true,
  24405. copy: function ( source, recursive ) {
  24406. Camera.prototype.copy.call( this, source, recursive );
  24407. this.left = source.left;
  24408. this.right = source.right;
  24409. this.top = source.top;
  24410. this.bottom = source.bottom;
  24411. this.near = source.near;
  24412. this.far = source.far;
  24413. this.zoom = source.zoom;
  24414. this.view = source.view === null ? null : Object.assign( {}, source.view );
  24415. return this;
  24416. },
  24417. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  24418. if ( this.view === null ) {
  24419. this.view = {
  24420. enabled: true,
  24421. fullWidth: 1,
  24422. fullHeight: 1,
  24423. offsetX: 0,
  24424. offsetY: 0,
  24425. width: 1,
  24426. height: 1
  24427. };
  24428. }
  24429. this.view.enabled = true;
  24430. this.view.fullWidth = fullWidth;
  24431. this.view.fullHeight = fullHeight;
  24432. this.view.offsetX = x;
  24433. this.view.offsetY = y;
  24434. this.view.width = width;
  24435. this.view.height = height;
  24436. this.updateProjectionMatrix();
  24437. },
  24438. clearViewOffset: function () {
  24439. if ( this.view !== null ) {
  24440. this.view.enabled = false;
  24441. }
  24442. this.updateProjectionMatrix();
  24443. },
  24444. updateProjectionMatrix: function () {
  24445. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  24446. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  24447. const cx = ( this.right + this.left ) / 2;
  24448. const cy = ( this.top + this.bottom ) / 2;
  24449. let left = cx - dx;
  24450. let right = cx + dx;
  24451. let top = cy + dy;
  24452. let bottom = cy - dy;
  24453. if ( this.view !== null && this.view.enabled ) {
  24454. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  24455. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  24456. left += scaleW * this.view.offsetX;
  24457. right = left + scaleW * this.view.width;
  24458. top -= scaleH * this.view.offsetY;
  24459. bottom = top - scaleH * this.view.height;
  24460. }
  24461. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  24462. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  24463. },
  24464. toJSON: function ( meta ) {
  24465. const data = Object3D.prototype.toJSON.call( this, meta );
  24466. data.object.zoom = this.zoom;
  24467. data.object.left = this.left;
  24468. data.object.right = this.right;
  24469. data.object.top = this.top;
  24470. data.object.bottom = this.bottom;
  24471. data.object.near = this.near;
  24472. data.object.far = this.far;
  24473. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  24474. return data;
  24475. }
  24476. } );
  24477. function DirectionalLightShadow() {
  24478. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24479. }
  24480. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24481. constructor: DirectionalLightShadow,
  24482. isDirectionalLightShadow: true,
  24483. updateMatrices: function ( light ) {
  24484. LightShadow.prototype.updateMatrices.call( this, light );
  24485. }
  24486. } );
  24487. function DirectionalLight( color, intensity ) {
  24488. Light.call( this, color, intensity );
  24489. this.type = 'DirectionalLight';
  24490. this.position.copy( Object3D.DefaultUp );
  24491. this.updateMatrix();
  24492. this.target = new Object3D();
  24493. this.shadow = new DirectionalLightShadow();
  24494. }
  24495. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24496. constructor: DirectionalLight,
  24497. isDirectionalLight: true,
  24498. copy: function ( source ) {
  24499. Light.prototype.copy.call( this, source );
  24500. this.target = source.target.clone();
  24501. this.shadow = source.shadow.clone();
  24502. return this;
  24503. }
  24504. } );
  24505. function AmbientLight( color, intensity ) {
  24506. Light.call( this, color, intensity );
  24507. this.type = 'AmbientLight';
  24508. }
  24509. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24510. constructor: AmbientLight,
  24511. isAmbientLight: true
  24512. } );
  24513. function RectAreaLight( color, intensity, width, height ) {
  24514. Light.call( this, color, intensity );
  24515. this.type = 'RectAreaLight';
  24516. this.width = ( width !== undefined ) ? width : 10;
  24517. this.height = ( height !== undefined ) ? height : 10;
  24518. }
  24519. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24520. constructor: RectAreaLight,
  24521. isRectAreaLight: true,
  24522. copy: function ( source ) {
  24523. Light.prototype.copy.call( this, source );
  24524. this.width = source.width;
  24525. this.height = source.height;
  24526. return this;
  24527. },
  24528. toJSON: function ( meta ) {
  24529. const data = Light.prototype.toJSON.call( this, meta );
  24530. data.object.width = this.width;
  24531. data.object.height = this.height;
  24532. return data;
  24533. }
  24534. } );
  24535. /**
  24536. * Primary reference:
  24537. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24538. *
  24539. * Secondary reference:
  24540. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24541. */
  24542. // 3-band SH defined by 9 coefficients
  24543. class SphericalHarmonics3 {
  24544. constructor() {
  24545. Object.defineProperty( this, 'isSphericalHarmonics3', { value: true } );
  24546. this.coefficients = [];
  24547. for ( let i = 0; i < 9; i ++ ) {
  24548. this.coefficients.push( new Vector3() );
  24549. }
  24550. }
  24551. set( coefficients ) {
  24552. for ( let i = 0; i < 9; i ++ ) {
  24553. this.coefficients[ i ].copy( coefficients[ i ] );
  24554. }
  24555. return this;
  24556. }
  24557. zero() {
  24558. for ( let i = 0; i < 9; i ++ ) {
  24559. this.coefficients[ i ].set( 0, 0, 0 );
  24560. }
  24561. return this;
  24562. }
  24563. // get the radiance in the direction of the normal
  24564. // target is a Vector3
  24565. getAt( normal, target ) {
  24566. // normal is assumed to be unit length
  24567. const x = normal.x, y = normal.y, z = normal.z;
  24568. const coeff = this.coefficients;
  24569. // band 0
  24570. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24571. // band 1
  24572. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24573. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24574. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24575. // band 2
  24576. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24577. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24578. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24579. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24580. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24581. return target;
  24582. }
  24583. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24584. // target is a Vector3
  24585. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24586. getIrradianceAt( normal, target ) {
  24587. // normal is assumed to be unit length
  24588. const x = normal.x, y = normal.y, z = normal.z;
  24589. const coeff = this.coefficients;
  24590. // band 0
  24591. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24592. // band 1
  24593. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24594. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24595. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24596. // band 2
  24597. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24598. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24599. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24600. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24601. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24602. return target;
  24603. }
  24604. add( sh ) {
  24605. for ( let i = 0; i < 9; i ++ ) {
  24606. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24607. }
  24608. return this;
  24609. }
  24610. addScaledSH( sh, s ) {
  24611. for ( let i = 0; i < 9; i ++ ) {
  24612. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24613. }
  24614. return this;
  24615. }
  24616. scale( s ) {
  24617. for ( let i = 0; i < 9; i ++ ) {
  24618. this.coefficients[ i ].multiplyScalar( s );
  24619. }
  24620. return this;
  24621. }
  24622. lerp( sh, alpha ) {
  24623. for ( let i = 0; i < 9; i ++ ) {
  24624. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24625. }
  24626. return this;
  24627. }
  24628. equals( sh ) {
  24629. for ( let i = 0; i < 9; i ++ ) {
  24630. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24631. return false;
  24632. }
  24633. }
  24634. return true;
  24635. }
  24636. copy( sh ) {
  24637. return this.set( sh.coefficients );
  24638. }
  24639. clone() {
  24640. return new this.constructor().copy( this );
  24641. }
  24642. fromArray( array, offset = 0 ) {
  24643. const coefficients = this.coefficients;
  24644. for ( let i = 0; i < 9; i ++ ) {
  24645. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24646. }
  24647. return this;
  24648. }
  24649. toArray( array = [], offset = 0 ) {
  24650. const coefficients = this.coefficients;
  24651. for ( let i = 0; i < 9; i ++ ) {
  24652. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24653. }
  24654. return array;
  24655. }
  24656. // evaluate the basis functions
  24657. // shBasis is an Array[ 9 ]
  24658. static getBasisAt( normal, shBasis ) {
  24659. // normal is assumed to be unit length
  24660. const x = normal.x, y = normal.y, z = normal.z;
  24661. // band 0
  24662. shBasis[ 0 ] = 0.282095;
  24663. // band 1
  24664. shBasis[ 1 ] = 0.488603 * y;
  24665. shBasis[ 2 ] = 0.488603 * z;
  24666. shBasis[ 3 ] = 0.488603 * x;
  24667. // band 2
  24668. shBasis[ 4 ] = 1.092548 * x * y;
  24669. shBasis[ 5 ] = 1.092548 * y * z;
  24670. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24671. shBasis[ 7 ] = 1.092548 * x * z;
  24672. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24673. }
  24674. }
  24675. function LightProbe( sh, intensity ) {
  24676. Light.call( this, undefined, intensity );
  24677. this.type = 'LightProbe';
  24678. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  24679. }
  24680. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  24681. constructor: LightProbe,
  24682. isLightProbe: true,
  24683. copy: function ( source ) {
  24684. Light.prototype.copy.call( this, source );
  24685. this.sh.copy( source.sh );
  24686. return this;
  24687. },
  24688. fromJSON: function ( json ) {
  24689. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24690. this.sh.fromArray( json.sh );
  24691. return this;
  24692. },
  24693. toJSON: function ( meta ) {
  24694. const data = Light.prototype.toJSON.call( this, meta );
  24695. data.object.sh = this.sh.toArray();
  24696. return data;
  24697. }
  24698. } );
  24699. function MaterialLoader( manager ) {
  24700. Loader.call( this, manager );
  24701. this.textures = {};
  24702. }
  24703. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24704. constructor: MaterialLoader,
  24705. load: function ( url, onLoad, onProgress, onError ) {
  24706. const scope = this;
  24707. const loader = new FileLoader( scope.manager );
  24708. loader.setPath( scope.path );
  24709. loader.setRequestHeader( scope.requestHeader );
  24710. loader.setWithCredentials( scope.withCredentials );
  24711. loader.load( url, function ( text ) {
  24712. try {
  24713. onLoad( scope.parse( JSON.parse( text ) ) );
  24714. } catch ( e ) {
  24715. if ( onError ) {
  24716. onError( e );
  24717. } else {
  24718. console.error( e );
  24719. }
  24720. scope.manager.itemError( url );
  24721. }
  24722. }, onProgress, onError );
  24723. },
  24724. parse: function ( json ) {
  24725. const textures = this.textures;
  24726. function getTexture( name ) {
  24727. if ( textures[ name ] === undefined ) {
  24728. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24729. }
  24730. return textures[ name ];
  24731. }
  24732. const material = new Materials[ json.type ]();
  24733. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24734. if ( json.name !== undefined ) material.name = json.name;
  24735. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24736. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24737. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24738. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  24739. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24740. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24741. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24742. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24743. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24744. if ( json.fog !== undefined ) material.fog = json.fog;
  24745. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24746. if ( json.blending !== undefined ) material.blending = json.blending;
  24747. if ( json.combine !== undefined ) material.combine = json.combine;
  24748. if ( json.side !== undefined ) material.side = json.side;
  24749. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24750. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24751. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24752. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24753. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24754. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24755. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24756. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24757. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24758. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24759. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24760. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24761. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24762. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24763. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24764. if ( json.wireframelineWidth !== undefined ) material.wireframelineWidth = json.wireframelineWidth;
  24765. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24766. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24767. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24768. if ( json.lineWidth !== 1 ) material.lineWidth = json.lineWidth;
  24769. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24770. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24771. if ( json.scale !== undefined ) material.scale = json.scale;
  24772. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24773. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24774. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24775. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  24776. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  24777. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  24778. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24779. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  24780. if ( json.visible !== undefined ) material.visible = json.visible;
  24781. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24782. if ( json.userData !== undefined ) material.userData = json.userData;
  24783. if ( json.vertexColors !== undefined ) {
  24784. if ( typeof json.vertexColors === 'number' ) {
  24785. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24786. } else {
  24787. material.vertexColors = json.vertexColors;
  24788. }
  24789. }
  24790. // Shader Material
  24791. if ( json.uniforms !== undefined ) {
  24792. for ( const name in json.uniforms ) {
  24793. const uniform = json.uniforms[ name ];
  24794. material.uniforms[ name ] = {};
  24795. switch ( uniform.type ) {
  24796. case 't':
  24797. material.uniforms[ name ].value = getTexture( uniform.value );
  24798. break;
  24799. case 'c':
  24800. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24801. break;
  24802. case 'v2':
  24803. material.uniforms[ name ].value = new Vector2$1().fromArray( uniform.value );
  24804. break;
  24805. case 'v3':
  24806. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24807. break;
  24808. case 'v4':
  24809. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24810. break;
  24811. case 'm3':
  24812. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24813. break;
  24814. case 'm4':
  24815. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24816. break;
  24817. default:
  24818. material.uniforms[ name ].value = uniform.value;
  24819. }
  24820. }
  24821. }
  24822. if ( json.defines !== undefined ) material.defines = json.defines;
  24823. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24824. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24825. if ( json.extensions !== undefined ) {
  24826. for ( const key in json.extensions ) {
  24827. material.extensions[ key ] = json.extensions[ key ];
  24828. }
  24829. }
  24830. // Deprecated
  24831. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24832. // for PointsMaterial
  24833. if ( json.size !== undefined ) material.size = json.size;
  24834. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24835. // maps
  24836. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24837. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24838. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24839. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24840. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24841. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24842. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24843. if ( json.normalScale !== undefined ) {
  24844. let normalScale = json.normalScale;
  24845. if ( Array.isArray( normalScale ) === false ) {
  24846. // Blender exporter used to export a scalar. See #7459
  24847. normalScale = [ normalScale, normalScale ];
  24848. }
  24849. material.normalScale = new Vector2$1().fromArray( normalScale );
  24850. }
  24851. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24852. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24853. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24854. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24855. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24856. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24857. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24858. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24859. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24860. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24861. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24862. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24863. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24864. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24865. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24866. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24867. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24868. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24869. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24870. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24871. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2$1().fromArray( json.clearcoatNormalScale );
  24872. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24873. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24874. return material;
  24875. },
  24876. setTextures: function ( value ) {
  24877. this.textures = value;
  24878. return this;
  24879. }
  24880. } );
  24881. const LoaderUtils = {
  24882. decodeText: function ( array ) {
  24883. if ( typeof TextDecoder !== 'undefined' ) {
  24884. return new TextDecoder().decode( array );
  24885. }
  24886. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24887. // throws a "maximum call stack size exceeded" error for large arrays.
  24888. let s = '';
  24889. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24890. // Implicitly assumes little-endian.
  24891. s += String.fromCharCode( array[ i ] );
  24892. }
  24893. try {
  24894. // merges multi-byte utf-8 characters.
  24895. return decodeURIComponent( escape( s ) );
  24896. } catch ( e ) { // see #16358
  24897. return s;
  24898. }
  24899. },
  24900. extractUrlBase: function ( url ) {
  24901. const index = url.lastIndexOf( '/' );
  24902. if ( index === - 1 ) return './';
  24903. return url.substr( 0, index + 1 );
  24904. }
  24905. };
  24906. function InstancedBufferGeometry() {
  24907. BufferGeometry.call( this );
  24908. this.type = 'InstancedBufferGeometry';
  24909. this.instanceCount = Infinity;
  24910. }
  24911. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  24912. constructor: InstancedBufferGeometry,
  24913. isInstancedBufferGeometry: true,
  24914. copy: function ( source ) {
  24915. BufferGeometry.prototype.copy.call( this, source );
  24916. this.instanceCount = source.instanceCount;
  24917. return this;
  24918. },
  24919. clone: function () {
  24920. return new this.constructor().copy( this );
  24921. },
  24922. toJSON: function () {
  24923. const data = BufferGeometry.prototype.toJSON.call( this );
  24924. data.instanceCount = this.instanceCount;
  24925. data.isInstancedBufferGeometry = true;
  24926. return data;
  24927. }
  24928. } );
  24929. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  24930. if ( typeof ( normalized ) === 'number' ) {
  24931. meshPerAttribute = normalized;
  24932. normalized = false;
  24933. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  24934. }
  24935. BufferAttribute.call( this, array, itemSize, normalized );
  24936. this.meshPerAttribute = meshPerAttribute || 1;
  24937. }
  24938. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24939. constructor: InstancedBufferAttribute,
  24940. isInstancedBufferAttribute: true,
  24941. copy: function ( source ) {
  24942. BufferAttribute.prototype.copy.call( this, source );
  24943. this.meshPerAttribute = source.meshPerAttribute;
  24944. return this;
  24945. },
  24946. toJSON: function () {
  24947. const data = BufferAttribute.prototype.toJSON.call( this );
  24948. data.meshPerAttribute = this.meshPerAttribute;
  24949. data.isInstancedBufferAttribute = true;
  24950. return data;
  24951. }
  24952. } );
  24953. function BufferGeometryLoader( manager ) {
  24954. Loader.call( this, manager );
  24955. }
  24956. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24957. constructor: BufferGeometryLoader,
  24958. load: function ( url, onLoad, onProgress, onError ) {
  24959. const scope = this;
  24960. const loader = new FileLoader( scope.manager );
  24961. loader.setPath( scope.path );
  24962. loader.setRequestHeader( scope.requestHeader );
  24963. loader.setWithCredentials( scope.withCredentials );
  24964. loader.load( url, function ( text ) {
  24965. try {
  24966. onLoad( scope.parse( JSON.parse( text ) ) );
  24967. } catch ( e ) {
  24968. if ( onError ) {
  24969. onError( e );
  24970. } else {
  24971. console.error( e );
  24972. }
  24973. scope.manager.itemError( url );
  24974. }
  24975. }, onProgress, onError );
  24976. },
  24977. parse: function ( json ) {
  24978. const interleavedBufferMap = {};
  24979. const arrayBufferMap = {};
  24980. function getInterleavedBuffer( json, uuid ) {
  24981. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24982. const interleavedBuffers = json.interleavedBuffers;
  24983. const interleavedBuffer = interleavedBuffers[ uuid ];
  24984. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24985. const array = getTypedArray( interleavedBuffer.type, buffer );
  24986. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24987. ib.uuid = interleavedBuffer.uuid;
  24988. interleavedBufferMap[ uuid ] = ib;
  24989. return ib;
  24990. }
  24991. function getArrayBuffer( json, uuid ) {
  24992. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24993. const arrayBuffers = json.arrayBuffers;
  24994. const arrayBuffer = arrayBuffers[ uuid ];
  24995. const ab = new Uint32Array( arrayBuffer ).buffer;
  24996. arrayBufferMap[ uuid ] = ab;
  24997. return ab;
  24998. }
  24999. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25000. const index = json.data.index;
  25001. if ( index !== undefined ) {
  25002. const typedArray = getTypedArray( index.type, index.array );
  25003. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25004. }
  25005. const attributes = json.data.attributes;
  25006. for ( const key in attributes ) {
  25007. const attribute = attributes[ key ];
  25008. let bufferAttribute;
  25009. if ( attribute.isInterleavedBufferAttribute ) {
  25010. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25011. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25012. } else {
  25013. const typedArray = getTypedArray( attribute.type, attribute.array );
  25014. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25015. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25016. }
  25017. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25018. geometry.setAttribute( key, bufferAttribute );
  25019. }
  25020. const morphAttributes = json.data.morphAttributes;
  25021. if ( morphAttributes ) {
  25022. for ( const key in morphAttributes ) {
  25023. const attributeArray = morphAttributes[ key ];
  25024. const array = [];
  25025. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25026. const attribute = attributeArray[ i ];
  25027. let bufferAttribute;
  25028. if ( attribute.isInterleavedBufferAttribute ) {
  25029. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25030. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25031. } else {
  25032. const typedArray = getTypedArray( attribute.type, attribute.array );
  25033. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25034. }
  25035. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25036. array.push( bufferAttribute );
  25037. }
  25038. geometry.morphAttributes[ key ] = array;
  25039. }
  25040. }
  25041. const morphTargetsRelative = json.data.morphTargetsRelative;
  25042. if ( morphTargetsRelative ) {
  25043. geometry.morphTargetsRelative = true;
  25044. }
  25045. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25046. if ( groups !== undefined ) {
  25047. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25048. const group = groups[ i ];
  25049. geometry.addGroup( group.start, group.count, group.materialIndex );
  25050. }
  25051. }
  25052. const boundingSphere = json.data.boundingSphere;
  25053. if ( boundingSphere !== undefined ) {
  25054. const center = new Vector3();
  25055. if ( boundingSphere.center !== undefined ) {
  25056. center.fromArray( boundingSphere.center );
  25057. }
  25058. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25059. }
  25060. if ( json.name ) geometry.name = json.name;
  25061. if ( json.userData ) geometry.userData = json.userData;
  25062. return geometry;
  25063. }
  25064. } );
  25065. class ObjectLoader extends Loader {
  25066. constructor( manager ) {
  25067. super( manager );
  25068. }
  25069. load( url, onLoad, onProgress, onError ) {
  25070. const scope = this;
  25071. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25072. this.resourcePath = this.resourcePath || path;
  25073. const loader = new FileLoader( this.manager );
  25074. loader.setPath( this.path );
  25075. loader.setRequestHeader( this.requestHeader );
  25076. loader.setWithCredentials( this.withCredentials );
  25077. loader.load( url, function ( text ) {
  25078. let json = null;
  25079. try {
  25080. json = JSON.parse( text );
  25081. } catch ( error ) {
  25082. if ( onError !== undefined ) onError( error );
  25083. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25084. return;
  25085. }
  25086. const metadata = json.metadata;
  25087. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25088. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25089. return;
  25090. }
  25091. scope.parse( json, onLoad );
  25092. }, onProgress, onError );
  25093. }
  25094. parse( json, onLoad ) {
  25095. const animations = this.parseAnimations( json.animations );
  25096. const shapes = this.parseShapes( json.shapes );
  25097. const geometries = this.parseGeometries( json.geometries, shapes );
  25098. const images = this.parseImages( json.images, function () {
  25099. if ( onLoad !== undefined ) onLoad( object );
  25100. } );
  25101. const textures = this.parseTextures( json.textures, images );
  25102. const materials = this.parseMaterials( json.materials, textures );
  25103. const object = this.parseObject( json.object, geometries, materials, animations );
  25104. const skeletons = this.parseSkeletons( json.skeletons, object );
  25105. this.bindSkeletons( object, skeletons );
  25106. //
  25107. if ( onLoad !== undefined ) {
  25108. let hasImages = false;
  25109. for ( const uuid in images ) {
  25110. if ( images[ uuid ] instanceof HTMLImageElement ) {
  25111. hasImages = true;
  25112. break;
  25113. }
  25114. }
  25115. if ( hasImages === false ) onLoad( object );
  25116. }
  25117. return object;
  25118. }
  25119. parseShapes( json ) {
  25120. const shapes = {};
  25121. if ( json !== undefined ) {
  25122. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25123. const shape = new Shape().fromJSON( json[ i ] );
  25124. shapes[ shape.uuid ] = shape;
  25125. }
  25126. }
  25127. return shapes;
  25128. }
  25129. parseSkeletons( json, object ) {
  25130. const skeletons = {};
  25131. const bones = {};
  25132. // generate bone lookup table
  25133. object.traverse( function ( child ) {
  25134. if ( child.isBone ) bones[ child.uuid ] = child;
  25135. } );
  25136. // create skeletons
  25137. if ( json !== undefined ) {
  25138. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25139. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25140. skeletons[ skeleton.uuid ] = skeleton;
  25141. }
  25142. }
  25143. return skeletons;
  25144. }
  25145. parseGeometries( json, shapes ) {
  25146. const geometries = {};
  25147. let geometryShapes;
  25148. if ( json !== undefined ) {
  25149. const bufferGeometryLoader = new BufferGeometryLoader();
  25150. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25151. let geometry;
  25152. const data = json[ i ];
  25153. switch ( data.type ) {
  25154. case 'PlaneGeometry':
  25155. case 'PlaneBufferGeometry':
  25156. geometry = new Geometries[ data.type ](
  25157. data.width,
  25158. data.height,
  25159. data.widthSegments,
  25160. data.heightSegments
  25161. );
  25162. break;
  25163. case 'BoxGeometry':
  25164. case 'BoxBufferGeometry':
  25165. case 'CubeGeometry': // backwards compatible
  25166. geometry = new Geometries[ data.type ](
  25167. data.width,
  25168. data.height,
  25169. data.depth,
  25170. data.widthSegments,
  25171. data.heightSegments,
  25172. data.depthSegments
  25173. );
  25174. break;
  25175. case 'CircleGeometry':
  25176. case 'CircleBufferGeometry':
  25177. geometry = new Geometries[ data.type ](
  25178. data.radius,
  25179. data.segments,
  25180. data.thetaStart,
  25181. data.thetaLength
  25182. );
  25183. break;
  25184. case 'CylinderGeometry':
  25185. case 'CylinderBufferGeometry':
  25186. geometry = new Geometries[ data.type ](
  25187. data.radiusTop,
  25188. data.radiusBottom,
  25189. data.height,
  25190. data.radialSegments,
  25191. data.heightSegments,
  25192. data.openEnded,
  25193. data.thetaStart,
  25194. data.thetaLength
  25195. );
  25196. break;
  25197. case 'ConeGeometry':
  25198. case 'ConeBufferGeometry':
  25199. geometry = new Geometries[ data.type ](
  25200. data.radius,
  25201. data.height,
  25202. data.radialSegments,
  25203. data.heightSegments,
  25204. data.openEnded,
  25205. data.thetaStart,
  25206. data.thetaLength
  25207. );
  25208. break;
  25209. case 'SphereGeometry':
  25210. case 'SphereBufferGeometry':
  25211. geometry = new Geometries[ data.type ](
  25212. data.radius,
  25213. data.widthSegments,
  25214. data.heightSegments,
  25215. data.phiStart,
  25216. data.phiLength,
  25217. data.thetaStart,
  25218. data.thetaLength
  25219. );
  25220. break;
  25221. case 'DodecahedronGeometry':
  25222. case 'DodecahedronBufferGeometry':
  25223. case 'IcosahedronGeometry':
  25224. case 'IcosahedronBufferGeometry':
  25225. case 'OctahedronGeometry':
  25226. case 'OctahedronBufferGeometry':
  25227. case 'TetrahedronGeometry':
  25228. case 'TetrahedronBufferGeometry':
  25229. geometry = new Geometries[ data.type ](
  25230. data.radius,
  25231. data.detail
  25232. );
  25233. break;
  25234. case 'RingGeometry':
  25235. case 'RingBufferGeometry':
  25236. geometry = new Geometries[ data.type ](
  25237. data.innerRadius,
  25238. data.outerRadius,
  25239. data.thetaSegments,
  25240. data.phiSegments,
  25241. data.thetaStart,
  25242. data.thetaLength
  25243. );
  25244. break;
  25245. case 'TorusGeometry':
  25246. case 'TorusBufferGeometry':
  25247. geometry = new Geometries[ data.type ](
  25248. data.radius,
  25249. data.tube,
  25250. data.radialSegments,
  25251. data.tubularSegments,
  25252. data.arc
  25253. );
  25254. break;
  25255. case 'TorusKnotGeometry':
  25256. case 'TorusKnotBufferGeometry':
  25257. geometry = new Geometries[ data.type ](
  25258. data.radius,
  25259. data.tube,
  25260. data.tubularSegments,
  25261. data.radialSegments,
  25262. data.p,
  25263. data.q
  25264. );
  25265. break;
  25266. case 'TubeGeometry':
  25267. case 'TubeBufferGeometry':
  25268. // This only works for built-in curves (e.g. CatmullRomCurve3).
  25269. // User defined curves or instances of CurvePath will not be deserialized.
  25270. geometry = new Geometries[ data.type ](
  25271. new Curves[ data.path.type ]().fromJSON( data.path ),
  25272. data.tubularSegments,
  25273. data.radius,
  25274. data.radialSegments,
  25275. data.closed
  25276. );
  25277. break;
  25278. case 'LatheGeometry':
  25279. case 'LatheBufferGeometry':
  25280. geometry = new Geometries[ data.type ](
  25281. data.points,
  25282. data.segments,
  25283. data.phiStart,
  25284. data.phiLength
  25285. );
  25286. break;
  25287. case 'PolyhedronGeometry':
  25288. case 'PolyhedronBufferGeometry':
  25289. geometry = new Geometries[ data.type ](
  25290. data.vertices,
  25291. data.indices,
  25292. data.radius,
  25293. data.details
  25294. );
  25295. break;
  25296. case 'ShapeGeometry':
  25297. case 'ShapeBufferGeometry':
  25298. geometryShapes = [];
  25299. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25300. const shape = shapes[ data.shapes[ j ] ];
  25301. geometryShapes.push( shape );
  25302. }
  25303. geometry = new Geometries[ data.type ](
  25304. geometryShapes,
  25305. data.curveSegments
  25306. );
  25307. break;
  25308. case 'ExtrudeGeometry':
  25309. case 'ExtrudeBufferGeometry':
  25310. geometryShapes = [];
  25311. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25312. const shape = shapes[ data.shapes[ j ] ];
  25313. geometryShapes.push( shape );
  25314. }
  25315. const extrudePath = data.options.extrudePath;
  25316. if ( extrudePath !== undefined ) {
  25317. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25318. }
  25319. geometry = new Geometries[ data.type ](
  25320. geometryShapes,
  25321. data.options
  25322. );
  25323. break;
  25324. case 'BufferGeometry':
  25325. case 'InstancedBufferGeometry':
  25326. geometry = bufferGeometryLoader.parse( data );
  25327. break;
  25328. case 'Geometry':
  25329. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  25330. break;
  25331. default:
  25332. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  25333. continue;
  25334. }
  25335. geometry.uuid = data.uuid;
  25336. if ( data.name !== undefined ) geometry.name = data.name;
  25337. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25338. geometries[ data.uuid ] = geometry;
  25339. }
  25340. }
  25341. return geometries;
  25342. }
  25343. parseMaterials( json, textures ) {
  25344. const cache = {}; // MultiMaterial
  25345. const materials = {};
  25346. if ( json !== undefined ) {
  25347. const loader = new MaterialLoader();
  25348. loader.setTextures( textures );
  25349. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25350. const data = json[ i ];
  25351. if ( data.type === 'MultiMaterial' ) {
  25352. // Deprecated
  25353. const array = [];
  25354. for ( let j = 0; j < data.materials.length; j ++ ) {
  25355. const material = data.materials[ j ];
  25356. if ( cache[ material.uuid ] === undefined ) {
  25357. cache[ material.uuid ] = loader.parse( material );
  25358. }
  25359. array.push( cache[ material.uuid ] );
  25360. }
  25361. materials[ data.uuid ] = array;
  25362. } else {
  25363. if ( cache[ data.uuid ] === undefined ) {
  25364. cache[ data.uuid ] = loader.parse( data );
  25365. }
  25366. materials[ data.uuid ] = cache[ data.uuid ];
  25367. }
  25368. }
  25369. }
  25370. return materials;
  25371. }
  25372. parseAnimations( json ) {
  25373. const animations = {};
  25374. if ( json !== undefined ) {
  25375. for ( let i = 0; i < json.length; i ++ ) {
  25376. const data = json[ i ];
  25377. const clip = AnimationClip.parse( data );
  25378. animations[ clip.uuid ] = clip;
  25379. }
  25380. }
  25381. return animations;
  25382. }
  25383. parseImages( json, onLoad ) {
  25384. const scope = this;
  25385. const images = {};
  25386. let loader;
  25387. function loadImage( url ) {
  25388. scope.manager.itemStart( url );
  25389. return loader.load( url, function () {
  25390. scope.manager.itemEnd( url );
  25391. }, undefined, function () {
  25392. scope.manager.itemError( url );
  25393. scope.manager.itemEnd( url );
  25394. } );
  25395. }
  25396. function deserializeImage( image ) {
  25397. if ( typeof image === 'string' ) {
  25398. const url = image;
  25399. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25400. return loadImage( path );
  25401. } else {
  25402. if ( image.data ) {
  25403. return {
  25404. data: getTypedArray( image.type, image.data ),
  25405. width: image.width,
  25406. height: image.height
  25407. };
  25408. } else {
  25409. return null;
  25410. }
  25411. }
  25412. }
  25413. if ( json !== undefined && json.length > 0 ) {
  25414. const manager = new LoadingManager( onLoad );
  25415. loader = new ImageLoader( manager );
  25416. loader.setCrossOrigin( this.crossOrigin );
  25417. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25418. const image = json[ i ];
  25419. const url = image.url;
  25420. if ( Array.isArray( url ) ) {
  25421. // load array of images e.g CubeTexture
  25422. images[ image.uuid ] = [];
  25423. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25424. const currentUrl = url[ j ];
  25425. const deserializedImage = deserializeImage( currentUrl );
  25426. if ( deserializedImage !== null ) {
  25427. if ( deserializedImage instanceof HTMLImageElement ) {
  25428. images[ image.uuid ].push( deserializedImage );
  25429. } else {
  25430. // special case: handle array of data textures for cube textures
  25431. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25432. }
  25433. }
  25434. }
  25435. } else {
  25436. // load single image
  25437. const deserializedImage = deserializeImage( image.url );
  25438. if ( deserializedImage !== null ) {
  25439. images[ image.uuid ] = deserializedImage;
  25440. }
  25441. }
  25442. }
  25443. }
  25444. return images;
  25445. }
  25446. parseTextures( json, images ) {
  25447. function parseConstant( value, type ) {
  25448. if ( typeof value === 'number' ) return value;
  25449. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25450. return type[ value ];
  25451. }
  25452. const textures = {};
  25453. if ( json !== undefined ) {
  25454. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25455. const data = json[ i ];
  25456. if ( data.image === undefined ) {
  25457. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25458. }
  25459. if ( images[ data.image ] === undefined ) {
  25460. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25461. }
  25462. let texture;
  25463. const image = images[ data.image ];
  25464. if ( Array.isArray( image ) ) {
  25465. texture = new CubeTexture( image );
  25466. if ( image.length === 6 ) texture.needsUpdate = true;
  25467. } else {
  25468. if ( image && image.data ) {
  25469. texture = new DataTexture( image.data, image.width, image.height );
  25470. } else {
  25471. texture = new Texture( image );
  25472. }
  25473. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25474. }
  25475. texture.uuid = data.uuid;
  25476. if ( data.name !== undefined ) texture.name = data.name;
  25477. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25478. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25479. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25480. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25481. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25482. if ( data.wrap !== undefined ) {
  25483. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25484. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25485. }
  25486. if ( data.format !== undefined ) texture.format = data.format;
  25487. if ( data.type !== undefined ) texture.type = data.type;
  25488. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25489. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25490. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25491. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25492. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25493. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25494. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25495. textures[ data.uuid ] = texture;
  25496. }
  25497. }
  25498. return textures;
  25499. }
  25500. parseObject( data, geometries, materials, animations ) {
  25501. let object;
  25502. function getGeometry( name ) {
  25503. if ( geometries[ name ] === undefined ) {
  25504. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25505. }
  25506. return geometries[ name ];
  25507. }
  25508. function getMaterial( name ) {
  25509. if ( name === undefined ) return undefined;
  25510. if ( Array.isArray( name ) ) {
  25511. const array = [];
  25512. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25513. const uuid = name[ i ];
  25514. if ( materials[ uuid ] === undefined ) {
  25515. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25516. }
  25517. array.push( materials[ uuid ] );
  25518. }
  25519. return array;
  25520. }
  25521. if ( materials[ name ] === undefined ) {
  25522. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25523. }
  25524. return materials[ name ];
  25525. }
  25526. let geometry, material;
  25527. switch ( data.type ) {
  25528. case 'Scene':
  25529. object = new Scene();
  25530. if ( data.background !== undefined ) {
  25531. if ( Number.isInteger( data.background ) ) {
  25532. object.background = new Color( data.background );
  25533. }
  25534. }
  25535. if ( data.fog !== undefined ) {
  25536. if ( data.fog.type === 'Fog' ) {
  25537. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25538. } else if ( data.fog.type === 'FogExp2' ) {
  25539. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25540. }
  25541. }
  25542. break;
  25543. case 'PerspectiveCamera':
  25544. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25545. if ( data.focus !== undefined ) object.focus = data.focus;
  25546. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25547. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25548. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25549. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25550. break;
  25551. case 'OrthographicCamera':
  25552. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25553. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25554. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25555. break;
  25556. case 'AmbientLight':
  25557. object = new AmbientLight( data.color, data.intensity );
  25558. break;
  25559. case 'DirectionalLight':
  25560. object = new DirectionalLight( data.color, data.intensity );
  25561. break;
  25562. case 'PointLight':
  25563. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25564. break;
  25565. case 'RectAreaLight':
  25566. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25567. break;
  25568. case 'SpotLight':
  25569. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25570. break;
  25571. case 'HemisphereLight':
  25572. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25573. break;
  25574. case 'LightProbe':
  25575. object = new LightProbe().fromJSON( data );
  25576. break;
  25577. case 'SkinnedMesh':
  25578. geometry = getGeometry( data.geometry );
  25579. material = getMaterial( data.material );
  25580. object = new SkinnedMesh( geometry, material );
  25581. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25582. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25583. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25584. break;
  25585. case 'Mesh':
  25586. geometry = getGeometry( data.geometry );
  25587. material = getMaterial( data.material );
  25588. object = new Mesh( geometry, material );
  25589. break;
  25590. case 'InstancedMesh':
  25591. geometry = getGeometry( data.geometry );
  25592. material = getMaterial( data.material );
  25593. const count = data.count;
  25594. const instanceMatrix = data.instanceMatrix;
  25595. object = new InstancedMesh( geometry, material, count );
  25596. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25597. break;
  25598. case 'LOD':
  25599. object = new LOD();
  25600. break;
  25601. case 'Line':
  25602. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25603. break;
  25604. case 'LineLoop':
  25605. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25606. break;
  25607. case 'LineSegments':
  25608. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25609. break;
  25610. case 'PointCloud':
  25611. case 'Points':
  25612. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25613. break;
  25614. case 'Sprite':
  25615. object = new Sprite( getMaterial( data.material ) );
  25616. break;
  25617. case 'Group':
  25618. object = new Group();
  25619. break;
  25620. case 'Bone':
  25621. object = new Bone();
  25622. break;
  25623. default:
  25624. object = new Object3D();
  25625. }
  25626. object.uuid = data.uuid;
  25627. if ( data.name !== undefined ) object.name = data.name;
  25628. if ( data.matrix !== undefined ) {
  25629. object.matrix.fromArray( data.matrix );
  25630. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25631. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25632. } else {
  25633. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25634. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25635. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25636. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25637. }
  25638. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25639. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25640. if ( data.shadow ) {
  25641. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25642. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25643. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25644. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25645. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25646. }
  25647. if ( data.visible !== undefined ) object.visible = data.visible;
  25648. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25649. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25650. if ( data.userData !== undefined ) object.userData = data.userData;
  25651. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25652. if ( data.children !== undefined ) {
  25653. const children = data.children;
  25654. for ( let i = 0; i < children.length; i ++ ) {
  25655. object.add( this.parseObject( children[ i ], geometries, materials, animations ) );
  25656. }
  25657. }
  25658. if ( data.animations !== undefined ) {
  25659. const objectAnimations = data.animations;
  25660. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25661. const uuid = objectAnimations[ i ];
  25662. object.animations.push( animations[ uuid ] );
  25663. }
  25664. }
  25665. if ( data.type === 'LOD' ) {
  25666. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25667. const levels = data.levels;
  25668. for ( let l = 0; l < levels.length; l ++ ) {
  25669. const level = levels[ l ];
  25670. const child = object.getObjectByProperty( 'uuid', level.object );
  25671. if ( child !== undefined ) {
  25672. object.addLevel( child, level.distance );
  25673. }
  25674. }
  25675. }
  25676. return object;
  25677. }
  25678. bindSkeletons( object, skeletons ) {
  25679. if ( Object.keys( skeletons ).length === 0 ) return;
  25680. object.traverse( function ( child ) {
  25681. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25682. const skeleton = skeletons[ child.skeleton ];
  25683. if ( skeleton === undefined ) {
  25684. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25685. } else {
  25686. child.bind( skeleton, child.bindMatrix );
  25687. }
  25688. }
  25689. } );
  25690. }
  25691. /* DEPRECATED */
  25692. setTexturePath( value ) {
  25693. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  25694. return this.setResourcePath( value );
  25695. }
  25696. }
  25697. const TEXTURE_MAPPING = {
  25698. UVMapping: UVMapping,
  25699. CubeReflectionMapping: CubeReflectionMapping,
  25700. CubeRefractionMapping: CubeRefractionMapping,
  25701. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25702. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25703. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25704. CubeUVRefractionMapping: CubeUVRefractionMapping
  25705. };
  25706. const TEXTURE_WRAPPING = {
  25707. RepeatWrapping: RepeatWrapping,
  25708. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25709. MirroredRepeatWrapping: MirroredRepeatWrapping
  25710. };
  25711. const TEXTURE_FILTER = {
  25712. NearestFilter: NearestFilter,
  25713. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25714. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25715. LinearFilter: LinearFilter,
  25716. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25717. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25718. };
  25719. function ImageBitmapLoader( manager ) {
  25720. if ( typeof createImageBitmap === 'undefined' ) {
  25721. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25722. }
  25723. if ( typeof fetch === 'undefined' ) {
  25724. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25725. }
  25726. Loader.call( this, manager );
  25727. this.options = { premultiplyAlpha: 'none' };
  25728. }
  25729. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25730. constructor: ImageBitmapLoader,
  25731. isImageBitmapLoader: true,
  25732. setOptions: function setOptions( options ) {
  25733. this.options = options;
  25734. return this;
  25735. },
  25736. load: function ( url, onLoad, onProgress, onError ) {
  25737. if ( url === undefined ) url = '';
  25738. if ( this.path !== undefined ) url = this.path + url;
  25739. url = this.manager.resolveURL( url );
  25740. const scope = this;
  25741. const cached = Cache.get( url );
  25742. if ( cached !== undefined ) {
  25743. scope.manager.itemStart( url );
  25744. setTimeout( function () {
  25745. if ( onLoad ) onLoad( cached );
  25746. scope.manager.itemEnd( url );
  25747. }, 0 );
  25748. return cached;
  25749. }
  25750. const fetchOptions = {};
  25751. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25752. fetch( url, fetchOptions ).then( function ( res ) {
  25753. return res.blob();
  25754. } ).then( function ( blob ) {
  25755. //console.log('getBlob', url )
  25756. return createImageBitmap( blob, scope.options );
  25757. } ).then( function ( imageBitmap ) {
  25758. Cache.add( url, imageBitmap );
  25759. if ( onLoad ) onLoad( imageBitmap );
  25760. scope.manager.itemEnd( url );
  25761. } ).catch( function ( e ) {
  25762. //console.log('error', url, e)
  25763. if ( onError ) onError( e, url );
  25764. scope.manager.itemError( url );
  25765. scope.manager.itemEnd( url );
  25766. } );
  25767. scope.manager.itemStart( url );
  25768. }
  25769. } );
  25770. function ShapePath() {
  25771. this.type = 'ShapePath';
  25772. this.color = new Color();
  25773. this.subPaths = [];
  25774. this.currentPath = null;
  25775. }
  25776. Object.assign( ShapePath.prototype, {
  25777. moveTo: function ( x, y ) {
  25778. this.currentPath = new Path();
  25779. this.subPaths.push( this.currentPath );
  25780. this.currentPath.moveTo( x, y );
  25781. return this;
  25782. },
  25783. lineTo: function ( x, y ) {
  25784. this.currentPath.lineTo( x, y );
  25785. return this;
  25786. },
  25787. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25788. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25789. return this;
  25790. },
  25791. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25792. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25793. return this;
  25794. },
  25795. splineThru: function ( pts ) {
  25796. this.currentPath.splineThru( pts );
  25797. return this;
  25798. },
  25799. toShapes: function ( isCCW, noHoles ) {
  25800. function toShapesNoHoles( inSubpaths ) {
  25801. const shapes = [];
  25802. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25803. const tmpPath = inSubpaths[ i ];
  25804. const tmpShape = new Shape();
  25805. tmpShape.curves = tmpPath.curves;
  25806. shapes.push( tmpShape );
  25807. }
  25808. return shapes;
  25809. }
  25810. function isPointInsidePolygon( inPt, inPolygon ) {
  25811. const polyLen = inPolygon.length;
  25812. // inPt on polygon contour => immediate success or
  25813. // toggling of inside/outside at every single! intersection point of an edge
  25814. // with the horizontal line through inPt, left of inPt
  25815. // not counting lowerY endpoints of edges and whole edges on that line
  25816. let inside = false;
  25817. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25818. let edgeLowPt = inPolygon[ p ];
  25819. let edgeHighPt = inPolygon[ q ];
  25820. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25821. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25822. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25823. // not parallel
  25824. if ( edgeDy < 0 ) {
  25825. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25826. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25827. }
  25828. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25829. if ( inPt.y === edgeLowPt.y ) {
  25830. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25831. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25832. } else {
  25833. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25834. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25835. if ( perpEdge < 0 ) continue;
  25836. inside = ! inside; // true intersection left of inPt
  25837. }
  25838. } else {
  25839. // parallel or collinear
  25840. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25841. // edge lies on the same horizontal line as inPt
  25842. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25843. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25844. // continue;
  25845. }
  25846. }
  25847. return inside;
  25848. }
  25849. const isClockWise = ShapeUtils.isClockWise;
  25850. const subPaths = this.subPaths;
  25851. if ( subPaths.length === 0 ) return [];
  25852. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25853. let solid, tmpPath, tmpShape;
  25854. const shapes = [];
  25855. if ( subPaths.length === 1 ) {
  25856. tmpPath = subPaths[ 0 ];
  25857. tmpShape = new Shape();
  25858. tmpShape.curves = tmpPath.curves;
  25859. shapes.push( tmpShape );
  25860. return shapes;
  25861. }
  25862. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25863. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25864. // console.log("Holes first", holesFirst);
  25865. const betterShapeHoles = [];
  25866. const newShapes = [];
  25867. let newShapeHoles = [];
  25868. let mainIdx = 0;
  25869. let tmpPoints;
  25870. newShapes[ mainIdx ] = undefined;
  25871. newShapeHoles[ mainIdx ] = [];
  25872. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  25873. tmpPath = subPaths[ i ];
  25874. tmpPoints = tmpPath.getPoints();
  25875. solid = isClockWise( tmpPoints );
  25876. solid = isCCW ? ! solid : solid;
  25877. if ( solid ) {
  25878. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25879. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25880. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25881. if ( holesFirst ) mainIdx ++;
  25882. newShapeHoles[ mainIdx ] = [];
  25883. //console.log('cw', i);
  25884. } else {
  25885. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25886. //console.log('ccw', i);
  25887. }
  25888. }
  25889. // only Holes? -> probably all Shapes with wrong orientation
  25890. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25891. if ( newShapes.length > 1 ) {
  25892. let ambiguous = false;
  25893. const toChange = [];
  25894. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25895. betterShapeHoles[ sIdx ] = [];
  25896. }
  25897. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25898. const sho = newShapeHoles[ sIdx ];
  25899. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25900. const ho = sho[ hIdx ];
  25901. let hole_unassigned = true;
  25902. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25903. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25904. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25905. if ( hole_unassigned ) {
  25906. hole_unassigned = false;
  25907. betterShapeHoles[ s2Idx ].push( ho );
  25908. } else {
  25909. ambiguous = true;
  25910. }
  25911. }
  25912. }
  25913. if ( hole_unassigned ) {
  25914. betterShapeHoles[ sIdx ].push( ho );
  25915. }
  25916. }
  25917. }
  25918. // console.log("ambiguous: ", ambiguous);
  25919. if ( toChange.length > 0 ) {
  25920. // console.log("to change: ", toChange);
  25921. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25922. }
  25923. }
  25924. let tmpHoles;
  25925. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  25926. tmpShape = newShapes[ i ].s;
  25927. shapes.push( tmpShape );
  25928. tmpHoles = newShapeHoles[ i ];
  25929. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25930. tmpShape.holes.push( tmpHoles[ j ].h );
  25931. }
  25932. }
  25933. //console.log("shape", shapes);
  25934. return shapes;
  25935. }
  25936. } );
  25937. function Font( data ) {
  25938. this.type = 'Font';
  25939. this.data = data;
  25940. }
  25941. Object.assign( Font.prototype, {
  25942. isFont: true,
  25943. generateShapes: function ( text, size = 100 ) {
  25944. const shapes = [];
  25945. const paths = createPaths( text, size, this.data );
  25946. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  25947. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25948. }
  25949. return shapes;
  25950. }
  25951. } );
  25952. function createPaths( text, size, data ) {
  25953. const chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  25954. const scale = size / data.resolution;
  25955. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25956. const paths = [];
  25957. let offsetX = 0, offsetY = 0;
  25958. for ( let i = 0; i < chars.length; i ++ ) {
  25959. const char = chars[ i ];
  25960. if ( char === '\n' ) {
  25961. offsetX = 0;
  25962. offsetY -= line_height;
  25963. } else {
  25964. const ret = createPath( char, scale, offsetX, offsetY, data );
  25965. offsetX += ret.offsetX;
  25966. paths.push( ret.path );
  25967. }
  25968. }
  25969. return paths;
  25970. }
  25971. function createPath( char, scale, offsetX, offsetY, data ) {
  25972. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  25973. if ( ! glyph ) {
  25974. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  25975. return;
  25976. }
  25977. const path = new ShapePath();
  25978. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25979. if ( glyph.o ) {
  25980. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25981. for ( let i = 0, l = outline.length; i < l; ) {
  25982. const action = outline[ i ++ ];
  25983. switch ( action ) {
  25984. case 'm': // moveTo
  25985. x = outline[ i ++ ] * scale + offsetX;
  25986. y = outline[ i ++ ] * scale + offsetY;
  25987. path.moveTo( x, y );
  25988. break;
  25989. case 'l': // lineTo
  25990. x = outline[ i ++ ] * scale + offsetX;
  25991. y = outline[ i ++ ] * scale + offsetY;
  25992. path.lineTo( x, y );
  25993. break;
  25994. case 'q': // quadraticCurveTo
  25995. cpx = outline[ i ++ ] * scale + offsetX;
  25996. cpy = outline[ i ++ ] * scale + offsetY;
  25997. cpx1 = outline[ i ++ ] * scale + offsetX;
  25998. cpy1 = outline[ i ++ ] * scale + offsetY;
  25999. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  26000. break;
  26001. case 'b': // bezierCurveTo
  26002. cpx = outline[ i ++ ] * scale + offsetX;
  26003. cpy = outline[ i ++ ] * scale + offsetY;
  26004. cpx1 = outline[ i ++ ] * scale + offsetX;
  26005. cpy1 = outline[ i ++ ] * scale + offsetY;
  26006. cpx2 = outline[ i ++ ] * scale + offsetX;
  26007. cpy2 = outline[ i ++ ] * scale + offsetY;
  26008. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  26009. break;
  26010. }
  26011. }
  26012. }
  26013. return { offsetX: glyph.ha * scale, path: path };
  26014. }
  26015. function FontLoader( manager ) {
  26016. Loader.call( this, manager );
  26017. }
  26018. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26019. constructor: FontLoader,
  26020. load: function ( url, onLoad, onProgress, onError ) {
  26021. const scope = this;
  26022. const loader = new FileLoader( this.manager );
  26023. loader.setPath( this.path );
  26024. loader.setRequestHeader( this.requestHeader );
  26025. loader.setWithCredentials( scope.withCredentials );
  26026. loader.load( url, function ( text ) {
  26027. let json;
  26028. try {
  26029. json = JSON.parse( text );
  26030. } catch ( e ) {
  26031. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  26032. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  26033. }
  26034. const font = scope.parse( json );
  26035. if ( onLoad ) onLoad( font );
  26036. }, onProgress, onError );
  26037. },
  26038. parse: function ( json ) {
  26039. return new Font( json );
  26040. }
  26041. } );
  26042. let _context;
  26043. const AudioContext = {
  26044. getContext: function () {
  26045. if ( _context === undefined ) {
  26046. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26047. }
  26048. return _context;
  26049. },
  26050. setContext: function ( value ) {
  26051. _context = value;
  26052. }
  26053. };
  26054. function AudioLoader( manager ) {
  26055. Loader.call( this, manager );
  26056. }
  26057. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26058. constructor: AudioLoader,
  26059. load: function ( url, onLoad, onProgress, onError ) {
  26060. const scope = this;
  26061. const loader = new FileLoader( scope.manager );
  26062. loader.setResponseType( 'arraybuffer' );
  26063. loader.setPath( scope.path );
  26064. loader.setRequestHeader( scope.requestHeader );
  26065. loader.setWithCredentials( scope.withCredentials );
  26066. loader.load( url, function ( buffer ) {
  26067. try {
  26068. // Create a copy of the buffer. The `decodeAudioData` method
  26069. // detaches the buffer when complete, preventing reuse.
  26070. const bufferCopy = buffer.slice( 0 );
  26071. const context = AudioContext.getContext();
  26072. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26073. onLoad( audioBuffer );
  26074. } );
  26075. } catch ( e ) {
  26076. if ( onError ) {
  26077. onError( e );
  26078. } else {
  26079. console.error( e );
  26080. }
  26081. scope.manager.itemError( url );
  26082. }
  26083. }, onProgress, onError );
  26084. }
  26085. } );
  26086. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  26087. LightProbe.call( this, undefined, intensity );
  26088. const color1 = new Color().set( skyColor );
  26089. const color2 = new Color().set( groundColor );
  26090. const sky = new Vector3( color1.r, color1.g, color1.b );
  26091. const ground = new Vector3( color2.r, color2.g, color2.b );
  26092. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26093. const c0 = Math.sqrt( Math.PI );
  26094. const c1 = c0 * Math.sqrt( 0.75 );
  26095. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26096. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26097. }
  26098. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  26099. constructor: HemisphereLightProbe,
  26100. isHemisphereLightProbe: true,
  26101. copy: function ( source ) { // modifying colors not currently supported
  26102. LightProbe.prototype.copy.call( this, source );
  26103. return this;
  26104. },
  26105. toJSON: function ( meta ) {
  26106. const data = LightProbe.prototype.toJSON.call( this, meta );
  26107. // data.sh = this.sh.toArray(); // todo
  26108. return data;
  26109. }
  26110. } );
  26111. function AmbientLightProbe( color, intensity ) {
  26112. LightProbe.call( this, undefined, intensity );
  26113. const color1 = new Color().set( color );
  26114. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26115. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26116. }
  26117. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  26118. constructor: AmbientLightProbe,
  26119. isAmbientLightProbe: true,
  26120. copy: function ( source ) { // modifying color not currently supported
  26121. LightProbe.prototype.copy.call( this, source );
  26122. return this;
  26123. },
  26124. toJSON: function ( meta ) {
  26125. const data = LightProbe.prototype.toJSON.call( this, meta );
  26126. // data.sh = this.sh.toArray(); // todo
  26127. return data;
  26128. }
  26129. } );
  26130. const _eyeRight = new Matrix4();
  26131. const _eyeLeft = new Matrix4();
  26132. function StereoCamera() {
  26133. this.type = 'StereoCamera';
  26134. this.aspect = 1;
  26135. this.eyeSep = 0.064;
  26136. this.cameraL = new PerspectiveCamera();
  26137. this.cameraL.layers.enable( 1 );
  26138. this.cameraL.matrixAutoUpdate = false;
  26139. this.cameraR = new PerspectiveCamera();
  26140. this.cameraR.layers.enable( 2 );
  26141. this.cameraR.matrixAutoUpdate = false;
  26142. this._cache = {
  26143. focus: null,
  26144. fov: null,
  26145. aspect: null,
  26146. near: null,
  26147. far: null,
  26148. zoom: null,
  26149. eyeSep: null
  26150. };
  26151. }
  26152. Object.assign( StereoCamera.prototype, {
  26153. update: function ( camera ) {
  26154. const cache = this._cache;
  26155. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26156. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26157. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26158. if ( needsUpdate ) {
  26159. cache.focus = camera.focus;
  26160. cache.fov = camera.fov;
  26161. cache.aspect = camera.aspect * this.aspect;
  26162. cache.near = camera.near;
  26163. cache.far = camera.far;
  26164. cache.zoom = camera.zoom;
  26165. cache.eyeSep = this.eyeSep;
  26166. // Off-axis stereoscopic effect based on
  26167. // http://paulbourke.net/stereographics/stereorender/
  26168. const projectionMatrix = camera.projectionMatrix.clone();
  26169. const eyeSepHalf = cache.eyeSep / 2;
  26170. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26171. const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26172. let xmin, xmax;
  26173. // translate xOffset
  26174. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26175. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26176. // for left eye
  26177. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26178. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26179. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26180. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26181. this.cameraL.projectionMatrix.copy( projectionMatrix );
  26182. // for right eye
  26183. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26184. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26185. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26186. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26187. this.cameraR.projectionMatrix.copy( projectionMatrix );
  26188. }
  26189. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26190. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26191. }
  26192. } );
  26193. class Clock {
  26194. constructor( autoStart ) {
  26195. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  26196. this.startTime = 0;
  26197. this.oldTime = 0;
  26198. this.elapsedTime = 0;
  26199. this.running = false;
  26200. }
  26201. start() {
  26202. this.startTime = now();
  26203. this.oldTime = this.startTime;
  26204. this.elapsedTime = 0;
  26205. this.running = true;
  26206. }
  26207. stop() {
  26208. this.getElapsedTime();
  26209. this.running = false;
  26210. this.autoStart = false;
  26211. }
  26212. getElapsedTime() {
  26213. this.getDelta();
  26214. return this.elapsedTime;
  26215. }
  26216. getDelta() {
  26217. let diff = 0;
  26218. if ( this.autoStart && ! this.running ) {
  26219. this.start();
  26220. return 0;
  26221. }
  26222. if ( this.running ) {
  26223. const newTime = now();
  26224. diff = ( newTime - this.oldTime ) / 1000;
  26225. this.oldTime = newTime;
  26226. this.elapsedTime += diff;
  26227. }
  26228. return diff;
  26229. }
  26230. }
  26231. function now() {
  26232. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26233. }
  26234. const _position$2 = /*@__PURE__*/ new Vector3();
  26235. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  26236. const _scale$1 = /*@__PURE__*/ new Vector3();
  26237. const _orientation = /*@__PURE__*/ new Vector3();
  26238. class AudioListener extends Object3D {
  26239. constructor() {
  26240. super();
  26241. this.type = 'AudioListener';
  26242. this.context = AudioContext.getContext();
  26243. this.gain = this.context.createGain();
  26244. this.gain.connect( this.context.destination );
  26245. this.filter = null;
  26246. this.timeDelta = 0;
  26247. // private
  26248. this._clock = new Clock();
  26249. }
  26250. getInput() {
  26251. return this.gain;
  26252. }
  26253. removeFilter() {
  26254. if ( this.filter !== null ) {
  26255. this.gain.disconnect( this.filter );
  26256. this.filter.disconnect( this.context.destination );
  26257. this.gain.connect( this.context.destination );
  26258. this.filter = null;
  26259. }
  26260. return this;
  26261. }
  26262. getFilter() {
  26263. return this.filter;
  26264. }
  26265. setFilter( value ) {
  26266. if ( this.filter !== null ) {
  26267. this.gain.disconnect( this.filter );
  26268. this.filter.disconnect( this.context.destination );
  26269. } else {
  26270. this.gain.disconnect( this.context.destination );
  26271. }
  26272. this.filter = value;
  26273. this.gain.connect( this.filter );
  26274. this.filter.connect( this.context.destination );
  26275. return this;
  26276. }
  26277. getMasterVolume() {
  26278. return this.gain.gain.value;
  26279. }
  26280. setMasterVolume( value ) {
  26281. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26282. return this;
  26283. }
  26284. updateMatrixWorld( force ) {
  26285. super.updateMatrixWorld( force );
  26286. const listener = this.context.listener;
  26287. const up = this.up;
  26288. this.timeDelta = this._clock.getDelta();
  26289. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  26290. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  26291. if ( listener.positionX ) {
  26292. // code path for Chrome (see #14393)
  26293. const endTime = this.context.currentTime + this.timeDelta;
  26294. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  26295. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  26296. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  26297. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  26298. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  26299. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  26300. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26301. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26302. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26303. } else {
  26304. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  26305. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  26306. }
  26307. }
  26308. }
  26309. class Audio extends Object3D {
  26310. constructor( listener ) {
  26311. super();
  26312. this.type = 'Audio';
  26313. this.listener = listener;
  26314. this.context = listener.context;
  26315. this.gain = this.context.createGain();
  26316. this.gain.connect( listener.getInput() );
  26317. this.autoplay = false;
  26318. this.buffer = null;
  26319. this.detune = 0;
  26320. this.loop = false;
  26321. this.loopStart = 0;
  26322. this.loopEnd = 0;
  26323. this.offset = 0;
  26324. this.duration = undefined;
  26325. this.playbackRate = 1;
  26326. this.isPlaying = false;
  26327. this.hasPlaybackControl = true;
  26328. this.source = null;
  26329. this.sourceType = 'empty';
  26330. this._startedAt = 0;
  26331. this._progress = 0;
  26332. this._connected = false;
  26333. this.filters = [];
  26334. }
  26335. getOutput() {
  26336. return this.gain;
  26337. }
  26338. setNodeSource( audioNode ) {
  26339. this.hasPlaybackControl = false;
  26340. this.sourceType = 'audioNode';
  26341. this.source = audioNode;
  26342. this.connect();
  26343. return this;
  26344. }
  26345. setMediaElementSource( mediaElement ) {
  26346. this.hasPlaybackControl = false;
  26347. this.sourceType = 'mediaNode';
  26348. this.source = this.context.createMediaElementSource( mediaElement );
  26349. this.connect();
  26350. return this;
  26351. }
  26352. setMediaStreamSource( mediaStream ) {
  26353. this.hasPlaybackControl = false;
  26354. this.sourceType = 'mediaStreamNode';
  26355. this.source = this.context.createMediaStreamSource( mediaStream );
  26356. this.connect();
  26357. return this;
  26358. }
  26359. setBuffer( audioBuffer ) {
  26360. this.buffer = audioBuffer;
  26361. this.sourceType = 'buffer';
  26362. if ( this.autoplay ) this.play();
  26363. return this;
  26364. }
  26365. play( delay = 0 ) {
  26366. if ( this.isPlaying === true ) {
  26367. console.warn( 'THREE.Audio: Audio is already playing.' );
  26368. return;
  26369. }
  26370. if ( this.hasPlaybackControl === false ) {
  26371. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26372. return;
  26373. }
  26374. this._startedAt = this.context.currentTime + delay;
  26375. const source = this.context.createBufferSource();
  26376. source.buffer = this.buffer;
  26377. source.loop = this.loop;
  26378. source.loopStart = this.loopStart;
  26379. source.loopEnd = this.loopEnd;
  26380. source.onended = this.onEnded.bind( this );
  26381. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26382. this.isPlaying = true;
  26383. this.source = source;
  26384. this.setDetune( this.detune );
  26385. this.setPlaybackRate( this.playbackRate );
  26386. return this.connect();
  26387. }
  26388. pause() {
  26389. if ( this.hasPlaybackControl === false ) {
  26390. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26391. return;
  26392. }
  26393. if ( this.isPlaying === true ) {
  26394. // update current progress
  26395. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26396. if ( this.loop === true ) {
  26397. // ensure _progress does not exceed duration with looped audios
  26398. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26399. }
  26400. this.source.stop();
  26401. this.source.onended = null;
  26402. this.isPlaying = false;
  26403. }
  26404. return this;
  26405. }
  26406. stop() {
  26407. if ( this.hasPlaybackControl === false ) {
  26408. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26409. return;
  26410. }
  26411. this._progress = 0;
  26412. this.source.stop();
  26413. this.source.onended = null;
  26414. this.isPlaying = false;
  26415. return this;
  26416. }
  26417. connect() {
  26418. if ( this.filters.length > 0 ) {
  26419. this.source.connect( this.filters[ 0 ] );
  26420. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26421. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26422. }
  26423. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26424. } else {
  26425. this.source.connect( this.getOutput() );
  26426. }
  26427. this._connected = true;
  26428. return this;
  26429. }
  26430. disconnect() {
  26431. if ( this.filters.length > 0 ) {
  26432. this.source.disconnect( this.filters[ 0 ] );
  26433. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26434. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26435. }
  26436. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26437. } else {
  26438. this.source.disconnect( this.getOutput() );
  26439. }
  26440. this._connected = false;
  26441. return this;
  26442. }
  26443. getFilters() {
  26444. return this.filters;
  26445. }
  26446. setFilters( value ) {
  26447. if ( ! value ) value = [];
  26448. if ( this._connected === true ) {
  26449. this.disconnect();
  26450. this.filters = value.slice();
  26451. this.connect();
  26452. } else {
  26453. this.filters = value.slice();
  26454. }
  26455. return this;
  26456. }
  26457. setDetune( value ) {
  26458. this.detune = value;
  26459. if ( this.source.detune === undefined ) return; // only set detune when available
  26460. if ( this.isPlaying === true ) {
  26461. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26462. }
  26463. return this;
  26464. }
  26465. getDetune() {
  26466. return this.detune;
  26467. }
  26468. getFilter() {
  26469. return this.getFilters()[ 0 ];
  26470. }
  26471. setFilter( filter ) {
  26472. return this.setFilters( filter ? [ filter ] : [] );
  26473. }
  26474. setPlaybackRate( value ) {
  26475. if ( this.hasPlaybackControl === false ) {
  26476. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26477. return;
  26478. }
  26479. this.playbackRate = value;
  26480. if ( this.isPlaying === true ) {
  26481. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26482. }
  26483. return this;
  26484. }
  26485. getPlaybackRate() {
  26486. return this.playbackRate;
  26487. }
  26488. onEnded() {
  26489. this.isPlaying = false;
  26490. }
  26491. getLoop() {
  26492. if ( this.hasPlaybackControl === false ) {
  26493. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26494. return false;
  26495. }
  26496. return this.loop;
  26497. }
  26498. setLoop( value ) {
  26499. if ( this.hasPlaybackControl === false ) {
  26500. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26501. return;
  26502. }
  26503. this.loop = value;
  26504. if ( this.isPlaying === true ) {
  26505. this.source.loop = this.loop;
  26506. }
  26507. return this;
  26508. }
  26509. setLoopStart( value ) {
  26510. this.loopStart = value;
  26511. return this;
  26512. }
  26513. setLoopEnd( value ) {
  26514. this.loopEnd = value;
  26515. return this;
  26516. }
  26517. getVolume() {
  26518. return this.gain.gain.value;
  26519. }
  26520. setVolume( value ) {
  26521. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26522. return this;
  26523. }
  26524. }
  26525. const _position$3 = /*@__PURE__*/ new Vector3();
  26526. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  26527. const _scale$2 = /*@__PURE__*/ new Vector3();
  26528. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26529. class PositionalAudio extends Audio {
  26530. constructor( listener ) {
  26531. super( listener );
  26532. this.panner = this.context.createPanner();
  26533. this.panner.panningModel = 'HRTF';
  26534. this.panner.connect( this.gain );
  26535. }
  26536. getOutput() {
  26537. return this.panner;
  26538. }
  26539. getRefDistance() {
  26540. return this.panner.refDistance;
  26541. }
  26542. setRefDistance( value ) {
  26543. this.panner.refDistance = value;
  26544. return this;
  26545. }
  26546. getRolloffFactor() {
  26547. return this.panner.rolloffFactor;
  26548. }
  26549. setRolloffFactor( value ) {
  26550. this.panner.rolloffFactor = value;
  26551. return this;
  26552. }
  26553. getDistanceModel() {
  26554. return this.panner.distanceModel;
  26555. }
  26556. setDistanceModel( value ) {
  26557. this.panner.distanceModel = value;
  26558. return this;
  26559. }
  26560. getMaxDistance() {
  26561. return this.panner.maxDistance;
  26562. }
  26563. setMaxDistance( value ) {
  26564. this.panner.maxDistance = value;
  26565. return this;
  26566. }
  26567. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26568. this.panner.coneInnerAngle = coneInnerAngle;
  26569. this.panner.coneOuterAngle = coneOuterAngle;
  26570. this.panner.coneOuterGain = coneOuterGain;
  26571. return this;
  26572. }
  26573. updateMatrixWorld( force ) {
  26574. super.updateMatrixWorld( force );
  26575. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26576. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  26577. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  26578. const panner = this.panner;
  26579. if ( panner.positionX ) {
  26580. // code path for Chrome and Firefox (see #14393)
  26581. const endTime = this.context.currentTime + this.listener.timeDelta;
  26582. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  26583. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  26584. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  26585. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26586. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26587. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26588. } else {
  26589. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  26590. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  26591. }
  26592. }
  26593. }
  26594. class AudioAnalyser {
  26595. constructor( audio, fftSize = 2048 ) {
  26596. this.analyser = audio.context.createAnalyser();
  26597. this.analyser.fftSize = fftSize;
  26598. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26599. audio.getOutput().connect( this.analyser );
  26600. }
  26601. getFrequencyData() {
  26602. this.analyser.getByteFrequencyData( this.data );
  26603. return this.data;
  26604. }
  26605. getAverageFrequency() {
  26606. let value = 0;
  26607. const data = this.getFrequencyData();
  26608. for ( let i = 0; i < data.length; i ++ ) {
  26609. value += data[ i ];
  26610. }
  26611. return value / data.length;
  26612. }
  26613. }
  26614. function PropertyMixer( binding, typeName, valueSize ) {
  26615. this.binding = binding;
  26616. this.valueSize = valueSize;
  26617. let mixFunction,
  26618. mixFunctionAdditive,
  26619. setIdentity;
  26620. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26621. //
  26622. // interpolators can use .buffer as their .result
  26623. // the data then goes to 'incoming'
  26624. //
  26625. // 'accu0' and 'accu1' are used frame-interleaved for
  26626. // the cumulative result and are compared to detect
  26627. // changes
  26628. //
  26629. // 'orig' stores the original state of the property
  26630. //
  26631. // 'add' is used for additive cumulative results
  26632. //
  26633. // 'work' is optional and is only present for quaternion types. It is used
  26634. // to store intermediate quaternion multiplication results
  26635. switch ( typeName ) {
  26636. case 'quaternion':
  26637. mixFunction = this._slerp;
  26638. mixFunctionAdditive = this._slerpAdditive;
  26639. setIdentity = this._setAdditiveIdentityQuaternion;
  26640. this.buffer = new Float64Array( valueSize * 6 );
  26641. this._workIndex = 5;
  26642. break;
  26643. case 'string':
  26644. case 'bool':
  26645. mixFunction = this._select;
  26646. // Use the regular mix function and for additive on these types,
  26647. // additive is not relevant for non-numeric types
  26648. mixFunctionAdditive = this._select;
  26649. setIdentity = this._setAdditiveIdentityOther;
  26650. this.buffer = new Array( valueSize * 5 );
  26651. break;
  26652. default:
  26653. mixFunction = this._lerp;
  26654. mixFunctionAdditive = this._lerpAdditive;
  26655. setIdentity = this._setAdditiveIdentityNumeric;
  26656. this.buffer = new Float64Array( valueSize * 5 );
  26657. }
  26658. this._mixBufferRegion = mixFunction;
  26659. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26660. this._setIdentity = setIdentity;
  26661. this._origIndex = 3;
  26662. this._addIndex = 4;
  26663. this.cumulativeWeight = 0;
  26664. this.cumulativeWeightAdditive = 0;
  26665. this.useCount = 0;
  26666. this.referenceCount = 0;
  26667. }
  26668. Object.assign( PropertyMixer.prototype, {
  26669. // accumulate data in the 'incoming' region into 'accu<i>'
  26670. accumulate: function ( accuIndex, weight ) {
  26671. // note: happily accumulating nothing when weight = 0, the caller knows
  26672. // the weight and shouldn't have made the call in the first place
  26673. const buffer = this.buffer,
  26674. stride = this.valueSize,
  26675. offset = accuIndex * stride + stride;
  26676. let currentWeight = this.cumulativeWeight;
  26677. if ( currentWeight === 0 ) {
  26678. // accuN := incoming * weight
  26679. for ( let i = 0; i !== stride; ++ i ) {
  26680. buffer[ offset + i ] = buffer[ i ];
  26681. }
  26682. currentWeight = weight;
  26683. } else {
  26684. // accuN := accuN + incoming * weight
  26685. currentWeight += weight;
  26686. const mix = weight / currentWeight;
  26687. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26688. }
  26689. this.cumulativeWeight = currentWeight;
  26690. },
  26691. // accumulate data in the 'incoming' region into 'add'
  26692. accumulateAdditive: function ( weight ) {
  26693. const buffer = this.buffer,
  26694. stride = this.valueSize,
  26695. offset = stride * this._addIndex;
  26696. if ( this.cumulativeWeightAdditive === 0 ) {
  26697. // add = identity
  26698. this._setIdentity();
  26699. }
  26700. // add := add + incoming * weight
  26701. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26702. this.cumulativeWeightAdditive += weight;
  26703. },
  26704. // apply the state of 'accu<i>' to the binding when accus differ
  26705. apply: function ( accuIndex ) {
  26706. const stride = this.valueSize,
  26707. buffer = this.buffer,
  26708. offset = accuIndex * stride + stride,
  26709. weight = this.cumulativeWeight,
  26710. weightAdditive = this.cumulativeWeightAdditive,
  26711. binding = this.binding;
  26712. this.cumulativeWeight = 0;
  26713. this.cumulativeWeightAdditive = 0;
  26714. if ( weight < 1 ) {
  26715. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26716. const originalValueOffset = stride * this._origIndex;
  26717. this._mixBufferRegion(
  26718. buffer, offset, originalValueOffset, 1 - weight, stride );
  26719. }
  26720. if ( weightAdditive > 0 ) {
  26721. // accuN := accuN + additive accuN
  26722. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26723. }
  26724. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26725. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26726. // value has changed -> update scene graph
  26727. binding.setValue( buffer, offset );
  26728. break;
  26729. }
  26730. }
  26731. },
  26732. // remember the state of the bound property and copy it to both accus
  26733. saveOriginalState: function () {
  26734. const binding = this.binding;
  26735. const buffer = this.buffer,
  26736. stride = this.valueSize,
  26737. originalValueOffset = stride * this._origIndex;
  26738. binding.getValue( buffer, originalValueOffset );
  26739. // accu[0..1] := orig -- initially detect changes against the original
  26740. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26741. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26742. }
  26743. // Add to identity for additive
  26744. this._setIdentity();
  26745. this.cumulativeWeight = 0;
  26746. this.cumulativeWeightAdditive = 0;
  26747. },
  26748. // apply the state previously taken via 'saveOriginalState' to the binding
  26749. restoreOriginalState: function () {
  26750. const originalValueOffset = this.valueSize * 3;
  26751. this.binding.setValue( this.buffer, originalValueOffset );
  26752. },
  26753. _setAdditiveIdentityNumeric: function () {
  26754. const startIndex = this._addIndex * this.valueSize;
  26755. const endIndex = startIndex + this.valueSize;
  26756. for ( let i = startIndex; i < endIndex; i ++ ) {
  26757. this.buffer[ i ] = 0;
  26758. }
  26759. },
  26760. _setAdditiveIdentityQuaternion: function () {
  26761. this._setAdditiveIdentityNumeric();
  26762. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26763. },
  26764. _setAdditiveIdentityOther: function () {
  26765. const startIndex = this._origIndex * this.valueSize;
  26766. const targetIndex = this._addIndex * this.valueSize;
  26767. for ( let i = 0; i < this.valueSize; i ++ ) {
  26768. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26769. }
  26770. },
  26771. // mix functions
  26772. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26773. if ( t >= 0.5 ) {
  26774. for ( let i = 0; i !== stride; ++ i ) {
  26775. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26776. }
  26777. }
  26778. },
  26779. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  26780. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26781. },
  26782. _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26783. const workOffset = this._workIndex * stride;
  26784. // Store result in intermediate buffer offset
  26785. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26786. // Slerp to the intermediate result
  26787. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26788. },
  26789. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26790. const s = 1 - t;
  26791. for ( let i = 0; i !== stride; ++ i ) {
  26792. const j = dstOffset + i;
  26793. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26794. }
  26795. },
  26796. _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26797. for ( let i = 0; i !== stride; ++ i ) {
  26798. const j = dstOffset + i;
  26799. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26800. }
  26801. }
  26802. } );
  26803. // Characters [].:/ are reserved for track binding syntax.
  26804. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26805. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26806. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26807. // only latin characters, and the unicode \p{L} is not yet supported. So
  26808. // instead, we exclude reserved characters and match everything else.
  26809. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26810. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26811. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26812. // be matched to parse the rest of the track name.
  26813. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26814. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26815. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26816. // Object on target node, and accessor. May not contain reserved
  26817. // characters. Accessor may contain any character except closing bracket.
  26818. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26819. // Property and accessor. May not contain reserved characters. Accessor may
  26820. // contain any non-bracket characters.
  26821. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26822. const _trackRe = new RegExp( ''
  26823. + '^'
  26824. + _directoryRe
  26825. + _nodeRe
  26826. + _objectRe
  26827. + _propertyRe
  26828. + '$'
  26829. );
  26830. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26831. function Composite( targetGroup, path, optionalParsedPath ) {
  26832. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26833. this._targetGroup = targetGroup;
  26834. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26835. }
  26836. Object.assign( Composite.prototype, {
  26837. getValue: function ( array, offset ) {
  26838. this.bind(); // bind all binding
  26839. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26840. binding = this._bindings[ firstValidIndex ];
  26841. // and only call .getValue on the first
  26842. if ( binding !== undefined ) binding.getValue( array, offset );
  26843. },
  26844. setValue: function ( array, offset ) {
  26845. const bindings = this._bindings;
  26846. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26847. bindings[ i ].setValue( array, offset );
  26848. }
  26849. },
  26850. bind: function () {
  26851. const bindings = this._bindings;
  26852. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26853. bindings[ i ].bind();
  26854. }
  26855. },
  26856. unbind: function () {
  26857. const bindings = this._bindings;
  26858. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26859. bindings[ i ].unbind();
  26860. }
  26861. }
  26862. } );
  26863. function PropertyBinding( rootNode, path, parsedPath ) {
  26864. this.path = path;
  26865. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26866. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26867. this.rootNode = rootNode;
  26868. }
  26869. Object.assign( PropertyBinding, {
  26870. Composite: Composite,
  26871. create: function ( root, path, parsedPath ) {
  26872. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26873. return new PropertyBinding( root, path, parsedPath );
  26874. } else {
  26875. return new PropertyBinding.Composite( root, path, parsedPath );
  26876. }
  26877. },
  26878. /**
  26879. * Replaces spaces with underscores and removes unsupported characters from
  26880. * node names, to ensure compatibility with parseTrackName().
  26881. *
  26882. * @param {string} name Node name to be sanitized.
  26883. * @return {string}
  26884. */
  26885. sanitizeNodeName: function ( name ) {
  26886. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26887. },
  26888. parseTrackName: function ( trackName ) {
  26889. const matches = _trackRe.exec( trackName );
  26890. if ( ! matches ) {
  26891. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26892. }
  26893. const results = {
  26894. // directoryName: matches[ 1 ], // (tschw) currently unused
  26895. nodeName: matches[ 2 ],
  26896. objectName: matches[ 3 ],
  26897. objectIndex: matches[ 4 ],
  26898. propertyName: matches[ 5 ], // required
  26899. propertyIndex: matches[ 6 ]
  26900. };
  26901. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26902. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26903. const objectName = results.nodeName.substring( lastDot + 1 );
  26904. // Object names must be checked against an allowlist. Otherwise, there
  26905. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26906. // 'bar' could be the objectName, or part of a nodeName (which can
  26907. // include '.' characters).
  26908. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26909. results.nodeName = results.nodeName.substring( 0, lastDot );
  26910. results.objectName = objectName;
  26911. }
  26912. }
  26913. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26914. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26915. }
  26916. return results;
  26917. },
  26918. findNode: function ( root, nodeName ) {
  26919. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26920. return root;
  26921. }
  26922. // search into skeleton bones.
  26923. if ( root.skeleton ) {
  26924. const bone = root.skeleton.getBoneByName( nodeName );
  26925. if ( bone !== undefined ) {
  26926. return bone;
  26927. }
  26928. }
  26929. // search into node subtree.
  26930. if ( root.children ) {
  26931. const searchNodeSubtree = function ( children ) {
  26932. for ( let i = 0; i < children.length; i ++ ) {
  26933. const childNode = children[ i ];
  26934. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26935. return childNode;
  26936. }
  26937. const result = searchNodeSubtree( childNode.children );
  26938. if ( result ) return result;
  26939. }
  26940. return null;
  26941. };
  26942. const subTreeNode = searchNodeSubtree( root.children );
  26943. if ( subTreeNode ) {
  26944. return subTreeNode;
  26945. }
  26946. }
  26947. return null;
  26948. }
  26949. } );
  26950. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26951. // these are used to "bind" a nonexistent property
  26952. _getValue_unavailable: function () {},
  26953. _setValue_unavailable: function () {},
  26954. BindingType: {
  26955. Direct: 0,
  26956. EntireArray: 1,
  26957. ArrayElement: 2,
  26958. HasFromToArray: 3
  26959. },
  26960. Versioning: {
  26961. None: 0,
  26962. NeedsUpdate: 1,
  26963. MatrixWorldNeedsUpdate: 2
  26964. },
  26965. GetterByBindingType: [
  26966. function getValue_direct( buffer, offset ) {
  26967. buffer[ offset ] = this.node[ this.propertyName ];
  26968. },
  26969. function getValue_array( buffer, offset ) {
  26970. const source = this.resolvedProperty;
  26971. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26972. buffer[ offset ++ ] = source[ i ];
  26973. }
  26974. },
  26975. function getValue_arrayElement( buffer, offset ) {
  26976. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26977. },
  26978. function getValue_toArray( buffer, offset ) {
  26979. this.resolvedProperty.toArray( buffer, offset );
  26980. }
  26981. ],
  26982. SetterByBindingTypeAndVersioning: [
  26983. [
  26984. // Direct
  26985. function setValue_direct( buffer, offset ) {
  26986. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26987. },
  26988. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26989. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26990. this.targetObject.needsUpdate = true;
  26991. },
  26992. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26993. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26994. this.targetObject.matrixWorldNeedsUpdate = true;
  26995. }
  26996. ], [
  26997. // EntireArray
  26998. function setValue_array( buffer, offset ) {
  26999. const dest = this.resolvedProperty;
  27000. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27001. dest[ i ] = buffer[ offset ++ ];
  27002. }
  27003. },
  27004. function setValue_array_setNeedsUpdate( buffer, offset ) {
  27005. const dest = this.resolvedProperty;
  27006. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27007. dest[ i ] = buffer[ offset ++ ];
  27008. }
  27009. this.targetObject.needsUpdate = true;
  27010. },
  27011. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27012. const dest = this.resolvedProperty;
  27013. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27014. dest[ i ] = buffer[ offset ++ ];
  27015. }
  27016. this.targetObject.matrixWorldNeedsUpdate = true;
  27017. }
  27018. ], [
  27019. // ArrayElement
  27020. function setValue_arrayElement( buffer, offset ) {
  27021. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27022. },
  27023. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27024. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27025. this.targetObject.needsUpdate = true;
  27026. },
  27027. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27028. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27029. this.targetObject.matrixWorldNeedsUpdate = true;
  27030. }
  27031. ], [
  27032. // HasToFromArray
  27033. function setValue_fromArray( buffer, offset ) {
  27034. this.resolvedProperty.fromArray( buffer, offset );
  27035. },
  27036. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27037. this.resolvedProperty.fromArray( buffer, offset );
  27038. this.targetObject.needsUpdate = true;
  27039. },
  27040. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27041. this.resolvedProperty.fromArray( buffer, offset );
  27042. this.targetObject.matrixWorldNeedsUpdate = true;
  27043. }
  27044. ]
  27045. ],
  27046. getValue: function getValue_unbound( targetArray, offset ) {
  27047. this.bind();
  27048. this.getValue( targetArray, offset );
  27049. // Note: This class uses a State pattern on a per-method basis:
  27050. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27051. // prototype version of these methods with one that represents
  27052. // the bound state. When the property is not found, the methods
  27053. // become no-ops.
  27054. },
  27055. setValue: function getValue_unbound( sourceArray, offset ) {
  27056. this.bind();
  27057. this.setValue( sourceArray, offset );
  27058. },
  27059. // create getter / setter pair for a property in the scene graph
  27060. bind: function () {
  27061. let targetObject = this.node;
  27062. const parsedPath = this.parsedPath;
  27063. const objectName = parsedPath.objectName;
  27064. const propertyName = parsedPath.propertyName;
  27065. let propertyIndex = parsedPath.propertyIndex;
  27066. if ( ! targetObject ) {
  27067. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27068. this.node = targetObject;
  27069. }
  27070. // set fail state so we can just 'return' on error
  27071. this.getValue = this._getValue_unavailable;
  27072. this.setValue = this._setValue_unavailable;
  27073. // ensure there is a value node
  27074. if ( ! targetObject ) {
  27075. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27076. return;
  27077. }
  27078. if ( objectName ) {
  27079. let objectIndex = parsedPath.objectIndex;
  27080. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27081. switch ( objectName ) {
  27082. case 'materials':
  27083. if ( ! targetObject.material ) {
  27084. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27085. return;
  27086. }
  27087. if ( ! targetObject.material.materials ) {
  27088. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27089. return;
  27090. }
  27091. targetObject = targetObject.material.materials;
  27092. break;
  27093. case 'bones':
  27094. if ( ! targetObject.skeleton ) {
  27095. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27096. return;
  27097. }
  27098. // potential future optimization: skip this if propertyIndex is already an integer
  27099. // and convert the integer string to a true integer.
  27100. targetObject = targetObject.skeleton.bones;
  27101. // support resolving morphTarget names into indices.
  27102. for ( let i = 0; i < targetObject.length; i ++ ) {
  27103. if ( targetObject[ i ].name === objectIndex ) {
  27104. objectIndex = i;
  27105. break;
  27106. }
  27107. }
  27108. break;
  27109. default:
  27110. if ( targetObject[ objectName ] === undefined ) {
  27111. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27112. return;
  27113. }
  27114. targetObject = targetObject[ objectName ];
  27115. }
  27116. if ( objectIndex !== undefined ) {
  27117. if ( targetObject[ objectIndex ] === undefined ) {
  27118. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27119. return;
  27120. }
  27121. targetObject = targetObject[ objectIndex ];
  27122. }
  27123. }
  27124. // resolve property
  27125. const nodeProperty = targetObject[ propertyName ];
  27126. if ( nodeProperty === undefined ) {
  27127. const nodeName = parsedPath.nodeName;
  27128. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27129. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27130. return;
  27131. }
  27132. // determine versioning scheme
  27133. let versioning = this.Versioning.None;
  27134. this.targetObject = targetObject;
  27135. if ( targetObject.needsUpdate !== undefined ) { // material
  27136. versioning = this.Versioning.NeedsUpdate;
  27137. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27138. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27139. }
  27140. // determine how the property gets bound
  27141. let bindingType = this.BindingType.Direct;
  27142. if ( propertyIndex !== undefined ) {
  27143. // access a sub element of the property array (only primitives are supported right now)
  27144. if ( propertyName === 'morphTargetInfluences' ) {
  27145. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27146. // support resolving morphTarget names into indices.
  27147. if ( ! targetObject.geometry ) {
  27148. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27149. return;
  27150. }
  27151. if ( targetObject.geometry.isBufferGeometry ) {
  27152. if ( ! targetObject.geometry.morphAttributes ) {
  27153. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27154. return;
  27155. }
  27156. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27157. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27158. }
  27159. } else {
  27160. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  27161. return;
  27162. }
  27163. }
  27164. bindingType = this.BindingType.ArrayElement;
  27165. this.resolvedProperty = nodeProperty;
  27166. this.propertyIndex = propertyIndex;
  27167. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27168. // must use copy for Object3D.Euler/Quaternion
  27169. bindingType = this.BindingType.HasFromToArray;
  27170. this.resolvedProperty = nodeProperty;
  27171. } else if ( Array.isArray( nodeProperty ) ) {
  27172. bindingType = this.BindingType.EntireArray;
  27173. this.resolvedProperty = nodeProperty;
  27174. } else {
  27175. this.propertyName = propertyName;
  27176. }
  27177. // select getter / setter
  27178. this.getValue = this.GetterByBindingType[ bindingType ];
  27179. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27180. },
  27181. unbind: function () {
  27182. this.node = null;
  27183. // back to the prototype version of getValue / setValue
  27184. // note: avoiding to mutate the shape of 'this' via 'delete'
  27185. this.getValue = this._getValue_unbound;
  27186. this.setValue = this._setValue_unbound;
  27187. }
  27188. } );
  27189. // DECLARE ALIAS AFTER assign prototype
  27190. Object.assign( PropertyBinding.prototype, {
  27191. // initial state of these methods that calls 'bind'
  27192. _getValue_unbound: PropertyBinding.prototype.getValue,
  27193. _setValue_unbound: PropertyBinding.prototype.setValue,
  27194. } );
  27195. /**
  27196. *
  27197. * A group of objects that receives a shared animation state.
  27198. *
  27199. * Usage:
  27200. *
  27201. * - Add objects you would otherwise pass as 'root' to the
  27202. * constructor or the .clipAction method of AnimationMixer.
  27203. *
  27204. * - Instead pass this object as 'root'.
  27205. *
  27206. * - You can also add and remove objects later when the mixer
  27207. * is running.
  27208. *
  27209. * Note:
  27210. *
  27211. * Objects of this class appear as one object to the mixer,
  27212. * so cache control of the individual objects must be done
  27213. * on the group.
  27214. *
  27215. * Limitation:
  27216. *
  27217. * - The animated properties must be compatible among the
  27218. * all objects in the group.
  27219. *
  27220. * - A single property can either be controlled through a
  27221. * target group or directly, but not both.
  27222. */
  27223. function AnimationObjectGroup() {
  27224. this.uuid = MathUtils.generateUUID();
  27225. // cached objects followed by the active ones
  27226. this._objects = Array.prototype.slice.call( arguments );
  27227. this.nCachedObjects_ = 0; // threshold
  27228. // note: read by PropertyBinding.Composite
  27229. const indices = {};
  27230. this._indicesByUUID = indices; // for bookkeeping
  27231. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27232. indices[ arguments[ i ].uuid ] = i;
  27233. }
  27234. this._paths = []; // inside: string
  27235. this._parsedPaths = []; // inside: { we don't care, here }
  27236. this._bindings = []; // inside: Array< PropertyBinding >
  27237. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27238. const scope = this;
  27239. this.stats = {
  27240. objects: {
  27241. get total() {
  27242. return scope._objects.length;
  27243. },
  27244. get inUse() {
  27245. return this.total - scope.nCachedObjects_;
  27246. }
  27247. },
  27248. get bindingsPerObject() {
  27249. return scope._bindings.length;
  27250. }
  27251. };
  27252. }
  27253. Object.assign( AnimationObjectGroup.prototype, {
  27254. isAnimationObjectGroup: true,
  27255. add: function () {
  27256. const objects = this._objects,
  27257. indicesByUUID = this._indicesByUUID,
  27258. paths = this._paths,
  27259. parsedPaths = this._parsedPaths,
  27260. bindings = this._bindings,
  27261. nBindings = bindings.length;
  27262. let knownObject = undefined,
  27263. nObjects = objects.length,
  27264. nCachedObjects = this.nCachedObjects_;
  27265. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27266. const object = arguments[ i ],
  27267. uuid = object.uuid;
  27268. let index = indicesByUUID[ uuid ];
  27269. if ( index === undefined ) {
  27270. // unknown object -> add it to the ACTIVE region
  27271. index = nObjects ++;
  27272. indicesByUUID[ uuid ] = index;
  27273. objects.push( object );
  27274. // accounting is done, now do the same for all bindings
  27275. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27276. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27277. }
  27278. } else if ( index < nCachedObjects ) {
  27279. knownObject = objects[ index ];
  27280. // move existing object to the ACTIVE region
  27281. const firstActiveIndex = -- nCachedObjects,
  27282. lastCachedObject = objects[ firstActiveIndex ];
  27283. indicesByUUID[ lastCachedObject.uuid ] = index;
  27284. objects[ index ] = lastCachedObject;
  27285. indicesByUUID[ uuid ] = firstActiveIndex;
  27286. objects[ firstActiveIndex ] = object;
  27287. // accounting is done, now do the same for all bindings
  27288. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27289. const bindingsForPath = bindings[ j ],
  27290. lastCached = bindingsForPath[ firstActiveIndex ];
  27291. let binding = bindingsForPath[ index ];
  27292. bindingsForPath[ index ] = lastCached;
  27293. if ( binding === undefined ) {
  27294. // since we do not bother to create new bindings
  27295. // for objects that are cached, the binding may
  27296. // or may not exist
  27297. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27298. }
  27299. bindingsForPath[ firstActiveIndex ] = binding;
  27300. }
  27301. } else if ( objects[ index ] !== knownObject ) {
  27302. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27303. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27304. } // else the object is already where we want it to be
  27305. } // for arguments
  27306. this.nCachedObjects_ = nCachedObjects;
  27307. },
  27308. remove: function () {
  27309. const objects = this._objects,
  27310. indicesByUUID = this._indicesByUUID,
  27311. bindings = this._bindings,
  27312. nBindings = bindings.length;
  27313. let nCachedObjects = this.nCachedObjects_;
  27314. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27315. const object = arguments[ i ],
  27316. uuid = object.uuid,
  27317. index = indicesByUUID[ uuid ];
  27318. if ( index !== undefined && index >= nCachedObjects ) {
  27319. // move existing object into the CACHED region
  27320. const lastCachedIndex = nCachedObjects ++,
  27321. firstActiveObject = objects[ lastCachedIndex ];
  27322. indicesByUUID[ firstActiveObject.uuid ] = index;
  27323. objects[ index ] = firstActiveObject;
  27324. indicesByUUID[ uuid ] = lastCachedIndex;
  27325. objects[ lastCachedIndex ] = object;
  27326. // accounting is done, now do the same for all bindings
  27327. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27328. const bindingsForPath = bindings[ j ],
  27329. firstActive = bindingsForPath[ lastCachedIndex ],
  27330. binding = bindingsForPath[ index ];
  27331. bindingsForPath[ index ] = firstActive;
  27332. bindingsForPath[ lastCachedIndex ] = binding;
  27333. }
  27334. }
  27335. } // for arguments
  27336. this.nCachedObjects_ = nCachedObjects;
  27337. },
  27338. // remove & forget
  27339. uncache: function () {
  27340. const objects = this._objects,
  27341. indicesByUUID = this._indicesByUUID,
  27342. bindings = this._bindings,
  27343. nBindings = bindings.length;
  27344. let nCachedObjects = this.nCachedObjects_,
  27345. nObjects = objects.length;
  27346. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27347. const object = arguments[ i ],
  27348. uuid = object.uuid,
  27349. index = indicesByUUID[ uuid ];
  27350. if ( index !== undefined ) {
  27351. delete indicesByUUID[ uuid ];
  27352. if ( index < nCachedObjects ) {
  27353. // object is cached, shrink the CACHED region
  27354. const firstActiveIndex = -- nCachedObjects,
  27355. lastCachedObject = objects[ firstActiveIndex ],
  27356. lastIndex = -- nObjects,
  27357. lastObject = objects[ lastIndex ];
  27358. // last cached object takes this object's place
  27359. indicesByUUID[ lastCachedObject.uuid ] = index;
  27360. objects[ index ] = lastCachedObject;
  27361. // last object goes to the activated slot and pop
  27362. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27363. objects[ firstActiveIndex ] = lastObject;
  27364. objects.pop();
  27365. // accounting is done, now do the same for all bindings
  27366. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27367. const bindingsForPath = bindings[ j ],
  27368. lastCached = bindingsForPath[ firstActiveIndex ],
  27369. last = bindingsForPath[ lastIndex ];
  27370. bindingsForPath[ index ] = lastCached;
  27371. bindingsForPath[ firstActiveIndex ] = last;
  27372. bindingsForPath.pop();
  27373. }
  27374. } else {
  27375. // object is active, just swap with the last and pop
  27376. const lastIndex = -- nObjects,
  27377. lastObject = objects[ lastIndex ];
  27378. if ( lastIndex > 0 ) {
  27379. indicesByUUID[ lastObject.uuid ] = index;
  27380. }
  27381. objects[ index ] = lastObject;
  27382. objects.pop();
  27383. // accounting is done, now do the same for all bindings
  27384. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27385. const bindingsForPath = bindings[ j ];
  27386. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27387. bindingsForPath.pop();
  27388. }
  27389. } // cached or active
  27390. } // if object is known
  27391. } // for arguments
  27392. this.nCachedObjects_ = nCachedObjects;
  27393. },
  27394. // Internal interface used by befriended PropertyBinding.Composite:
  27395. subscribe_: function ( path, parsedPath ) {
  27396. // returns an array of bindings for the given path that is changed
  27397. // according to the contained objects in the group
  27398. const indicesByPath = this._bindingsIndicesByPath;
  27399. let index = indicesByPath[ path ];
  27400. const bindings = this._bindings;
  27401. if ( index !== undefined ) return bindings[ index ];
  27402. const paths = this._paths,
  27403. parsedPaths = this._parsedPaths,
  27404. objects = this._objects,
  27405. nObjects = objects.length,
  27406. nCachedObjects = this.nCachedObjects_,
  27407. bindingsForPath = new Array( nObjects );
  27408. index = bindings.length;
  27409. indicesByPath[ path ] = index;
  27410. paths.push( path );
  27411. parsedPaths.push( parsedPath );
  27412. bindings.push( bindingsForPath );
  27413. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27414. const object = objects[ i ];
  27415. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27416. }
  27417. return bindingsForPath;
  27418. },
  27419. unsubscribe_: function ( path ) {
  27420. // tells the group to forget about a property path and no longer
  27421. // update the array previously obtained with 'subscribe_'
  27422. const indicesByPath = this._bindingsIndicesByPath,
  27423. index = indicesByPath[ path ];
  27424. if ( index !== undefined ) {
  27425. const paths = this._paths,
  27426. parsedPaths = this._parsedPaths,
  27427. bindings = this._bindings,
  27428. lastBindingsIndex = bindings.length - 1,
  27429. lastBindings = bindings[ lastBindingsIndex ],
  27430. lastBindingsPath = path[ lastBindingsIndex ];
  27431. indicesByPath[ lastBindingsPath ] = index;
  27432. bindings[ index ] = lastBindings;
  27433. bindings.pop();
  27434. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27435. parsedPaths.pop();
  27436. paths[ index ] = paths[ lastBindingsIndex ];
  27437. paths.pop();
  27438. }
  27439. }
  27440. } );
  27441. class AnimationAction {
  27442. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27443. this._mixer = mixer;
  27444. this._clip = clip;
  27445. this._localRoot = localRoot;
  27446. this.blendMode = blendMode;
  27447. const tracks = clip.tracks,
  27448. nTracks = tracks.length,
  27449. interpolants = new Array( nTracks );
  27450. const interpolantSettings = {
  27451. endingStart: ZeroCurvatureEnding,
  27452. endingEnd: ZeroCurvatureEnding
  27453. };
  27454. for ( let i = 0; i !== nTracks; ++ i ) {
  27455. const interpolant = tracks[ i ].createInterpolant( null );
  27456. interpolants[ i ] = interpolant;
  27457. interpolant.settings = interpolantSettings;
  27458. }
  27459. this._interpolantSettings = interpolantSettings;
  27460. this._interpolants = interpolants; // bound by the mixer
  27461. // inside: PropertyMixer (managed by the mixer)
  27462. this._propertyBindings = new Array( nTracks );
  27463. this._cacheIndex = null; // for the memory manager
  27464. this._byClipCacheIndex = null; // for the memory manager
  27465. this._timeScaleInterpolant = null;
  27466. this._weightInterpolant = null;
  27467. this.loop = LoopRepeat;
  27468. this._loopCount = - 1;
  27469. // global mixer time when the action is to be started
  27470. // it's set back to 'null' upon start of the action
  27471. this._startTime = null;
  27472. // scaled local time of the action
  27473. // gets clamped or wrapped to 0..clip.duration according to loop
  27474. this.time = 0;
  27475. this.timeScale = 1;
  27476. this._effectiveTimeScale = 1;
  27477. this.weight = 1;
  27478. this._effectiveWeight = 1;
  27479. this.repetitions = Infinity; // no. of repetitions when looping
  27480. this.paused = false; // true -> zero effective time scale
  27481. this.enabled = true; // false -> zero effective weight
  27482. this.clampWhenFinished = false;// keep feeding the last frame?
  27483. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27484. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27485. }
  27486. // State & Scheduling
  27487. play() {
  27488. this._mixer._activateAction( this );
  27489. return this;
  27490. }
  27491. stop() {
  27492. this._mixer._deactivateAction( this );
  27493. return this.reset();
  27494. }
  27495. reset() {
  27496. this.paused = false;
  27497. this.enabled = true;
  27498. this.time = 0; // restart clip
  27499. this._loopCount = - 1;// forget previous loops
  27500. this._startTime = null;// forget scheduling
  27501. return this.stopFading().stopWarping();
  27502. }
  27503. isRunning() {
  27504. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27505. this._startTime === null && this._mixer._isActiveAction( this );
  27506. }
  27507. // return true when play has been called
  27508. isScheduled() {
  27509. return this._mixer._isActiveAction( this );
  27510. }
  27511. startAt( time ) {
  27512. this._startTime = time;
  27513. return this;
  27514. }
  27515. setLoop( mode, repetitions ) {
  27516. this.loop = mode;
  27517. this.repetitions = repetitions;
  27518. return this;
  27519. }
  27520. // Weight
  27521. // set the weight stopping any scheduled fading
  27522. // although .enabled = false yields an effective weight of zero, this
  27523. // method does *not* change .enabled, because it would be confusing
  27524. setEffectiveWeight( weight ) {
  27525. this.weight = weight;
  27526. // note: same logic as when updated at runtime
  27527. this._effectiveWeight = this.enabled ? weight : 0;
  27528. return this.stopFading();
  27529. }
  27530. // return the weight considering fading and .enabled
  27531. getEffectiveWeight() {
  27532. return this._effectiveWeight;
  27533. }
  27534. fadeIn( duration ) {
  27535. return this._scheduleFading( duration, 0, 1 );
  27536. }
  27537. fadeOut( duration ) {
  27538. return this._scheduleFading( duration, 1, 0 );
  27539. }
  27540. crossFadeFrom( fadeOutAction, duration, warp ) {
  27541. fadeOutAction.fadeOut( duration );
  27542. this.fadeIn( duration );
  27543. if ( warp ) {
  27544. const fadeInDuration = this._clip.duration,
  27545. fadeOutDuration = fadeOutAction._clip.duration,
  27546. startEndRatio = fadeOutDuration / fadeInDuration,
  27547. endStartRatio = fadeInDuration / fadeOutDuration;
  27548. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27549. this.warp( endStartRatio, 1.0, duration );
  27550. }
  27551. return this;
  27552. }
  27553. crossFadeTo( fadeInAction, duration, warp ) {
  27554. return fadeInAction.crossFadeFrom( this, duration, warp );
  27555. }
  27556. stopFading() {
  27557. const weightInterpolant = this._weightInterpolant;
  27558. if ( weightInterpolant !== null ) {
  27559. this._weightInterpolant = null;
  27560. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27561. }
  27562. return this;
  27563. }
  27564. // Time Scale Control
  27565. // set the time scale stopping any scheduled warping
  27566. // although .paused = true yields an effective time scale of zero, this
  27567. // method does *not* change .paused, because it would be confusing
  27568. setEffectiveTimeScale( timeScale ) {
  27569. this.timeScale = timeScale;
  27570. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27571. return this.stopWarping();
  27572. }
  27573. // return the time scale considering warping and .paused
  27574. getEffectiveTimeScale() {
  27575. return this._effectiveTimeScale;
  27576. }
  27577. setDuration( duration ) {
  27578. this.timeScale = this._clip.duration / duration;
  27579. return this.stopWarping();
  27580. }
  27581. syncWith( action ) {
  27582. this.time = action.time;
  27583. this.timeScale = action.timeScale;
  27584. return this.stopWarping();
  27585. }
  27586. halt( duration ) {
  27587. return this.warp( this._effectiveTimeScale, 0, duration );
  27588. }
  27589. warp( startTimeScale, endTimeScale, duration ) {
  27590. const mixer = this._mixer,
  27591. now = mixer.time,
  27592. timeScale = this.timeScale;
  27593. let interpolant = this._timeScaleInterpolant;
  27594. if ( interpolant === null ) {
  27595. interpolant = mixer._lendControlInterpolant();
  27596. this._timeScaleInterpolant = interpolant;
  27597. }
  27598. const times = interpolant.parameterPositions,
  27599. values = interpolant.sampleValues;
  27600. times[ 0 ] = now;
  27601. times[ 1 ] = now + duration;
  27602. values[ 0 ] = startTimeScale / timeScale;
  27603. values[ 1 ] = endTimeScale / timeScale;
  27604. return this;
  27605. }
  27606. stopWarping() {
  27607. const timeScaleInterpolant = this._timeScaleInterpolant;
  27608. if ( timeScaleInterpolant !== null ) {
  27609. this._timeScaleInterpolant = null;
  27610. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27611. }
  27612. return this;
  27613. }
  27614. // Object Accessors
  27615. getMixer() {
  27616. return this._mixer;
  27617. }
  27618. getClip() {
  27619. return this._clip;
  27620. }
  27621. getRoot() {
  27622. return this._localRoot || this._mixer._root;
  27623. }
  27624. // Interna
  27625. _update( time, deltaTime, timeDirection, accuIndex ) {
  27626. // called by the mixer
  27627. if ( ! this.enabled ) {
  27628. // call ._updateWeight() to update ._effectiveWeight
  27629. this._updateWeight( time );
  27630. return;
  27631. }
  27632. const startTime = this._startTime;
  27633. if ( startTime !== null ) {
  27634. // check for scheduled start of action
  27635. const timeRunning = ( time - startTime ) * timeDirection;
  27636. if ( timeRunning < 0 || timeDirection === 0 ) {
  27637. return; // yet to come / don't decide when delta = 0
  27638. }
  27639. // start
  27640. this._startTime = null; // unschedule
  27641. deltaTime = timeDirection * timeRunning;
  27642. }
  27643. // apply time scale and advance time
  27644. deltaTime *= this._updateTimeScale( time );
  27645. const clipTime = this._updateTime( deltaTime );
  27646. // note: _updateTime may disable the action resulting in
  27647. // an effective weight of 0
  27648. const weight = this._updateWeight( time );
  27649. if ( weight > 0 ) {
  27650. const interpolants = this._interpolants;
  27651. const propertyMixers = this._propertyBindings;
  27652. switch ( this.blendMode ) {
  27653. case AdditiveAnimationBlendMode:
  27654. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27655. interpolants[ j ].evaluate( clipTime );
  27656. propertyMixers[ j ].accumulateAdditive( weight );
  27657. }
  27658. break;
  27659. case NormalAnimationBlendMode:
  27660. default:
  27661. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27662. interpolants[ j ].evaluate( clipTime );
  27663. propertyMixers[ j ].accumulate( accuIndex, weight );
  27664. }
  27665. }
  27666. }
  27667. }
  27668. _updateWeight( time ) {
  27669. let weight = 0;
  27670. if ( this.enabled ) {
  27671. weight = this.weight;
  27672. const interpolant = this._weightInterpolant;
  27673. if ( interpolant !== null ) {
  27674. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27675. weight *= interpolantValue;
  27676. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27677. this.stopFading();
  27678. if ( interpolantValue === 0 ) {
  27679. // faded out, disable
  27680. this.enabled = false;
  27681. }
  27682. }
  27683. }
  27684. }
  27685. this._effectiveWeight = weight;
  27686. return weight;
  27687. }
  27688. _updateTimeScale( time ) {
  27689. let timeScale = 0;
  27690. if ( ! this.paused ) {
  27691. timeScale = this.timeScale;
  27692. const interpolant = this._timeScaleInterpolant;
  27693. if ( interpolant !== null ) {
  27694. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27695. timeScale *= interpolantValue;
  27696. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27697. this.stopWarping();
  27698. if ( timeScale === 0 ) {
  27699. // motion has halted, pause
  27700. this.paused = true;
  27701. } else {
  27702. // warp done - apply final time scale
  27703. this.timeScale = timeScale;
  27704. }
  27705. }
  27706. }
  27707. }
  27708. this._effectiveTimeScale = timeScale;
  27709. return timeScale;
  27710. }
  27711. _updateTime( deltaTime ) {
  27712. const duration = this._clip.duration;
  27713. const loop = this.loop;
  27714. let time = this.time + deltaTime;
  27715. let loopCount = this._loopCount;
  27716. const pingPong = ( loop === LoopPingPong );
  27717. if ( deltaTime === 0 ) {
  27718. if ( loopCount === - 1 ) return time;
  27719. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27720. }
  27721. if ( loop === LoopOnce ) {
  27722. if ( loopCount === - 1 ) {
  27723. // just started
  27724. this._loopCount = 0;
  27725. this._setEndings( true, true, false );
  27726. }
  27727. handle_stop: {
  27728. if ( time >= duration ) {
  27729. time = duration;
  27730. } else if ( time < 0 ) {
  27731. time = 0;
  27732. } else {
  27733. this.time = time;
  27734. break handle_stop;
  27735. }
  27736. if ( this.clampWhenFinished ) this.paused = true;
  27737. else this.enabled = false;
  27738. this.time = time;
  27739. this._mixer.dispatchEvent( {
  27740. type: 'finished', action: this,
  27741. direction: deltaTime < 0 ? - 1 : 1
  27742. } );
  27743. }
  27744. } else { // repetitive Repeat or PingPong
  27745. if ( loopCount === - 1 ) {
  27746. // just started
  27747. if ( deltaTime >= 0 ) {
  27748. loopCount = 0;
  27749. this._setEndings( true, this.repetitions === 0, pingPong );
  27750. } else {
  27751. // when looping in reverse direction, the initial
  27752. // transition through zero counts as a repetition,
  27753. // so leave loopCount at -1
  27754. this._setEndings( this.repetitions === 0, true, pingPong );
  27755. }
  27756. }
  27757. if ( time >= duration || time < 0 ) {
  27758. // wrap around
  27759. const loopDelta = Math.floor( time / duration ); // signed
  27760. time -= duration * loopDelta;
  27761. loopCount += Math.abs( loopDelta );
  27762. const pending = this.repetitions - loopCount;
  27763. if ( pending <= 0 ) {
  27764. // have to stop (switch state, clamp time, fire event)
  27765. if ( this.clampWhenFinished ) this.paused = true;
  27766. else this.enabled = false;
  27767. time = deltaTime > 0 ? duration : 0;
  27768. this.time = time;
  27769. this._mixer.dispatchEvent( {
  27770. type: 'finished', action: this,
  27771. direction: deltaTime > 0 ? 1 : - 1
  27772. } );
  27773. } else {
  27774. // keep running
  27775. if ( pending === 1 ) {
  27776. // entering the last round
  27777. const atStart = deltaTime < 0;
  27778. this._setEndings( atStart, ! atStart, pingPong );
  27779. } else {
  27780. this._setEndings( false, false, pingPong );
  27781. }
  27782. this._loopCount = loopCount;
  27783. this.time = time;
  27784. this._mixer.dispatchEvent( {
  27785. type: 'loop', action: this, loopDelta: loopDelta
  27786. } );
  27787. }
  27788. } else {
  27789. this.time = time;
  27790. }
  27791. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27792. // invert time for the "pong round"
  27793. return duration - time;
  27794. }
  27795. }
  27796. return time;
  27797. }
  27798. _setEndings( atStart, atEnd, pingPong ) {
  27799. const settings = this._interpolantSettings;
  27800. if ( pingPong ) {
  27801. settings.endingStart = ZeroSlopeEnding;
  27802. settings.endingEnd = ZeroSlopeEnding;
  27803. } else {
  27804. // assuming for LoopOnce atStart == atEnd == true
  27805. if ( atStart ) {
  27806. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27807. } else {
  27808. settings.endingStart = WrapAroundEnding;
  27809. }
  27810. if ( atEnd ) {
  27811. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27812. } else {
  27813. settings.endingEnd = WrapAroundEnding;
  27814. }
  27815. }
  27816. }
  27817. _scheduleFading( duration, weightNow, weightThen ) {
  27818. const mixer = this._mixer, now = mixer.time;
  27819. let interpolant = this._weightInterpolant;
  27820. if ( interpolant === null ) {
  27821. interpolant = mixer._lendControlInterpolant();
  27822. this._weightInterpolant = interpolant;
  27823. }
  27824. const times = interpolant.parameterPositions,
  27825. values = interpolant.sampleValues;
  27826. times[ 0 ] = now;
  27827. values[ 0 ] = weightNow;
  27828. times[ 1 ] = now + duration;
  27829. values[ 1 ] = weightThen;
  27830. return this;
  27831. }
  27832. }
  27833. function AnimationMixer( root ) {
  27834. this._root = root;
  27835. this._initMemoryManager();
  27836. this._accuIndex = 0;
  27837. this.time = 0;
  27838. this.timeScale = 1.0;
  27839. }
  27840. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  27841. constructor: AnimationMixer,
  27842. _bindAction: function ( action, prototypeAction ) {
  27843. const root = action._localRoot || this._root,
  27844. tracks = action._clip.tracks,
  27845. nTracks = tracks.length,
  27846. bindings = action._propertyBindings,
  27847. interpolants = action._interpolants,
  27848. rootUuid = root.uuid,
  27849. bindingsByRoot = this._bindingsByRootAndName;
  27850. let bindingsByName = bindingsByRoot[ rootUuid ];
  27851. if ( bindingsByName === undefined ) {
  27852. bindingsByName = {};
  27853. bindingsByRoot[ rootUuid ] = bindingsByName;
  27854. }
  27855. for ( let i = 0; i !== nTracks; ++ i ) {
  27856. const track = tracks[ i ],
  27857. trackName = track.name;
  27858. let binding = bindingsByName[ trackName ];
  27859. if ( binding !== undefined ) {
  27860. bindings[ i ] = binding;
  27861. } else {
  27862. binding = bindings[ i ];
  27863. if ( binding !== undefined ) {
  27864. // existing binding, make sure the cache knows
  27865. if ( binding._cacheIndex === null ) {
  27866. ++ binding.referenceCount;
  27867. this._addInactiveBinding( binding, rootUuid, trackName );
  27868. }
  27869. continue;
  27870. }
  27871. const path = prototypeAction && prototypeAction.
  27872. _propertyBindings[ i ].binding.parsedPath;
  27873. binding = new PropertyMixer(
  27874. PropertyBinding.create( root, trackName, path ),
  27875. track.ValueTypeName, track.getValueSize() );
  27876. ++ binding.referenceCount;
  27877. this._addInactiveBinding( binding, rootUuid, trackName );
  27878. bindings[ i ] = binding;
  27879. }
  27880. interpolants[ i ].resultBuffer = binding.buffer;
  27881. }
  27882. },
  27883. _activateAction: function ( action ) {
  27884. if ( ! this._isActiveAction( action ) ) {
  27885. if ( action._cacheIndex === null ) {
  27886. // this action has been forgotten by the cache, but the user
  27887. // appears to be still using it -> rebind
  27888. const rootUuid = ( action._localRoot || this._root ).uuid,
  27889. clipUuid = action._clip.uuid,
  27890. actionsForClip = this._actionsByClip[ clipUuid ];
  27891. this._bindAction( action,
  27892. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27893. this._addInactiveAction( action, clipUuid, rootUuid );
  27894. }
  27895. const bindings = action._propertyBindings;
  27896. // increment reference counts / sort out state
  27897. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27898. const binding = bindings[ i ];
  27899. if ( binding.useCount ++ === 0 ) {
  27900. this._lendBinding( binding );
  27901. binding.saveOriginalState();
  27902. }
  27903. }
  27904. this._lendAction( action );
  27905. }
  27906. },
  27907. _deactivateAction: function ( action ) {
  27908. if ( this._isActiveAction( action ) ) {
  27909. const bindings = action._propertyBindings;
  27910. // decrement reference counts / sort out state
  27911. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27912. const binding = bindings[ i ];
  27913. if ( -- binding.useCount === 0 ) {
  27914. binding.restoreOriginalState();
  27915. this._takeBackBinding( binding );
  27916. }
  27917. }
  27918. this._takeBackAction( action );
  27919. }
  27920. },
  27921. // Memory manager
  27922. _initMemoryManager: function () {
  27923. this._actions = []; // 'nActiveActions' followed by inactive ones
  27924. this._nActiveActions = 0;
  27925. this._actionsByClip = {};
  27926. // inside:
  27927. // {
  27928. // knownActions: Array< AnimationAction > - used as prototypes
  27929. // actionByRoot: AnimationAction - lookup
  27930. // }
  27931. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27932. this._nActiveBindings = 0;
  27933. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27934. this._controlInterpolants = []; // same game as above
  27935. this._nActiveControlInterpolants = 0;
  27936. const scope = this;
  27937. this.stats = {
  27938. actions: {
  27939. get total() {
  27940. return scope._actions.length;
  27941. },
  27942. get inUse() {
  27943. return scope._nActiveActions;
  27944. }
  27945. },
  27946. bindings: {
  27947. get total() {
  27948. return scope._bindings.length;
  27949. },
  27950. get inUse() {
  27951. return scope._nActiveBindings;
  27952. }
  27953. },
  27954. controlInterpolants: {
  27955. get total() {
  27956. return scope._controlInterpolants.length;
  27957. },
  27958. get inUse() {
  27959. return scope._nActiveControlInterpolants;
  27960. }
  27961. }
  27962. };
  27963. },
  27964. // Memory management for AnimationAction objects
  27965. _isActiveAction: function ( action ) {
  27966. const index = action._cacheIndex;
  27967. return index !== null && index < this._nActiveActions;
  27968. },
  27969. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27970. const actions = this._actions,
  27971. actionsByClip = this._actionsByClip;
  27972. let actionsForClip = actionsByClip[ clipUuid ];
  27973. if ( actionsForClip === undefined ) {
  27974. actionsForClip = {
  27975. knownActions: [ action ],
  27976. actionByRoot: {}
  27977. };
  27978. action._byClipCacheIndex = 0;
  27979. actionsByClip[ clipUuid ] = actionsForClip;
  27980. } else {
  27981. const knownActions = actionsForClip.knownActions;
  27982. action._byClipCacheIndex = knownActions.length;
  27983. knownActions.push( action );
  27984. }
  27985. action._cacheIndex = actions.length;
  27986. actions.push( action );
  27987. actionsForClip.actionByRoot[ rootUuid ] = action;
  27988. },
  27989. _removeInactiveAction: function ( action ) {
  27990. const actions = this._actions,
  27991. lastInactiveAction = actions[ actions.length - 1 ],
  27992. cacheIndex = action._cacheIndex;
  27993. lastInactiveAction._cacheIndex = cacheIndex;
  27994. actions[ cacheIndex ] = lastInactiveAction;
  27995. actions.pop();
  27996. action._cacheIndex = null;
  27997. const clipUuid = action._clip.uuid,
  27998. actionsByClip = this._actionsByClip,
  27999. actionsForClip = actionsByClip[ clipUuid ],
  28000. knownActionsForClip = actionsForClip.knownActions,
  28001. lastKnownAction =
  28002. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28003. byClipCacheIndex = action._byClipCacheIndex;
  28004. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28005. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28006. knownActionsForClip.pop();
  28007. action._byClipCacheIndex = null;
  28008. const actionByRoot = actionsForClip.actionByRoot,
  28009. rootUuid = ( action._localRoot || this._root ).uuid;
  28010. delete actionByRoot[ rootUuid ];
  28011. if ( knownActionsForClip.length === 0 ) {
  28012. delete actionsByClip[ clipUuid ];
  28013. }
  28014. this._removeInactiveBindingsForAction( action );
  28015. },
  28016. _removeInactiveBindingsForAction: function ( action ) {
  28017. const bindings = action._propertyBindings;
  28018. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28019. const binding = bindings[ i ];
  28020. if ( -- binding.referenceCount === 0 ) {
  28021. this._removeInactiveBinding( binding );
  28022. }
  28023. }
  28024. },
  28025. _lendAction: function ( action ) {
  28026. // [ active actions | inactive actions ]
  28027. // [ active actions >| inactive actions ]
  28028. // s a
  28029. // <-swap->
  28030. // a s
  28031. const actions = this._actions,
  28032. prevIndex = action._cacheIndex,
  28033. lastActiveIndex = this._nActiveActions ++,
  28034. firstInactiveAction = actions[ lastActiveIndex ];
  28035. action._cacheIndex = lastActiveIndex;
  28036. actions[ lastActiveIndex ] = action;
  28037. firstInactiveAction._cacheIndex = prevIndex;
  28038. actions[ prevIndex ] = firstInactiveAction;
  28039. },
  28040. _takeBackAction: function ( action ) {
  28041. // [ active actions | inactive actions ]
  28042. // [ active actions |< inactive actions ]
  28043. // a s
  28044. // <-swap->
  28045. // s a
  28046. const actions = this._actions,
  28047. prevIndex = action._cacheIndex,
  28048. firstInactiveIndex = -- this._nActiveActions,
  28049. lastActiveAction = actions[ firstInactiveIndex ];
  28050. action._cacheIndex = firstInactiveIndex;
  28051. actions[ firstInactiveIndex ] = action;
  28052. lastActiveAction._cacheIndex = prevIndex;
  28053. actions[ prevIndex ] = lastActiveAction;
  28054. },
  28055. // Memory management for PropertyMixer objects
  28056. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  28057. const bindingsByRoot = this._bindingsByRootAndName,
  28058. bindings = this._bindings;
  28059. let bindingByName = bindingsByRoot[ rootUuid ];
  28060. if ( bindingByName === undefined ) {
  28061. bindingByName = {};
  28062. bindingsByRoot[ rootUuid ] = bindingByName;
  28063. }
  28064. bindingByName[ trackName ] = binding;
  28065. binding._cacheIndex = bindings.length;
  28066. bindings.push( binding );
  28067. },
  28068. _removeInactiveBinding: function ( binding ) {
  28069. const bindings = this._bindings,
  28070. propBinding = binding.binding,
  28071. rootUuid = propBinding.rootNode.uuid,
  28072. trackName = propBinding.path,
  28073. bindingsByRoot = this._bindingsByRootAndName,
  28074. bindingByName = bindingsByRoot[ rootUuid ],
  28075. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28076. cacheIndex = binding._cacheIndex;
  28077. lastInactiveBinding._cacheIndex = cacheIndex;
  28078. bindings[ cacheIndex ] = lastInactiveBinding;
  28079. bindings.pop();
  28080. delete bindingByName[ trackName ];
  28081. if ( Object.keys( bindingByName ).length === 0 ) {
  28082. delete bindingsByRoot[ rootUuid ];
  28083. }
  28084. },
  28085. _lendBinding: function ( binding ) {
  28086. const bindings = this._bindings,
  28087. prevIndex = binding._cacheIndex,
  28088. lastActiveIndex = this._nActiveBindings ++,
  28089. firstInactiveBinding = bindings[ lastActiveIndex ];
  28090. binding._cacheIndex = lastActiveIndex;
  28091. bindings[ lastActiveIndex ] = binding;
  28092. firstInactiveBinding._cacheIndex = prevIndex;
  28093. bindings[ prevIndex ] = firstInactiveBinding;
  28094. },
  28095. _takeBackBinding: function ( binding ) {
  28096. const bindings = this._bindings,
  28097. prevIndex = binding._cacheIndex,
  28098. firstInactiveIndex = -- this._nActiveBindings,
  28099. lastActiveBinding = bindings[ firstInactiveIndex ];
  28100. binding._cacheIndex = firstInactiveIndex;
  28101. bindings[ firstInactiveIndex ] = binding;
  28102. lastActiveBinding._cacheIndex = prevIndex;
  28103. bindings[ prevIndex ] = lastActiveBinding;
  28104. },
  28105. // Memory management of Interpolants for weight and time scale
  28106. _lendControlInterpolant: function () {
  28107. const interpolants = this._controlInterpolants,
  28108. lastActiveIndex = this._nActiveControlInterpolants ++;
  28109. let interpolant = interpolants[ lastActiveIndex ];
  28110. if ( interpolant === undefined ) {
  28111. interpolant = new LinearInterpolant(
  28112. new Float32Array( 2 ), new Float32Array( 2 ),
  28113. 1, this._controlInterpolantsResultBuffer );
  28114. interpolant.__cacheIndex = lastActiveIndex;
  28115. interpolants[ lastActiveIndex ] = interpolant;
  28116. }
  28117. return interpolant;
  28118. },
  28119. _takeBackControlInterpolant: function ( interpolant ) {
  28120. const interpolants = this._controlInterpolants,
  28121. prevIndex = interpolant.__cacheIndex,
  28122. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28123. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28124. interpolant.__cacheIndex = firstInactiveIndex;
  28125. interpolants[ firstInactiveIndex ] = interpolant;
  28126. lastActiveInterpolant.__cacheIndex = prevIndex;
  28127. interpolants[ prevIndex ] = lastActiveInterpolant;
  28128. },
  28129. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  28130. // return an action for a clip optionally using a custom root target
  28131. // object (this method allocates a lot of dynamic memory in case a
  28132. // previously unknown clip/root combination is specified)
  28133. clipAction: function ( clip, optionalRoot, blendMode ) {
  28134. const root = optionalRoot || this._root,
  28135. rootUuid = root.uuid;
  28136. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28137. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28138. const actionsForClip = this._actionsByClip[ clipUuid ];
  28139. let prototypeAction = null;
  28140. if ( blendMode === undefined ) {
  28141. if ( clipObject !== null ) {
  28142. blendMode = clipObject.blendMode;
  28143. } else {
  28144. blendMode = NormalAnimationBlendMode;
  28145. }
  28146. }
  28147. if ( actionsForClip !== undefined ) {
  28148. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28149. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28150. return existingAction;
  28151. }
  28152. // we know the clip, so we don't have to parse all
  28153. // the bindings again but can just copy
  28154. prototypeAction = actionsForClip.knownActions[ 0 ];
  28155. // also, take the clip from the prototype action
  28156. if ( clipObject === null )
  28157. clipObject = prototypeAction._clip;
  28158. }
  28159. // clip must be known when specified via string
  28160. if ( clipObject === null ) return null;
  28161. // allocate all resources required to run it
  28162. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28163. this._bindAction( newAction, prototypeAction );
  28164. // and make the action known to the memory manager
  28165. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28166. return newAction;
  28167. },
  28168. // get an existing action
  28169. existingAction: function ( clip, optionalRoot ) {
  28170. const root = optionalRoot || this._root,
  28171. rootUuid = root.uuid,
  28172. clipObject = typeof clip === 'string' ?
  28173. AnimationClip.findByName( root, clip ) : clip,
  28174. clipUuid = clipObject ? clipObject.uuid : clip,
  28175. actionsForClip = this._actionsByClip[ clipUuid ];
  28176. if ( actionsForClip !== undefined ) {
  28177. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28178. }
  28179. return null;
  28180. },
  28181. // deactivates all previously scheduled actions
  28182. stopAllAction: function () {
  28183. const actions = this._actions,
  28184. nActions = this._nActiveActions;
  28185. for ( let i = nActions - 1; i >= 0; -- i ) {
  28186. actions[ i ].stop();
  28187. }
  28188. return this;
  28189. },
  28190. // advance the time and update apply the animation
  28191. update: function ( deltaTime ) {
  28192. deltaTime *= this.timeScale;
  28193. const actions = this._actions,
  28194. nActions = this._nActiveActions,
  28195. time = this.time += deltaTime,
  28196. timeDirection = Math.sign( deltaTime ),
  28197. accuIndex = this._accuIndex ^= 1;
  28198. // run active actions
  28199. for ( let i = 0; i !== nActions; ++ i ) {
  28200. const action = actions[ i ];
  28201. action._update( time, deltaTime, timeDirection, accuIndex );
  28202. }
  28203. // update scene graph
  28204. const bindings = this._bindings,
  28205. nBindings = this._nActiveBindings;
  28206. for ( let i = 0; i !== nBindings; ++ i ) {
  28207. bindings[ i ].apply( accuIndex );
  28208. }
  28209. return this;
  28210. },
  28211. // Allows you to seek to a specific time in an animation.
  28212. setTime: function ( timeInSeconds ) {
  28213. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28214. for ( let i = 0; i < this._actions.length; i ++ ) {
  28215. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28216. }
  28217. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28218. },
  28219. // return this mixer's root target object
  28220. getRoot: function () {
  28221. return this._root;
  28222. },
  28223. // free all resources specific to a particular clip
  28224. uncacheClip: function ( clip ) {
  28225. const actions = this._actions,
  28226. clipUuid = clip.uuid,
  28227. actionsByClip = this._actionsByClip,
  28228. actionsForClip = actionsByClip[ clipUuid ];
  28229. if ( actionsForClip !== undefined ) {
  28230. // note: just calling _removeInactiveAction would mess up the
  28231. // iteration state and also require updating the state we can
  28232. // just throw away
  28233. const actionsToRemove = actionsForClip.knownActions;
  28234. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28235. const action = actionsToRemove[ i ];
  28236. this._deactivateAction( action );
  28237. const cacheIndex = action._cacheIndex,
  28238. lastInactiveAction = actions[ actions.length - 1 ];
  28239. action._cacheIndex = null;
  28240. action._byClipCacheIndex = null;
  28241. lastInactiveAction._cacheIndex = cacheIndex;
  28242. actions[ cacheIndex ] = lastInactiveAction;
  28243. actions.pop();
  28244. this._removeInactiveBindingsForAction( action );
  28245. }
  28246. delete actionsByClip[ clipUuid ];
  28247. }
  28248. },
  28249. // free all resources specific to a particular root target object
  28250. uncacheRoot: function ( root ) {
  28251. const rootUuid = root.uuid,
  28252. actionsByClip = this._actionsByClip;
  28253. for ( const clipUuid in actionsByClip ) {
  28254. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28255. action = actionByRoot[ rootUuid ];
  28256. if ( action !== undefined ) {
  28257. this._deactivateAction( action );
  28258. this._removeInactiveAction( action );
  28259. }
  28260. }
  28261. const bindingsByRoot = this._bindingsByRootAndName,
  28262. bindingByName = bindingsByRoot[ rootUuid ];
  28263. if ( bindingByName !== undefined ) {
  28264. for ( const trackName in bindingByName ) {
  28265. const binding = bindingByName[ trackName ];
  28266. binding.restoreOriginalState();
  28267. this._removeInactiveBinding( binding );
  28268. }
  28269. }
  28270. },
  28271. // remove a targeted clip from the cache
  28272. uncacheAction: function ( clip, optionalRoot ) {
  28273. const action = this.existingAction( clip, optionalRoot );
  28274. if ( action !== null ) {
  28275. this._deactivateAction( action );
  28276. this._removeInactiveAction( action );
  28277. }
  28278. }
  28279. } );
  28280. class Uniform {
  28281. constructor( value ) {
  28282. if ( typeof value === 'string' ) {
  28283. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  28284. value = arguments[ 1 ];
  28285. }
  28286. this.value = value;
  28287. }
  28288. clone() {
  28289. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28290. }
  28291. }
  28292. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  28293. InterleavedBuffer.call( this, array, stride );
  28294. this.meshPerAttribute = meshPerAttribute || 1;
  28295. }
  28296. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  28297. constructor: InstancedInterleavedBuffer,
  28298. isInstancedInterleavedBuffer: true,
  28299. copy: function ( source ) {
  28300. InterleavedBuffer.prototype.copy.call( this, source );
  28301. this.meshPerAttribute = source.meshPerAttribute;
  28302. return this;
  28303. },
  28304. clone: function ( data ) {
  28305. const ib = InterleavedBuffer.prototype.clone.call( this, data );
  28306. ib.meshPerAttribute = this.meshPerAttribute;
  28307. return ib;
  28308. },
  28309. toJSON: function ( data ) {
  28310. const json = InterleavedBuffer.prototype.toJSON.call( this, data );
  28311. json.isInstancedInterleavedBuffer = true;
  28312. json.meshPerAttribute = this.meshPerAttribute;
  28313. return json;
  28314. }
  28315. } );
  28316. function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) {
  28317. this.buffer = buffer;
  28318. this.type = type;
  28319. this.itemSize = itemSize;
  28320. this.elementSize = elementSize;
  28321. this.count = count;
  28322. this.version = 0;
  28323. }
  28324. Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', {
  28325. set: function ( value ) {
  28326. if ( value === true ) this.version ++;
  28327. }
  28328. } );
  28329. Object.assign( GLBufferAttribute.prototype, {
  28330. isGLBufferAttribute: true,
  28331. setBuffer: function ( buffer ) {
  28332. this.buffer = buffer;
  28333. return this;
  28334. },
  28335. setType: function ( type, elementSize ) {
  28336. this.type = type;
  28337. this.elementSize = elementSize;
  28338. return this;
  28339. },
  28340. setItemSize: function ( itemSize ) {
  28341. this.itemSize = itemSize;
  28342. return this;
  28343. },
  28344. setCount: function ( count ) {
  28345. this.count = count;
  28346. return this;
  28347. },
  28348. } );
  28349. function Raycaster( origin, direction, near, far ) {
  28350. this.ray = new Ray( origin, direction );
  28351. // direction is assumed to be normalized (for accurate distance calculations)
  28352. this.near = near || 0;
  28353. this.far = far || Infinity;
  28354. this.camera = null;
  28355. this.layers = new Layers();
  28356. this.params = {
  28357. Mesh: {},
  28358. Line: { threshold: 1 },
  28359. LOD: {},
  28360. Points: { threshold: 1 },
  28361. Sprite: {}
  28362. };
  28363. Object.defineProperties( this.params, {
  28364. PointCloud: {
  28365. get: function () {
  28366. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  28367. return this.Points;
  28368. }
  28369. }
  28370. } );
  28371. }
  28372. function ascSort( a, b ) {
  28373. return a.distance - b.distance;
  28374. }
  28375. function intersectObject( object, raycaster, intersects, recursive ) {
  28376. if ( object.layers.test( raycaster.layers ) ) {
  28377. object.raycast( raycaster, intersects );
  28378. }
  28379. if ( recursive === true ) {
  28380. const children = object.children;
  28381. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28382. intersectObject( children[ i ], raycaster, intersects, true );
  28383. }
  28384. }
  28385. }
  28386. Object.assign( Raycaster.prototype, {
  28387. set: function ( origin, direction ) {
  28388. // direction is assumed to be normalized (for accurate distance calculations)
  28389. this.ray.set( origin, direction );
  28390. },
  28391. setFromCamera: function ( coords, camera ) {
  28392. if ( camera && camera.isPerspectiveCamera ) {
  28393. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28394. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28395. this.camera = camera;
  28396. } else if ( camera && camera.isOrthographicCamera ) {
  28397. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28398. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28399. this.camera = camera;
  28400. } else {
  28401. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28402. }
  28403. },
  28404. intersectObject: function ( object, recursive, optionalTarget ) {
  28405. const intersects = optionalTarget || [];
  28406. intersectObject( object, this, intersects, recursive );
  28407. intersects.sort( ascSort );
  28408. return intersects;
  28409. },
  28410. intersectObjects: function ( objects, recursive, optionalTarget ) {
  28411. const intersects = optionalTarget || [];
  28412. if ( Array.isArray( objects ) === false ) {
  28413. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  28414. return intersects;
  28415. }
  28416. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28417. intersectObject( objects[ i ], this, intersects, recursive );
  28418. }
  28419. intersects.sort( ascSort );
  28420. return intersects;
  28421. }
  28422. } );
  28423. /**
  28424. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28425. *
  28426. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28427. * The azimuthal angle (theta) is measured from the positive z-axis.
  28428. */
  28429. class Spherical {
  28430. constructor( radius = 1, phi = 0, theta = 0 ) {
  28431. this.radius = radius;
  28432. this.phi = phi; // polar angle
  28433. this.theta = theta; // azimuthal angle
  28434. return this;
  28435. }
  28436. set( radius, phi, theta ) {
  28437. this.radius = radius;
  28438. this.phi = phi;
  28439. this.theta = theta;
  28440. return this;
  28441. }
  28442. clone() {
  28443. return new this.constructor().copy( this );
  28444. }
  28445. copy( other ) {
  28446. this.radius = other.radius;
  28447. this.phi = other.phi;
  28448. this.theta = other.theta;
  28449. return this;
  28450. }
  28451. // restrict phi to be betwee EPS and PI-EPS
  28452. makeSafe() {
  28453. const EPS = 0.000001;
  28454. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28455. return this;
  28456. }
  28457. setFromVector3( v ) {
  28458. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28459. }
  28460. setFromCartesianCoords( x, y, z ) {
  28461. this.radius = Math.sqrt( x * x + y * y + z * z );
  28462. if ( this.radius === 0 ) {
  28463. this.theta = 0;
  28464. this.phi = 0;
  28465. } else {
  28466. this.theta = Math.atan2( x, z );
  28467. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  28468. }
  28469. return this;
  28470. }
  28471. }
  28472. /**
  28473. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28474. */
  28475. class Cylindrical {
  28476. constructor( radius, theta, y ) {
  28477. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  28478. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28479. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  28480. return this;
  28481. }
  28482. set( radius, theta, y ) {
  28483. this.radius = radius;
  28484. this.theta = theta;
  28485. this.y = y;
  28486. return this;
  28487. }
  28488. clone() {
  28489. return new this.constructor().copy( this );
  28490. }
  28491. copy( other ) {
  28492. this.radius = other.radius;
  28493. this.theta = other.theta;
  28494. this.y = other.y;
  28495. return this;
  28496. }
  28497. setFromVector3( v ) {
  28498. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28499. }
  28500. setFromCartesianCoords( x, y, z ) {
  28501. this.radius = Math.sqrt( x * x + z * z );
  28502. this.theta = Math.atan2( x, z );
  28503. this.y = y;
  28504. return this;
  28505. }
  28506. }
  28507. const _vector$8 = /*@__PURE__*/ new Vector2$1();
  28508. class Box2 {
  28509. constructor( min, max ) {
  28510. Object.defineProperty( this, 'isBox2', { value: true } );
  28511. this.min = ( min !== undefined ) ? min : new Vector2$1( + Infinity, + Infinity );
  28512. this.max = ( max !== undefined ) ? max : new Vector2$1( - Infinity, - Infinity );
  28513. }
  28514. set( min, max ) {
  28515. this.min.copy( min );
  28516. this.max.copy( max );
  28517. return this;
  28518. }
  28519. setFromPoints( points ) {
  28520. this.makeEmpty();
  28521. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28522. this.expandByPoint( points[ i ] );
  28523. }
  28524. return this;
  28525. }
  28526. setFromCenterAndSize( center, size ) {
  28527. const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 );
  28528. this.min.copy( center ).sub( halfSize );
  28529. this.max.copy( center ).add( halfSize );
  28530. return this;
  28531. }
  28532. clone() {
  28533. return new this.constructor().copy( this );
  28534. }
  28535. copy( box ) {
  28536. this.min.copy( box.min );
  28537. this.max.copy( box.max );
  28538. return this;
  28539. }
  28540. makeEmpty() {
  28541. this.min.x = this.min.y = + Infinity;
  28542. this.max.x = this.max.y = - Infinity;
  28543. return this;
  28544. }
  28545. isEmpty() {
  28546. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28547. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28548. }
  28549. getCenter( target ) {
  28550. if ( target === undefined ) {
  28551. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  28552. target = new Vector2$1();
  28553. }
  28554. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28555. }
  28556. getSize( target ) {
  28557. if ( target === undefined ) {
  28558. console.warn( 'THREE.Box2: .getSize() target is now required' );
  28559. target = new Vector2$1();
  28560. }
  28561. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28562. }
  28563. expandByPoint( point ) {
  28564. this.min.min( point );
  28565. this.max.max( point );
  28566. return this;
  28567. }
  28568. expandByVector( vector ) {
  28569. this.min.sub( vector );
  28570. this.max.add( vector );
  28571. return this;
  28572. }
  28573. expandByScalar( scalar ) {
  28574. this.min.addScalar( - scalar );
  28575. this.max.addScalar( scalar );
  28576. return this;
  28577. }
  28578. containsPoint( point ) {
  28579. return point.x < this.min.x || point.x > this.max.x ||
  28580. point.y < this.min.y || point.y > this.max.y ? false : true;
  28581. }
  28582. containsBox( box ) {
  28583. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28584. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28585. }
  28586. getParameter( point, target ) {
  28587. // This can potentially have a divide by zero if the box
  28588. // has a size dimension of 0.
  28589. if ( target === undefined ) {
  28590. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  28591. target = new Vector2$1();
  28592. }
  28593. return target.set(
  28594. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28595. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28596. );
  28597. }
  28598. intersectsBox( box ) {
  28599. // using 4 splitting planes to rule out intersections
  28600. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28601. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28602. }
  28603. clampPoint( point, target ) {
  28604. if ( target === undefined ) {
  28605. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  28606. target = new Vector2$1();
  28607. }
  28608. return target.copy( point ).clamp( this.min, this.max );
  28609. }
  28610. distanceToPoint( point ) {
  28611. const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max );
  28612. return clampedPoint.sub( point ).length();
  28613. }
  28614. intersect( box ) {
  28615. this.min.max( box.min );
  28616. this.max.min( box.max );
  28617. return this;
  28618. }
  28619. union( box ) {
  28620. this.min.min( box.min );
  28621. this.max.max( box.max );
  28622. return this;
  28623. }
  28624. translate( offset ) {
  28625. this.min.add( offset );
  28626. this.max.add( offset );
  28627. return this;
  28628. }
  28629. equals( box ) {
  28630. return box.min.equals( this.min ) && box.max.equals( this.max );
  28631. }
  28632. }
  28633. const _startP = /*@__PURE__*/ new Vector3();
  28634. const _startEnd = /*@__PURE__*/ new Vector3();
  28635. class Line3 {
  28636. constructor( start, end ) {
  28637. this.start = ( start !== undefined ) ? start : new Vector3();
  28638. this.end = ( end !== undefined ) ? end : new Vector3();
  28639. }
  28640. set( start, end ) {
  28641. this.start.copy( start );
  28642. this.end.copy( end );
  28643. return this;
  28644. }
  28645. clone() {
  28646. return new this.constructor().copy( this );
  28647. }
  28648. copy( line ) {
  28649. this.start.copy( line.start );
  28650. this.end.copy( line.end );
  28651. return this;
  28652. }
  28653. getCenter( target ) {
  28654. if ( target === undefined ) {
  28655. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  28656. target = new Vector3();
  28657. }
  28658. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28659. }
  28660. delta( target ) {
  28661. if ( target === undefined ) {
  28662. console.warn( 'THREE.Line3: .delta() target is now required' );
  28663. target = new Vector3();
  28664. }
  28665. return target.subVectors( this.end, this.start );
  28666. }
  28667. distanceSq() {
  28668. return this.start.distanceToSquared( this.end );
  28669. }
  28670. distance() {
  28671. return this.start.distanceTo( this.end );
  28672. }
  28673. at( t, target ) {
  28674. if ( target === undefined ) {
  28675. console.warn( 'THREE.Line3: .at() target is now required' );
  28676. target = new Vector3();
  28677. }
  28678. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28679. }
  28680. closestPointToPointParameter( point, clampToLine ) {
  28681. _startP.subVectors( point, this.start );
  28682. _startEnd.subVectors( this.end, this.start );
  28683. const startEnd2 = _startEnd.dot( _startEnd );
  28684. const startEnd_startP = _startEnd.dot( _startP );
  28685. let t = startEnd_startP / startEnd2;
  28686. if ( clampToLine ) {
  28687. t = MathUtils.clamp( t, 0, 1 );
  28688. }
  28689. return t;
  28690. }
  28691. closestPointToPoint( point, clampToLine, target ) {
  28692. const t = this.closestPointToPointParameter( point, clampToLine );
  28693. if ( target === undefined ) {
  28694. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  28695. target = new Vector3();
  28696. }
  28697. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28698. }
  28699. applyMatrix4( matrix ) {
  28700. this.start.applyMatrix4( matrix );
  28701. this.end.applyMatrix4( matrix );
  28702. return this;
  28703. }
  28704. equals( line ) {
  28705. return line.start.equals( this.start ) && line.end.equals( this.end );
  28706. }
  28707. }
  28708. function ImmediateRenderObject( material ) {
  28709. Object3D.call( this );
  28710. this.material = material;
  28711. this.render = function ( /* renderCallback */ ) {};
  28712. this.hasPositions = false;
  28713. this.hasNormals = false;
  28714. this.hasColors = false;
  28715. this.hasUvs = false;
  28716. this.positionArray = null;
  28717. this.normalArray = null;
  28718. this.colorArray = null;
  28719. this.uvArray = null;
  28720. this.count = 0;
  28721. }
  28722. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  28723. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28724. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28725. const _vector$9 = /*@__PURE__*/ new Vector3();
  28726. class SpotLightHelper extends Object3D {
  28727. constructor( light, color ) {
  28728. super();
  28729. this.light = light;
  28730. this.light.updateMatrixWorld();
  28731. this.matrix = light.matrixWorld;
  28732. this.matrixAutoUpdate = false;
  28733. this.color = color;
  28734. const geometry = new BufferGeometry();
  28735. const positions = [
  28736. 0, 0, 0, 0, 0, 1,
  28737. 0, 0, 0, 1, 0, 1,
  28738. 0, 0, 0, - 1, 0, 1,
  28739. 0, 0, 0, 0, 1, 1,
  28740. 0, 0, 0, 0, - 1, 1
  28741. ];
  28742. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28743. const p1 = ( i / l ) * Math.PI * 2;
  28744. const p2 = ( j / l ) * Math.PI * 2;
  28745. positions.push(
  28746. Math.cos( p1 ), Math.sin( p1 ), 1,
  28747. Math.cos( p2 ), Math.sin( p2 ), 1
  28748. );
  28749. }
  28750. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28751. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28752. this.cone = new LineSegments( geometry, material );
  28753. this.add( this.cone );
  28754. this.update();
  28755. }
  28756. dispose() {
  28757. this.cone.geometry.dispose();
  28758. this.cone.material.dispose();
  28759. }
  28760. update() {
  28761. this.light.updateMatrixWorld();
  28762. const coneLength = this.light.distance ? this.light.distance : 1000;
  28763. const coneWidth = coneLength * Math.tan( this.light.angle );
  28764. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28765. _vector$9.setFromMatrixPosition( this.light.target.matrixWorld );
  28766. this.cone.lookAt( _vector$9 );
  28767. if ( this.color !== undefined ) {
  28768. this.cone.material.color.set( this.color );
  28769. } else {
  28770. this.cone.material.color.copy( this.light.color );
  28771. }
  28772. }
  28773. }
  28774. const _vector$a = /*@__PURE__*/ new Vector3();
  28775. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28776. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28777. class SkeletonHelper extends LineSegments {
  28778. constructor( object ) {
  28779. const bones = getBoneList( object );
  28780. const geometry = new BufferGeometry();
  28781. const vertices = [];
  28782. const colors = [];
  28783. const color1 = new Color( 0, 0, 1 );
  28784. const color2 = new Color( 0, 1, 0 );
  28785. for ( let i = 0; i < bones.length; i ++ ) {
  28786. const bone = bones[ i ];
  28787. if ( bone.parent && bone.parent.isBone ) {
  28788. vertices.push( 0, 0, 0 );
  28789. vertices.push( 0, 0, 0 );
  28790. colors.push( color1.r, color1.g, color1.b );
  28791. colors.push( color2.r, color2.g, color2.b );
  28792. }
  28793. }
  28794. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28795. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28796. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28797. super( geometry, material );
  28798. this.type = 'SkeletonHelper';
  28799. this.isSkeletonHelper = true;
  28800. this.root = object;
  28801. this.bones = bones;
  28802. this.matrix = object.matrixWorld;
  28803. this.matrixAutoUpdate = false;
  28804. }
  28805. updateMatrixWorld( force ) {
  28806. const bones = this.bones;
  28807. const geometry = this.geometry;
  28808. const position = geometry.getAttribute( 'position' );
  28809. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28810. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28811. const bone = bones[ i ];
  28812. if ( bone.parent && bone.parent.isBone ) {
  28813. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28814. _vector$a.setFromMatrixPosition( _boneMatrix );
  28815. position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z );
  28816. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28817. _vector$a.setFromMatrixPosition( _boneMatrix );
  28818. position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z );
  28819. j += 2;
  28820. }
  28821. }
  28822. geometry.getAttribute( 'position' ).needsUpdate = true;
  28823. super.updateMatrixWorld( force );
  28824. }
  28825. }
  28826. function getBoneList( object ) {
  28827. const boneList = [];
  28828. if ( object && object.isBone ) {
  28829. boneList.push( object );
  28830. }
  28831. for ( let i = 0; i < object.children.length; i ++ ) {
  28832. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28833. }
  28834. return boneList;
  28835. }
  28836. class PointLightHelper extends Mesh {
  28837. constructor( light, sphereSize, color ) {
  28838. const geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28839. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28840. super( geometry, material );
  28841. this.light = light;
  28842. this.light.updateMatrixWorld();
  28843. this.color = color;
  28844. this.type = 'PointLightHelper';
  28845. this.matrix = this.light.matrixWorld;
  28846. this.matrixAutoUpdate = false;
  28847. this.update();
  28848. /*
  28849. // TODO: delete this comment?
  28850. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28851. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28852. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28853. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28854. const d = light.distance;
  28855. if ( d === 0.0 ) {
  28856. this.lightDistance.visible = false;
  28857. } else {
  28858. this.lightDistance.scale.set( d, d, d );
  28859. }
  28860. this.add( this.lightDistance );
  28861. */
  28862. }
  28863. dispose() {
  28864. this.geometry.dispose();
  28865. this.material.dispose();
  28866. }
  28867. update() {
  28868. if ( this.color !== undefined ) {
  28869. this.material.color.set( this.color );
  28870. } else {
  28871. this.material.color.copy( this.light.color );
  28872. }
  28873. /*
  28874. const d = this.light.distance;
  28875. if ( d === 0.0 ) {
  28876. this.lightDistance.visible = false;
  28877. } else {
  28878. this.lightDistance.visible = true;
  28879. this.lightDistance.scale.set( d, d, d );
  28880. }
  28881. */
  28882. }
  28883. }
  28884. const _vector$b = /*@__PURE__*/ new Vector3();
  28885. const _color1 = /*@__PURE__*/ new Color();
  28886. const _color2 = /*@__PURE__*/ new Color();
  28887. class HemisphereLightHelper extends Object3D {
  28888. constructor( light, size, color ) {
  28889. super();
  28890. this.light = light;
  28891. this.light.updateMatrixWorld();
  28892. this.matrix = light.matrixWorld;
  28893. this.matrixAutoUpdate = false;
  28894. this.color = color;
  28895. const geometry = new OctahedronBufferGeometry( size );
  28896. geometry.rotateY( Math.PI * 0.5 );
  28897. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28898. if ( this.color === undefined ) this.material.vertexColors = true;
  28899. const position = geometry.getAttribute( 'position' );
  28900. const colors = new Float32Array( position.count * 3 );
  28901. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28902. this.add( new Mesh( geometry, this.material ) );
  28903. this.update();
  28904. }
  28905. dispose() {
  28906. this.children[ 0 ].geometry.dispose();
  28907. this.children[ 0 ].material.dispose();
  28908. }
  28909. update() {
  28910. const mesh = this.children[ 0 ];
  28911. if ( this.color !== undefined ) {
  28912. this.material.color.set( this.color );
  28913. } else {
  28914. const colors = mesh.geometry.getAttribute( 'color' );
  28915. _color1.copy( this.light.color );
  28916. _color2.copy( this.light.groundColor );
  28917. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28918. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28919. colors.setXYZ( i, color.r, color.g, color.b );
  28920. }
  28921. colors.needsUpdate = true;
  28922. }
  28923. mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28924. }
  28925. }
  28926. class GridHelper extends LineSegments {
  28927. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28928. color1 = new Color( color1 );
  28929. color2 = new Color( color2 );
  28930. const center = divisions / 2;
  28931. const step = size / divisions;
  28932. const halfSize = size / 2;
  28933. const vertices = [], colors = [];
  28934. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28935. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28936. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28937. const color = i === center ? color1 : color2;
  28938. color.toArray( colors, j ); j += 3;
  28939. color.toArray( colors, j ); j += 3;
  28940. color.toArray( colors, j ); j += 3;
  28941. color.toArray( colors, j ); j += 3;
  28942. }
  28943. const geometry = new BufferGeometry();
  28944. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28945. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28946. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28947. super( geometry, material );
  28948. this.type = 'GridHelper';
  28949. }
  28950. }
  28951. class PolarGridHelper extends LineSegments {
  28952. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28953. color1 = new Color( color1 );
  28954. color2 = new Color( color2 );
  28955. const vertices = [];
  28956. const colors = [];
  28957. // create the radials
  28958. for ( let i = 0; i <= radials; i ++ ) {
  28959. const v = ( i / radials ) * ( Math.PI * 2 );
  28960. const x = Math.sin( v ) * radius;
  28961. const z = Math.cos( v ) * radius;
  28962. vertices.push( 0, 0, 0 );
  28963. vertices.push( x, 0, z );
  28964. const color = ( i & 1 ) ? color1 : color2;
  28965. colors.push( color.r, color.g, color.b );
  28966. colors.push( color.r, color.g, color.b );
  28967. }
  28968. // create the circles
  28969. for ( let i = 0; i <= circles; i ++ ) {
  28970. const color = ( i & 1 ) ? color1 : color2;
  28971. const r = radius - ( radius / circles * i );
  28972. for ( let j = 0; j < divisions; j ++ ) {
  28973. // first vertex
  28974. let v = ( j / divisions ) * ( Math.PI * 2 );
  28975. let x = Math.sin( v ) * r;
  28976. let z = Math.cos( v ) * r;
  28977. vertices.push( x, 0, z );
  28978. colors.push( color.r, color.g, color.b );
  28979. // second vertex
  28980. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28981. x = Math.sin( v ) * r;
  28982. z = Math.cos( v ) * r;
  28983. vertices.push( x, 0, z );
  28984. colors.push( color.r, color.g, color.b );
  28985. }
  28986. }
  28987. const geometry = new BufferGeometry();
  28988. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28989. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28990. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28991. super( geometry, material );
  28992. this.type = 'PolarGridHelper';
  28993. }
  28994. }
  28995. const _v1$6 = /*@__PURE__*/ new Vector3();
  28996. const _v2$3 = /*@__PURE__*/ new Vector3();
  28997. const _v3$1 = /*@__PURE__*/ new Vector3();
  28998. class DirectionalLightHelper extends Object3D {
  28999. constructor( light, size, color ) {
  29000. super();
  29001. this.light = light;
  29002. this.light.updateMatrixWorld();
  29003. this.matrix = light.matrixWorld;
  29004. this.matrixAutoUpdate = false;
  29005. this.color = color;
  29006. if ( size === undefined ) size = 1;
  29007. let geometry = new BufferGeometry();
  29008. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29009. - size, size, 0,
  29010. size, size, 0,
  29011. size, - size, 0,
  29012. - size, - size, 0,
  29013. - size, size, 0
  29014. ], 3 ) );
  29015. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29016. this.lightPlane = new Line( geometry, material );
  29017. this.add( this.lightPlane );
  29018. geometry = new BufferGeometry();
  29019. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29020. this.targetLine = new Line( geometry, material );
  29021. this.add( this.targetLine );
  29022. this.update();
  29023. }
  29024. dispose() {
  29025. this.lightPlane.geometry.dispose();
  29026. this.lightPlane.material.dispose();
  29027. this.targetLine.geometry.dispose();
  29028. this.targetLine.material.dispose();
  29029. }
  29030. update() {
  29031. _v1$6.setFromMatrixPosition( this.light.matrixWorld );
  29032. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29033. _v3$1.subVectors( _v2$3, _v1$6 );
  29034. this.lightPlane.lookAt( _v2$3 );
  29035. if ( this.color !== undefined ) {
  29036. this.lightPlane.material.color.set( this.color );
  29037. this.targetLine.material.color.set( this.color );
  29038. } else {
  29039. this.lightPlane.material.color.copy( this.light.color );
  29040. this.targetLine.material.color.copy( this.light.color );
  29041. }
  29042. this.targetLine.lookAt( _v2$3 );
  29043. this.targetLine.scale.z = _v3$1.length();
  29044. }
  29045. }
  29046. const _vector$c = /*@__PURE__*/ new Vector3();
  29047. const _camera = /*@__PURE__*/ new Camera();
  29048. /**
  29049. * - shows frustum, line of sight and up of the camera
  29050. * - suitable for fast updates
  29051. * - based on frustum visualization in lightgl.js shadowmap example
  29052. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29053. */
  29054. class CameraHelper extends LineSegments {
  29055. constructor( camera ) {
  29056. const geometry = new BufferGeometry();
  29057. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29058. const vertices = [];
  29059. const colors = [];
  29060. const pointMap = {};
  29061. // colors
  29062. const colorFrustum = new Color( 0xffaa00 );
  29063. const colorCone = new Color( 0xff0000 );
  29064. const colorUp = new Color( 0x00aaff );
  29065. const colorTarget = new Color( 0xffffff );
  29066. const colorCross = new Color( 0x333333 );
  29067. // near
  29068. addLine( 'n1', 'n2', colorFrustum );
  29069. addLine( 'n2', 'n4', colorFrustum );
  29070. addLine( 'n4', 'n3', colorFrustum );
  29071. addLine( 'n3', 'n1', colorFrustum );
  29072. // far
  29073. addLine( 'f1', 'f2', colorFrustum );
  29074. addLine( 'f2', 'f4', colorFrustum );
  29075. addLine( 'f4', 'f3', colorFrustum );
  29076. addLine( 'f3', 'f1', colorFrustum );
  29077. // sides
  29078. addLine( 'n1', 'f1', colorFrustum );
  29079. addLine( 'n2', 'f2', colorFrustum );
  29080. addLine( 'n3', 'f3', colorFrustum );
  29081. addLine( 'n4', 'f4', colorFrustum );
  29082. // cone
  29083. addLine( 'p', 'n1', colorCone );
  29084. addLine( 'p', 'n2', colorCone );
  29085. addLine( 'p', 'n3', colorCone );
  29086. addLine( 'p', 'n4', colorCone );
  29087. // up
  29088. addLine( 'u1', 'u2', colorUp );
  29089. addLine( 'u2', 'u3', colorUp );
  29090. addLine( 'u3', 'u1', colorUp );
  29091. // target
  29092. addLine( 'c', 't', colorTarget );
  29093. addLine( 'p', 'c', colorCross );
  29094. // cross
  29095. addLine( 'cn1', 'cn2', colorCross );
  29096. addLine( 'cn3', 'cn4', colorCross );
  29097. addLine( 'cf1', 'cf2', colorCross );
  29098. addLine( 'cf3', 'cf4', colorCross );
  29099. function addLine( a, b, color ) {
  29100. addPoint( a, color );
  29101. addPoint( b, color );
  29102. }
  29103. function addPoint( id, color ) {
  29104. vertices.push( 0, 0, 0 );
  29105. colors.push( color.r, color.g, color.b );
  29106. if ( pointMap[ id ] === undefined ) {
  29107. pointMap[ id ] = [];
  29108. }
  29109. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29110. }
  29111. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29112. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29113. super( geometry, material );
  29114. this.type = 'CameraHelper';
  29115. this.camera = camera;
  29116. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29117. this.matrix = camera.matrixWorld;
  29118. this.matrixAutoUpdate = false;
  29119. this.pointMap = pointMap;
  29120. this.update();
  29121. }
  29122. update() {
  29123. const geometry = this.geometry;
  29124. const pointMap = this.pointMap;
  29125. const w = 1, h = 1;
  29126. // we need just camera projection matrix inverse
  29127. // world matrix must be identity
  29128. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29129. // center / target
  29130. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29131. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29132. // near
  29133. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29134. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29135. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29136. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29137. // far
  29138. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29139. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29140. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29141. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29142. // up
  29143. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29144. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29145. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29146. // cross
  29147. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29148. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29149. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29150. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29151. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29152. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29153. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29154. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29155. geometry.getAttribute( 'position' ).needsUpdate = true;
  29156. }
  29157. }
  29158. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29159. _vector$c.set( x, y, z ).unproject( camera );
  29160. const points = pointMap[ point ];
  29161. if ( points !== undefined ) {
  29162. const position = geometry.getAttribute( 'position' );
  29163. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29164. position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z );
  29165. }
  29166. }
  29167. }
  29168. const _box$3 = /*@__PURE__*/ new Box3();
  29169. class BoxHelper extends LineSegments {
  29170. constructor( object, color = 0xffff00 ) {
  29171. 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 ] );
  29172. const positions = new Float32Array( 8 * 3 );
  29173. const geometry = new BufferGeometry();
  29174. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29175. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29176. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29177. this.object = object;
  29178. this.type = 'BoxHelper';
  29179. this.matrixAutoUpdate = false;
  29180. this.update();
  29181. }
  29182. update( object ) {
  29183. if ( object !== undefined ) {
  29184. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29185. }
  29186. if ( this.object !== undefined ) {
  29187. _box$3.setFromObject( this.object );
  29188. }
  29189. if ( _box$3.isEmpty() ) return;
  29190. const min = _box$3.min;
  29191. const max = _box$3.max;
  29192. /*
  29193. 5____4
  29194. 1/___0/|
  29195. | 6__|_7
  29196. 2/___3/
  29197. 0: max.x, max.y, max.z
  29198. 1: min.x, max.y, max.z
  29199. 2: min.x, min.y, max.z
  29200. 3: max.x, min.y, max.z
  29201. 4: max.x, max.y, min.z
  29202. 5: min.x, max.y, min.z
  29203. 6: min.x, min.y, min.z
  29204. 7: max.x, min.y, min.z
  29205. */
  29206. const position = this.geometry.attributes.position;
  29207. const array = position.array;
  29208. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29209. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29210. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29211. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29212. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29213. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29214. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29215. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29216. position.needsUpdate = true;
  29217. this.geometry.computeBoundingSphere();
  29218. }
  29219. setFromObject( object ) {
  29220. this.object = object;
  29221. this.update();
  29222. return this;
  29223. }
  29224. copy( source ) {
  29225. LineSegments.prototype.copy.call( this, source );
  29226. this.object = source.object;
  29227. return this;
  29228. }
  29229. }
  29230. class Box3Helper extends LineSegments {
  29231. constructor( box, color = 0xffff00 ) {
  29232. 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 ] );
  29233. 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 ];
  29234. const geometry = new BufferGeometry();
  29235. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29236. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29237. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29238. this.box = box;
  29239. this.type = 'Box3Helper';
  29240. this.geometry.computeBoundingSphere();
  29241. }
  29242. updateMatrixWorld( force ) {
  29243. const box = this.box;
  29244. if ( box.isEmpty() ) return;
  29245. box.getCenter( this.position );
  29246. box.getSize( this.scale );
  29247. this.scale.multiplyScalar( 0.5 );
  29248. super.updateMatrixWorld( force );
  29249. }
  29250. }
  29251. class PlaneHelper extends Line {
  29252. constructor( plane, size = 1, hex = 0xffff00 ) {
  29253. const color = hex;
  29254. 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 ];
  29255. const geometry = new BufferGeometry();
  29256. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29257. geometry.computeBoundingSphere();
  29258. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29259. this.type = 'PlaneHelper';
  29260. this.plane = plane;
  29261. this.size = size;
  29262. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  29263. const geometry2 = new BufferGeometry();
  29264. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29265. geometry2.computeBoundingSphere();
  29266. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29267. }
  29268. updateMatrixWorld( force ) {
  29269. let scale = - this.plane.constant;
  29270. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  29271. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  29272. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29273. this.lookAt( this.plane.normal );
  29274. super.updateMatrixWorld( force );
  29275. }
  29276. }
  29277. const _axis = /*@__PURE__*/ new Vector3();
  29278. let _lineGeometry, _coneGeometry;
  29279. class ArrowHelper extends Object3D {
  29280. constructor( dir, origin, length, color, headLength, headWidth ) {
  29281. super();
  29282. // dir is assumed to be normalized
  29283. this.type = 'ArrowHelper';
  29284. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  29285. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  29286. if ( length === undefined ) length = 1;
  29287. if ( color === undefined ) color = 0xffff00;
  29288. if ( headLength === undefined ) headLength = 0.2 * length;
  29289. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29290. if ( _lineGeometry === undefined ) {
  29291. _lineGeometry = new BufferGeometry();
  29292. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29293. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  29294. _coneGeometry.translate( 0, - 0.5, 0 );
  29295. }
  29296. this.position.copy( origin );
  29297. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29298. this.line.matrixAutoUpdate = false;
  29299. this.add( this.line );
  29300. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29301. this.cone.matrixAutoUpdate = false;
  29302. this.add( this.cone );
  29303. this.setDirection( dir );
  29304. this.setLength( length, headLength, headWidth );
  29305. }
  29306. setDirection( dir ) {
  29307. // dir is assumed to be normalized
  29308. if ( dir.y > 0.99999 ) {
  29309. this.quaternion.set( 0, 0, 0, 1 );
  29310. } else if ( dir.y < - 0.99999 ) {
  29311. this.quaternion.set( 1, 0, 0, 0 );
  29312. } else {
  29313. _axis.set( dir.z, 0, - dir.x ).normalize();
  29314. const radians = Math.acos( dir.y );
  29315. this.quaternion.setFromAxisAngle( _axis, radians );
  29316. }
  29317. }
  29318. setLength( length, headLength, headWidth ) {
  29319. if ( headLength === undefined ) headLength = 0.2 * length;
  29320. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29321. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29322. this.line.updateMatrix();
  29323. this.cone.scale.set( headWidth, headLength, headWidth );
  29324. this.cone.position.y = length;
  29325. this.cone.updateMatrix();
  29326. }
  29327. setColor( color ) {
  29328. this.line.material.color.set( color );
  29329. this.cone.material.color.set( color );
  29330. }
  29331. copy( source ) {
  29332. super.copy( source, false );
  29333. this.line.copy( source.line );
  29334. this.cone.copy( source.cone );
  29335. return this;
  29336. }
  29337. }
  29338. class AxesHelper extends LineSegments {
  29339. constructor( size = 1 ) {
  29340. const vertices = [
  29341. 0, 0, 0, size, 0, 0,
  29342. 0, 0, 0, 0, size, 0,
  29343. 0, 0, 0, 0, 0, size
  29344. ];
  29345. const colors = [
  29346. 1, 0, 0, 1, 0.6, 0,
  29347. 0, 1, 0, 0.6, 1, 0,
  29348. 0, 0, 1, 0, 0.6, 1
  29349. ];
  29350. const geometry = new BufferGeometry();
  29351. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29352. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29353. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29354. super( geometry, material );
  29355. this.type = 'AxesHelper';
  29356. }
  29357. }
  29358. const _floatView = new Float32Array( 1 );
  29359. const _int32View = new Int32Array( _floatView.buffer );
  29360. const DataUtils = {
  29361. // Converts float32 to float16 (stored as uint16 value).
  29362. toHalfFloat: function ( val ) {
  29363. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  29364. /* This method is faster than the OpenEXR implementation (very often
  29365. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  29366. * by James Tursa?s half-precision code. */
  29367. _floatView[ 0 ] = val;
  29368. const x = _int32View[ 0 ];
  29369. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  29370. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  29371. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  29372. /* If zero, or denormal, or exponent underflows too much for a denormal
  29373. * half, return signed zero. */
  29374. if ( e < 103 ) return bits;
  29375. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  29376. if ( e > 142 ) {
  29377. bits |= 0x7c00;
  29378. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  29379. * not Inf, so make sure we set one mantissa bit too. */
  29380. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  29381. return bits;
  29382. }
  29383. /* If exponent underflows but not too much, return a denormal */
  29384. if ( e < 113 ) {
  29385. m |= 0x0800;
  29386. /* Extra rounding may overflow and set mantissa to 0 and exponent
  29387. * to 1, which is OK. */
  29388. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  29389. return bits;
  29390. }
  29391. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  29392. /* Extra rounding. An overflow will set mantissa to 0 and increment
  29393. * the exponent, which is OK. */
  29394. bits += m & 1;
  29395. return bits;
  29396. }
  29397. };
  29398. const LOD_MIN = 4;
  29399. const LOD_MAX = 8;
  29400. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  29401. // The standard deviations (radians) associated with the extra mips. These are
  29402. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29403. // geometric shadowing function. These sigma values squared must match the
  29404. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29405. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29406. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29407. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29408. // samples and exit early, but not recompile the shader.
  29409. const MAX_SAMPLES = 20;
  29410. const ENCODINGS = {
  29411. [ LinearEncoding ]: 0,
  29412. [ sRGBEncoding ]: 1,
  29413. [ RGBEEncoding ]: 2,
  29414. [ RGBM7Encoding ]: 3,
  29415. [ RGBM16Encoding ]: 4,
  29416. [ RGBDEncoding ]: 5,
  29417. [ GammaEncoding ]: 6
  29418. };
  29419. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  29420. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  29421. const _clearColor = /*@__PURE__*/ new Color();
  29422. let _oldTarget = null;
  29423. // Golden Ratio
  29424. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29425. const INV_PHI = 1 / PHI;
  29426. // Vertices of a dodecahedron (except the opposites, which represent the
  29427. // same axis), used as axis directions evenly spread on a sphere.
  29428. const _axisDirections = [
  29429. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  29430. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  29431. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  29432. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  29433. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29434. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29435. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29436. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29437. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29438. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  29439. /**
  29440. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29441. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29442. * blur to be quickly accessed based on material roughness. It is packed into a
  29443. * special CubeUV format that allows us to perform custom interpolation so that
  29444. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29445. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29446. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29447. * higher roughness levels. In this way we maintain resolution to smoothly
  29448. * interpolate diffuse lighting while limiting sampling computation.
  29449. */
  29450. class PMREMGenerator {
  29451. constructor( renderer ) {
  29452. this._renderer = renderer;
  29453. this._pingPongRenderTarget = null;
  29454. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  29455. this._equirectShader = null;
  29456. this._cubemapShader = null;
  29457. this._compileMaterial( this._blurMaterial );
  29458. }
  29459. /**
  29460. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29461. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29462. * in radians to be applied to the scene before PMREM generation. Optional near
  29463. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29464. * is placed at the origin).
  29465. */
  29466. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  29467. _oldTarget = this._renderer.getRenderTarget();
  29468. const cubeUVRenderTarget = this._allocateTargets();
  29469. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29470. if ( sigma > 0 ) {
  29471. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29472. }
  29473. this._applyPMREM( cubeUVRenderTarget );
  29474. this._cleanup( cubeUVRenderTarget );
  29475. return cubeUVRenderTarget;
  29476. }
  29477. /**
  29478. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29479. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  29480. * as this matches best with the 256 x 256 cubemap output.
  29481. */
  29482. fromEquirectangular( equirectangular ) {
  29483. return this._fromTexture( equirectangular );
  29484. }
  29485. /**
  29486. * Generates a PMREM from an cubemap texture, which can be either LDR
  29487. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  29488. * as this matches best with the 256 x 256 cubemap output.
  29489. */
  29490. fromCubemap( cubemap ) {
  29491. return this._fromTexture( cubemap );
  29492. }
  29493. /**
  29494. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29495. * your texture's network fetch for increased concurrency.
  29496. */
  29497. compileCubemapShader() {
  29498. if ( this._cubemapShader === null ) {
  29499. this._cubemapShader = _getCubemapShader();
  29500. this._compileMaterial( this._cubemapShader );
  29501. }
  29502. }
  29503. /**
  29504. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29505. * your texture's network fetch for increased concurrency.
  29506. */
  29507. compileEquirectangularShader() {
  29508. if ( this._equirectShader === null ) {
  29509. this._equirectShader = _getEquirectShader();
  29510. this._compileMaterial( this._equirectShader );
  29511. }
  29512. }
  29513. /**
  29514. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29515. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29516. * one of them will cause any others to also become unusable.
  29517. */
  29518. dispose() {
  29519. this._blurMaterial.dispose();
  29520. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  29521. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  29522. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  29523. _lodPlanes[ i ].dispose();
  29524. }
  29525. }
  29526. // private interface
  29527. _cleanup( outputTarget ) {
  29528. this._pingPongRenderTarget.dispose();
  29529. this._renderer.setRenderTarget( _oldTarget );
  29530. outputTarget.scissorTest = false;
  29531. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29532. }
  29533. _fromTexture( texture ) {
  29534. _oldTarget = this._renderer.getRenderTarget();
  29535. const cubeUVRenderTarget = this._allocateTargets( texture );
  29536. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29537. this._applyPMREM( cubeUVRenderTarget );
  29538. this._cleanup( cubeUVRenderTarget );
  29539. return cubeUVRenderTarget;
  29540. }
  29541. _allocateTargets( texture ) { // warning: null texture is valid
  29542. const params = {
  29543. magFilter: NearestFilter,
  29544. minFilter: NearestFilter,
  29545. generateMipmaps: false,
  29546. type: UnsignedByteType,
  29547. format: RGBEFormat,
  29548. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  29549. depthBuffer: false
  29550. };
  29551. const cubeUVRenderTarget = _createRenderTarget( params );
  29552. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  29553. this._pingPongRenderTarget = _createRenderTarget( params );
  29554. return cubeUVRenderTarget;
  29555. }
  29556. _compileMaterial( material ) {
  29557. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  29558. this._renderer.compile( tmpMesh, _flatCamera );
  29559. }
  29560. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29561. const fov = 90;
  29562. const aspect = 1;
  29563. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  29564. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  29565. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  29566. const renderer = this._renderer;
  29567. const outputEncoding = renderer.outputEncoding;
  29568. const toneMapping = renderer.toneMapping;
  29569. renderer.getClearColor( _clearColor );
  29570. const clearAlpha = renderer.getClearAlpha();
  29571. renderer.toneMapping = NoToneMapping;
  29572. renderer.outputEncoding = LinearEncoding;
  29573. let background = scene.background;
  29574. if ( background && background.isColor ) {
  29575. background.convertSRGBToLinear();
  29576. // Convert linear to RGBE
  29577. const maxComponent = Math.max( background.r, background.g, background.b );
  29578. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  29579. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  29580. const alpha = ( fExp + 128.0 ) / 255.0;
  29581. renderer.setClearColor( background, alpha );
  29582. scene.background = null;
  29583. }
  29584. for ( let i = 0; i < 6; i ++ ) {
  29585. const col = i % 3;
  29586. if ( col == 0 ) {
  29587. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29588. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29589. } else if ( col == 1 ) {
  29590. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29591. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29592. } else {
  29593. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29594. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29595. }
  29596. _setViewport( cubeUVRenderTarget,
  29597. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  29598. renderer.setRenderTarget( cubeUVRenderTarget );
  29599. renderer.render( scene, cubeCamera );
  29600. }
  29601. renderer.toneMapping = toneMapping;
  29602. renderer.outputEncoding = outputEncoding;
  29603. renderer.setClearColor( _clearColor, clearAlpha );
  29604. }
  29605. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29606. const renderer = this._renderer;
  29607. if ( texture.isCubeTexture ) {
  29608. if ( this._cubemapShader == null ) {
  29609. this._cubemapShader = _getCubemapShader();
  29610. }
  29611. } else {
  29612. if ( this._equirectShader == null ) {
  29613. this._equirectShader = _getEquirectShader();
  29614. }
  29615. }
  29616. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  29617. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  29618. const uniforms = material.uniforms;
  29619. uniforms[ 'envMap' ].value = texture;
  29620. if ( ! texture.isCubeTexture ) {
  29621. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  29622. }
  29623. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  29624. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  29625. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  29626. renderer.setRenderTarget( cubeUVRenderTarget );
  29627. renderer.render( mesh, _flatCamera );
  29628. }
  29629. _applyPMREM( cubeUVRenderTarget ) {
  29630. const renderer = this._renderer;
  29631. const autoClear = renderer.autoClear;
  29632. renderer.autoClear = false;
  29633. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  29634. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  29635. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  29636. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29637. }
  29638. renderer.autoClear = autoClear;
  29639. }
  29640. /**
  29641. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29642. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29643. * the blur latitudinally (around the poles), and then longitudinally (towards
  29644. * the poles) to approximate the orthogonally-separable blur. It is least
  29645. * accurate at the poles, but still does a decent job.
  29646. */
  29647. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29648. const pingPongRenderTarget = this._pingPongRenderTarget;
  29649. this._halfBlur(
  29650. cubeUVRenderTarget,
  29651. pingPongRenderTarget,
  29652. lodIn,
  29653. lodOut,
  29654. sigma,
  29655. 'latitudinal',
  29656. poleAxis );
  29657. this._halfBlur(
  29658. pingPongRenderTarget,
  29659. cubeUVRenderTarget,
  29660. lodOut,
  29661. lodOut,
  29662. sigma,
  29663. 'longitudinal',
  29664. poleAxis );
  29665. }
  29666. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29667. const renderer = this._renderer;
  29668. const blurMaterial = this._blurMaterial;
  29669. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29670. console.error(
  29671. 'blur direction must be either latitudinal or longitudinal!' );
  29672. }
  29673. // Number of standard deviations at which to cut off the discrete approximation.
  29674. const STANDARD_DEVIATIONS = 3;
  29675. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  29676. const blurUniforms = blurMaterial.uniforms;
  29677. const pixels = _sizeLods[ lodIn ] - 1;
  29678. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29679. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29680. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29681. if ( samples > MAX_SAMPLES ) {
  29682. console.warn( `sigmaRadians, ${
  29683. sigmaRadians}, is too large and will clip, as it requested ${
  29684. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29685. }
  29686. const weights = [];
  29687. let sum = 0;
  29688. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29689. const x = i / sigmaPixels;
  29690. const weight = Math.exp( - x * x / 2 );
  29691. weights.push( weight );
  29692. if ( i == 0 ) {
  29693. sum += weight;
  29694. } else if ( i < samples ) {
  29695. sum += 2 * weight;
  29696. }
  29697. }
  29698. for ( let i = 0; i < weights.length; i ++ ) {
  29699. weights[ i ] = weights[ i ] / sum;
  29700. }
  29701. blurUniforms[ 'envMap' ].value = targetIn.texture;
  29702. blurUniforms[ 'samples' ].value = samples;
  29703. blurUniforms[ 'weights' ].value = weights;
  29704. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  29705. if ( poleAxis ) {
  29706. blurUniforms[ 'poleAxis' ].value = poleAxis;
  29707. }
  29708. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  29709. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  29710. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  29711. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  29712. const outputSize = _sizeLods[ lodOut ];
  29713. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  29714. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  29715. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29716. renderer.setRenderTarget( targetOut );
  29717. renderer.render( blurMesh, _flatCamera );
  29718. }
  29719. }
  29720. function _isLDR( texture ) {
  29721. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  29722. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  29723. }
  29724. function _createPlanes() {
  29725. const _lodPlanes = [];
  29726. const _sizeLods = [];
  29727. const _sigmas = [];
  29728. let lod = LOD_MAX;
  29729. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  29730. const sizeLod = Math.pow( 2, lod );
  29731. _sizeLods.push( sizeLod );
  29732. let sigma = 1.0 / sizeLod;
  29733. if ( i > LOD_MAX - LOD_MIN ) {
  29734. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  29735. } else if ( i == 0 ) {
  29736. sigma = 0;
  29737. }
  29738. _sigmas.push( sigma );
  29739. const texelSize = 1.0 / ( sizeLod - 1 );
  29740. const min = - texelSize / 2;
  29741. const max = 1 + texelSize / 2;
  29742. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29743. const cubeFaces = 6;
  29744. const vertices = 6;
  29745. const positionSize = 3;
  29746. const uvSize = 2;
  29747. const faceIndexSize = 1;
  29748. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29749. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29750. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29751. for ( let face = 0; face < cubeFaces; face ++ ) {
  29752. const x = ( face % 3 ) * 2 / 3 - 1;
  29753. const y = face > 2 ? 0 : - 1;
  29754. const coordinates = [
  29755. x, y, 0,
  29756. x + 2 / 3, y, 0,
  29757. x + 2 / 3, y + 1, 0,
  29758. x, y, 0,
  29759. x + 2 / 3, y + 1, 0,
  29760. x, y + 1, 0
  29761. ];
  29762. position.set( coordinates, positionSize * vertices * face );
  29763. uv.set( uv1, uvSize * vertices * face );
  29764. const fill = [ face, face, face, face, face, face ];
  29765. faceIndex.set( fill, faceIndexSize * vertices * face );
  29766. }
  29767. const planes = new BufferGeometry();
  29768. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29769. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29770. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29771. _lodPlanes.push( planes );
  29772. if ( lod > LOD_MIN ) {
  29773. lod --;
  29774. }
  29775. }
  29776. return { _lodPlanes, _sizeLods, _sigmas };
  29777. }
  29778. function _createRenderTarget( params ) {
  29779. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  29780. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29781. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29782. cubeUVRenderTarget.scissorTest = true;
  29783. return cubeUVRenderTarget;
  29784. }
  29785. function _setViewport( target, x, y, width, height ) {
  29786. target.viewport.set( x, y, width, height );
  29787. target.scissor.set( x, y, width, height );
  29788. }
  29789. function _getBlurShader( maxSamples ) {
  29790. const weights = new Float32Array( maxSamples );
  29791. const poleAxis = new Vector3( 0, 1, 0 );
  29792. const shaderMaterial = new RawShaderMaterial( {
  29793. name: 'SphericalGaussianBlur',
  29794. defines: { 'n': maxSamples },
  29795. uniforms: {
  29796. 'envMap': { value: null },
  29797. 'samples': { value: 1 },
  29798. 'weights': { value: weights },
  29799. 'latitudinal': { value: false },
  29800. 'dTheta': { value: 0 },
  29801. 'mipInt': { value: 0 },
  29802. 'poleAxis': { value: poleAxis },
  29803. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29804. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29805. },
  29806. vertexShader: _getCommonVertexShader(),
  29807. fragmentShader: /* glsl */`
  29808. precision mediump float;
  29809. precision mediump int;
  29810. varying vec3 vOutputDirection;
  29811. uniform sampler2D envMap;
  29812. uniform int samples;
  29813. uniform float weights[ n ];
  29814. uniform bool latitudinal;
  29815. uniform float dTheta;
  29816. uniform float mipInt;
  29817. uniform vec3 poleAxis;
  29818. ${ _getEncodings() }
  29819. #define ENVMAP_TYPE_CUBE_UV
  29820. #include <cube_uv_reflection_fragment>
  29821. vec3 getSample( float theta, vec3 axis ) {
  29822. float cosTheta = cos( theta );
  29823. // Rodrigues' axis-angle rotation
  29824. vec3 sampleDirection = vOutputDirection * cosTheta
  29825. + cross( axis, vOutputDirection ) * sin( theta )
  29826. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29827. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29828. }
  29829. void main() {
  29830. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29831. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29832. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29833. }
  29834. axis = normalize( axis );
  29835. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29836. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29837. for ( int i = 1; i < n; i++ ) {
  29838. if ( i >= samples ) {
  29839. break;
  29840. }
  29841. float theta = dTheta * float( i );
  29842. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29843. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29844. }
  29845. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29846. }
  29847. `,
  29848. blending: NoBlending,
  29849. depthTest: false,
  29850. depthWrite: false
  29851. } );
  29852. return shaderMaterial;
  29853. }
  29854. function _getEquirectShader() {
  29855. const texelSize = new Vector2$1( 1, 1 );
  29856. const shaderMaterial = new RawShaderMaterial( {
  29857. name: 'EquirectangularToCubeUV',
  29858. uniforms: {
  29859. 'envMap': { value: null },
  29860. 'texelSize': { value: texelSize },
  29861. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29862. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29863. },
  29864. vertexShader: _getCommonVertexShader(),
  29865. fragmentShader: /* glsl */`
  29866. precision mediump float;
  29867. precision mediump int;
  29868. varying vec3 vOutputDirection;
  29869. uniform sampler2D envMap;
  29870. uniform vec2 texelSize;
  29871. ${ _getEncodings() }
  29872. #include <common>
  29873. void main() {
  29874. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29875. vec3 outputDirection = normalize( vOutputDirection );
  29876. vec2 uv = equirectUv( outputDirection );
  29877. vec2 f = fract( uv / texelSize - 0.5 );
  29878. uv -= f * texelSize;
  29879. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29880. uv.x += texelSize.x;
  29881. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29882. uv.y += texelSize.y;
  29883. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29884. uv.x -= texelSize.x;
  29885. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29886. vec3 tm = mix( tl, tr, f.x );
  29887. vec3 bm = mix( bl, br, f.x );
  29888. gl_FragColor.rgb = mix( tm, bm, f.y );
  29889. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29890. }
  29891. `,
  29892. blending: NoBlending,
  29893. depthTest: false,
  29894. depthWrite: false
  29895. } );
  29896. return shaderMaterial;
  29897. }
  29898. function _getCubemapShader() {
  29899. const shaderMaterial = new RawShaderMaterial( {
  29900. name: 'CubemapToCubeUV',
  29901. uniforms: {
  29902. 'envMap': { value: null },
  29903. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29904. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29905. },
  29906. vertexShader: _getCommonVertexShader(),
  29907. fragmentShader: /* glsl */`
  29908. precision mediump float;
  29909. precision mediump int;
  29910. varying vec3 vOutputDirection;
  29911. uniform samplerCube envMap;
  29912. ${ _getEncodings() }
  29913. void main() {
  29914. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29915. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29916. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29917. }
  29918. `,
  29919. blending: NoBlending,
  29920. depthTest: false,
  29921. depthWrite: false
  29922. } );
  29923. return shaderMaterial;
  29924. }
  29925. function _getCommonVertexShader() {
  29926. return /* glsl */`
  29927. precision mediump float;
  29928. precision mediump int;
  29929. attribute vec3 position;
  29930. attribute vec2 uv;
  29931. attribute float faceIndex;
  29932. varying vec3 vOutputDirection;
  29933. // RH coordinate system; PMREM face-indexing convention
  29934. vec3 getDirection( vec2 uv, float face ) {
  29935. uv = 2.0 * uv - 1.0;
  29936. vec3 direction = vec3( uv, 1.0 );
  29937. if ( face == 0.0 ) {
  29938. direction = direction.zyx; // ( 1, v, u ) pos x
  29939. } else if ( face == 1.0 ) {
  29940. direction = direction.xzy;
  29941. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29942. } else if ( face == 2.0 ) {
  29943. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29944. } else if ( face == 3.0 ) {
  29945. direction = direction.zyx;
  29946. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29947. } else if ( face == 4.0 ) {
  29948. direction = direction.xzy;
  29949. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29950. } else if ( face == 5.0 ) {
  29951. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29952. }
  29953. return direction;
  29954. }
  29955. void main() {
  29956. vOutputDirection = getDirection( uv, faceIndex );
  29957. gl_Position = vec4( position, 1.0 );
  29958. }
  29959. `;
  29960. }
  29961. function _getEncodings() {
  29962. return /* glsl */`
  29963. uniform int inputEncoding;
  29964. uniform int outputEncoding;
  29965. #include <encodings_pars_fragment>
  29966. vec4 inputTexelToLinear( vec4 value ) {
  29967. if ( inputEncoding == 0 ) {
  29968. return value;
  29969. } else if ( inputEncoding == 1 ) {
  29970. return sRGBToLinear( value );
  29971. } else if ( inputEncoding == 2 ) {
  29972. return RGBEToLinear( value );
  29973. } else if ( inputEncoding == 3 ) {
  29974. return RGBMToLinear( value, 7.0 );
  29975. } else if ( inputEncoding == 4 ) {
  29976. return RGBMToLinear( value, 16.0 );
  29977. } else if ( inputEncoding == 5 ) {
  29978. return RGBDToLinear( value, 256.0 );
  29979. } else {
  29980. return GammaToLinear( value, 2.2 );
  29981. }
  29982. }
  29983. vec4 linearToOutputTexel( vec4 value ) {
  29984. if ( outputEncoding == 0 ) {
  29985. return value;
  29986. } else if ( outputEncoding == 1 ) {
  29987. return LinearTosRGB( value );
  29988. } else if ( outputEncoding == 2 ) {
  29989. return LinearToRGBE( value );
  29990. } else if ( outputEncoding == 3 ) {
  29991. return LinearToRGBM( value, 7.0 );
  29992. } else if ( outputEncoding == 4 ) {
  29993. return LinearToRGBM( value, 16.0 );
  29994. } else if ( outputEncoding == 5 ) {
  29995. return LinearToRGBD( value, 256.0 );
  29996. } else {
  29997. return LinearToGamma( value, 2.2 );
  29998. }
  29999. }
  30000. vec4 envMapTexelToLinear( vec4 color ) {
  30001. return inputTexelToLinear( color );
  30002. }
  30003. `;
  30004. }
  30005. function Face4( a, b, c, d, normal, color, materialIndex ) {
  30006. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  30007. return new Face3( a, b, c, normal, color, materialIndex );
  30008. }
  30009. const LineStrip = 0;
  30010. const LinePieces = 1;
  30011. const NoColors = 0;
  30012. const FaceColors = 1;
  30013. const VertexColors = 2;
  30014. function MeshFaceMaterial( materials ) {
  30015. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  30016. return materials;
  30017. }
  30018. function MultiMaterial( materials = [] ) {
  30019. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  30020. materials.isMultiMaterial = true;
  30021. materials.materials = materials;
  30022. materials.clone = function () {
  30023. return materials.slice();
  30024. };
  30025. return materials;
  30026. }
  30027. function PointCloud( geometry, material ) {
  30028. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  30029. return new Points( geometry, material );
  30030. }
  30031. function Particle( material ) {
  30032. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  30033. return new Sprite( material );
  30034. }
  30035. function ParticleSystem( geometry, material ) {
  30036. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  30037. return new Points( geometry, material );
  30038. }
  30039. function PointCloudMaterial( parameters ) {
  30040. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  30041. return new PointsMaterial( parameters );
  30042. }
  30043. function ParticleBasicMaterial( parameters ) {
  30044. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  30045. return new PointsMaterial( parameters );
  30046. }
  30047. function ParticleSystemMaterial( parameters ) {
  30048. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  30049. return new PointsMaterial( parameters );
  30050. }
  30051. function Vertex( x, y, z ) {
  30052. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  30053. return new Vector3( x, y, z );
  30054. }
  30055. //
  30056. function DynamicBufferAttribute( array, itemSize ) {
  30057. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  30058. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  30059. }
  30060. function Int8Attribute( array, itemSize ) {
  30061. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  30062. return new Int8BufferAttribute( array, itemSize );
  30063. }
  30064. function Uint8Attribute( array, itemSize ) {
  30065. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  30066. return new Uint8BufferAttribute( array, itemSize );
  30067. }
  30068. function Uint8ClampedAttribute( array, itemSize ) {
  30069. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  30070. return new Uint8ClampedBufferAttribute( array, itemSize );
  30071. }
  30072. function Int16Attribute( array, itemSize ) {
  30073. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  30074. return new Int16BufferAttribute( array, itemSize );
  30075. }
  30076. function Uint16Attribute( array, itemSize ) {
  30077. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  30078. return new Uint16BufferAttribute( array, itemSize );
  30079. }
  30080. function Int32Attribute( array, itemSize ) {
  30081. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  30082. return new Int32BufferAttribute( array, itemSize );
  30083. }
  30084. function Uint32Attribute( array, itemSize ) {
  30085. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  30086. return new Uint32BufferAttribute( array, itemSize );
  30087. }
  30088. function Float32Attribute( array, itemSize ) {
  30089. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  30090. return new Float32BufferAttribute( array, itemSize );
  30091. }
  30092. function Float64Attribute( array, itemSize ) {
  30093. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  30094. return new Float64BufferAttribute( array, itemSize );
  30095. }
  30096. //
  30097. Curve.create = function ( construct, getPoint ) {
  30098. console.log( 'THREE.Curve.create() has been deprecated' );
  30099. construct.prototype = Object.create( Curve.prototype );
  30100. construct.prototype.constructor = construct;
  30101. construct.prototype.getPoint = getPoint;
  30102. return construct;
  30103. };
  30104. //
  30105. Object.assign( CurvePath.prototype, {
  30106. createPointsGeometry: function ( divisions ) {
  30107. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30108. // generate geometry from path points (for Line or Points objects)
  30109. const pts = this.getPoints( divisions );
  30110. return this.createGeometry( pts );
  30111. },
  30112. createSpacedPointsGeometry: function ( divisions ) {
  30113. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30114. // generate geometry from equidistant sampling along the path
  30115. const pts = this.getSpacedPoints( divisions );
  30116. return this.createGeometry( pts );
  30117. },
  30118. createGeometry: function ( points ) {
  30119. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30120. const geometry = new Geometry();
  30121. for ( let i = 0, l = points.length; i < l; i ++ ) {
  30122. const point = points[ i ];
  30123. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  30124. }
  30125. return geometry;
  30126. }
  30127. } );
  30128. //
  30129. Object.assign( Path.prototype, {
  30130. fromPoints: function ( points ) {
  30131. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  30132. return this.setFromPoints( points );
  30133. }
  30134. } );
  30135. //
  30136. function ClosedSplineCurve3( points ) {
  30137. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30138. CatmullRomCurve3.call( this, points );
  30139. this.type = 'catmullrom';
  30140. this.closed = true;
  30141. }
  30142. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30143. //
  30144. function SplineCurve3( points ) {
  30145. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30146. CatmullRomCurve3.call( this, points );
  30147. this.type = 'catmullrom';
  30148. }
  30149. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30150. //
  30151. function Spline( points ) {
  30152. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  30153. CatmullRomCurve3.call( this, points );
  30154. this.type = 'catmullrom';
  30155. }
  30156. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  30157. Object.assign( Spline.prototype, {
  30158. initFromArray: function ( /* a */ ) {
  30159. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  30160. },
  30161. getControlPointsArray: function ( /* optionalTarget */ ) {
  30162. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  30163. },
  30164. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  30165. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  30166. }
  30167. } );
  30168. //
  30169. function AxisHelper( size ) {
  30170. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  30171. return new AxesHelper( size );
  30172. }
  30173. function BoundingBoxHelper( object, color ) {
  30174. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  30175. return new BoxHelper( object, color );
  30176. }
  30177. function EdgesHelper( object, hex ) {
  30178. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  30179. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30180. }
  30181. GridHelper.prototype.setColors = function () {
  30182. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  30183. };
  30184. SkeletonHelper.prototype.update = function () {
  30185. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  30186. };
  30187. function WireframeHelper( object, hex ) {
  30188. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  30189. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30190. }
  30191. //
  30192. Object.assign( Loader.prototype, {
  30193. extractUrlBase: function ( url ) {
  30194. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  30195. return LoaderUtils.extractUrlBase( url );
  30196. }
  30197. } );
  30198. Loader.Handlers = {
  30199. add: function ( /* regex, loader */ ) {
  30200. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  30201. },
  30202. get: function ( /* file */ ) {
  30203. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  30204. }
  30205. };
  30206. function XHRLoader( manager ) {
  30207. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  30208. return new FileLoader( manager );
  30209. }
  30210. function BinaryTextureLoader( manager ) {
  30211. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  30212. return new DataTextureLoader( manager );
  30213. }
  30214. //
  30215. Object.assign( Box2.prototype, {
  30216. center: function ( optionalTarget ) {
  30217. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  30218. return this.getCenter( optionalTarget );
  30219. },
  30220. empty: function () {
  30221. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  30222. return this.isEmpty();
  30223. },
  30224. isIntersectionBox: function ( box ) {
  30225. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30226. return this.intersectsBox( box );
  30227. },
  30228. size: function ( optionalTarget ) {
  30229. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  30230. return this.getSize( optionalTarget );
  30231. }
  30232. } );
  30233. Object.assign( Box3.prototype, {
  30234. center: function ( optionalTarget ) {
  30235. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  30236. return this.getCenter( optionalTarget );
  30237. },
  30238. empty: function () {
  30239. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  30240. return this.isEmpty();
  30241. },
  30242. isIntersectionBox: function ( box ) {
  30243. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30244. return this.intersectsBox( box );
  30245. },
  30246. isIntersectionSphere: function ( sphere ) {
  30247. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30248. return this.intersectsSphere( sphere );
  30249. },
  30250. size: function ( optionalTarget ) {
  30251. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  30252. return this.getSize( optionalTarget );
  30253. }
  30254. } );
  30255. Object.assign( Sphere.prototype, {
  30256. empty: function () {
  30257. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  30258. return this.isEmpty();
  30259. },
  30260. } );
  30261. Frustum.prototype.setFromMatrix = function ( m ) {
  30262. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  30263. return this.setFromProjectionMatrix( m );
  30264. };
  30265. Line3.prototype.center = function ( optionalTarget ) {
  30266. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  30267. return this.getCenter( optionalTarget );
  30268. };
  30269. Object.assign( MathUtils, {
  30270. random16: function () {
  30271. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  30272. return Math.random();
  30273. },
  30274. nearestPowerOfTwo: function ( value ) {
  30275. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  30276. return MathUtils.floorPowerOfTwo( value );
  30277. },
  30278. nextPowerOfTwo: function ( value ) {
  30279. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  30280. return MathUtils.ceilPowerOfTwo( value );
  30281. }
  30282. } );
  30283. Object.assign( Matrix3.prototype, {
  30284. flattenToArrayOffset: function ( array, offset ) {
  30285. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30286. return this.toArray( array, offset );
  30287. },
  30288. multiplyVector3: function ( vector ) {
  30289. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  30290. return vector.applyMatrix3( this );
  30291. },
  30292. multiplyVector3Array: function ( /* a */ ) {
  30293. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  30294. },
  30295. applyToBufferAttribute: function ( attribute ) {
  30296. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  30297. return attribute.applyMatrix3( this );
  30298. },
  30299. applyToVector3Array: function ( /* array, offset, length */ ) {
  30300. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  30301. },
  30302. getInverse: function ( matrix ) {
  30303. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30304. return this.copy( matrix ).invert();
  30305. }
  30306. } );
  30307. Object.assign( Matrix4.prototype, {
  30308. extractPosition: function ( m ) {
  30309. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  30310. return this.copyPosition( m );
  30311. },
  30312. flattenToArrayOffset: function ( array, offset ) {
  30313. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30314. return this.toArray( array, offset );
  30315. },
  30316. getPosition: function () {
  30317. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  30318. return new Vector3().setFromMatrixColumn( this, 3 );
  30319. },
  30320. setRotationFromQuaternion: function ( q ) {
  30321. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  30322. return this.makeRotationFromQuaternion( q );
  30323. },
  30324. multiplyToArray: function () {
  30325. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  30326. },
  30327. multiplyVector3: function ( vector ) {
  30328. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30329. return vector.applyMatrix4( this );
  30330. },
  30331. multiplyVector4: function ( vector ) {
  30332. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30333. return vector.applyMatrix4( this );
  30334. },
  30335. multiplyVector3Array: function ( /* a */ ) {
  30336. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  30337. },
  30338. rotateAxis: function ( v ) {
  30339. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  30340. v.transformDirection( this );
  30341. },
  30342. crossVector: function ( vector ) {
  30343. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30344. return vector.applyMatrix4( this );
  30345. },
  30346. translate: function () {
  30347. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  30348. },
  30349. rotateX: function () {
  30350. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  30351. },
  30352. rotateY: function () {
  30353. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  30354. },
  30355. rotateZ: function () {
  30356. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  30357. },
  30358. rotateByAxis: function () {
  30359. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  30360. },
  30361. applyToBufferAttribute: function ( attribute ) {
  30362. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  30363. return attribute.applyMatrix4( this );
  30364. },
  30365. applyToVector3Array: function ( /* array, offset, length */ ) {
  30366. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  30367. },
  30368. makeFrustum: function ( left, right, bottom, top, near, far ) {
  30369. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  30370. return this.makePerspective( left, right, top, bottom, near, far );
  30371. },
  30372. getInverse: function ( matrix ) {
  30373. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30374. return this.copy( matrix ).invert();
  30375. }
  30376. } );
  30377. Plane.prototype.isIntersectionLine = function ( line ) {
  30378. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  30379. return this.intersectsLine( line );
  30380. };
  30381. Object.assign( Quaternion.prototype, {
  30382. multiplyVector3: function ( vector ) {
  30383. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  30384. return vector.applyQuaternion( this );
  30385. },
  30386. inverse: function ( ) {
  30387. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  30388. return this.invert();
  30389. }
  30390. } );
  30391. Object.assign( Ray.prototype, {
  30392. isIntersectionBox: function ( box ) {
  30393. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30394. return this.intersectsBox( box );
  30395. },
  30396. isIntersectionPlane: function ( plane ) {
  30397. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  30398. return this.intersectsPlane( plane );
  30399. },
  30400. isIntersectionSphere: function ( sphere ) {
  30401. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30402. return this.intersectsSphere( sphere );
  30403. }
  30404. } );
  30405. Object.assign( Triangle.prototype, {
  30406. area: function () {
  30407. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  30408. return this.getArea();
  30409. },
  30410. barycoordFromPoint: function ( point, target ) {
  30411. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30412. return this.getBarycoord( point, target );
  30413. },
  30414. midpoint: function ( target ) {
  30415. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  30416. return this.getMidpoint( target );
  30417. },
  30418. normal: function ( target ) {
  30419. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30420. return this.getNormal( target );
  30421. },
  30422. plane: function ( target ) {
  30423. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  30424. return this.getPlane( target );
  30425. }
  30426. } );
  30427. Object.assign( Triangle, {
  30428. barycoordFromPoint: function ( point, a, b, c, target ) {
  30429. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30430. return Triangle.getBarycoord( point, a, b, c, target );
  30431. },
  30432. normal: function ( a, b, c, target ) {
  30433. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30434. return Triangle.getNormal( a, b, c, target );
  30435. }
  30436. } );
  30437. Object.assign( Shape.prototype, {
  30438. extractAllPoints: function ( divisions ) {
  30439. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  30440. return this.extractPoints( divisions );
  30441. },
  30442. extrude: function ( options ) {
  30443. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  30444. return new ExtrudeGeometry( this, options );
  30445. },
  30446. makeGeometry: function ( options ) {
  30447. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  30448. return new ShapeGeometry( this, options );
  30449. }
  30450. } );
  30451. Object.assign( Vector2$1.prototype, {
  30452. fromAttribute: function ( attribute, index, offset ) {
  30453. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30454. return this.fromBufferAttribute( attribute, index, offset );
  30455. },
  30456. distanceToManhattan: function ( v ) {
  30457. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30458. return this.manhattanDistanceTo( v );
  30459. },
  30460. lengthManhattan: function () {
  30461. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  30462. return this.manhattanLength();
  30463. }
  30464. } );
  30465. Object.assign( Vector3.prototype, {
  30466. setEulerFromRotationMatrix: function () {
  30467. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  30468. },
  30469. setEulerFromQuaternion: function () {
  30470. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  30471. },
  30472. getPositionFromMatrix: function ( m ) {
  30473. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  30474. return this.setFromMatrixPosition( m );
  30475. },
  30476. getScaleFromMatrix: function ( m ) {
  30477. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  30478. return this.setFromMatrixScale( m );
  30479. },
  30480. getColumnFromMatrix: function ( index, matrix ) {
  30481. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  30482. return this.setFromMatrixColumn( matrix, index );
  30483. },
  30484. applyProjection: function ( m ) {
  30485. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  30486. return this.applyMatrix4( m );
  30487. },
  30488. fromAttribute: function ( attribute, index, offset ) {
  30489. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30490. return this.fromBufferAttribute( attribute, index, offset );
  30491. },
  30492. distanceToManhattan: function ( v ) {
  30493. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30494. return this.manhattanDistanceTo( v );
  30495. },
  30496. lengthManhattan: function () {
  30497. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  30498. return this.manhattanLength();
  30499. }
  30500. } );
  30501. Object.assign( Vector4.prototype, {
  30502. fromAttribute: function ( attribute, index, offset ) {
  30503. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30504. return this.fromBufferAttribute( attribute, index, offset );
  30505. },
  30506. lengthManhattan: function () {
  30507. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  30508. return this.manhattanLength();
  30509. }
  30510. } );
  30511. //
  30512. Object.assign( Geometry.prototype, {
  30513. computeTangents: function () {
  30514. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  30515. },
  30516. computeLineDistances: function () {
  30517. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  30518. },
  30519. applyMatrix: function ( matrix ) {
  30520. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30521. return this.applyMatrix4( matrix );
  30522. }
  30523. } );
  30524. Object.assign( Object3D.prototype, {
  30525. getChildByName: function ( name ) {
  30526. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  30527. return this.getObjectByName( name );
  30528. },
  30529. renderDepth: function () {
  30530. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  30531. },
  30532. translate: function ( distance, axis ) {
  30533. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  30534. return this.translateOnAxis( axis, distance );
  30535. },
  30536. getWorldRotation: function () {
  30537. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  30538. },
  30539. applyMatrix: function ( matrix ) {
  30540. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  30541. return this.applyMatrix4( matrix );
  30542. }
  30543. } );
  30544. Object.defineProperties( Object3D.prototype, {
  30545. eulerOrder: {
  30546. get: function () {
  30547. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30548. return this.rotation.order;
  30549. },
  30550. set: function ( value ) {
  30551. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30552. this.rotation.order = value;
  30553. }
  30554. },
  30555. useQuaternion: {
  30556. get: function () {
  30557. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30558. },
  30559. set: function () {
  30560. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30561. }
  30562. }
  30563. } );
  30564. Object.assign( Mesh.prototype, {
  30565. setDrawMode: function () {
  30566. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30567. },
  30568. } );
  30569. Object.defineProperties( Mesh.prototype, {
  30570. drawMode: {
  30571. get: function () {
  30572. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  30573. return TrianglesDrawMode;
  30574. },
  30575. set: function () {
  30576. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30577. }
  30578. }
  30579. } );
  30580. Object.defineProperties( LOD.prototype, {
  30581. objects: {
  30582. get: function () {
  30583. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  30584. return this.levels;
  30585. }
  30586. }
  30587. } );
  30588. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  30589. get: function () {
  30590. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30591. },
  30592. set: function () {
  30593. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30594. }
  30595. } );
  30596. SkinnedMesh.prototype.initBones = function () {
  30597. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  30598. };
  30599. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  30600. get: function () {
  30601. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30602. return this.arcLengthDivisions;
  30603. },
  30604. set: function ( value ) {
  30605. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30606. this.arcLengthDivisions = value;
  30607. }
  30608. } );
  30609. //
  30610. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  30611. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  30612. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  30613. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  30614. this.setFocalLength( focalLength );
  30615. };
  30616. //
  30617. Object.defineProperties( Light.prototype, {
  30618. onlyShadow: {
  30619. set: function () {
  30620. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  30621. }
  30622. },
  30623. shadowCameraFov: {
  30624. set: function ( value ) {
  30625. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  30626. this.shadow.camera.fov = value;
  30627. }
  30628. },
  30629. shadowCameraLeft: {
  30630. set: function ( value ) {
  30631. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  30632. this.shadow.camera.left = value;
  30633. }
  30634. },
  30635. shadowCameraRight: {
  30636. set: function ( value ) {
  30637. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  30638. this.shadow.camera.right = value;
  30639. }
  30640. },
  30641. shadowCameraTop: {
  30642. set: function ( value ) {
  30643. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  30644. this.shadow.camera.top = value;
  30645. }
  30646. },
  30647. shadowCameraBottom: {
  30648. set: function ( value ) {
  30649. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  30650. this.shadow.camera.bottom = value;
  30651. }
  30652. },
  30653. shadowCameraNear: {
  30654. set: function ( value ) {
  30655. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  30656. this.shadow.camera.near = value;
  30657. }
  30658. },
  30659. shadowCameraFar: {
  30660. set: function ( value ) {
  30661. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  30662. this.shadow.camera.far = value;
  30663. }
  30664. },
  30665. shadowCameraVisible: {
  30666. set: function () {
  30667. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  30668. }
  30669. },
  30670. shadowBias: {
  30671. set: function ( value ) {
  30672. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  30673. this.shadow.bias = value;
  30674. }
  30675. },
  30676. shadowDarkness: {
  30677. set: function () {
  30678. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  30679. }
  30680. },
  30681. shadowMapWidth: {
  30682. set: function ( value ) {
  30683. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  30684. this.shadow.mapSize.width = value;
  30685. }
  30686. },
  30687. shadowMapHeight: {
  30688. set: function ( value ) {
  30689. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  30690. this.shadow.mapSize.height = value;
  30691. }
  30692. }
  30693. } );
  30694. //
  30695. Object.defineProperties( BufferAttribute.prototype, {
  30696. length: {
  30697. get: function () {
  30698. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  30699. return this.array.length;
  30700. }
  30701. },
  30702. dynamic: {
  30703. get: function () {
  30704. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30705. return this.usage === DynamicDrawUsage;
  30706. },
  30707. set: function ( /* value */ ) {
  30708. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30709. this.setUsage( DynamicDrawUsage );
  30710. }
  30711. }
  30712. } );
  30713. Object.assign( BufferAttribute.prototype, {
  30714. setDynamic: function ( value ) {
  30715. //console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30716. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30717. return this;
  30718. },
  30719. copyIndicesArray: function ( /* indices */ ) {
  30720. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  30721. },
  30722. setArray: function ( /* array */ ) {
  30723. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30724. }
  30725. } );
  30726. Object.assign( BufferGeometry.prototype, {
  30727. addIndex: function ( index ) {
  30728. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  30729. this.setIndex( index );
  30730. },
  30731. addAttribute: function ( name, attribute ) {
  30732. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  30733. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  30734. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  30735. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  30736. }
  30737. if ( name === 'index' ) {
  30738. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  30739. this.setIndex( attribute );
  30740. return this;
  30741. }
  30742. return this.setAttribute( name, attribute );
  30743. },
  30744. addDrawCall: function ( start, count, indexOffset ) {
  30745. if ( indexOffset !== undefined ) {
  30746. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  30747. }
  30748. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30749. this.addGroup( start, count );
  30750. },
  30751. clearDrawCalls: function () {
  30752. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30753. this.clearGroups();
  30754. },
  30755. computeTangents: function () {
  30756. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  30757. },
  30758. computeOffsets: function () {
  30759. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30760. },
  30761. removeAttribute: function ( name ) {
  30762. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  30763. return this.deleteAttribute( name );
  30764. },
  30765. applyMatrix: function ( matrix ) {
  30766. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30767. return this.applyMatrix4( matrix );
  30768. }
  30769. } );
  30770. Object.defineProperties( BufferGeometry.prototype, {
  30771. drawcalls: {
  30772. get: function () {
  30773. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30774. return this.groups;
  30775. }
  30776. },
  30777. offsets: {
  30778. get: function () {
  30779. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30780. return this.groups;
  30781. }
  30782. }
  30783. } );
  30784. Object.defineProperties( InstancedBufferGeometry.prototype, {
  30785. maxInstancedCount: {
  30786. get: function () {
  30787. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30788. return this.instanceCount;
  30789. },
  30790. set: function ( value ) {
  30791. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30792. this.instanceCount = value;
  30793. }
  30794. }
  30795. } );
  30796. Object.defineProperties( Raycaster.prototype, {
  30797. linePrecision: {
  30798. get: function () {
  30799. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30800. return this.params.Line.threshold;
  30801. },
  30802. set: function ( value ) {
  30803. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30804. this.params.Line.threshold = value;
  30805. }
  30806. }
  30807. } );
  30808. Object.defineProperties( InterleavedBuffer.prototype, {
  30809. dynamic: {
  30810. get: function () {
  30811. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30812. return this.usage === DynamicDrawUsage;
  30813. },
  30814. set: function ( value ) {
  30815. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30816. this.setUsage( value );
  30817. }
  30818. }
  30819. } );
  30820. Object.assign( InterleavedBuffer.prototype, {
  30821. setDynamic: function ( value ) {
  30822. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30823. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30824. return this;
  30825. },
  30826. setArray: function ( /* array */ ) {
  30827. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30828. }
  30829. } );
  30830. //
  30831. Object.assign( ExtrudeBufferGeometry.prototype, {
  30832. getArrays: function () {
  30833. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  30834. },
  30835. addShapeList: function () {
  30836. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  30837. },
  30838. addShape: function () {
  30839. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  30840. }
  30841. } );
  30842. //
  30843. Object.assign( Scene.prototype, {
  30844. dispose: function () {
  30845. console.error( 'THREE.Scene: .dispose() has been removed.' );
  30846. }
  30847. } );
  30848. //
  30849. Object.defineProperties( Uniform.prototype, {
  30850. dynamic: {
  30851. set: function () {
  30852. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  30853. }
  30854. },
  30855. onUpdate: {
  30856. value: function () {
  30857. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30858. return this;
  30859. }
  30860. }
  30861. } );
  30862. //
  30863. Object.defineProperties( Material.prototype, {
  30864. wrapAround: {
  30865. get: function () {
  30866. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30867. },
  30868. set: function () {
  30869. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30870. }
  30871. },
  30872. overdraw: {
  30873. get: function () {
  30874. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30875. },
  30876. set: function () {
  30877. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30878. }
  30879. },
  30880. wrapRGB: {
  30881. get: function () {
  30882. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30883. return new Color();
  30884. }
  30885. },
  30886. shading: {
  30887. get: function () {
  30888. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30889. },
  30890. set: function ( value ) {
  30891. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30892. this.flatShading = ( value === FlatShading );
  30893. }
  30894. },
  30895. stencilMask: {
  30896. get: function () {
  30897. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30898. return this.stencilFuncMask;
  30899. },
  30900. set: function ( value ) {
  30901. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30902. this.stencilFuncMask = value;
  30903. }
  30904. }
  30905. } );
  30906. Object.defineProperties( MeshPhongMaterial.prototype, {
  30907. metal: {
  30908. get: function () {
  30909. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  30910. return false;
  30911. },
  30912. set: function () {
  30913. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  30914. }
  30915. }
  30916. } );
  30917. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  30918. transparency: {
  30919. get: function () {
  30920. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30921. return this.transmission;
  30922. },
  30923. set: function ( value ) {
  30924. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30925. this.transmission = value;
  30926. }
  30927. }
  30928. } );
  30929. Object.defineProperties( ShaderMaterial.prototype, {
  30930. derivatives: {
  30931. get: function () {
  30932. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30933. return this.extensions.derivatives;
  30934. },
  30935. set: function ( value ) {
  30936. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30937. this.extensions.derivatives = value;
  30938. }
  30939. }
  30940. } );
  30941. //
  30942. Object.assign( WebGLRenderer.prototype, {
  30943. clearTarget: function ( renderTarget, color, depth, stencil ) {
  30944. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  30945. this.setRenderTarget( renderTarget );
  30946. this.clear( color, depth, stencil );
  30947. },
  30948. animate: function ( callback ) {
  30949. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  30950. this.setAnimationLoop( callback );
  30951. },
  30952. getCurrentRenderTarget: function () {
  30953. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30954. return this.getRenderTarget();
  30955. },
  30956. getMaxAnisotropy: function () {
  30957. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30958. return this.capabilities.getMaxAnisotropy();
  30959. },
  30960. getPrecision: function () {
  30961. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30962. return this.capabilities.precision;
  30963. },
  30964. resetGLState: function () {
  30965. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  30966. return this.state.reset();
  30967. },
  30968. supportsFloatTextures: function () {
  30969. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30970. return this.extensions.get( 'OES_texture_float' );
  30971. },
  30972. supportsHalfFloatTextures: function () {
  30973. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30974. return this.extensions.get( 'OES_texture_half_float' );
  30975. },
  30976. supportsStandardDerivatives: function () {
  30977. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30978. return this.extensions.get( 'OES_standard_derivatives' );
  30979. },
  30980. supportsCompressedTextureS3TC: function () {
  30981. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30982. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30983. },
  30984. supportsCompressedTexturePVRTC: function () {
  30985. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30986. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30987. },
  30988. supportsBlendMinMax: function () {
  30989. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30990. return this.extensions.get( 'EXT_blend_minmax' );
  30991. },
  30992. supportsVertexTextures: function () {
  30993. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30994. return this.capabilities.vertexTextures;
  30995. },
  30996. supportsInstancedArrays: function () {
  30997. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30998. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30999. },
  31000. enableScissorTest: function ( boolean ) {
  31001. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  31002. this.setScissorTest( boolean );
  31003. },
  31004. initMaterial: function () {
  31005. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  31006. },
  31007. addPrePlugin: function () {
  31008. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  31009. },
  31010. addPostPlugin: function () {
  31011. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  31012. },
  31013. updateShadowMap: function () {
  31014. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  31015. },
  31016. setFaceCulling: function () {
  31017. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  31018. },
  31019. allocTextureUnit: function () {
  31020. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  31021. },
  31022. setTexture: function () {
  31023. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  31024. },
  31025. setTexture2D: function () {
  31026. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  31027. },
  31028. setTextureCube: function () {
  31029. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  31030. },
  31031. getActiveMipMapLevel: function () {
  31032. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  31033. return this.getActiveMipmapLevel();
  31034. }
  31035. } );
  31036. Object.defineProperties( WebGLRenderer.prototype, {
  31037. shadowMapEnabled: {
  31038. get: function () {
  31039. return this.shadowMap.enabled;
  31040. },
  31041. set: function ( value ) {
  31042. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  31043. this.shadowMap.enabled = value;
  31044. }
  31045. },
  31046. shadowMapType: {
  31047. get: function () {
  31048. return this.shadowMap.type;
  31049. },
  31050. set: function ( value ) {
  31051. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  31052. this.shadowMap.type = value;
  31053. }
  31054. },
  31055. shadowMapCullFace: {
  31056. get: function () {
  31057. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31058. return undefined;
  31059. },
  31060. set: function ( /* value */ ) {
  31061. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31062. }
  31063. },
  31064. context: {
  31065. get: function () {
  31066. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  31067. return this.getContext();
  31068. }
  31069. },
  31070. vr: {
  31071. get: function () {
  31072. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  31073. return this.xr;
  31074. }
  31075. },
  31076. gammaInput: {
  31077. get: function () {
  31078. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  31079. return false;
  31080. },
  31081. set: function () {
  31082. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  31083. }
  31084. },
  31085. gammaOutput: {
  31086. get: function () {
  31087. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  31088. return false;
  31089. },
  31090. set: function ( value ) {
  31091. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  31092. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  31093. }
  31094. },
  31095. toneMappingWhitePoint: {
  31096. get: function () {
  31097. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  31098. return 1.0;
  31099. },
  31100. set: function () {
  31101. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  31102. }
  31103. },
  31104. } );
  31105. Object.defineProperties( WebGLShadowMap.prototype, {
  31106. cullFace: {
  31107. get: function () {
  31108. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31109. return undefined;
  31110. },
  31111. set: function ( /* cullFace */ ) {
  31112. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31113. }
  31114. },
  31115. renderReverseSided: {
  31116. get: function () {
  31117. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31118. return undefined;
  31119. },
  31120. set: function () {
  31121. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31122. }
  31123. },
  31124. renderSingleSided: {
  31125. get: function () {
  31126. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31127. return undefined;
  31128. },
  31129. set: function () {
  31130. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31131. }
  31132. }
  31133. } );
  31134. function WebGLRenderTargetCube( width, height, options ) {
  31135. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  31136. return new WebGLCubeRenderTarget( width, options );
  31137. }
  31138. //
  31139. Object.defineProperties( WebGLRenderTarget.prototype, {
  31140. wrapS: {
  31141. get: function () {
  31142. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31143. return this.texture.wrapS;
  31144. },
  31145. set: function ( value ) {
  31146. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31147. this.texture.wrapS = value;
  31148. }
  31149. },
  31150. wrapT: {
  31151. get: function () {
  31152. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31153. return this.texture.wrapT;
  31154. },
  31155. set: function ( value ) {
  31156. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31157. this.texture.wrapT = value;
  31158. }
  31159. },
  31160. magFilter: {
  31161. get: function () {
  31162. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31163. return this.texture.magFilter;
  31164. },
  31165. set: function ( value ) {
  31166. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31167. this.texture.magFilter = value;
  31168. }
  31169. },
  31170. minFilter: {
  31171. get: function () {
  31172. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31173. return this.texture.minFilter;
  31174. },
  31175. set: function ( value ) {
  31176. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31177. this.texture.minFilter = value;
  31178. }
  31179. },
  31180. anisotropy: {
  31181. get: function () {
  31182. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31183. return this.texture.anisotropy;
  31184. },
  31185. set: function ( value ) {
  31186. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31187. this.texture.anisotropy = value;
  31188. }
  31189. },
  31190. offset: {
  31191. get: function () {
  31192. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31193. return this.texture.offset;
  31194. },
  31195. set: function ( value ) {
  31196. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31197. this.texture.offset = value;
  31198. }
  31199. },
  31200. repeat: {
  31201. get: function () {
  31202. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31203. return this.texture.repeat;
  31204. },
  31205. set: function ( value ) {
  31206. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31207. this.texture.repeat = value;
  31208. }
  31209. },
  31210. format: {
  31211. get: function () {
  31212. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31213. return this.texture.format;
  31214. },
  31215. set: function ( value ) {
  31216. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31217. this.texture.format = value;
  31218. }
  31219. },
  31220. type: {
  31221. get: function () {
  31222. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31223. return this.texture.type;
  31224. },
  31225. set: function ( value ) {
  31226. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31227. this.texture.type = value;
  31228. }
  31229. },
  31230. generateMipmaps: {
  31231. get: function () {
  31232. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31233. return this.texture.generateMipmaps;
  31234. },
  31235. set: function ( value ) {
  31236. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31237. this.texture.generateMipmaps = value;
  31238. }
  31239. }
  31240. } );
  31241. //
  31242. Object.defineProperties( Audio.prototype, {
  31243. load: {
  31244. value: function ( file ) {
  31245. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  31246. const scope = this;
  31247. const audioLoader = new AudioLoader();
  31248. audioLoader.load( file, function ( buffer ) {
  31249. scope.setBuffer( buffer );
  31250. } );
  31251. return this;
  31252. }
  31253. },
  31254. startTime: {
  31255. set: function () {
  31256. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  31257. }
  31258. }
  31259. } );
  31260. AudioAnalyser.prototype.getData = function () {
  31261. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  31262. return this.getFrequencyData();
  31263. };
  31264. //
  31265. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  31266. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  31267. return this.update( renderer, scene );
  31268. };
  31269. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  31270. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  31271. return this.renderTarget.clear( renderer, color, depth, stencil );
  31272. };
  31273. //
  31274. const GeometryUtils = {
  31275. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  31276. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  31277. let matrix;
  31278. if ( geometry2.isMesh ) {
  31279. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  31280. matrix = geometry2.matrix;
  31281. geometry2 = geometry2.geometry;
  31282. }
  31283. geometry1.merge( geometry2, matrix, materialIndexOffset );
  31284. },
  31285. center: function ( geometry ) {
  31286. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  31287. return geometry.center();
  31288. }
  31289. };
  31290. ImageUtils.crossOrigin = undefined;
  31291. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  31292. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  31293. const loader = new TextureLoader();
  31294. loader.setCrossOrigin( this.crossOrigin );
  31295. const texture = loader.load( url, onLoad, undefined, onError );
  31296. if ( mapping ) texture.mapping = mapping;
  31297. return texture;
  31298. };
  31299. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  31300. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  31301. const loader = new CubeTextureLoader();
  31302. loader.setCrossOrigin( this.crossOrigin );
  31303. const texture = loader.load( urls, onLoad, undefined, onError );
  31304. if ( mapping ) texture.mapping = mapping;
  31305. return texture;
  31306. };
  31307. ImageUtils.loadCompressedTexture = function () {
  31308. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  31309. };
  31310. ImageUtils.loadCompressedTextureCube = function () {
  31311. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  31312. };
  31313. //
  31314. function CanvasRenderer() {
  31315. console.error( 'THREE.CanvasRenderer has been removed' );
  31316. }
  31317. //
  31318. function JSONLoader() {
  31319. console.error( 'THREE.JSONLoader has been removed.' );
  31320. }
  31321. //
  31322. const SceneUtils = {
  31323. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  31324. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31325. },
  31326. detach: function ( /* child, parent, scene */ ) {
  31327. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31328. },
  31329. attach: function ( /* child, scene, parent */ ) {
  31330. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31331. }
  31332. };
  31333. //
  31334. function LensFlare() {
  31335. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  31336. }
  31337. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31338. /* eslint-disable no-undef */
  31339. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31340. revision: REVISION,
  31341. } } ) );
  31342. /* eslint-enable no-undef */
  31343. }
  31344. var THREE$1 = /*#__PURE__*/Object.freeze({
  31345. __proto__: null,
  31346. ACESFilmicToneMapping: ACESFilmicToneMapping,
  31347. AddEquation: AddEquation,
  31348. AddOperation: AddOperation,
  31349. AdditiveAnimationBlendMode: AdditiveAnimationBlendMode,
  31350. AdditiveBlending: AdditiveBlending,
  31351. AlphaFormat: AlphaFormat,
  31352. AlwaysDepth: AlwaysDepth,
  31353. AlwaysStencilFunc: AlwaysStencilFunc,
  31354. AmbientLight: AmbientLight,
  31355. AmbientLightProbe: AmbientLightProbe,
  31356. AnimationClip: AnimationClip,
  31357. AnimationLoader: AnimationLoader,
  31358. AnimationMixer: AnimationMixer,
  31359. AnimationObjectGroup: AnimationObjectGroup,
  31360. AnimationUtils: AnimationUtils,
  31361. ArcCurve: ArcCurve,
  31362. ArrayCamera: ArrayCamera,
  31363. ArrowHelper: ArrowHelper,
  31364. Audio: Audio,
  31365. AudioAnalyser: AudioAnalyser,
  31366. AudioContext: AudioContext,
  31367. AudioListener: AudioListener,
  31368. AudioLoader: AudioLoader,
  31369. AxesHelper: AxesHelper,
  31370. AxisHelper: AxisHelper,
  31371. BackSide: BackSide,
  31372. BasicDepthPacking: BasicDepthPacking,
  31373. BasicShadowMap: BasicShadowMap,
  31374. BinaryTextureLoader: BinaryTextureLoader,
  31375. Bone: Bone,
  31376. BooleanKeyframeTrack: BooleanKeyframeTrack,
  31377. BoundingBoxHelper: BoundingBoxHelper,
  31378. Box2: Box2,
  31379. Box3: Box3,
  31380. Box3Helper: Box3Helper,
  31381. BoxBufferGeometry: BoxBufferGeometry,
  31382. BoxGeometry: BoxGeometry,
  31383. BoxHelper: BoxHelper,
  31384. BufferAttribute: BufferAttribute,
  31385. BufferGeometry: BufferGeometry,
  31386. BufferGeometryLoader: BufferGeometryLoader,
  31387. ByteType: ByteType,
  31388. Cache: Cache,
  31389. Camera: Camera,
  31390. CameraHelper: CameraHelper,
  31391. CanvasRenderer: CanvasRenderer,
  31392. CanvasTexture: CanvasTexture,
  31393. CatmullRomCurve3: CatmullRomCurve3,
  31394. CineonToneMapping: CineonToneMapping,
  31395. CircleBufferGeometry: CircleBufferGeometry,
  31396. CircleGeometry: CircleGeometry,
  31397. ClampToEdgeWrapping: ClampToEdgeWrapping,
  31398. Clock: Clock,
  31399. ClosedSplineCurve3: ClosedSplineCurve3,
  31400. Color: Color,
  31401. ColorKeyframeTrack: ColorKeyframeTrack,
  31402. CompressedTexture: CompressedTexture,
  31403. CompressedTextureLoader: CompressedTextureLoader,
  31404. ConeBufferGeometry: ConeBufferGeometry,
  31405. ConeGeometry: ConeGeometry,
  31406. CubeCamera: CubeCamera,
  31407. CubeGeometry: BoxGeometry,
  31408. CubeReflectionMapping: CubeReflectionMapping,
  31409. CubeRefractionMapping: CubeRefractionMapping,
  31410. CubeTexture: CubeTexture,
  31411. CubeTextureLoader: CubeTextureLoader,
  31412. CubeUVReflectionMapping: CubeUVReflectionMapping,
  31413. CubeUVRefractionMapping: CubeUVRefractionMapping,
  31414. CubicBezierCurve: CubicBezierCurve,
  31415. CubicBezierCurve3: CubicBezierCurve3,
  31416. CubicInterpolant: CubicInterpolant,
  31417. CullFaceBack: CullFaceBack,
  31418. CullFaceFront: CullFaceFront,
  31419. CullFaceFrontBack: CullFaceFrontBack,
  31420. CullFaceNone: CullFaceNone,
  31421. Curve: Curve,
  31422. CurvePath: CurvePath,
  31423. CustomBlending: CustomBlending,
  31424. CustomToneMapping: CustomToneMapping,
  31425. CylinderBufferGeometry: CylinderBufferGeometry,
  31426. CylinderGeometry: CylinderGeometry,
  31427. Cylindrical: Cylindrical,
  31428. DataTexture: DataTexture,
  31429. DataTexture2DArray: DataTexture2DArray,
  31430. DataTexture3D: DataTexture3D,
  31431. DataTextureLoader: DataTextureLoader,
  31432. DataUtils: DataUtils,
  31433. DecrementStencilOp: DecrementStencilOp,
  31434. DecrementWrapStencilOp: DecrementWrapStencilOp,
  31435. DefaultLoadingManager: DefaultLoadingManager,
  31436. DepthFormat: DepthFormat,
  31437. DepthStencilFormat: DepthStencilFormat,
  31438. DepthTexture: DepthTexture,
  31439. DirectionalLight: DirectionalLight,
  31440. DirectionalLightHelper: DirectionalLightHelper,
  31441. DiscreteInterpolant: DiscreteInterpolant,
  31442. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  31443. DodecahedronGeometry: DodecahedronGeometry,
  31444. DoubleSide: DoubleSide,
  31445. DstAlphaFactor: DstAlphaFactor,
  31446. DstColorFactor: DstColorFactor,
  31447. DynamicBufferAttribute: DynamicBufferAttribute,
  31448. DynamicCopyUsage: DynamicCopyUsage,
  31449. DynamicDrawUsage: DynamicDrawUsage,
  31450. DynamicReadUsage: DynamicReadUsage,
  31451. EdgesGeometry: EdgesGeometry,
  31452. EdgesHelper: EdgesHelper,
  31453. EllipseCurve: EllipseCurve,
  31454. EqualDepth: EqualDepth,
  31455. EqualStencilFunc: EqualStencilFunc,
  31456. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  31457. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  31458. Euler: Euler,
  31459. EventDispatcher: EventDispatcher,
  31460. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  31461. ExtrudeGeometry: ExtrudeGeometry,
  31462. Face3: Face3,
  31463. Face4: Face4,
  31464. FaceColors: FaceColors,
  31465. FileLoader: FileLoader,
  31466. FlatShading: FlatShading,
  31467. Float16BufferAttribute: Float16BufferAttribute,
  31468. Float32Attribute: Float32Attribute,
  31469. Float32BufferAttribute: Float32BufferAttribute,
  31470. Float64Attribute: Float64Attribute,
  31471. Float64BufferAttribute: Float64BufferAttribute,
  31472. FloatType: FloatType,
  31473. Fog: Fog,
  31474. FogExp2: FogExp2,
  31475. Font: Font,
  31476. FontLoader: FontLoader,
  31477. FrontSide: FrontSide,
  31478. Frustum: Frustum,
  31479. GLBufferAttribute: GLBufferAttribute,
  31480. GLSL1: GLSL1,
  31481. GLSL3: GLSL3,
  31482. GammaEncoding: GammaEncoding,
  31483. Geometry: Geometry,
  31484. GeometryUtils: GeometryUtils,
  31485. GreaterDepth: GreaterDepth,
  31486. GreaterEqualDepth: GreaterEqualDepth,
  31487. GreaterEqualStencilFunc: GreaterEqualStencilFunc,
  31488. GreaterStencilFunc: GreaterStencilFunc,
  31489. GridHelper: GridHelper,
  31490. Group: Group,
  31491. HalfFloatType: HalfFloatType,
  31492. HemisphereLight: HemisphereLight,
  31493. HemisphereLightHelper: HemisphereLightHelper,
  31494. HemisphereLightProbe: HemisphereLightProbe,
  31495. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  31496. IcosahedronGeometry: IcosahedronGeometry,
  31497. ImageBitmapLoader: ImageBitmapLoader,
  31498. ImageLoader: ImageLoader,
  31499. ImageUtils: ImageUtils,
  31500. ImmediateRenderObject: ImmediateRenderObject,
  31501. IncrementStencilOp: IncrementStencilOp,
  31502. IncrementWrapStencilOp: IncrementWrapStencilOp,
  31503. InstancedBufferAttribute: InstancedBufferAttribute,
  31504. InstancedBufferGeometry: InstancedBufferGeometry,
  31505. InstancedInterleavedBuffer: InstancedInterleavedBuffer,
  31506. InstancedMesh: InstancedMesh,
  31507. Int16Attribute: Int16Attribute,
  31508. Int16BufferAttribute: Int16BufferAttribute,
  31509. Int32Attribute: Int32Attribute,
  31510. Int32BufferAttribute: Int32BufferAttribute,
  31511. Int8Attribute: Int8Attribute,
  31512. Int8BufferAttribute: Int8BufferAttribute,
  31513. IntType: IntType,
  31514. InterleavedBuffer: InterleavedBuffer,
  31515. InterleavedBufferAttribute: InterleavedBufferAttribute,
  31516. Interpolant: Interpolant,
  31517. InterpolateDiscrete: InterpolateDiscrete,
  31518. InterpolateLinear: InterpolateLinear,
  31519. InterpolateSmooth: InterpolateSmooth,
  31520. InvertStencilOp: InvertStencilOp,
  31521. JSONLoader: JSONLoader,
  31522. KeepStencilOp: KeepStencilOp,
  31523. KeyframeTrack: KeyframeTrack,
  31524. LOD: LOD,
  31525. LatheBufferGeometry: LatheBufferGeometry,
  31526. LatheGeometry: LatheGeometry,
  31527. Layers: Layers,
  31528. LensFlare: LensFlare,
  31529. LessDepth: LessDepth,
  31530. LessEqualDepth: LessEqualDepth,
  31531. LessEqualStencilFunc: LessEqualStencilFunc,
  31532. LessStencilFunc: LessStencilFunc,
  31533. Light: Light,
  31534. LightProbe: LightProbe,
  31535. Line: Line,
  31536. Line3: Line3,
  31537. LineBasicMaterial: LineBasicMaterial,
  31538. LineCurve: LineCurve,
  31539. LineCurve3: LineCurve3,
  31540. LineDashedMaterial: LineDashedMaterial,
  31541. LineLoop: LineLoop,
  31542. LinePieces: LinePieces,
  31543. LineSegments: LineSegments,
  31544. LineStrip: LineStrip,
  31545. LinearEncoding: LinearEncoding,
  31546. LinearFilter: LinearFilter,
  31547. LinearInterpolant: LinearInterpolant,
  31548. LinearMipMapLinearFilter: LinearMipMapLinearFilter,
  31549. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  31550. LinearMipmapLinearFilter: LinearMipmapLinearFilter,
  31551. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  31552. LinearToneMapping: LinearToneMapping,
  31553. Loader: Loader,
  31554. LoaderUtils: LoaderUtils,
  31555. LoadingManager: LoadingManager,
  31556. LogLuvEncoding: LogLuvEncoding,
  31557. LoopOnce: LoopOnce,
  31558. LoopPingPong: LoopPingPong,
  31559. LoopRepeat: LoopRepeat,
  31560. LuminanceAlphaFormat: LuminanceAlphaFormat,
  31561. LuminanceFormat: LuminanceFormat,
  31562. MOUSE: MOUSE,
  31563. Material: Material,
  31564. MaterialLoader: MaterialLoader,
  31565. Math: MathUtils,
  31566. MathUtils: MathUtils,
  31567. Matrix3: Matrix3,
  31568. Matrix4: Matrix4,
  31569. MaxEquation: MaxEquation,
  31570. Mesh: Mesh,
  31571. MeshBasicMaterial: MeshBasicMaterial,
  31572. MeshDepthMaterial: MeshDepthMaterial,
  31573. MeshDistanceMaterial: MeshDistanceMaterial,
  31574. MeshFaceMaterial: MeshFaceMaterial,
  31575. MeshLambertMaterial: MeshLambertMaterial,
  31576. MeshMatcapMaterial: MeshMatcapMaterial,
  31577. MeshNormalMaterial: MeshNormalMaterial,
  31578. MeshPhongMaterial: MeshPhongMaterial,
  31579. MeshPhysicalMaterial: MeshPhysicalMaterial,
  31580. MeshStandardMaterial: MeshStandardMaterial,
  31581. MeshToonMaterial: MeshToonMaterial,
  31582. MinEquation: MinEquation,
  31583. MirroredRepeatWrapping: MirroredRepeatWrapping,
  31584. MixOperation: MixOperation,
  31585. MultiMaterial: MultiMaterial,
  31586. MultiplyBlending: MultiplyBlending,
  31587. MultiplyOperation: MultiplyOperation,
  31588. NearestFilter: NearestFilter,
  31589. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  31590. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  31591. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  31592. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  31593. NeverDepth: NeverDepth,
  31594. NeverStencilFunc: NeverStencilFunc,
  31595. NoBlending: NoBlending,
  31596. NoColors: NoColors,
  31597. NoToneMapping: NoToneMapping,
  31598. NormalAnimationBlendMode: NormalAnimationBlendMode,
  31599. NormalBlending: NormalBlending,
  31600. NotEqualDepth: NotEqualDepth,
  31601. NotEqualStencilFunc: NotEqualStencilFunc,
  31602. NumberKeyframeTrack: NumberKeyframeTrack,
  31603. Object3D: Object3D,
  31604. ObjectLoader: ObjectLoader,
  31605. ObjectSpaceNormalMap: ObjectSpaceNormalMap,
  31606. OctahedronBufferGeometry: OctahedronBufferGeometry,
  31607. OctahedronGeometry: OctahedronGeometry,
  31608. OneFactor: OneFactor,
  31609. OneMinusDstAlphaFactor: OneMinusDstAlphaFactor,
  31610. OneMinusDstColorFactor: OneMinusDstColorFactor,
  31611. OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor,
  31612. OneMinusSrcColorFactor: OneMinusSrcColorFactor,
  31613. OrthographicCamera: OrthographicCamera,
  31614. PCFShadowMap: PCFShadowMap,
  31615. PCFSoftShadowMap: PCFSoftShadowMap,
  31616. PMREMGenerator: PMREMGenerator,
  31617. ParametricBufferGeometry: ParametricBufferGeometry,
  31618. ParametricGeometry: ParametricGeometry,
  31619. Particle: Particle,
  31620. ParticleBasicMaterial: ParticleBasicMaterial,
  31621. ParticleSystem: ParticleSystem,
  31622. ParticleSystemMaterial: ParticleSystemMaterial,
  31623. Path: Path,
  31624. PerspectiveCamera: PerspectiveCamera,
  31625. Plane: Plane,
  31626. PlaneBufferGeometry: PlaneBufferGeometry,
  31627. PlaneGeometry: PlaneGeometry,
  31628. PlaneHelper: PlaneHelper,
  31629. PointCloud: PointCloud,
  31630. PointCloudMaterial: PointCloudMaterial,
  31631. PointLight: PointLight,
  31632. PointLightHelper: PointLightHelper,
  31633. Points: Points,
  31634. PointsMaterial: PointsMaterial,
  31635. PolarGridHelper: PolarGridHelper,
  31636. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  31637. PolyhedronGeometry: PolyhedronGeometry,
  31638. PositionalAudio: PositionalAudio,
  31639. PropertyBinding: PropertyBinding,
  31640. PropertyMixer: PropertyMixer,
  31641. QuadraticBezierCurve: QuadraticBezierCurve,
  31642. QuadraticBezierCurve3: QuadraticBezierCurve3,
  31643. Quaternion: Quaternion,
  31644. QuaternionKeyframeTrack: QuaternionKeyframeTrack,
  31645. QuaternionLinearInterpolant: QuaternionLinearInterpolant,
  31646. REVISION: REVISION,
  31647. RGBADepthPacking: RGBADepthPacking,
  31648. RGBAFormat: RGBAFormat,
  31649. RGBAIntegerFormat: RGBAIntegerFormat,
  31650. RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format,
  31651. RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format,
  31652. RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format,
  31653. RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format,
  31654. RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format,
  31655. RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format,
  31656. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  31657. RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format,
  31658. RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format,
  31659. RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format,
  31660. RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format,
  31661. RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format,
  31662. RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format,
  31663. RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format,
  31664. RGBA_BPTC_Format: RGBA_BPTC_Format,
  31665. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  31666. RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format,
  31667. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  31668. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format$1,
  31669. RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format,
  31670. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  31671. RGBDEncoding: RGBDEncoding,
  31672. RGBEEncoding: RGBEEncoding,
  31673. RGBEFormat: RGBEFormat,
  31674. RGBFormat: RGBFormat,
  31675. RGBIntegerFormat: RGBIntegerFormat,
  31676. RGBM16Encoding: RGBM16Encoding,
  31677. RGBM7Encoding: RGBM7Encoding,
  31678. RGB_ETC1_Format: RGB_ETC1_Format,
  31679. RGB_ETC2_Format: RGB_ETC2_Format,
  31680. RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format,
  31681. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  31682. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  31683. RGFormat: RGFormat,
  31684. RGIntegerFormat: RGIntegerFormat,
  31685. RawShaderMaterial: RawShaderMaterial,
  31686. Ray: Ray,
  31687. Raycaster: Raycaster,
  31688. RectAreaLight: RectAreaLight,
  31689. RedFormat: RedFormat,
  31690. RedIntegerFormat: RedIntegerFormat,
  31691. ReinhardToneMapping: ReinhardToneMapping,
  31692. RepeatWrapping: RepeatWrapping,
  31693. ReplaceStencilOp: ReplaceStencilOp,
  31694. ReverseSubtractEquation: ReverseSubtractEquation,
  31695. RingBufferGeometry: RingBufferGeometry,
  31696. RingGeometry: RingGeometry,
  31697. SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format,
  31698. SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format,
  31699. SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format,
  31700. SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format,
  31701. SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format,
  31702. SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format,
  31703. SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format,
  31704. SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format,
  31705. SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format,
  31706. SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format,
  31707. SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format,
  31708. SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format,
  31709. SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format,
  31710. SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format,
  31711. Scene: Scene,
  31712. SceneUtils: SceneUtils,
  31713. ShaderChunk: ShaderChunk,
  31714. ShaderLib: ShaderLib,
  31715. ShaderMaterial: ShaderMaterial,
  31716. ShadowMaterial: ShadowMaterial,
  31717. Shape: Shape,
  31718. ShapeBufferGeometry: ShapeBufferGeometry,
  31719. ShapeGeometry: ShapeGeometry,
  31720. ShapePath: ShapePath,
  31721. ShapeUtils: ShapeUtils,
  31722. ShortType: ShortType,
  31723. Skeleton: Skeleton,
  31724. SkeletonHelper: SkeletonHelper,
  31725. SkinnedMesh: SkinnedMesh,
  31726. SmoothShading: SmoothShading,
  31727. Sphere: Sphere,
  31728. SphereBufferGeometry: SphereBufferGeometry,
  31729. SphereGeometry: SphereGeometry,
  31730. Spherical: Spherical,
  31731. SphericalHarmonics3: SphericalHarmonics3,
  31732. Spline: Spline,
  31733. SplineCurve: SplineCurve,
  31734. SplineCurve3: SplineCurve3,
  31735. SpotLight: SpotLight,
  31736. SpotLightHelper: SpotLightHelper,
  31737. Sprite: Sprite,
  31738. SpriteMaterial: SpriteMaterial,
  31739. SrcAlphaFactor: SrcAlphaFactor,
  31740. SrcAlphaSaturateFactor: SrcAlphaSaturateFactor,
  31741. SrcColorFactor: SrcColorFactor,
  31742. StaticCopyUsage: StaticCopyUsage,
  31743. StaticDrawUsage: StaticDrawUsage,
  31744. StaticReadUsage: StaticReadUsage,
  31745. StereoCamera: StereoCamera,
  31746. StreamCopyUsage: StreamCopyUsage,
  31747. StreamDrawUsage: StreamDrawUsage,
  31748. StreamReadUsage: StreamReadUsage,
  31749. StringKeyframeTrack: StringKeyframeTrack,
  31750. SubtractEquation: SubtractEquation,
  31751. SubtractiveBlending: SubtractiveBlending,
  31752. TOUCH: TOUCH,
  31753. TangentSpaceNormalMap: TangentSpaceNormalMap,
  31754. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  31755. TetrahedronGeometry: TetrahedronGeometry,
  31756. TextBufferGeometry: TextBufferGeometry,
  31757. TextGeometry: TextGeometry,
  31758. Texture: Texture,
  31759. TextureLoader: TextureLoader,
  31760. TorusBufferGeometry: TorusBufferGeometry,
  31761. TorusGeometry: TorusGeometry,
  31762. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  31763. TorusKnotGeometry: TorusKnotGeometry,
  31764. Triangle: Triangle,
  31765. TriangleFanDrawMode: TriangleFanDrawMode,
  31766. TriangleStripDrawMode: TriangleStripDrawMode,
  31767. TrianglesDrawMode: TrianglesDrawMode,
  31768. TubeBufferGeometry: TubeBufferGeometry,
  31769. TubeGeometry: TubeGeometry,
  31770. UVMapping: UVMapping,
  31771. Uint16Attribute: Uint16Attribute,
  31772. Uint16BufferAttribute: Uint16BufferAttribute,
  31773. Uint32Attribute: Uint32Attribute,
  31774. Uint32BufferAttribute: Uint32BufferAttribute,
  31775. Uint8Attribute: Uint8Attribute,
  31776. Uint8BufferAttribute: Uint8BufferAttribute,
  31777. Uint8ClampedAttribute: Uint8ClampedAttribute,
  31778. Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute,
  31779. Uniform: Uniform,
  31780. UniformsLib: UniformsLib,
  31781. UniformsUtils: UniformsUtils,
  31782. UnsignedByteType: UnsignedByteType,
  31783. UnsignedInt248Type: UnsignedInt248Type$1,
  31784. UnsignedIntType: UnsignedIntType,
  31785. UnsignedShort4444Type: UnsignedShort4444Type,
  31786. UnsignedShort5551Type: UnsignedShort5551Type,
  31787. UnsignedShort565Type: UnsignedShort565Type,
  31788. UnsignedShortType: UnsignedShortType,
  31789. VSMShadowMap: VSMShadowMap,
  31790. Vector2: Vector2$1,
  31791. Vector3: Vector3,
  31792. Vector4: Vector4,
  31793. VectorKeyframeTrack: VectorKeyframeTrack,
  31794. Vertex: Vertex,
  31795. VertexColors: VertexColors,
  31796. VideoTexture: VideoTexture,
  31797. WebGL1Renderer: WebGL1Renderer,
  31798. WebGLCubeRenderTarget: WebGLCubeRenderTarget,
  31799. WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget,
  31800. WebGLRenderTarget: WebGLRenderTarget,
  31801. WebGLRenderTargetCube: WebGLRenderTargetCube,
  31802. WebGLRenderer: WebGLRenderer,
  31803. WebGLUtils: WebGLUtils,
  31804. WireframeGeometry: WireframeGeometry,
  31805. WireframeHelper: WireframeHelper,
  31806. WrapAroundEnding: WrapAroundEnding,
  31807. XHRLoader: XHRLoader,
  31808. ZeroCurvatureEnding: ZeroCurvatureEnding,
  31809. ZeroFactor: ZeroFactor,
  31810. ZeroSlopeEnding: ZeroSlopeEnding,
  31811. ZeroStencilOp: ZeroStencilOp,
  31812. sRGBEncoding: sRGBEncoding
  31813. });
  31814. var points = [];
  31815. var lines = [];
  31816. var rings = [];
  31817. var precision = 0.1; //容错精度 //正常是0.01 但是在编辑时容易出现交错的线看不出来,导致需要getSliceLines 然后多出新增点
  31818. var getPoint = function(o, type){
  31819. var point;
  31820. if(typeof o == "string" || typeof o == "number")point = points.find(p=> p.ids.includes(o));
  31821. else {
  31822. point = points.find(p=> math.closeTo(p.x , o.x, precision) && math.closeTo(p.y , o.y, precision) );
  31823. if(!point) point = new Point(o.x, o.y,{record:true, id:o.id}, type);
  31824. else {
  31825. //console.log('addPoint', point, o)
  31826. point.addPoint(o.id);
  31827. }
  31828. }
  31829. if(!point){
  31830. console.log("no point!");
  31831. }
  31832. return point
  31833. };
  31834. var getLine = function(id){
  31835. return lines.find(line=> line.ids.includes(id));
  31836. };
  31837. var getAngleInfo = function(points){
  31838. var info = {};
  31839. info.angle = points[1].clone().sub(points[0]).angle();
  31840. if(math.closeTo(info.angle, Math.PI*2)){ //如360-0.01
  31841. info.angle -= Math.PI*2; //有可能得到负数-0.001
  31842. }else if(info.angle > Math.PI || math.closeTo(info.angle, Math.PI)){//如180+-0.01
  31843. info.angle -= Math.PI;
  31844. info.reverse = true;
  31845. }
  31846. return info //结果大约是 0 - 3.14
  31847. };
  31848. class Point extends Vector2$1{
  31849. constructor(x, y, o={}){
  31850. super(x, y);
  31851. if(o.record){
  31852. this.id = o.id;
  31853. if(this.id == void 0) this.id = "add_"+points.length;
  31854. this.ids = [this.id] ;//存储拥有该坐标的点原始数据的id
  31855. points.push(this);
  31856. }
  31857. this.type = o.type || "";
  31858. this.lines = [];
  31859. }
  31860. addPoint(id){
  31861. this.ids.push(id);
  31862. }
  31863. searchLineByFactor(dir, type, comeLine){
  31864. var lines = this.lines.filter(line=>line.searchTime<2);
  31865. if(lines.length==0)return;
  31866. else if(lines.length==1)return lines[0];
  31867. else lines = lines.filter(line=>line!=comeLine);
  31868. if(lines.length==1)return lines[0];
  31869. var result;
  31870. lines.forEach(line=>{
  31871. var vec = line.getVector();
  31872. if(line.points[1] == this) vec.negate();
  31873. var factor = math.getVec2Angle(dir, vec);
  31874. if(new Vector3(dir.x, dir.y, 0).cross(new Vector3(vec.x, vec.y, 0)).z<0) factor*= -1; /////
  31875. if(!result){
  31876. result = {line, factor};
  31877. }
  31878. else {
  31879. if(type == "min" && factor<result.factor || type == "max" && factor>result.factor) result = {line, factor};
  31880. }
  31881. });
  31882. return result.line;
  31883. }
  31884. }
  31885. var lineLen=0;
  31886. class Line$1{
  31887. constructor(o){
  31888. if(o.points[0] == o.points[1])return;
  31889. this.points = o.points;
  31890. this.type = o.type || 'line';
  31891. if(this.type == 'line'){
  31892. var oldLine = lines.find(line=>line.points.includes(o.points[0]) && line.points.includes(o.points[1]));
  31893. if(oldLine){
  31894. o.id != void 0 && oldLine.ids.push(o.id);
  31895. return oldLine;
  31896. }
  31897. this.id = o.id == void 0 ? ("line"+lineLen ++) : o.id;
  31898. this.ids = [this.id];
  31899. o.dontWriteToPoint || this.points.forEach((point)=>{point.lines.push(this);});
  31900. o.isChild || lines.push(this);
  31901. this.searchTime = 0; // 最多两次
  31902. }
  31903. this.children = [];//分割
  31904. this.parents = [];//分割
  31905. this.match = [];
  31906. }
  31907. getAngleInfo(){
  31908. var angleInfo = getAngleInfo(this.points);
  31909. this.angle = angleInfo.angle;
  31910. this.reverse = angleInfo.reverse;
  31911. }
  31912. getIntersectWithLine(line, precision){
  31913. var joint = line.points.find(point=>this.points.includes(point));
  31914. if(joint)return {point:joint, type:"joint"};
  31915. var intersect = math.isLineIntersect( line.points , this.points , false, precision );
  31916. if(intersect) return {point: intersect, type:"intersect"};
  31917. }
  31918. writeToPoint(){
  31919. this.points.forEach((point)=>{point.lines.includes(this) || point.lines.push(this);});
  31920. }
  31921. checkIfParent(line){
  31922. if(this == line){
  31923. return true;//原因就是slice的点和端点很近 误差导致
  31924. }
  31925. else return this.parents.find(e=>e.checkIfParent(line))
  31926. }
  31927. splitByPoint(point){
  31928. var line1 = new Line$1({points:[point, this.points[0]], dontWriteToPoint:true, hasntsure:true});
  31929. var line2 = new Line$1({points:[point, this.points[1]], dontWriteToPoint:true, hasntsure:true});
  31930. if(!line1.points || !line2.points){//有至少一个是点相同的,没写到group.lines里
  31931. console.warn('splitByPoint 线有点相同');
  31932. return;
  31933. }
  31934. if(this.checkIfParent(line1)||this.checkIfParent(line2) || line1.checkIfParent(this) || line2.checkIfParent(this)){
  31935. console.warn("splitByPoint 发现parent和children一样");//,请检查getSliceWalls,尤其 if(math.closeTo(line1.angle,line2.angle)){ 处
  31936. return;
  31937. }
  31938. var deal = (line)=>{
  31939. this.children.push(line);
  31940. line.parents.push(this);
  31941. if(!lines.includes(line))lines.push(line);
  31942. line.writeToPoint();
  31943. };
  31944. deal(line1);
  31945. deal(line2);
  31946. var index = this.points[0].lines.indexOf(this);
  31947. index > -1 && this.points[0].lines.splice(index,1);
  31948. var index = this.points[1].lines.indexOf(this);
  31949. index > -1 && this.points[1].lines.splice(index,1);
  31950. return [line1,line2]
  31951. }
  31952. splitByPoints(points){
  31953. points = points.map(point=>{return {dis:point.distanceTo(this.points[0]), point:point}});
  31954. points.sort((point1, point2)=>{return point1.dis - point2.dis});
  31955. var children = [];
  31956. points.forEach((point, index)=>{
  31957. var line1 = new Line$1({points:[point.point, index==0?this.points[0]:points[index-1].point ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31958. children.push(line1);
  31959. });
  31960. var line2 = new Line$1({points:[points[points.length-1].point, this.points[1] ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31961. children.push(line2);
  31962. var a = children.find(line=> !line.points || this.checkIfParent(line) || line.checkIfParent(this));
  31963. if(a){
  31964. console.error("splitByPoints return");
  31965. return;
  31966. }
  31967. children.forEach(line=>{
  31968. this.children.push(line);
  31969. line.parents.push(this);
  31970. if(!lines.includes(line))lines.push(line);
  31971. line.writeToPoint();
  31972. line.writeToPoint();
  31973. });
  31974. var index = this.points[0].lines.indexOf(this);
  31975. index > -1 && this.points[0].lines.splice(index,1);
  31976. var index = this.points[1].lines.indexOf(this);
  31977. index > -1 && this.points[1].lines.splice(index,1);
  31978. }
  31979. getAllSlices(){//如果有被分割的片段 就返回片段,否则返回自身
  31980. var children = [];
  31981. var traverse = function(elem){
  31982. if(elem.children.length == 0) children.push(elem);
  31983. else elem.children.forEach(traverse);
  31984. };
  31985. traverse(this);
  31986. return children
  31987. }
  31988. getVector(){
  31989. return this.points[1].clone().sub(this.points[0]);
  31990. }
  31991. getLength(){
  31992. return this.points[0].distanceTo(this.points[1])
  31993. }
  31994. getCenter(){
  31995. return this.points[1].clone().add(this.points[0]).multiplyScalar(.5);
  31996. }
  31997. }
  31998. var getMixedSet = function(arr1, arr2){//交集
  31999. return arr1.filter(item=>arr2.includes(item));
  32000. };
  32001. var getUnionSet = function(arr1, arr2){//并集
  32002. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  32003. };
  32004. var getDifferenceSet = function(arr1, arr2){//差集
  32005. var arr11 = arr1.filter(item=>!arr2.includes(item));
  32006. var arr22 = arr2.filter(item=>!arr1.includes(item));
  32007. return arr11.concat(arr22)
  32008. };
  32009. var getDifferenceSetMuti = function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  32010. var set = [];
  32011. arr.forEach(arr1=>{
  32012. arr1.forEach(item=>{
  32013. var index = set.indexOf(item);
  32014. if(index>-1){
  32015. set.splice(index, 1);
  32016. }else {
  32017. set.push(item);
  32018. }
  32019. });
  32020. });
  32021. return set;
  32022. };
  32023. function DoorAtWhichLine(points, lines){
  32024. var mid = points[0].clone().add(points[1]).multiplyScalar(0.5);
  32025. lines = lines.filter(line=>math.ifPointAtLineBound(mid, line.points, precision));
  32026. if(lines.length == 0)return
  32027. var result = {line:null, dis:Infinity};
  32028. lines.forEach(line=>{
  32029. var foot = math.getFootPoint(mid, line.points[0], line.points[1] );
  32030. var dis = foot.distanceTo(mid);
  32031. if(dis<result.dis){
  32032. result.line = line; result.dis = dis;
  32033. }
  32034. });
  32035. return result
  32036. }
  32037. var ringLen = 0;
  32038. class Ring{
  32039. constructor(o){
  32040. this.id = ringLen ++;
  32041. this.type = o.type || 'normal';
  32042. this.points = o.points;
  32043. this.lines = o.lines;
  32044. rings.push(this);
  32045. this.child = [];//包含的环
  32046. this.parent = [];//被包含的环
  32047. this.smallNeibours = [];//相邻最小环(存在和它有一个以上的相同边的最小环)
  32048. var area = math.getArea(this.points);
  32049. this.area = Math.abs(area);
  32050. this.isClockwise = area<0;//是否逆时针。一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  32051. }
  32052. }
  32053. var findLine = function(p1,p2){
  32054. return lines.find(line=>line.points.includes(p1) && line.points.includes(p2) )
  32055. };
  32056. var ifSamePart = function(checkPart , part){//checkPart中所包含的part片段是否和基准part的顺序一样(逆序也可以, 中间有其他数也可以,起始不同也行。比如 01234和204一样的)
  32057. var axis, startIndex, newCheckPart=[];
  32058. for(var j=0,len1 = checkPart.length; j<len1; j++){//将checkPart中比part多的数除去,使两个数组中包含的数完全相同。
  32059. if(part.indexOf(checkPart[j])>-1)newCheckPart.push(checkPart[j]);
  32060. }
  32061. for(var i=0,len = part.length; i<len; i++){
  32062. var index = newCheckPart.indexOf(part[i]);
  32063. if(index == -1)return false;
  32064. if(i == 0) startIndex = index;//标记第一个查找点对应的index
  32065. else if(i == 1){//标记查找顺序是正还是逆
  32066. axis = index - startIndex;
  32067. if(axis == len - 1) axis = -1;//刚好是首和尾
  32068. else if(axis == 1- len) axis = 1;
  32069. if(axis != -1 && axis != 1){
  32070. return false
  32071. }
  32072. }else {//判断是否是按顺序的
  32073. if(index != ((startIndex+axis * i + len) % len) ) return false;
  32074. }
  32075. }
  32076. return {sameAxis:axis>0}; //如果一样的话返回正逆是否相同
  32077. };
  32078. //或者判断是否有相同边(但是相同点是可以组成不同环)
  32079. var ifSameRing = function(ring1, ring2){//判断两个环是否相等。 除了可以逆向外顺序要对
  32080. if(ring1 instanceof Ring)ring1 = ring1.points;
  32081. if(ring2 instanceof Ring)ring2 = ring2.points;
  32082. if(ring1.length != ring2.length)return false;
  32083. if(ring1.lines && ring2.lines){
  32084. if(getDifferenceSet(ring1.lines , ring2.lines).length == 0)return true;//差集个数为0
  32085. }else {
  32086. if(ifSamePart(ring1, ring2))return true
  32087. }
  32088. };
  32089. var atWhichChildLine = function(point, line, precision){
  32090. if(line.children.length == 0){//这里可能要放低精度 保证能找到
  32091. if(math.ifPointAtLineBound(point, line.points, precision)) return line;
  32092. }else {
  32093. for(var i=0;i<line.children.length;i++){
  32094. var at = atWhichChildLine(point, line.children[i], precision);
  32095. if(at)return at
  32096. }
  32097. }
  32098. };
  32099. function getSliceLines(){
  32100. var len = lines.length;
  32101. var deal = function(line1,line2){
  32102. if(line1 == line2)return;
  32103. if(line1.angle == void 0) line1.getAngleInfo();
  32104. if(line2.angle == void 0) line2.getAngleInfo();
  32105. var intersect = line1.getIntersectWithLine(line2, precision);
  32106. if(intersect){
  32107. var point; //得到交点
  32108. if(intersect.type == "intersect"){
  32109. point = getPoint(intersect.point, "whenGetSliceLines");
  32110. var line1_ = atWhichChildLine(point, line1);
  32111. var line2_ = atWhichChildLine(point, line2);
  32112. //重合的情况还没考虑(平行)
  32113. if(!line1_) line1_ = atWhichChildLine(point, line1, precision);//降低精度
  32114. if(!line1_) line1_ = atWhichChildLine(point, line1, precision*2);//降低精度
  32115. if(!line2_) line2_ = atWhichChildLine(point, line2, precision);
  32116. if(!line2_) line2_ = atWhichChildLine(point, line2, precision*2);//降低精度
  32117. //拆分线条:
  32118. //如果还报错,找不到ChildLine,就直接返回吧 或者搞个循环 逐渐降低精度
  32119. if(!line1_ || !line2_){
  32120. console.warn("atWhichChildLine仍旧找不到 :" + line1.id + ',' + line2.id + ", pointId: "+point.id);
  32121. line1_ || console.warn("找不到line1");
  32122. line2_ || console.warn("找不到line2");
  32123. return;
  32124. }
  32125. if(line1_.points.find(p=>p == point) && line2_.points.find(p=>p == point)){//这个点是line1_、 line2_端点,不做处理
  32126. //console.log("joint型 "+point.id)
  32127. }else if(line1_.points.find(p=>p == point)){//T型交叉
  32128. line2_.splitByPoint(point);//加入到母线中,之后还先用母线判断交点
  32129. //console.log("T型交叉1 "+point.id)
  32130. }else if(line2_.points.find(p=>p == point)){//T型交叉
  32131. line1_.splitByPoint(point);
  32132. //console.log("T型交叉2 "+point.id)
  32133. }else {//十字交叉
  32134. line1_.splitByPoint(point);
  32135. line2_.splitByPoint(point);
  32136. }
  32137. }else {
  32138. point = intersect.point;//交点是端点
  32139. if(math.closeTo(line1.angle,line2.angle)){ //重合一部分
  32140. var children1 = line1.getAllSlices();
  32141. var children2 = line2.getAllSlices();
  32142. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  32143. children1.forEach(child1=>{
  32144. children2.forEach(child2=>{
  32145. deal(child1, child2);
  32146. });
  32147. });
  32148. return;
  32149. }
  32150. var anotherPoint1 = line1.points.find(point_=>point_!=point);
  32151. var anotherPoint2 = line2.points.find(point_=>point_!=point);
  32152. if(math.ifPointAtLineBound(anotherPoint1, line2.points)){
  32153. line2.splitByPoint(anotherPoint1);
  32154. }else if(math.ifPointAtLineBound(anotherPoint2, line1.points)){
  32155. line1.splitByPoint(anotherPoint2);
  32156. }
  32157. }
  32158. }
  32159. }else if(math.closeTo(line1.angle,line2.angle)){
  32160. var vec1 = line1.getVector();
  32161. var vec = line1.points[0].clone().sub(line2.points[0]);
  32162. var cos = math.getVec2Cos(vec1, vec);
  32163. if(math.closeTo(cos, -1, 1e-4) || math.closeTo(cos, 1, 1e-4)){ //共线
  32164. var children1 = line1.getAllSlices();
  32165. var children2 = line2.getAllSlices();
  32166. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  32167. children1.forEach(child1=>{
  32168. children2.forEach(child2=>{
  32169. deal(child1, child2);
  32170. });
  32171. });
  32172. return;
  32173. }
  32174. //判断是否重叠
  32175. var A = line1.points[0];
  32176. var C = line1.reverse == line2.reverse ? line2.points[0] : line2.points[1];
  32177. var B = line1.points[1];
  32178. var D = line1.reverse == line2.reverse ? line2.points[1] : line2.points[0];
  32179. var BC = C.clone().sub(B);
  32180. var AD = D.clone().sub(A);
  32181. if(BC.length()<AD.length()){
  32182. var BA = A.clone().sub(B);
  32183. if(math.getVec2Angle(BC, BA) >= 1.57 )return;//没有重叠部分
  32184. }else {
  32185. var AB = B.clone().sub(A);
  32186. if(math.getVec2Angle(AD, AB) >= 1.57 )return;
  32187. }
  32188. var f = function(line1,line2){
  32189. var one = math.ifPointAtLineBound(line1.points[0], line2.points);
  32190. var two = math.ifPointAtLineBound(line1.points[1], line2.points);
  32191. if(one && two){//line1在line2上
  32192. line2.splitByPoints( line1.points );
  32193. return true
  32194. }else if(one || two){//错开
  32195. var point1 = one ? line1.points[0] : line1.points[1];
  32196. var anotherPoint1 = one ? line1.points[1] : line1.points[0];
  32197. var dis1 = line2.points[0].distanceTo(anotherPoint1);
  32198. var dis2 = line2.points[1].distanceTo(anotherPoint1);
  32199. var point2 = dis1 < dis2 ? line2.points[0] : line2.points[1];
  32200. line1.splitByPoint(point2);
  32201. line2.splitByPoint(point1);
  32202. return true
  32203. }
  32204. };
  32205. f(line1, line2) || f(line2, line1);
  32206. }
  32207. }
  32208. };
  32209. for(let i=0;i<len;i++){
  32210. let line1 = lines[i];
  32211. for(let j=i+1;j<len;j++){
  32212. let line2 = lines[j];
  32213. deal(line1,line2);
  32214. }
  32215. }
  32216. //console.log("原有线条个数:"+len)
  32217. //lines = lines.filter((line)=>{return line.children.length == 0})
  32218. //console.log("现有线条个数:"+lines.length)
  32219. }
  32220. var bound = new Box2();
  32221. var build = function(o){
  32222. //融合了相近点
  32223. //根据bound 处理precision
  32224. o.points.forEach(p=>{
  32225. bound.expandByPoint(new Vector2$1(p.x,p.y));
  32226. });
  32227. if(o.precision != void 0){
  32228. precision = o.precision;
  32229. }else {
  32230. var boundSize = bound.getSize(new Vector2$1);
  32231. precision = MathUtils.clamp(Math.max(boundSize.x, boundSize.y) / 70, 0.2, 2);
  32232. }
  32233. o.points.forEach(point=>getPoint(point));//{x:..,y:..}
  32234. o.lines.forEach(line=>{ //{p1:id1. p2:id2}
  32235. new Line$1({points:[getPoint(line.p1), getPoint(line.p2)], id:line.id });
  32236. });
  32237. //注意:不能出现一条线的两个点坐标一致,否则寻路时方向出错。 所以手动融合下相近点。
  32238. };
  32239. var searchRings = function(o={}){
  32240. points = [];
  32241. lines = [];
  32242. rings = [];
  32243. lineLen = ringLen = 0;
  32244. o.points = o.points || [];
  32245. o.lines = o.lines || [];
  32246. build(o);
  32247. if(!o.dontSliceLines){
  32248. getSliceLines();
  32249. }
  32250. //查找最小回路:
  32251. //参考: 引入方向因子的最小回路、最大回路搜索算法.pdf
  32252. //方法: 逆时针寻找(标记)最外层大环 -->从走过的点开始逆时针寻找最小环(直到所有可走的路被走过两次)-->逆时针寻找最外层大环(直到所有可走的路被走过两次)-->..
  32253. //其中找大环时选择方向因子最小的路, 而小环则相反(但只有开始第一条路是一样的, 都是选择最左边的点的因子最小的路)。
  32254. //标记方法: 每条线需要被搜索两次才算完毕。搜索完毕的线退出搜索。(依据:搜索完全部最小回路后 , 在无向图中删除搜索过 2 次的边及孤立节点得到退化图 , 恰好构成最大回路。)
  32255. var searchTime = 0;
  32256. var addRingJudgeCount = 0;
  32257. var addRingJudge = function(ring, lines, connectedLines, type){// 处理拣出的片段
  32258. addRingJudgeCount++;
  32259. //console.log("addRingJudge points("+ type+"):"+ ring.map(point=>point.id) )
  32260. if(o.onlyGetOutRing && type == "small")return
  32261. if(type == "small" || o.onlyGetOutRing){//挑出回路:
  32262. var newRings = [];
  32263. while(ring.length){
  32264. var road = [];
  32265. var turnBack = false;
  32266. for(let i=0;i<ring.length;i++){
  32267. if(road.includes(ring[i])){//如果走到方才的点,可能形成回路。 无论是不是回路都要摘去这段。
  32268. var index = road.indexOf(ring[i]);
  32269. var pointArr = ring.slice(index, i);
  32270. var linesArr = lines.slice(index, i);
  32271. ring.splice(index,i-index);
  32272. lines.splice(index,i-index);
  32273. if(pointArr.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  32274. if( !rings.find(ring_=>ifSameRing(pointArr, ring_))) newRings.push( new Ring({points: pointArr, lines:linesArr}) );
  32275. }
  32276. turnBack = true;
  32277. break;
  32278. }else {
  32279. road.push(ring[i]);
  32280. turnBack = false;
  32281. }
  32282. }
  32283. if(!turnBack){//没有重复的点,那么就直接处理整条。
  32284. if(ring.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  32285. if( !rings.find(ring_=>ifSameRing(ring, ring_))) newRings.push( new Ring({points: ring, lines}) );
  32286. }
  32287. break;
  32288. }
  32289. }
  32290. if(type != 'small'){
  32291. newRings.forEach(e=>e.isOutRing = true);
  32292. }
  32293. //console.log(newRings)
  32294. }else {
  32295. return ring
  32296. }
  32297. };
  32298. var search = function(point2d, comeRoad, type, connectedLines){
  32299. searchTime++;
  32300. var goLine;
  32301. var direction;
  32302. if(type.includes("big")){
  32303. if(!comeRoad){
  32304. if(type.includes("Left")){//逆时针
  32305. direction = new Vector2$1(1,0);
  32306. }else {
  32307. direction = new Vector2$1(-1,0);
  32308. }
  32309. goLine = point2d.searchLineByFactor(direction,"min");
  32310. }else {
  32311. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  32312. direction = point2d.clone().sub(lastPoint);
  32313. goLine = point2d.searchLineByFactor(direction,"min", findLine(point2d, lastPoint));
  32314. }
  32315. }else {
  32316. if(!comeRoad){
  32317. //似乎找最小环时,第一条线也是找最小的因子,这样才能保证逆时针(除非只有顺时针一条路)
  32318. direction = new Vector2$1(1,0);
  32319. goLine = point2d.searchLineByFactor(direction,"min");
  32320. }else {
  32321. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  32322. direction = point2d.clone().sub(lastPoint);
  32323. goLine = point2d.searchLineByFactor(direction,"max", findLine(point2d, lastPoint));
  32324. }
  32325. }
  32326. if(!goLine)return
  32327. goLine.searchTime++;
  32328. connectedLines.includes(goLine) || connectedLines.push(goLine);
  32329. var nextPoint = goLine.points.find( point => point2d!=point );
  32330. //if( comeRoad && comeRoad.points[comeRoad.points.length - 1] == nextPoint ) return;//不能查找来时的方向(反方向)
  32331. //走不通就原路返回
  32332. var roadPoints = comeRoad ? comeRoad.points.concat([point2d]) : [point2d];//每个分叉都能构成一条新的road
  32333. var roadLines = comeRoad ? comeRoad.lines.concat([goLine]) : [goLine];
  32334. //走到第一个点就算停止,这时候可能得到一个环、或者一段走了两遍的线、或者一条线上带了些环。
  32335. if(nextPoint == roadPoints[0]) return addRingJudge(roadPoints, roadLines, connectedLines, type) //形成环
  32336. else {
  32337. /* var len = roadPoints.indexOf(nextPoint);
  32338. if( len > -1){ //走到走过的路的某一点 构成这段路的回路
  32339. var points = roadPoints.slice(len, roadPoints.length);
  32340. var lines = roadLines.slice(len, roadPoints.length);
  32341. addRingJudge(points, lines)
  32342. }else{ */
  32343. return search(nextPoint, {lines:roadLines, points:roadPoints}, type, connectedLines);//继续寻路
  32344. //}
  32345. }
  32346. };
  32347. while(1){//搜寻一次大环
  32348. var connectedLines = [];//被搜寻过的且searchTime<2的线。一旦全部搜完就说明该连通区域搜寻完毕,继续查下一个连通区域。
  32349. var startPoint = null;
  32350. points.forEach(point=>{//找出x最小的点
  32351. if(!point.lines.find(line=>line.searchTime<2))return;
  32352. if(!startPoint)startPoint = point;
  32353. else if(point.x < startPoint.x)startPoint = point;
  32354. });
  32355. if(!startPoint)break; //说明全部找完
  32356. var ring = search(startPoint, null, "bigLeft", connectedLines);//逆时针
  32357. //search(startPoint, null, "bigRight", connectedLines);//顺时针(为了防止最外层不是回路之前写了顺时针,但如果是回路就会走重复。后来发现只要逆时针即可,因为走完后剩下的可以再次找大环)
  32358. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  32359. while(connectedLines.length>0){//目标是顺着connectedLines把所有连通的小环都找到
  32360. let points_ = [];//connectedLines中所有的点
  32361. connectedLines.forEach(line=>line.points.forEach(point=>{if(!points_.includes(point))points_.push(point); }));
  32362. var startPoint = null;
  32363. points_.forEach(point=>{//找出x最小的点
  32364. if(!point.lines.find(line=>line.searchTime<2))return;
  32365. if(!startPoint)startPoint = point;
  32366. else if(point.x < startPoint.x)startPoint = point;
  32367. });
  32368. if(!startPoint)break;
  32369. search(startPoint, null, "small", connectedLines);
  32370. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  32371. }
  32372. }
  32373. /* if(o.onlyGetOutRing){
  32374. rings = rings.filter(e=>e.isOutRing)
  32375. } */
  32376. //console.log("searchTime "+searchTime + ", addRingJudgeCount " +addRingJudgeCount)
  32377. //找出所有的相邻关系,包括公共边
  32378. var len = rings.length;
  32379. for(let i=0; i<len; i++){
  32380. let ring1 = rings[i];
  32381. for(let j=i+1; j<len; j++){
  32382. let ring2 = rings[j];
  32383. var bothHasLines = getMixedSet(ring1.lines, ring2.lines);
  32384. if(bothHasLines.length){//ring1oíring2?àáú
  32385. ring1.smallNeibours.push(ring2);
  32386. ring2.smallNeibours.push(ring1);
  32387. }else {
  32388. }
  32389. }
  32390. }
  32391. rings.forEach(ring1=>{
  32392. for(let i=0; i<len; i++){
  32393. var ring2 = rings[i];
  32394. if(ring1 == ring2 || ring1.smallNeibours.includes(ring2))continue;
  32395. let inside;
  32396. for(let u=0;u<ring1.points.length;u++){
  32397. inside = math.isPointInArea(ring2.points, null, ring1.points[u]);
  32398. if(!inside)break
  32399. else if(inside && !inside.atLine){
  32400. break
  32401. }
  32402. }
  32403. if(inside){ //只要其中一个点在ring2内,就说明ring1是内环
  32404. if(inside.atLine){//(还是会存在点全在线上的情况,这时候判断中心点)
  32405. var center = math.getCenterOfGravityPoint(ring1.points);
  32406. let inside1 = math.isPointInArea(ring2.points, null, center);
  32407. if(!inside1){
  32408. continue
  32409. }
  32410. }
  32411. ring2.child.push(ring1);
  32412. ring1.parent.push(ring2);
  32413. }
  32414. }
  32415. });
  32416. //去除非最小的ring 是否应该检测parent child?
  32417. /*
  32418. like this:
  32419. |———————————————————————|
  32420. |———|———————|———————| |
  32421. | | | | |
  32422. | |———————|———————| |
  32423. |———————————————————————|
  32424. */
  32425. var wiseRings = rings.filter(r=>!r.isClockwise);//一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  32426. if(wiseRings.length > 0){
  32427. //console.log('%c存在非最小的ring! 进行处理:',"color:#00f");
  32428. wiseRings.forEach(ring=>{ //(此案例验证出smallNeibours就是它的最小构成,可以再看看别的案例)
  32429. if(ring.smallNeibours.length>0){//另:如果内部只有一个,说明它是最小环,不需要处理
  32430. var is = false;
  32431. var difference = getDifferenceSet(ring.lines , getDifferenceSetMuti(ring.smallNeibours.concat(ring.child).map(ring=>ring.lines)));//获取所有smallNeibours和child的边中没有重复过的边(就是outline) 和该ring的线比较
  32432. is = difference.every(line=> ring.child.find(r=>r.lines.includes(line)) ); //多出的线只能是child中的线
  32433. if(is){
  32434. console.log('%c删除非最小环 ring'+ring.id,"color:#00f");
  32435. console.log(ring);
  32436. rings.splice(rings.indexOf(ring), 1);
  32437. ring.child.forEach(c=>{var index = c.parent.indexOf(ring);index>-1 && c.parent.splice(index,1);});
  32438. ring.parent.forEach(c=>{var index = c.child.indexOf(ring);index>-1 && c.child.splice(index,1);});
  32439. ring.smallNeibours.forEach(c=>{var index = c.smallNeibours.indexOf(ring);index>-1 && c.smallNeibours.splice(index,1);});
  32440. }
  32441. }
  32442. });
  32443. }
  32444. /* rings = rings.filter(ring=>{
  32445. rings = rings.filter(ring=>{
  32446. var enoughSize = ring.area > 0.5
  32447. if(!enoughSize){console.log('因面积过小去除ring '+ring.id + " , area: "+ring.area)}
  32448. return enoughSize
  32449. })
  32450. rings.forEach(ring=>{
  32451. if(ring.closetChilds){
  32452. ring.closetChilds = ring.closetChilds.filter(e=>rings.includes(e))
  32453. }
  32454. })
  32455. return rings
  32456. }) */ //在dealRings前不能随意删除rings,因为判断是否是最小环时需要全部的环
  32457. rings.forEach(ring=>{ //这里和cad中的不太一样, cad中双数个parent算外环,单数内环; 这里不分内外, 只看有无parent child
  32458. if(ring.parent.length){
  32459. ring.closetParent = ring.parent.find(ring_ => ring_.parent.length == ring.parent.length - 1);//最近一层的大环就是比它的parent个数少一的
  32460. ring.closetParent.closetChilds || (ring.closetParent.closetChilds = []);//内环可能多个
  32461. ring.closetParent.closetChilds.push(ring);
  32462. }
  32463. });
  32464. //console.log(rings)
  32465. var _ring = rings.map(ring=>{
  32466. var data = {
  32467. id: ring.id,
  32468. points: ring.points.map(point=>{return {id: point.ids[0], x:point.x, y:point.y}}),
  32469. /* doors : o.doors.filter(door=>{
  32470. if(ring.closetChilds){
  32471. var childOutLines = getDifferenceSetMuti(ring.closetChilds.map(ring=>ring.lines)) //最近子环的外边
  32472. return ring.lines.concat(childOutLines).includes(door.atLine)
  32473. }else{
  32474. return ring.lines.includes(door.atLine)
  32475. }
  32476. }), */
  32477. area:ring.area,
  32478. closetParent : ring.closetParent && ring.closetParent.id,
  32479. closetChilds : ring.closetChilds && ring.closetChilds.map(e=>e.id)
  32480. };
  32481. return data
  32482. });
  32483. //console.log(JSON.stringify(_ring))
  32484. return _ring
  32485. };
  32486. var math = {
  32487. getBaseLog(x, y) {//返回以 x 为底 y 的对数(即 logx y) . Math.log 返回一个数的自然对数
  32488. return Math.log(y) / Math.log(x);
  32489. }
  32490. ,
  32491. convertVector : {
  32492. ZupToYup: function(e){//navvis -> 4dkk
  32493. return new Vector3(e.x,e.z,-e.y)
  32494. },
  32495. YupToZup: function(e){//4dkk -> navvis
  32496. return new Vector3(e.x,-e.z,e.y)
  32497. },
  32498. },
  32499. convertQuaternion: {
  32500. ZupToYup: function(e){//navvis -> 4dkk //不同于convertVisionQuaternion
  32501. let rotation = new Euler(-Math.PI/2,0,0);
  32502. let quaternion = new Quaternion().setFromEuler(rotation);
  32503. return e.clone().premultiply(quaternion)
  32504. //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)))
  32505. },
  32506. YupToZup: function(e){//4dkk -> navvis
  32507. let rotation = new Euler(Math.PI/2,0,0);
  32508. let quaternion = new Quaternion().setFromEuler(rotation);
  32509. return e.clone().premultiply(quaternion)
  32510. },
  32511. },
  32512. convertVisionQuaternion: function(e) {
  32513. return new Quaternion(e.x,e.z,-e.y,e.w).multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(90)))
  32514. },
  32515. invertVisionQuaternion : function(e) {//反转给算法部
  32516. var a = e.clone().multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(-90)));
  32517. return new Quaternion(a.x,-a.z,a.y,a.w)
  32518. },
  32519. //------------
  32520. getVec2Angle : function(dir1,dir2){
  32521. return Math.acos( MathUtils.clamp(this.getVec2Cos(dir1,dir2), -1,1) )
  32522. },
  32523. getVec2Cos : function(dir1,dir2){
  32524. return dir1.dot(dir2) / dir1.length() / dir2.length()
  32525. },
  32526. getAngle:function(vec1, vec2, axis){//带方向的角度 vector3
  32527. var angle = vec1.angleTo(vec2);
  32528. var axis_ = vec1.clone().cross(vec2);
  32529. if(typeof axis == 'string'){
  32530. if(axis_[axis] < 0){
  32531. angle *= -1;
  32532. }
  32533. }else {//vector3
  32534. if(axis_.dot(axis)< 0){
  32535. angle *= -1;
  32536. }
  32537. }
  32538. return angle
  32539. },
  32540. closeTo : function(a,b, precision=1e-6){
  32541. let f = (a,b)=>{
  32542. return Math.abs(a-b) < precision;
  32543. };
  32544. if(typeof (a) == 'number'){
  32545. return f(a, b);
  32546. }else {
  32547. let judge = (name)=>{
  32548. if(a[name] == void 0)return true //有值就判断,没值就不判断
  32549. else return f(a[name],b[name])
  32550. };
  32551. return judge('x') && judge('y') && judge('z') && judge('w')
  32552. }
  32553. },
  32554. toPrecision: function (e, t) {//xzw change 保留小数
  32555. var f = function (e, t) {
  32556. var i = Math.pow(10, t);
  32557. return Math.round(e * i) / i
  32558. };
  32559. if (e instanceof Array) {
  32560. for (var s = 0; s < e.length; s++) {
  32561. e[s] = f(e[s], t);
  32562. }
  32563. return e;
  32564. } else if (e instanceof Object) {
  32565. for (var s in e) {
  32566. e[s] = f(e[s], t);
  32567. }
  32568. return e;
  32569. } else return f(e, t)
  32570. },
  32571. isEmptyQuaternion: function(e) {
  32572. return 0 === Math.abs(e.x) && 0 === Math.abs(e.y) && 0 === Math.abs(e.z) && 0 === Math.abs(e.w)
  32573. },
  32574. projectPositionToCanvas: function(e, t, i) {
  32575. i = i || new Vector3,
  32576. i.copy(e);
  32577. var r = .5 * $('#player').width()
  32578. , o = .5 * $('#player').height();
  32579. return i.project(t),
  32580. i.x = i.x * r + r,
  32581. i.y = -(i.y * o) + o,
  32582. i
  32583. },
  32584. handelPadResize:false,
  32585. /* handelPadding : function () { //去除player左边和上面的宽高,因为pc的player左上有其他element 许钟文
  32586. var pads = [];//记录下来避免反复计算
  32587. var index = [];
  32588. var resetPad = function(){
  32589. pads = [];
  32590. index = [];
  32591. math.handelPadResize = false; //switchview时resized为true
  32592. }
  32593. if(config.isEdit && !config.isMobile){
  32594. window.addEventListener('resize',resetPad);
  32595. }
  32596. return function(x, y, domE){
  32597. if(!config.isEdit || config.isMobile) {
  32598. return {
  32599. x: x,
  32600. y: y
  32601. }
  32602. }
  32603. if(this.handelPadResize)resetPad();
  32604. domE = domE || $('#player')[0];
  32605. var pad;
  32606. var i = index.indexOf(domE);
  32607. if (i == -1){
  32608. index.push(domE);
  32609. pad = {
  32610. x: this.getOffset("left", domE),
  32611. y: this.getOffset("top", domE)
  32612. }
  32613. pads.push(pad)
  32614. }
  32615. else pad = pads[i];
  32616. return {
  32617. x: x - pad.x,
  32618. y: y - pad.y
  32619. }
  32620. }
  32621. }(), */
  32622. getOffset: function (type, element, parent) {//获取元素的边距 许钟文
  32623. var offset = (type == "left") ? element.offsetLeft : element.offsetTop;
  32624. if (!parent) parent = $("body")[0];
  32625. while (element = element.offsetParent) {
  32626. if (element == parent) break;
  32627. offset += (type == "left") ? element.offsetLeft : element.offsetTop;
  32628. }
  32629. return offset;
  32630. }
  32631. ,
  32632. constrainedTurn: function(e) {
  32633. var t = e % (2 * Math.PI);
  32634. return t = t > Math.PI ? t -= 2 * Math.PI : t < -Math.PI ? t += 2 * Math.PI : t
  32635. },
  32636. getFOVDotThreshold: function(e) {
  32637. return Math.cos(MathUtils.degToRad(e / 2))
  32638. },
  32639. transform2DForwardVectorByCubeFace: function(e, t, i, n) {
  32640. switch (e) {
  32641. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  32642. i.set(1, t.y, t.x);
  32643. break;
  32644. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  32645. i.set(-1, t.y, -t.x);
  32646. break;
  32647. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  32648. i.set(-t.x, 1, -t.y);
  32649. break;
  32650. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  32651. i.set(-t.x, -1, t.y);
  32652. break;
  32653. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  32654. i.set(-t.x, t.y, 1);
  32655. break;
  32656. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  32657. i.set(t.x, t.y, -1);
  32658. }
  32659. n && i.normalize();
  32660. },
  32661. getFootPoint : function(oldPos, p1, p2, restricInline){ //找oldPos在线段p1, p2上的垂足
  32662. /* if(isWorld){//输出全局坐标 需要考虑meshGroup.position
  32663. p1 = p1.clone();
  32664. p2 = p2.clone();
  32665. p1.y += mainDesign.meshGroup.position.y;
  32666. p2.y += mainDesign.meshGroup.position.y;
  32667. } */
  32668. if(p1.equals(p2))return p1.clone()
  32669. var op1 = oldPos.clone().sub(p1);
  32670. var p1p2 = p1.clone().sub(p2);
  32671. var p1p2Len = p1p2.length();
  32672. var leftLen = op1.dot(p1p2) / p1p2Len;
  32673. var pos = p1.clone().add(p1p2.multiplyScalar( leftLen/p1p2Len ));
  32674. if(restricInline && pos.clone().sub(p1).dot( pos.clone().sub(p2) ) > 0){//foot不在线段上
  32675. if(pos.distanceTo(p1) < pos.distanceTo(p2)) pos = p1.clone();
  32676. else pos = p2.clone();
  32677. }
  32678. return pos;
  32679. },
  32680. /**
  32681. * 计算多边形的重心
  32682. * @param {*} points
  32683. */
  32684. getCenterOfGravityPoint : function(mPoints){
  32685. var area = 0.0;//多边形面积
  32686. var Gx = 0.0, Gy = 0.0;// 重心的x、y
  32687. for (var i = 1; i <= mPoints.length; i++) {
  32688. var ix = mPoints[i % mPoints.length].x;
  32689. var iy = mPoints[i % mPoints.length].y;
  32690. var nx = mPoints[i - 1].x;
  32691. var ny = mPoints[i - 1].y;
  32692. var temp = (ix * ny - iy * nx) / 2.0;
  32693. area += temp;
  32694. Gx += temp * (ix + nx) / 3.0;
  32695. Gy += temp * (iy + ny) / 3.0;
  32696. }
  32697. Gx = Gx / area;
  32698. Gy = Gy / area;
  32699. return { x: Gx, y: Gy };
  32700. },
  32701. getBound : function(ring){
  32702. var bound = new Box2();
  32703. for(var j=0,len = ring.length; j<len; j++){
  32704. bound.expandByPoint(ring[j]);
  32705. }
  32706. return bound;
  32707. },
  32708. isPointInArea : function(ring, holes, point, ifAtLine){//判断点是否在某个环内, 若传递了holes代表还要不能在内环内
  32709. var bound = this.getBound(ring);
  32710. if(point.x < bound.min.x || point.x > bound.max.x || point.y < bound.min.y || point.y > bound.max.y)return false;
  32711. var inside = false;
  32712. var x = point.x,
  32713. y = point.y;
  32714. for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
  32715. var xi = ring[i].x,
  32716. yi = ring[i].y;
  32717. var xj = ring[j].x,
  32718. yj = ring[j].y;
  32719. if((xi - x)*(yj - y) == (xi - x)*(yi - y) && x>=Math.min(xi,xj) && x<=Math.max(xi,xj)//xzw add
  32720. && y>=Math.min(yi,yj) && y<=Math.max(yi,yj)
  32721. ){
  32722. //return !!ifAtLine;//在线段上,则判断为…… (默认在外)
  32723. return {atLine:true}
  32724. }
  32725. if (((yi > y) != (yj > y)) &&
  32726. (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
  32727. ) {
  32728. inside = !inside;
  32729. }
  32730. }
  32731. if(inside && holes){
  32732. return !holes.some(ring=>this.isPointInArea(ring, null, point, ifAtLine) ) //不能存在于任何一个二级内环内
  32733. }else {
  32734. return inside;
  32735. }
  32736. },
  32737. getArea : function (ring) { //求面积 顺时针为正 来自three shape
  32738. for (var t = ring.length, i = 0, n = t - 1, r = 0; r < t; n = r++)
  32739. i += ring[n].x * ring[r].y - ring[r].x * ring[n].y;
  32740. return -.5 * i
  32741. },
  32742. isInBetween : function(a, b, c, precision) {
  32743. // 如果b几乎等于a或c,返回false.为了避免浮点运行时两值几乎相等,但存在相差0.00000...0001的这种情况出现使用下面方式进行避免
  32744. /* if (Math.abs(a - b) < 0.000001 || Math.abs(b - c) < 0.000001) {
  32745. return false;
  32746. }
  32747. return (a <= b && b <= c) || (c <= b && b <= a);*/
  32748. //更改:如果b和a或c中一个接近 就算在a和c之间
  32749. return (a <= b && b <= c) || (c <= b && b <= a) || this.closeTo(a,b,precision) || this.closeTo(b,c,precision);
  32750. },
  32751. ifPointAtLineBound:function(point, linePoints, precision){
  32752. //待验证 横线和竖线比较特殊
  32753. return math.isInBetween(linePoints[0].x, point.x, linePoints[1].x, precision) && math.isInBetween(linePoints[0].y, point.y, linePoints[1].y, precision)
  32754. }
  32755. ,
  32756. isLineIntersect: function (line1, line2, notSegment, precision) {//线段和线段是否有交点. notSegment代表是直线而不是线段
  32757. var a1 = line1[1].y - line1[0].y;
  32758. var b1 = line1[0].x - line1[1].x;
  32759. var c1 = a1 * line1[0].x + b1 * line1[0].y;
  32760. //转换成一般式: Ax+By = C
  32761. var a2 = line2[1].y - line2[0].y;
  32762. var b2 = line2[0].x - line2[1].x;
  32763. var c2 = a2 * line2[0].x + b2 * line2[0].y;
  32764. // 计算交点
  32765. var d = a1 * b2 - a2 * b1;
  32766. // 当d==0时,两线平行
  32767. if (d == 0) {
  32768. return false;
  32769. } else {
  32770. var x = (b2 * c1 - b1 * c2) / d;
  32771. var y = (a1 * c2 - a2 * c1) / d;
  32772. // 检测交点是否在两条线段上
  32773. /* if (notSegment || (isInBetween(line1[0].x, x, line1[1].x) || isInBetween(line1[0].y, y, line1[1].y)) &&
  32774. (isInBetween(line2[0].x, x, line2[1].x) || isInBetween(line2[0].y, y, line2[1].y))) {
  32775. return {x,y};
  32776. } */
  32777. if (notSegment || math.ifPointAtLineBound({x,y}, line1, precision) && math.ifPointAtLineBound({x,y}, line2, precision)){
  32778. return {x,y};
  32779. }
  32780. }
  32781. },
  32782. getNormal2d : function(o={} ){//获取二维法向量 方向向内
  32783. var x,y, x1,y1;
  32784. //line2d的向量
  32785. if(o.vec){
  32786. x1 = o.vec.x; y1 = o.vec.y;
  32787. }else {
  32788. x1 = o.p1.x - o.p2.x;
  32789. y1 = o.p1.y - o.p2.y;
  32790. }
  32791. //假设法向量的x或y固定为1或-1
  32792. if(y1 != 0){
  32793. x = 1;
  32794. y = - (x1 * x) / y1;
  32795. }else if(x1 != 0){//y如果为0,正常情况x不会是0
  32796. y = 1;
  32797. x = - (y1 * y) / x1;
  32798. }else {
  32799. console.log("两个点一样");
  32800. return null;
  32801. }
  32802. //判断方向里或者外:
  32803. var vNormal = new Vector3(x, 0, y);
  32804. var vLine = new Vector3(x1, 0, y1);
  32805. var vDir = vNormal.cross(vLine);
  32806. if(vDir.y>0){
  32807. x *= -1;
  32808. y *= -1;
  32809. }
  32810. return new Vector2$1(x, y).normalize();
  32811. },
  32812. getQuaBetween2Vector:function(oriVec, newVec, upVec){ //获取从oriVec旋转到newVec可以应用的quaternion
  32813. var angle = oriVec.angleTo(newVec);
  32814. var axis = oriVec.clone().cross( newVec).normalize();//两个up之间
  32815. if(axis.length() == 0){//当夹角为180 或 0 度时,得到的axis为(0,0,0),故使用备用的指定upVec
  32816. return new Quaternion().setFromAxisAngle( upVec, angle );
  32817. }
  32818. return new Quaternion().setFromAxisAngle( axis, angle );
  32819. }
  32820. /* ,
  32821. getQuaBetween2Vector2 : function(oriVec, newVec ){//not camera
  32822. var _ = (new THREE.Matrix4).lookAt( oriVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  32823. var aimQua = (new THREE.Quaternion).setFromRotationMatrix(_)
  32824. var _2 = (new THREE.Matrix4).lookAt( newVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  32825. var aimQua2 = (new THREE.Quaternion).setFromRotationMatrix(_2)
  32826. return aimQua2.multiply(aimQua.clone().inverse())
  32827. } */
  32828. ,
  32829. getScaleForConstantSize : function(){ //获得规定二维大小的mesh的scale值。可以避免因camera的projection造成的mesh视觉大小改变。 来源:tag.updateDisc
  32830. var w;
  32831. var i = new Vector3, o = new Vector3, l = new Vector3, c = new Vector3, h = new Vector3;
  32832. return function(op={}){
  32833. if(op.width2d) w = op.width2d; //如果恒定二维宽度
  32834. else {//否则考虑上距离,加一丢丢近大远小的效果
  32835. var currentDis, nearBound, farBound;
  32836. if(op.camera.type == "OrthographicCamera"){
  32837. currentDis = 200 / op.camera.zoom; //(op.camera.right - op.camera.left) / op.camera.zoom
  32838. }else {
  32839. currentDis = op.position.distanceTo(op.camera.position);
  32840. }
  32841. w = op.maxSize - ( op.maxSize - op.minSize) * MathUtils.smoothstep(currentDis, op.nearBound, op.farBound);
  32842. //maxSize : mesh要表现的最大像素宽度; nearBound: 最近距离,若比nearBound近,则使用maxSize
  32843. }
  32844. i.copy(op.position).project(op.camera), //tag中心在屏幕上的二维坐标
  32845. o.set(op.resolution.x / 2, op.resolution.y / 2, 1).multiply(i), //转化成px -w/2 到 w/2的范围
  32846. l.set(w / 2, 0, 0).add(o), //加上tag宽度的一半
  32847. c.set(2 / op.resolution.x, 2 / op.resolution.y, 1).multiply(l), //再转回 -1 到 1的范围
  32848. h.copy(c).unproject(op.camera);//再转成三维坐标,求得tag边缘的位置
  32849. var g = h.distanceTo(op.position);//就能得到tag的三维半径
  32850. //这里使用的都是resolution2, 好处是手机端不会太小, 坏处是pc更改网页显示百分比时显示的大小会变(或许可以自己算出设备真实的deviceRatio, 因window.screen是不会改变的),但考虑到用户可以自行调节字大小也许是好的
  32851. return g //可能NAN 当相机和position重叠时
  32852. }
  32853. }()
  32854. ,
  32855. //W , H, left, top分别是rect的宽、高、左、上
  32856. getCrossPointAtRect : function(p1, aim, W , H, left, top){//求射线p1-aim在rect边界上的交点,其中aim在rect范围内,p1则不一定(交点在aim这边的延长线上)
  32857. var x,y, borderX;
  32858. var r = (aim.x - p1.x) / (aim.y - p1.y);//根据相似三角形原理先求出这个比值
  32859. var getX = function(y){
  32860. return r * (y-p1.y) + p1.x;
  32861. };
  32862. var getY = function(x){
  32863. return 1/r * (x-p1.x) + p1.y;
  32864. };
  32865. if(aim.x >= p1.x){
  32866. borderX = W+left;
  32867. }else {
  32868. borderX = left;
  32869. }
  32870. x = borderX;
  32871. y = getY(x);
  32872. if(y < top || y > top+H){
  32873. if(y < top){
  32874. y = top;
  32875. }else {
  32876. y = top+H;
  32877. }
  32878. x = getX(y);
  32879. }
  32880. return new Vector2$1(x, y);
  32881. },
  32882. getDirFromUV : function(uv){ //获取dir 反向计算 - - 二维转三维比较麻烦
  32883. var dirB; //所求 单位向量
  32884. var y = Math.cos(uv.y * Math.PI); //uv中纵向可以直接确定y, 根据上面getUVfromDir的反向计算
  32885. // 故 uv.y * Math.PI 就是到垂直线(向上)的夹角
  32886. var angle = 2 * Math.PI * uv.x - Math.PI; //x/z代表的是角度
  32887. var axisX, axisZ; //axis为1代表是正,-1是负数
  32888. if (-Math.PI <= angle && angle < 0) {
  32889. axisX = -1; //下半圆
  32890. } else {
  32891. axisX = 1; //上半圆
  32892. }
  32893. if (-Math.PI / 2 <= angle && angle < Math.PI / 2) {
  32894. axisZ = 1; //右半圆
  32895. } else {
  32896. axisZ = -1; //左半圆
  32897. }
  32898. var XDivideZ = Math.tan(angle);
  32899. var z = Math.sqrt((1 - y * y) / (1 + XDivideZ * XDivideZ));
  32900. var x = XDivideZ * z;
  32901. if (z * axisZ < 0) { //异号
  32902. z *= -1;
  32903. x *= -1;
  32904. if (x * axisX < 0) {
  32905. // console.log("wrong!!!!!??????????")
  32906. }
  32907. }
  32908. x *= -1; //计算完成后这里不能漏掉 *= -1
  32909. dirB = this.convertVector.YupToZup(new Vector3(x, y, z));
  32910. //理想状态下x和z和anotherDir相同
  32911. return dirB
  32912. },
  32913. getUVfromDir : function(dir) { //获取UV 同shader里的计算
  32914. var dir = this.convertVector.ZupToYup(dir);
  32915. dir.x *= -1; //计算前这里不能漏掉 *= -1 见shader
  32916. var tx = Math.atan2(dir.x, dir.z) / (Math.PI * 2.0) + 0.5; //atan2(y,x) 返回从 X 轴正向逆时针旋转到点 (x,y) 时经过的角度。区间是-PI 到 PI 之间的值
  32917. var ty = Math.acos(dir.y) / Math.PI;
  32918. return new Vector2$1(tx, ty)
  32919. //理想状态下tx相同
  32920. },
  32921. getDirByLonLat : function(lon,lat){
  32922. var dir = new Vector3;
  32923. var phi = MathUtils.degToRad(90 - lat);
  32924. var theta = MathUtils.degToRad(lon);
  32925. dir.x = Math.sin(phi) * Math.cos(theta);
  32926. dir.y = Math.cos(phi);
  32927. dir.z = Math.sin(phi) * Math.sin(theta);
  32928. return dir
  32929. } //0,0 => (1,0,0) 270=>(0,0,-1)
  32930. ,
  32931. projectPointAtPlane:function(o={}){//获取一个点在一个面上的投影 {facePoints:[a,b,c], point:}
  32932. var plane = new Plane().setFromCoplanarPoints(...o.facePoints);
  32933. return plane.projectPoint(o.point, new Vector3() )
  32934. }
  32935. ,
  32936. getPolygonsMixedRings:function( polygons, onlyGetOutRing){//{points:[vector2,...],holes:[[],[]]}
  32937. let points = [];
  32938. let lines = [];
  32939. let i = 0;
  32940. polygons.forEach(e=> points.push(...e.map(a=>new Vector2$1().copy(a) )) );
  32941. polygons.forEach((ps,j)=>{
  32942. let length = ps.length;
  32943. let index = 0;
  32944. while(index<length){
  32945. lines.push({p1:index+i,p2:(index+1)%length+i});
  32946. index ++;
  32947. }
  32948. i+=length;
  32949. });
  32950. points.forEach((p,j)=>{p.id = j;});
  32951. let rings = searchRings({
  32952. points,
  32953. lines,
  32954. onlyGetOutRing
  32955. });
  32956. //console.log(rings)
  32957. rings = rings.filter(e=>e.closetParent == void 0);// 子环不加,被外环包含了
  32958. return rings
  32959. },
  32960. getQuaFromPosAim( position, target ){
  32961. let matrix = (new Matrix4).lookAt(position, target, new Vector3(0,0,1));
  32962. return (new Quaternion).setFromRotationMatrix(matrix)
  32963. },
  32964. getBoundByPoints(points, minSize){
  32965. var bound = new Box3;
  32966. points.forEach(point=>{
  32967. bound.expandByPoint(point);
  32968. });
  32969. let center = bound.getCenter(new Vector3);
  32970. if(minSize){
  32971. let minBound = (new Box3()).setFromCenterAndSize(center, minSize);
  32972. bound.union(minBound);
  32973. }
  32974. return {
  32975. bounding:bound,
  32976. size: bound.getSize(new Vector3),
  32977. center,
  32978. }
  32979. },
  32980. };
  32981. Potree.math = math;
  32982. !function() {
  32983. if ("performance"in window == 0 && (window.performance = {}),
  32984. "now"in window.performance == 0) {
  32985. var e = Date.now();
  32986. performance.timing && performance.timing.navigationStart && (e = performance.timing.navigationStart),
  32987. window.performance.now = function() {
  32988. return Date.now() - e
  32989. };
  32990. }
  32991. }(),
  32992. WebGLRenderer.prototype.paramThreeToGL = function(e) {
  32993. var t, i = this.extensions, r = this.getContext();//context;
  32994. if (e === RepeatWrapping)
  32995. return r.REPEAT;
  32996. if (e === ClampToEdgeWrapping)
  32997. return r.CLAMP_TO_EDGE;
  32998. if (e === MirroredRepeatWrapping)
  32999. return r.MIRRORED_REPEAT;
  33000. if (e === NearestFilter)
  33001. return r.NEAREST;
  33002. if (e === NearestMipMapNearestFilter)
  33003. return r.NEAREST_MIPMAP_NEAREST;
  33004. if (e === NearestMipMapLinearFilter)
  33005. return r.NEAREST_MIPMAP_LINEAR;
  33006. if (e === LinearFilter)
  33007. return r.LINEAR;
  33008. if (e === LinearMipMapNearestFilter)
  33009. return r.LINEAR_MIPMAP_NEAREST;
  33010. if (e === LinearMipMapLinearFilter)
  33011. return r.LINEAR_MIPMAP_LINEAR;
  33012. if (e === UnsignedByteType)
  33013. return r.UNSIGNED_BYTE;
  33014. if (e === UnsignedShort4444Type)
  33015. return r.UNSIGNED_SHORT_4_4_4_4;
  33016. if (e === UnsignedShort5551Type)
  33017. return r.UNSIGNED_SHORT_5_5_5_1;
  33018. if (e === UnsignedShort565Type)
  33019. return r.UNSIGNED_SHORT_5_6_5;
  33020. if (e === ByteType)
  33021. return r.BYTE;
  33022. if (e === ShortType)
  33023. return r.SHORT;
  33024. if (e === UnsignedShortType)
  33025. return r.UNSIGNED_SHORT;
  33026. if (e === IntType)
  33027. return r.INT;
  33028. if (e === UnsignedIntType)
  33029. return r.UNSIGNED_INT;
  33030. if (e === FloatType)
  33031. return r.FLOAT;
  33032. if (t = i.get("OES_texture_half_float"),
  33033. null !== t && e === HalfFloatType)
  33034. return t.HALF_FLOAT_OES;
  33035. if (e === AlphaFormat)
  33036. return r.ALPHA;
  33037. if (e === RGBFormat)
  33038. return r.RGB;
  33039. if (e === RGBAFormat)
  33040. return r.RGBA;
  33041. if (e === LuminanceFormat)
  33042. return r.LUMINANCE;
  33043. if (e === LuminanceAlphaFormat)
  33044. return r.LUMINANCE_ALPHA;
  33045. if (e === AddEquation)
  33046. return r.FUNC_ADD;
  33047. if (e === SubtractEquation)
  33048. return r.FUNC_SUBTRACT;
  33049. if (e === ReverseSubtractEquation)
  33050. return r.FUNC_REVERSE_SUBTRACT;
  33051. if (e === ZeroFactor)
  33052. return r.ZERO;
  33053. if (e === OneFactor)
  33054. return r.ONE;
  33055. if (e === SrcColorFactor)
  33056. return r.SRC_COLOR;
  33057. if (e === OneMinusSrcColorFactor)
  33058. return r.ONE_MINUS_SRC_COLOR;
  33059. if (e === SrcAlphaFactor)
  33060. return r.SRC_ALPHA;
  33061. if (e === OneMinusSrcAlphaFactor)
  33062. return r.ONE_MINUS_SRC_ALPHA;
  33063. if (e === DstAlphaFactor)
  33064. return r.DST_ALPHA;
  33065. if (e === OneMinusDstAlphaFactor)
  33066. return r.ONE_MINUS_DST_ALPHA;
  33067. if (e === DstColorFactor)
  33068. return r.DST_COLOR;
  33069. if (e === OneMinusDstColorFactor)
  33070. return r.ONE_MINUS_DST_COLOR;
  33071. if (e === SrcAlphaSaturateFactor)
  33072. return r.SRC_ALPHA_SATURATE;
  33073. if (t = i.get("WEBGL_compressed_texture_s3tc"),
  33074. null !== t) {
  33075. if (e === RGB_S3TC_DXT1_Format)
  33076. return t.COMPRESSED_RGB_S3TC_DXT1_EXT;
  33077. if (e === RGBA_S3TC_DXT1_Format$1)
  33078. return t.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33079. if (e === RGBA_S3TC_DXT3_Format)
  33080. return t.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33081. if (e === RGBA_S3TC_DXT5_Format$1)
  33082. return t.COMPRESSED_RGBA_S3TC_DXT5_EXT
  33083. }
  33084. if (t = i.get("WEBGL_compressed_texture_pvrtc"),
  33085. null !== t) {
  33086. if (e === RGB_PVRTC_4BPPV1_Format)
  33087. return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  33088. if (e === RGB_PVRTC_2BPPV1_Format)
  33089. return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  33090. if (e === RGBA_PVRTC_4BPPV1_Format)
  33091. return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  33092. if (e === RGBA_PVRTC_2BPPV1_Format)
  33093. return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  33094. }
  33095. if (t = i.get("WEBGL_compressed_texture_etc1"),
  33096. null !== t && e === RGB_ETC1_Format)
  33097. return t.COMPRESSED_RGB_ETC1_WEBGL;
  33098. if (t = i.get("EXT_blend_minmax"),
  33099. null !== t) {
  33100. if (e === MinEquation)
  33101. return t.MIN_EXT;
  33102. if (e === MaxEquation)
  33103. return t.MAX_EXT
  33104. }
  33105. return 0
  33106. };
  33107. /* ,
  33108. THREE.WebGLState = function(e, t, i) {
  33109. var r = this
  33110. , o = new THREE.Vector4
  33111. , a = e.getParameter(e.MAX_VERTEX_ATTRIBS)
  33112. , s = new Uint8Array(a)
  33113. , l = new Uint8Array(a)
  33114. , c = new Uint8Array(a)
  33115. , h = {}
  33116. , u = null
  33117. , d = null
  33118. , p = null
  33119. , f = null
  33120. , g = null
  33121. , m = null
  33122. , v = null
  33123. , A = null
  33124. , y = !1
  33125. , C = null
  33126. , I = null
  33127. , E = null
  33128. , b = null
  33129. , w = null
  33130. , _ = null
  33131. , T = null
  33132. , x = null
  33133. , S = null
  33134. , M = null
  33135. , R = null
  33136. , P = null
  33137. , O = null
  33138. , L = null
  33139. , D = null
  33140. , N = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)
  33141. , B = void 0
  33142. , F = {}
  33143. , V = new THREE.Vector4
  33144. , U = null
  33145. , k = null
  33146. , H = new THREE.Vector4
  33147. , G = new THREE.Vector4;
  33148. this.init = function() {
  33149. this.clearColor(0, 0, 0, 1),
  33150. this.clearDepth(1),
  33151. this.clearStencil(0),
  33152. this.enable(e.DEPTH_TEST),
  33153. e.depthFunc(e.LEQUAL),
  33154. e.frontFace(e.CCW),
  33155. e.cullFace(e.BACK),
  33156. this.enable(e.CULL_FACE),
  33157. this.enable(e.BLEND),
  33158. e.blendEquation(e.FUNC_ADD),
  33159. e.blendFunc(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA)
  33160. }
  33161. ,
  33162. this.initAttributes = function() {
  33163. for (var e = 0, t = s.length; e < t; e++)
  33164. s[e] = 0
  33165. }
  33166. ,
  33167. this.enableAttribute = function(i) {
  33168. if (s[i] = 1,
  33169. 0 === l[i] && (e.enableVertexAttribArray(i),
  33170. l[i] = 1),
  33171. 0 !== c[i]) {
  33172. var n = t.get("ANGLE_instanced_arrays");
  33173. n.vertexAttribDivisorANGLE(i, 0),
  33174. c[i] = 0
  33175. }
  33176. }
  33177. ,
  33178. this.enableAttributeAndDivisor = function(t, i, n) {
  33179. s[t] = 1,
  33180. 0 === l[t] && (e.enableVertexAttribArray(t),
  33181. l[t] = 1),
  33182. c[t] !== i && (n.vertexAttribDivisorANGLE(t, i),
  33183. c[t] = i)
  33184. }
  33185. ,
  33186. this.disableUnusedAttributes = function() {
  33187. for (var t = 0, i = l.length; t < i; t++)
  33188. l[t] !== s[t] && (e.disableVertexAttribArray(t),
  33189. l[t] = 0)
  33190. }
  33191. ,
  33192. this.enable = function(t) {
  33193. h[t] !== !0 && (e.enable(t),
  33194. h[t] = !0)
  33195. }
  33196. ,
  33197. this.disable = function(t) {
  33198. h[t] !== !1 && (e.disable(t),
  33199. h[t] = !1)
  33200. }
  33201. ,
  33202. this.getCompressedTextureFormats = function() {
  33203. if (null === u && (u = [],
  33204. t.get("WEBGL_compressed_texture_pvrtc") || t.get("WEBGL_compressed_texture_s3tc") || t.get("WEBGL_compressed_texture_etc1")))
  33205. for (var i = e.getParameter(e.COMPRESSED_TEXTURE_FORMATS), n = 0; n < i.length; n++)
  33206. u.push(i[n]);
  33207. return u
  33208. }
  33209. ,
  33210. this.setBlending = function(t, r, o, a, s, l, c, h) {
  33211. t === THREE.NoBlending ? this.disable(e.BLEND) : this.enable(e.BLEND),
  33212. t === d && h === y || (t === THREE.AdditiveBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33213. e.blendFuncSeparate(e.ONE, e.ONE, e.ONE, e.ONE)) : (e.blendEquation(e.FUNC_ADD),
  33214. e.blendFunc(e.SRC_ALPHA, e.ONE)) : t === THREE.SubtractiveBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33215. e.blendFuncSeparate(e.ZERO, e.ZERO, e.ONE_MINUS_SRC_COLOR, e.ONE_MINUS_SRC_ALPHA)) : (e.blendEquation(e.FUNC_ADD),
  33216. e.blendFunc(e.ZERO, e.ONE_MINUS_SRC_COLOR)) : t === THREE.MultiplyBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33217. e.blendFuncSeparate(e.ZERO, e.ZERO, e.SRC_COLOR, e.SRC_ALPHA)) : (e.blendEquation(e.FUNC_ADD),
  33218. e.blendFunc(e.ZERO, e.SRC_COLOR)) : h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33219. e.blendFuncSeparate(e.ONE, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA)) : (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33220. e.blendFuncSeparate(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA)),
  33221. d = t,
  33222. y = h),
  33223. t === THREE.CustomBlending ? (s = s || r,
  33224. l = l || o,
  33225. c = c || a,
  33226. r === p && s === m || (e.blendEquationSeparate(i(r), i(s)),
  33227. p = r,
  33228. m = s),
  33229. o === f && a === g && l === v && c === A || (e.blendFuncSeparate(i(o), i(a), i(l), i(c)),
  33230. f = o,
  33231. g = a,
  33232. v = l,
  33233. A = c)) : (p = null,
  33234. f = null,
  33235. g = null,
  33236. m = null,
  33237. v = null,
  33238. A = null)
  33239. }
  33240. ,
  33241. this.setDepthFunc = function(t) {
  33242. if (C !== t) {
  33243. if (t)
  33244. switch (t) {
  33245. case THREE.NeverDepth:
  33246. e.depthFunc(e.NEVER);
  33247. break;
  33248. case THREE.AlwaysDepth:
  33249. e.depthFunc(e.ALWAYS);
  33250. break;
  33251. case THREE.LessDepth:
  33252. e.depthFunc(e.LESS);
  33253. break;
  33254. case THREE.LessEqualDepth:
  33255. e.depthFunc(e.LEQUAL);
  33256. break;
  33257. case THREE.EqualDepth:
  33258. e.depthFunc(e.EQUAL);
  33259. break;
  33260. case THREE.GreaterEqualDepth:
  33261. e.depthFunc(e.GEQUAL);
  33262. break;
  33263. case THREE.GreaterDepth:
  33264. e.depthFunc(e.GREATER);
  33265. break;
  33266. case THREE.NotEqualDepth:
  33267. e.depthFunc(e.NOTEQUAL);
  33268. break;
  33269. default:
  33270. e.depthFunc(e.LEQUAL)
  33271. }
  33272. else
  33273. e.depthFunc(e.LEQUAL);
  33274. C = t
  33275. }
  33276. }
  33277. ,
  33278. this.setDepthTest = function(t) {
  33279. t ? this.enable(e.DEPTH_TEST) : this.disable(e.DEPTH_TEST)
  33280. }
  33281. ,
  33282. this.setDepthWrite = function(t) {
  33283. I !== t && (e.depthMask(t),
  33284. I = t)
  33285. }
  33286. ,
  33287. this.setColorWrite = function(t) {
  33288. E !== t && (e.colorMask(t, t, t, t),
  33289. E = t)
  33290. }
  33291. ,
  33292. this.setStencilFunc = function(t, i, n) {
  33293. w === t && _ === i && T === n || (e.stencilFunc(t, i, n),
  33294. w = t,
  33295. _ = i,
  33296. T = n)
  33297. }
  33298. ,
  33299. this.setStencilOp = function(t, i, n) {
  33300. x === t && S === i && M === n || (e.stencilOp(t, i, n),
  33301. x = t,
  33302. S = i,
  33303. M = n)
  33304. }
  33305. ,
  33306. this.setStencilTest = function(t) {
  33307. t ? this.enable(e.STENCIL_TEST) : this.disable(e.STENCIL_TEST)
  33308. }
  33309. ,
  33310. this.setStencilWrite = function(t) {
  33311. b !== t && (e.stencilMask(t),
  33312. b = t)
  33313. }
  33314. ,
  33315. this.setFlipSided = function(t) {
  33316. R !== t && (t ? e.frontFace(e.CW) : e.frontFace(e.CCW),
  33317. R = t)
  33318. }
  33319. ,
  33320. this.setLineWidth = function(t) {
  33321. t !== P && (e.lineWidth(t),
  33322. P = t)
  33323. }
  33324. ,
  33325. this.setPolygonOffset = function(t, i, n) {
  33326. t ? this.enable(e.POLYGON_OFFSET_FILL) : this.disable(e.POLYGON_OFFSET_FILL),
  33327. !t || O === i && L === n || (e.polygonOffset(i, n),
  33328. O = i,
  33329. L = n)
  33330. }
  33331. ,
  33332. this.getScissorTest = function() {
  33333. return D
  33334. }
  33335. ,
  33336. this.setScissorTest = function(t) {
  33337. D = t,
  33338. t ? this.enable(e.SCISSOR_TEST) : this.disable(e.SCISSOR_TEST)
  33339. }
  33340. ,
  33341. this.activeTexture = function(t) {
  33342. void 0 === t && (t = e.TEXTURE0 + N - 1),
  33343. B !== t && (e.activeTexture(t),
  33344. B = t)
  33345. }
  33346. ,
  33347. this.bindTexture = function(t, i) {
  33348. void 0 === B && r.activeTexture();
  33349. var n = F[B];
  33350. void 0 === n && (n = {
  33351. type: void 0,
  33352. texture: void 0
  33353. },
  33354. F[B] = n),
  33355. n.type === t && n.texture === i || (e.bindTexture(t, i),
  33356. n.type = t,
  33357. n.texture = i)
  33358. }
  33359. ,
  33360. this.compressedTexImage2D = function() {
  33361. try {
  33362. e.compressedTexImage2D.apply(e, arguments)
  33363. } catch (e) {
  33364. console.error(e)
  33365. }
  33366. }
  33367. ,
  33368. this.texImage2D = function() {
  33369. try {
  33370. e.texImage2D.apply(e, arguments)
  33371. } catch (e) {
  33372. console.error(e)
  33373. }
  33374. }
  33375. ,
  33376. this.clearColor = function(t, i, n, r) {
  33377. o.set(t, i, n, r),
  33378. V.equals(o) === !1 && (e.clearColor(t, i, n, r),
  33379. V.copy(o))
  33380. }
  33381. ,
  33382. this.clearDepth = function(t) {
  33383. U !== t && (e.clearDepth(t),
  33384. U = t)
  33385. }
  33386. ,
  33387. this.clearStencil = function(t) {
  33388. k !== t && (e.clearStencil(t),
  33389. k = t)
  33390. }
  33391. ,
  33392. this.scissor = function(t) {
  33393. H.equals(t) === !1 && (e.scissor(t.x, t.y, t.z, t.w),
  33394. H.copy(t))
  33395. }
  33396. ,
  33397. this.viewport = function(t) {
  33398. G.equals(t) === !1 && (e.viewport(t.x, t.y, t.z, t.w),
  33399. G.copy(t))
  33400. }
  33401. ,
  33402. this.reset = function() {
  33403. for (var t = 0; t < l.length; t++)
  33404. 1 === l[t] && (e.disableVertexAttribArray(t),
  33405. l[t] = 0);
  33406. h = {},
  33407. u = null,
  33408. B = void 0,
  33409. F = {},
  33410. d = null,
  33411. E = null,
  33412. I = null,
  33413. b = null,
  33414. R = null
  33415. }
  33416. } */
  33417. const XHRFactory = {
  33418. config: {
  33419. withCredentials: false,
  33420. customHeaders: [
  33421. { header: null, value: null }
  33422. ]
  33423. },
  33424. createXMLHttpRequest: function () {
  33425. let xhr = new XMLHttpRequest();
  33426. if (this.config.customHeaders &&
  33427. Array.isArray(this.config.customHeaders) &&
  33428. this.config.customHeaders.length > 0) {
  33429. let baseOpen = xhr.open;
  33430. let customHeaders = this.config.customHeaders;
  33431. xhr.open = function () {
  33432. baseOpen.apply(this, [].slice.call(arguments));
  33433. customHeaders.forEach(function (customHeader) {
  33434. if (!!customHeader.header && !!customHeader.value) {
  33435. xhr.setRequestHeader(customHeader.header, customHeader.value);
  33436. }
  33437. });
  33438. };
  33439. }
  33440. return xhr;
  33441. }
  33442. };
  33443. let Shaders = {};
  33444. Shaders["pointcloud.vs"] = `
  33445. precision highp float;
  33446. precision highp int;
  33447. #define max_clip_polygons 8
  33448. #define PI 3.141592653589793
  33449. #if defined(usePanoMap)
  33450. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  33451. uniform samplerCube pano1Map;
  33452. uniform float progress;
  33453. uniform float easeInOutRatio;
  33454. uniform vec3 pano0Position;
  33455. uniform mat4 pano0Matrix;
  33456. uniform vec3 pano1Position;
  33457. uniform mat4 pano1Matrix;
  33458. /*
  33459. varying vec3 vWorldPosition0;
  33460. varying vec3 vWorldPosition1;
  33461. */
  33462. #endif
  33463. //--------------
  33464. attribute vec3 position;
  33465. attribute vec3 color;
  33466. attribute float intensity;
  33467. attribute float classification;
  33468. attribute float returnNumber;
  33469. attribute float numberOfReturns;
  33470. attribute float pointSourceID;
  33471. attribute vec4 indices; //每个点的index
  33472. attribute float spacing;
  33473. attribute float gpsTime;
  33474. attribute vec3 normal;
  33475. attribute float aExtra;
  33476. uniform mat4 modelMatrix;
  33477. uniform mat4 modelViewMatrix;
  33478. uniform mat4 projectionMatrix;
  33479. uniform mat4 viewMatrix;
  33480. uniform mat4 uViewInv;
  33481. //uniform float uScreenWidth;
  33482. //uniform float uScreenHeight;
  33483. uniform vec2 resolution;
  33484. uniform float fov;
  33485. uniform float near;
  33486. uniform float far;
  33487. uniform bool uDebug;
  33488. uniform bool uUseOrthographicCamera;
  33489. uniform float uOrthoWidth;
  33490. uniform float uOrthoHeight;
  33491. #define CLIPTASK_NONE 0
  33492. #define CLIPTASK_HIGHLIGHT 1
  33493. #define CLIPTASK_SHOW_INSIDE 2
  33494. #define CLIPTASK_SHOW_OUTSIDE 3
  33495. #define CLIPMETHOD_INSIDE_ANY 0
  33496. #define CLIPMETHOD_INSIDE_ALL 1
  33497. uniform int clipTask;
  33498. uniform int clipMethod;
  33499. #if defined(num_clipboxes) && num_clipboxes > 0
  33500. uniform mat4 clipBoxes[num_clipboxes];
  33501. #endif
  33502. #if defined(num_clipspheres) && num_clipspheres > 0
  33503. uniform mat4 uClipSpheres[num_clipspheres];
  33504. #endif
  33505. #if defined(num_clippolygons) && num_clippolygons > 0
  33506. uniform int uClipPolygonVCount[num_clippolygons];
  33507. uniform vec3 uClipPolygonVertices[num_clippolygons * 8];
  33508. uniform mat4 uClipPolygonWVP[num_clippolygons];
  33509. #endif
  33510. uniform float size;
  33511. uniform float minSize;
  33512. uniform float maxSize;
  33513. uniform float uPCIndex;
  33514. uniform float uOctreeSpacing;
  33515. uniform float uNodeSpacing;
  33516. uniform float uOctreeSize;
  33517. uniform vec3 uBBSize;
  33518. uniform float uLevel;
  33519. uniform float uVNStart;
  33520. uniform bool uIsLeafNode;
  33521. uniform vec3 uColor;
  33522. uniform float uOpacity;
  33523. varying float vOpacity; //add
  33524. uniform vec2 elevationRange;
  33525. uniform vec2 intensityRange;
  33526. uniform vec2 uFilterReturnNumberRange;
  33527. uniform vec2 uFilterNumberOfReturnsRange;
  33528. uniform vec2 uFilterPointSourceIDClipRange;
  33529. uniform vec2 uFilterGPSTimeClipRange;
  33530. //uniform float ufilterByNormalThreshold;
  33531. uniform float uGpsScale;
  33532. uniform float uGpsOffset;
  33533. uniform vec2 uNormalizedGpsBufferRange;
  33534. uniform vec3 uIntensity_gbc;
  33535. uniform vec3 uRGB_gbc;
  33536. uniform vec3 uExtra_gbc;
  33537. uniform float uTransition;
  33538. uniform float wRGB;
  33539. uniform float wIntensity;
  33540. uniform float wElevation;
  33541. uniform float wClassification;
  33542. uniform float wReturnNumber;
  33543. uniform float wSourceID;
  33544. uniform vec2 uExtraNormalizedRange;
  33545. uniform vec2 uExtraRange;
  33546. uniform float uExtraScale;
  33547. uniform float uExtraOffset;
  33548. uniform vec3 uShadowColor;
  33549. uniform sampler2D visibleNodes;
  33550. uniform sampler2D gradient;
  33551. uniform sampler2D classificationLUT;
  33552. #if defined(color_type_matcap)
  33553. uniform sampler2D matcapTextureUniform;
  33554. #endif
  33555. uniform bool backfaceCulling;
  33556. #if defined(num_shadowmaps) && num_shadowmaps > 0
  33557. uniform sampler2D uShadowMap[num_shadowmaps];
  33558. uniform mat4 uShadowWorldView[num_shadowmaps];
  33559. uniform mat4 uShadowProj[num_shadowmaps];
  33560. #endif
  33561. varying vec3 vColor;
  33562. varying float vLogDepth;
  33563. varying vec3 vViewPosition;
  33564. varying float vRadius;
  33565. varying float vPointSize;
  33566. float round(float number){
  33567. return floor(number + 0.5);
  33568. }
  33569. //
  33570. // ### ######## ### ######## ######## #### ## ## ######## ###### #### ######## ######## ######
  33571. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33572. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33573. // ## ## ## ## ## ## ######## ## ## ## ## ###### ###### ## ## ###### ######
  33574. // ######### ## ## ######### ## ## ## ## ## ## ## ## ## ## ##
  33575. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33576. // ## ## ######## ## ## ## ## #### ### ######## ###### #### ######## ######## ######
  33577. //
  33578. // ---------------------
  33579. // OCTREE
  33580. // ---------------------
  33581. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_octree)
  33582. /**
  33583. * number of 1-bits up to inclusive index position
  33584. * number is treated as if it were an integer in the range 0-255
  33585. *
  33586. */
  33587. int numberOfOnes(int number, int index){
  33588. int numOnes = 0;
  33589. int tmp = 128;
  33590. for(int i = 7; i >= 0; i--){
  33591. if(number >= tmp){
  33592. number = number - tmp;
  33593. if(i <= index){
  33594. numOnes++;
  33595. }
  33596. }
  33597. tmp = tmp / 2;
  33598. }
  33599. return numOnes;
  33600. }
  33601. /**
  33602. * checks whether the bit at index is 1
  33603. * number is treated as if it were an integer in the range 0-255
  33604. *
  33605. */
  33606. bool isBitSet(int number, int index){
  33607. // weird multi else if due to lack of proper array, int and bitwise support in WebGL 1.0
  33608. int powi = 1;
  33609. if(index == 0){
  33610. powi = 1;
  33611. }else if(index == 1){
  33612. powi = 2;
  33613. }else if(index == 2){
  33614. powi = 4;
  33615. }else if(index == 3){
  33616. powi = 8;
  33617. }else if(index == 4){
  33618. powi = 16;
  33619. }else if(index == 5){
  33620. powi = 32;
  33621. }else if(index == 6){
  33622. powi = 64;
  33623. }else if(index == 7){
  33624. powi = 128;
  33625. }else{
  33626. return false;
  33627. }
  33628. int ndp = number / powi;
  33629. return mod(float(ndp), 2.0) != 0.0;
  33630. }
  33631. /**
  33632. * find the LOD at the point position
  33633. */
  33634. float getLOD(){//////
  33635. vec3 offset = vec3(0.0, 0.0, 0.0);
  33636. int iOffset = int(uVNStart);
  33637. float depth = uLevel;
  33638. for(float i = 0.0; i <= 30.0; i++){
  33639. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  33640. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  33641. index3d = floor(index3d + 0.5);
  33642. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  33643. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  33644. int mask = int(round(value.r * 255.0));
  33645. if(isBitSet(mask, index)){
  33646. // there are more visible child nodes at this position
  33647. int advanceG = int(round(value.g * 255.0)) * 256;
  33648. int advanceB = int(round(value.b * 255.0));
  33649. int advanceChild = numberOfOnes(mask, index - 1);
  33650. int advance = advanceG + advanceB + advanceChild;
  33651. iOffset = iOffset + advance;
  33652. depth++;
  33653. }else{
  33654. // no more visible child nodes at this position
  33655. //return value.a * 255.0;
  33656. float lodOffset = (255.0 * value.a) / 10.0 - 10.0;
  33657. return depth + lodOffset;
  33658. }
  33659. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  33660. }
  33661. return depth;
  33662. }
  33663. float getSpacing(){
  33664. vec3 offset = vec3(0.0, 0.0, 0.0);
  33665. int iOffset = int(uVNStart);
  33666. float depth = uLevel;
  33667. float spacing = uNodeSpacing;
  33668. for(float i = 0.0; i <= 30.0; i++){
  33669. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  33670. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  33671. index3d = floor(index3d + 0.5);
  33672. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  33673. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  33674. int mask = int(round(value.r * 255.0));
  33675. float spacingFactor = value.a;
  33676. if(i > 0.0){
  33677. spacing = spacing / (255.0 * spacingFactor);
  33678. }
  33679. if(isBitSet(mask, index)){
  33680. // there are more visible child nodes at this position
  33681. int advanceG = int(round(value.g * 255.0)) * 256;
  33682. int advanceB = int(round(value.b * 255.0));
  33683. int advanceChild = numberOfOnes(mask, index - 1);
  33684. int advance = advanceG + advanceB + advanceChild;
  33685. iOffset = iOffset + advance;
  33686. //spacing = spacing / (255.0 * spacingFactor);
  33687. //spacing = spacing / 3.0;
  33688. depth++;
  33689. }else{
  33690. // no more visible child nodes at this position
  33691. return spacing;
  33692. }
  33693. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  33694. }
  33695. return spacing;
  33696. }
  33697. float getPointSizeAttenuation(){
  33698. return pow(2.0, getLOD());
  33699. }
  33700. #endif
  33701. // ---------------------
  33702. // KD-TREE
  33703. // ---------------------
  33704. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_kdtree)
  33705. float getLOD(){
  33706. vec3 offset = vec3(0.0, 0.0, 0.0);
  33707. float iOffset = 0.0;
  33708. float depth = 0.0;
  33709. vec3 size = uBBSize;
  33710. vec3 pos = position;
  33711. for(float i = 0.0; i <= 1000.0; i++){
  33712. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  33713. int children = int(value.r * 255.0);
  33714. float next = value.g * 255.0;
  33715. int split = int(value.b * 255.0);
  33716. if(next == 0.0){
  33717. return depth;
  33718. }
  33719. vec3 splitv = vec3(0.0, 0.0, 0.0);
  33720. if(split == 1){
  33721. splitv.x = 1.0;
  33722. }else if(split == 2){
  33723. splitv.y = 1.0;
  33724. }else if(split == 4){
  33725. splitv.z = 1.0;
  33726. }
  33727. iOffset = iOffset + next;
  33728. float factor = length(pos * splitv / size);
  33729. if(factor < 0.5){
  33730. // left
  33731. if(children == 0 || children == 2){
  33732. return depth;
  33733. }
  33734. }else{
  33735. // right
  33736. pos = pos - size * splitv * 0.5;
  33737. if(children == 0 || children == 1){
  33738. return depth;
  33739. }
  33740. if(children == 3){
  33741. iOffset = iOffset + 1.0;
  33742. }
  33743. }
  33744. size = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);
  33745. depth++;
  33746. }
  33747. return depth;
  33748. }
  33749. float getPointSizeAttenuation(){
  33750. return 0.5 * pow(1.3, getLOD());
  33751. }
  33752. #endif
  33753. //
  33754. // ### ######## ######## ######## #### ######## ## ## ######## ######## ######
  33755. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33756. // ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33757. // ## ## ## ## ######## ## ######## ## ## ## ###### ######
  33758. // ######### ## ## ## ## ## ## ## ## ## ## ## ##
  33759. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33760. // ## ## ## ## ## ## #### ######## ####### ## ######## ######
  33761. //
  33762. // formula adapted from: http://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/
  33763. float getContrastFactor(float contrast){
  33764. return (1.0158730158730156 * (contrast + 1.0)) / (1.0158730158730156 - contrast);
  33765. }
  33766. vec3 getRGB(){
  33767. vec3 rgb = color;
  33768. rgb = pow(rgb, vec3(uRGB_gbc.x));
  33769. rgb = rgb + uRGB_gbc.y;
  33770. rgb = (rgb - 0.5) * getContrastFactor(uRGB_gbc.z) + 0.5;
  33771. rgb = clamp(rgb, 0.0, 1.0);
  33772. return rgb;
  33773. }
  33774. float getIntensity(){
  33775. float w = (intensity - intensityRange.x) / (intensityRange.y - intensityRange.x);
  33776. w = pow(w, uIntensity_gbc.x);
  33777. w = w + uIntensity_gbc.y;
  33778. w = (w - 0.5) * getContrastFactor(uIntensity_gbc.z) + 0.5;
  33779. w = clamp(w, 0.0, 1.0);
  33780. return w;
  33781. }
  33782. vec3 getGpsTime(){
  33783. float w = (gpsTime + uGpsOffset) * uGpsScale;
  33784. vec3 c = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  33785. // vec2 r = uNormalizedGpsBufferRange;
  33786. // float w = gpsTime * (r.y - r.x) + r.x;
  33787. // w = clamp(w, 0.0, 1.0);
  33788. // vec3 c = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33789. return c;
  33790. }
  33791. vec3 getElevation(){
  33792. vec4 world = modelMatrix * vec4( position, 1.0 );
  33793. float w = (world.z - elevationRange.x) / (elevationRange.y - elevationRange.x);
  33794. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33795. return cElevation;
  33796. }
  33797. vec4 getClassification(){
  33798. vec2 uv = vec2(classification / 255.0, 0.5);
  33799. vec4 classColor = texture2D(classificationLUT, uv);
  33800. return classColor;
  33801. }
  33802. vec3 getReturns(){
  33803. // 0b 00_000_111
  33804. float rn = mod(returnNumber, 8.0);
  33805. // 0b 00_111_000
  33806. float nr = mod(returnNumber / 8.0, 8.0);
  33807. if(nr <= 1.0){
  33808. return vec3(1.0, 0.0, 0.0);
  33809. }else{
  33810. return vec3(0.0, 1.0, 0.0);
  33811. }
  33812. // return vec3(nr / 4.0, 0.0, 0.0);
  33813. // if(nr == 1.0){
  33814. // return vec3(1.0, 1.0, 0.0);
  33815. // }else{
  33816. // if(rn == 1.0){
  33817. // return vec3(1.0, 0.0, 0.0);
  33818. // }else if(rn == nr){
  33819. // return vec3(0.0, 0.0, 1.0);
  33820. // }else{
  33821. // return vec3(0.0, 1.0, 0.0);
  33822. // }
  33823. // }
  33824. // if(numberOfReturns == 1.0){
  33825. // return vec3(1.0, 1.0, 0.0);
  33826. // }else{
  33827. // if(returnNumber == 1.0){
  33828. // return vec3(1.0, 0.0, 0.0);
  33829. // }else if(returnNumber == numberOfReturns){
  33830. // return vec3(0.0, 0.0, 1.0);
  33831. // }else{
  33832. // return vec3(0.0, 1.0, 0.0);
  33833. // }
  33834. // }
  33835. }
  33836. vec3 getReturnNumber(){
  33837. if(numberOfReturns == 1.0){
  33838. return vec3(1.0, 1.0, 0.0);
  33839. }else{
  33840. if(returnNumber == 1.0){
  33841. return vec3(1.0, 0.0, 0.0);
  33842. }else if(returnNumber == numberOfReturns){
  33843. return vec3(0.0, 0.0, 1.0);
  33844. }else{
  33845. return vec3(0.0, 1.0, 0.0);
  33846. }
  33847. }
  33848. }
  33849. vec3 getNumberOfReturns(){
  33850. float value = numberOfReturns;
  33851. float w = value / 6.0;
  33852. vec3 color = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  33853. return color;
  33854. }
  33855. vec3 getSourceID(){
  33856. float w = mod(pointSourceID, 10.0) / 10.0;
  33857. return texture2D(gradient, vec2(w,1.0 - w)).rgb;
  33858. }
  33859. vec3 getCompositeColor(){
  33860. vec3 c;
  33861. float w;
  33862. c += wRGB * getRGB();
  33863. w += wRGB;
  33864. c += wIntensity * getIntensity() * vec3(1.0, 1.0, 1.0);
  33865. w += wIntensity;
  33866. c += wElevation * getElevation();
  33867. w += wElevation;
  33868. c += wReturnNumber * getReturnNumber();
  33869. w += wReturnNumber;
  33870. c += wSourceID * getSourceID();
  33871. w += wSourceID;
  33872. vec4 cl = wClassification * getClassification();
  33873. c += cl.a * cl.rgb;
  33874. w += wClassification * cl.a;
  33875. c = c / w;
  33876. if(w == 0.0){
  33877. //c = color;
  33878. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  33879. }
  33880. return c;
  33881. }
  33882. vec3 getNormal(){
  33883. //vec3 n_hsv = vec3( modelMatrix * vec4( normal, 0.0 )) * 0.5 + 0.5; // (n_world.xyz + vec3(1.,1.,1.)) / 2.;
  33884. vec3 n_view = normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  33885. return n_view;
  33886. }
  33887. bool applyBackfaceCulling() {
  33888. // Black not facing vertices / Backface culling
  33889. vec3 e = normalize(vec3(modelViewMatrix * vec4( position, 1. )));
  33890. vec3 n = getNormal(); // normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  33891. if((uUseOrthographicCamera && n.z <= 0.) || (!uUseOrthographicCamera && dot( n, e ) >= 0.)) {
  33892. return true;
  33893. } else {
  33894. return false;
  33895. }
  33896. }
  33897. #if defined(color_type_matcap)
  33898. // Matcap Material
  33899. vec3 getMatcap(){
  33900. vec3 eye = normalize( vec3( modelViewMatrix * vec4( position, 1. ) ) );
  33901. if(uUseOrthographicCamera) {
  33902. eye = vec3(0., 0., -1.);
  33903. }
  33904. vec3 r_en = reflect( eye, getNormal() ); // or r_en = e - 2. * dot( n, e ) * n;
  33905. float m = 2. * sqrt(pow( r_en.x, 2. ) + pow( r_en.y, 2. ) + pow( r_en.z + 1., 2. ));
  33906. vec2 vN = r_en.xy / m + .5;
  33907. return texture2D(matcapTextureUniform, vN).rgb;
  33908. }
  33909. #endif
  33910. vec3 getExtra(){
  33911. float w = (aExtra + uExtraOffset) * uExtraScale;
  33912. w = clamp(w, 0.0, 1.0);
  33913. vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33914. // vec2 r = uExtraNormalizedRange;
  33915. // float w = aExtra * (r.y - r.x) + r.x;
  33916. // w = (w - uExtraRange.x) / (uExtraRange.y - uExtraRange.x);
  33917. // w = clamp(w, 0.0, 1.0);
  33918. // vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33919. return color;
  33920. }
  33921. vec3 getColor(){
  33922. vec3 color;
  33923. #ifdef color_type_rgba
  33924. color = getRGB();
  33925. #elif defined color_type_height || defined color_type_elevation
  33926. color = getElevation();
  33927. #elif defined color_type_rgb_height
  33928. vec3 cHeight = getElevation();
  33929. color = (1.0 - uTransition) * getRGB() + uTransition * cHeight;
  33930. #elif defined color_type_depth
  33931. float linearDepth = gl_Position.w;
  33932. float expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;
  33933. color = vec3(linearDepth, expDepth, 0.0);
  33934. //color = vec3(1.0, 0.5, 0.3);
  33935. #elif defined color_type_intensity
  33936. float w = getIntensity();
  33937. color = vec3(w, w, w);
  33938. #elif defined color_type_gps_time
  33939. color = getGpsTime();
  33940. #elif defined color_type_intensity_gradient
  33941. float w = getIntensity();
  33942. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33943. #elif defined color_type_color
  33944. color = uColor;
  33945. #elif defined color_type_level_of_detail
  33946. float depth = getLOD();
  33947. float w = depth / 10.0;
  33948. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33949. #elif defined color_type_indices
  33950. color = indices.rgb;
  33951. #elif defined color_type_classification
  33952. vec4 cl = getClassification();
  33953. color = cl.rgb;
  33954. #elif defined color_type_return_number
  33955. color = getReturnNumber();
  33956. #elif defined color_type_returns
  33957. color = getReturns();
  33958. #elif defined color_type_number_of_returns
  33959. color = getNumberOfReturns();
  33960. #elif defined color_type_source_id
  33961. color = getSourceID();
  33962. #elif defined color_type_point_source_id
  33963. color = getSourceID();
  33964. #elif defined color_type_normal
  33965. color = (modelMatrix * vec4(normal, 0.0)).xyz;
  33966. #elif defined color_type_phong
  33967. color = color;
  33968. #elif defined color_type_composite
  33969. color = getCompositeColor();
  33970. #elif defined color_type_matcap
  33971. color = getMatcap();
  33972. #else
  33973. color = getExtra();
  33974. #endif
  33975. if (backfaceCulling && applyBackfaceCulling()){
  33976. //color = vec3(0.);
  33977. }
  33978. //applyBackfaceCulling直接返回false或者注释color = vec3(0.);都没问题
  33979. return color;
  33980. }
  33981. float getPointSize(){
  33982. float pointSize = 1.0;
  33983. float slope = tan(fov / 2.0);
  33984. float projFactor = -0.5 * resolution.y / (slope * vViewPosition.z);
  33985. /*
  33986. float scale = length(
  33987. modelViewMatrix * vec4(0, 0, 0, 1) -
  33988. modelViewMatrix * vec4(uOctreeSpacing, 0, 0, 1)
  33989. ) / uOctreeSpacing;
  33990. projFactor = projFactor * scale;
  33991. */
  33992. float r = uOctreeSpacing * 1.7;
  33993. //vRadius = r;
  33994. #if defined fixed_point_size
  33995. pointSize = size;
  33996. #elif defined attenuated_point_size
  33997. if(uUseOrthographicCamera){
  33998. pointSize = size * 10.0; //加个乘数
  33999. }else{ //近大远小,模拟真实mesh,边缘放大
  34000. //pointSize = size * spacing * projFactor; //spacing是attribute 为空 如果有这个值就能更自适应填补
  34001. //pointSize = size * uOctreeSpacing * projFactor / 18.0; //直接用cloud的spacing里,不过因为都一样所以可能没有什么意义
  34002. //pointSize = pointSize * projFactor;
  34003. pointSize = size * projFactor ;
  34004. }
  34005. #elif defined adaptive_point_size
  34006. if(uUseOrthographicCamera) {
  34007. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  34008. pointSize = (worldSpaceSize / uOrthoWidth) * resolution.x; //uScreenWidth;
  34009. } else {
  34010. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  34011. pointSize = worldSpaceSize * projFactor;
  34012. }
  34013. #endif
  34014. pointSize = max(minSize, pointSize);
  34015. pointSize = min(maxSize, pointSize);
  34016. vRadius = pointSize / projFactor;
  34017. return pointSize;
  34018. }
  34019. #if defined(num_clippolygons) && num_clippolygons > 0
  34020. bool pointInClipPolygon(vec3 point, int polyIdx) {
  34021. mat4 wvp = uClipPolygonWVP[polyIdx];
  34022. //vec4 screenClipPos = uClipPolygonVP[polyIdx] * modelMatrix * vec4(point, 1.0);
  34023. //screenClipPos.xy = screenClipPos.xy / screenClipPos.w * 0.5 + 0.5;
  34024. vec4 pointNDC = wvp * vec4(point, 1.0);
  34025. pointNDC.xy = pointNDC.xy / pointNDC.w;
  34026. int j = uClipPolygonVCount[polyIdx] - 1;
  34027. bool c = false;
  34028. for(int i = 0; i < 8; i++) {
  34029. if(i == uClipPolygonVCount[polyIdx]) {
  34030. break;
  34031. }
  34032. //vec4 verti = wvp * vec4(uClipPolygonVertices[polyIdx * 8 + i], 1);
  34033. //vec4 vertj = wvp * vec4(uClipPolygonVertices[polyIdx * 8 + j], 1);
  34034. //verti.xy = verti.xy / verti.w;
  34035. //vertj.xy = vertj.xy / vertj.w;
  34036. //verti.xy = verti.xy / verti.w * 0.5 + 0.5;
  34037. //vertj.xy = vertj.xy / vertj.w * 0.5 + 0.5;
  34038. vec3 verti = uClipPolygonVertices[polyIdx * 8 + i];
  34039. vec3 vertj = uClipPolygonVertices[polyIdx * 8 + j];
  34040. if( ((verti.y > pointNDC.y) != (vertj.y > pointNDC.y)) &&
  34041. (pointNDC.x < (vertj.x-verti.x) * (pointNDC.y-verti.y) / (vertj.y-verti.y) + verti.x) ) {
  34042. c = !c;
  34043. }
  34044. j = i;
  34045. }
  34046. return c;
  34047. }
  34048. #endif
  34049. void doClipping(){
  34050. {
  34051. vec4 cl = getClassification();
  34052. if(cl.a == 0.0){
  34053. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34054. return;
  34055. }
  34056. }
  34057. #if defined(clip_return_number_enabled)
  34058. { // return number filter
  34059. vec2 range = uFilterReturnNumberRange;
  34060. if(returnNumber < range.x || returnNumber > range.y){
  34061. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34062. return;
  34063. }
  34064. }
  34065. #endif
  34066. #if defined(clip_number_of_returns_enabled)
  34067. { // number of return filter
  34068. vec2 range = uFilterNumberOfReturnsRange;
  34069. if(numberOfReturns < range.x || numberOfReturns > range.y){
  34070. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34071. return;
  34072. }
  34073. }
  34074. #endif
  34075. #if defined(clip_gps_enabled)
  34076. { // GPS time filter
  34077. float time = (gpsTime + uGpsOffset) * uGpsScale;
  34078. vec2 range = uFilterGPSTimeClipRange;
  34079. if(time < range.x || time > range.y){
  34080. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34081. return;
  34082. }
  34083. }
  34084. #endif
  34085. #if defined(clip_point_source_id_enabled)
  34086. { // point source id filter
  34087. vec2 range = uFilterPointSourceIDClipRange;
  34088. if(pointSourceID < range.x || pointSourceID > range.y){
  34089. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34090. return;
  34091. }
  34092. }
  34093. #endif
  34094. int clipVolumesCount = 0;
  34095. int insideCount = 0;
  34096. #if defined(num_clipboxes) && num_clipboxes > 0
  34097. for(int i = 0; i < num_clipboxes; i++){
  34098. vec4 clipPosition = clipBoxes[i] * modelMatrix * vec4( position, 1.0 );
  34099. bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;
  34100. inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;
  34101. inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;
  34102. insideCount = insideCount + (inside ? 1 : 0);
  34103. clipVolumesCount++;
  34104. }
  34105. #endif
  34106. #if defined(num_clippolygons) && num_clippolygons > 0
  34107. for(int i = 0; i < num_clippolygons; i++) {
  34108. bool inside = pointInClipPolygon(position, i);
  34109. insideCount = insideCount + (inside ? 1 : 0);
  34110. clipVolumesCount++;
  34111. }
  34112. #endif
  34113. bool insideAny = insideCount > 0;
  34114. bool insideAll = (clipVolumesCount > 0) && (clipVolumesCount == insideCount);
  34115. if(clipMethod == CLIPMETHOD_INSIDE_ANY){
  34116. if(insideAny && clipTask == CLIPTASK_HIGHLIGHT){
  34117. vColor.r += 0.5;
  34118. }else if(!insideAny && clipTask == CLIPTASK_SHOW_INSIDE){
  34119. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34120. }else if(insideAny && clipTask == CLIPTASK_SHOW_OUTSIDE){
  34121. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34122. }
  34123. }else if(clipMethod == CLIPMETHOD_INSIDE_ALL){
  34124. if(insideAll && clipTask == CLIPTASK_HIGHLIGHT){
  34125. vColor.r += 0.5;
  34126. }else if(!insideAll && clipTask == CLIPTASK_SHOW_INSIDE){
  34127. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34128. }else if(insideAll && clipTask == CLIPTASK_SHOW_OUTSIDE){
  34129. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34130. }
  34131. }
  34132. }
  34133. //
  34134. // ## ## ### #### ## ##
  34135. // ### ### ## ## ## ### ##
  34136. // #### #### ## ## ## #### ##
  34137. // ## ### ## ## ## ## ## ## ##
  34138. // ## ## ######### ## ## ####
  34139. // ## ## ## ## ## ## ###
  34140. // ## ## ## ## #### ## ##
  34141. //
  34142. vec2 getSamplerCoord( vec3 direction )
  34143. {
  34144. direction = normalize(direction);
  34145. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  34146. float ty=acos(direction.z)/PI;
  34147. return vec2(tx,ty);
  34148. }
  34149. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  34150. {
  34151. float y = direction.y;
  34152. direction.y = direction.z;
  34153. direction.z = -y;
  34154. return direction;
  34155. }
  34156. void main() {
  34157. //bool filtered_by_normal = false;
  34158. float normalZ = 0.0;
  34159. #ifdef use_filter_by_normal
  34160. /*if(abs(getNormal().z) > 0.4) { //ufilterByNormalThreshold 暂定 3
  34161. // Move point outside clip space space to discard it.
  34162. //gl_Position = vec4(0.0, 0.0, 2.0, 1.0); //gl_Position的可视区域是 x,y,z都是[-1,1]
  34163. //return;
  34164. //filtered_by_normal = true; //标记一下。不直接不绘制,因为有的法线都是垂直向上
  34165. }*/
  34166. normalZ = abs(getNormal().z);
  34167. #endif
  34168. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 );
  34169. vViewPosition = mvPosition.xyz;
  34170. gl_Position = projectionMatrix * mvPosition;
  34171. vLogDepth = log2(-mvPosition.z);
  34172. // COLOR
  34173. //加-------------------
  34174. #if defined(usePanoMap)
  34175. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  34176. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  34177. vec3 vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  34178. vWorldPosition0.x *= -1.0;
  34179. vWorldPosition0 = transformAxis(vWorldPosition0);
  34180. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  34181. vec3 vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  34182. vWorldPosition1.x *= -1.0;
  34183. vWorldPosition1 = transformAxis(vWorldPosition1);
  34184. /*
  34185. vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  34186. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  34187. vec4 colorFromPano0 = texture2D(pano0Map,samplerCoord0);
  34188. vec4 colorFromPano1 = texture2D(pano1Map,samplerCoord1);
  34189. */
  34190. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  34191. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  34192. vColor = mix(colorFromPano0,colorFromPano1,progress).xyz;
  34193. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  34194. if(progress < easeInOutRatio){
  34195. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  34196. vec3 vColor1 = getColor();
  34197. vColor = mix(vColor,vColor1,easeProgress);
  34198. }else if(progress > 1.0 - easeInOutRatio){
  34199. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  34200. vec3 vColor1 = getColor();
  34201. vColor = mix(vColor,vColor1,easeProgress);
  34202. }
  34203. #else
  34204. vColor = getColor();
  34205. #endif
  34206. //-------------------
  34207. #ifdef attenuated_opacity
  34208. //zoom不会改变z 所以这并不是用在分屏时候的
  34209. //vOpacity = uOpacity * exp(-length(-mvPosition.xyz) / 1000.0); // e为底的指数函数 opacityAttenuation = 1000
  34210. vOpacity = uOpacity * exp(gl_Position.z/50.0);
  34211. vOpacity = clamp(vOpacity, 0.001, 1.0);
  34212. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34213. vOpacity *= 0.2;
  34214. vOpacity = clamp(vOpacity, 0.0001, 0.1);
  34215. } */
  34216. #else
  34217. vOpacity = uOpacity;
  34218. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34219. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34220. vOpacity *= 0.3;
  34221. vOpacity = clamp(vOpacity, 0.0001, 0.1);
  34222. }*/
  34223. vOpacity *= max(0.1, (1.0 - normalZ));
  34224. #endif
  34225. // POINT SIZE
  34226. float pointSize = getPointSize();
  34227. gl_PointSize = pointSize;
  34228. vPointSize = pointSize;
  34229. // only for "replacing" approaches
  34230. // if(getLOD() != uLevel){
  34231. // gl_Position = vec4(10.0, 10.0, 10.0, 1.0);
  34232. // }
  34233. #if defined hq_depth_pass
  34234. float originalDepth = gl_Position.w;
  34235. float adjustedDepth = originalDepth + 2.0 * vRadius;
  34236. float adjust = adjustedDepth / originalDepth;
  34237. mvPosition.xyz = mvPosition.xyz * adjust;
  34238. gl_Position = projectionMatrix * mvPosition;
  34239. #endif
  34240. // CLIPPING
  34241. doClipping();
  34242. #if defined(num_clipspheres) && num_clipspheres > 0
  34243. for(int i = 0; i < num_clipspheres; i++){
  34244. vec4 sphereLocal = uClipSpheres[i] * mvPosition;
  34245. float distance = length(sphereLocal.xyz);
  34246. if(distance < 1.0){
  34247. float w = distance;
  34248. vec3 cGradient = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  34249. vColor = cGradient;
  34250. //vColor = cGradient * 0.7 + vColor * 0.3;
  34251. }
  34252. }
  34253. #endif
  34254. #if defined(num_shadowmaps) && num_shadowmaps > 0
  34255. const float sm_near = 0.1;
  34256. const float sm_far = 10000.0;
  34257. for(int i = 0; i < num_shadowmaps; i++){
  34258. vec3 viewPos = (uShadowWorldView[i] * vec4(position, 1.0)).xyz;
  34259. float distanceToLight = abs(viewPos.z);
  34260. vec4 projPos = uShadowProj[i] * uShadowWorldView[i] * vec4(position, 1);
  34261. vec3 nc = projPos.xyz / projPos.w;
  34262. float u = nc.x * 0.5 + 0.5;
  34263. float v = nc.y * 0.5 + 0.5;
  34264. vec2 sampleStep = vec2(1.0 / (2.0*1024.0), 1.0 / (2.0*1024.0)) * 1.5;
  34265. vec2 sampleLocations[9];
  34266. sampleLocations[0] = vec2(0.0, 0.0);
  34267. sampleLocations[1] = sampleStep;
  34268. sampleLocations[2] = -sampleStep;
  34269. sampleLocations[3] = vec2(sampleStep.x, -sampleStep.y);
  34270. sampleLocations[4] = vec2(-sampleStep.x, sampleStep.y);
  34271. sampleLocations[5] = vec2(0.0, sampleStep.y);
  34272. sampleLocations[6] = vec2(0.0, -sampleStep.y);
  34273. sampleLocations[7] = vec2(sampleStep.x, 0.0);
  34274. sampleLocations[8] = vec2(-sampleStep.x, 0.0);
  34275. float visibleSamples = 0.0;
  34276. float numSamples = 0.0;
  34277. float bias = vRadius * 2.0;
  34278. for(int j = 0; j < 9; j++){
  34279. vec4 depthMapValue = texture2D(uShadowMap[i], vec2(u, v) + sampleLocations[j]);
  34280. float linearDepthFromSM = depthMapValue.x + bias;
  34281. float linearDepthFromViewer = distanceToLight;
  34282. if(linearDepthFromSM > linearDepthFromViewer){
  34283. visibleSamples += 1.0;
  34284. }
  34285. numSamples += 1.0;
  34286. }
  34287. float visibility = visibleSamples / numSamples;
  34288. 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){
  34289. //vColor = vec3(0.0, 0.0, 0.2);
  34290. }else{
  34291. //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);
  34292. vColor = vColor * visibility + vColor * uShadowColor * (1.0 - visibility);
  34293. }
  34294. }
  34295. #endif
  34296. }
  34297. `;
  34298. Shaders["pointcloud.fs"] = `
  34299. #if defined paraboloid_point_shape
  34300. #extension GL_EXT_frag_depth : enable
  34301. #endif
  34302. #define PI 3.141592653589793
  34303. precision highp float;
  34304. precision highp int;
  34305. /*
  34306. #if defined(usePanoMap)
  34307. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  34308. uniform samplerCube pano1Map;
  34309. uniform float progress;
  34310. uniform float easeInOutRatio;
  34311. uniform vec3 pano0Position;
  34312. uniform mat4 pano0Matrix;
  34313. uniform vec3 pano1Position;
  34314. uniform mat4 pano1Matrix;
  34315. varying vec3 vWorldPosition0;
  34316. varying vec3 vWorldPosition1;
  34317. #endif
  34318. */
  34319. //------------
  34320. uniform mat4 viewMatrix;
  34321. uniform mat4 uViewInv;
  34322. uniform mat4 uProjInv;
  34323. uniform vec3 cameraPosition;
  34324. uniform mat4 projectionMatrix;
  34325. //uniform float uOpacity;
  34326. varying float vOpacity; //add
  34327. uniform float blendHardness;
  34328. uniform float blendDepthSupplement;
  34329. uniform float fov;
  34330. uniform float uSpacing;
  34331. uniform float near;
  34332. uniform float far;
  34333. uniform float uPCIndex;
  34334. uniform float uScreenWidth;
  34335. uniform float uScreenHeight;
  34336. varying vec3 vColor;
  34337. varying float vLogDepth;
  34338. varying vec3 vViewPosition;
  34339. varying float vRadius;
  34340. varying float vPointSize;
  34341. varying vec3 vPosition;
  34342. float specularStrength = 1.0;
  34343. vec2 getSamplerCoord( vec3 direction )
  34344. {
  34345. direction = normalize(direction);
  34346. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  34347. float ty=acos(direction.z)/PI;
  34348. return vec2(tx,ty);
  34349. }
  34350. void main() {
  34351. vec3 color = vColor;
  34352. /*#if defined(usePanoMap) //加 经测试,即使全部写在fragment里也是无论pointsize多大都是一个点一个颜色,所以干脆写在vectex里
  34353. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  34354. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  34355. color = mix(colorFromPano0,colorFromPano1,progress).xyz;
  34356. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  34357. if(progress < easeInOutRatio){
  34358. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  34359. color = mix(color,vColor,easeProgress);
  34360. }else if(progress > 1.0 - easeInOutRatio){
  34361. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  34362. color = mix(color,vColor,easeProgress);
  34363. }
  34364. #else
  34365. color = vColor;
  34366. #endif*/
  34367. float depth = gl_FragCoord.z;
  34368. #if defined(circle_point_shape) || defined(paraboloid_point_shape)
  34369. float u = 2.0 * gl_PointCoord.x - 1.0;
  34370. float v = 2.0 * gl_PointCoord.y - 1.0;
  34371. #endif
  34372. #if defined(circle_point_shape)
  34373. float cc = u*u + v*v;
  34374. if(cc > 1.0){
  34375. discard;
  34376. }
  34377. #endif
  34378. #if defined color_type_indices //pick point recognize
  34379. gl_FragColor = vec4(color, uPCIndex / 255.0); //uPCIndex : node Index
  34380. #else
  34381. gl_FragColor = vec4(color, vOpacity);
  34382. #endif
  34383. #if defined paraboloid_point_shape
  34384. float wi = 0.0 - ( u*u + v*v);
  34385. vec4 pos = vec4(vViewPosition, 1.0);
  34386. pos.z += wi * vRadius;
  34387. float linearDepth = -pos.z;
  34388. pos = projectionMatrix * pos;
  34389. pos = pos / pos.w;
  34390. float expDepth = pos.z;
  34391. depth = (pos.z + 1.0) / 2.0;
  34392. gl_FragDepthEXT = depth;
  34393. #if defined(color_type_depth)
  34394. color.r = linearDepth;
  34395. color.g = expDepth;
  34396. #endif
  34397. #if defined(use_edl)
  34398. gl_FragColor.a = log2(linearDepth);
  34399. #endif
  34400. #else
  34401. #if defined(use_edl)
  34402. gl_FragColor.a = vLogDepth;
  34403. #endif
  34404. #endif
  34405. #if defined(weighted_splats)
  34406. float distance = 2.0 * length(gl_PointCoord.xy - 0.5);
  34407. float weight = max(0.0, 1.0 - distance);
  34408. weight = pow(weight, 1.5);
  34409. gl_FragColor.a = weight;
  34410. gl_FragColor.xyz = gl_FragColor.xyz * weight;
  34411. #endif
  34412. //gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);
  34413. }
  34414. `;
  34415. Shaders["pointcloud_sm.vs"] = `
  34416. precision mediump float;
  34417. precision mediump int;
  34418. attribute vec3 position;
  34419. attribute vec3 color;
  34420. uniform mat4 modelMatrix;
  34421. uniform mat4 modelViewMatrix;
  34422. uniform mat4 projectionMatrix;
  34423. uniform mat4 viewMatrix;
  34424. uniform float uScreenWidth;
  34425. uniform float uScreenHeight;
  34426. uniform float near;
  34427. uniform float far;
  34428. uniform float uSpacing;
  34429. uniform float uOctreeSize;
  34430. uniform float uLevel;
  34431. uniform float uVNStart;
  34432. uniform sampler2D visibleNodes;
  34433. varying float vLinearDepth;
  34434. varying vec3 vColor;
  34435. #define PI 3.141592653589793
  34436. // ---------------------
  34437. // OCTREE
  34438. // ---------------------
  34439. #if defined(adaptive_point_size)
  34440. /**
  34441. * number of 1-bits up to inclusive index position
  34442. * number is treated as if it were an integer in the range 0-255
  34443. *
  34444. */
  34445. float numberOfOnes(float number, float index){
  34446. float tmp = mod(number, pow(2.0, index + 1.0));
  34447. float numOnes = 0.0;
  34448. for(float i = 0.0; i < 8.0; i++){
  34449. if(mod(tmp, 2.0) != 0.0){
  34450. numOnes++;
  34451. }
  34452. tmp = floor(tmp / 2.0);
  34453. }
  34454. return numOnes;
  34455. }
  34456. /**
  34457. * checks whether the bit at index is 1
  34458. * number is treated as if it were an integer in the range 0-255
  34459. *
  34460. */
  34461. bool isBitSet(float number, float index){
  34462. return mod(floor(number / pow(2.0, index)), 2.0) != 0.0;
  34463. }
  34464. /**
  34465. * find the LOD at the point position
  34466. */
  34467. float getLOD(){
  34468. vec3 offset = vec3(0.0, 0.0, 0.0);
  34469. float iOffset = uVNStart;
  34470. float depth = uLevel;
  34471. for(float i = 0.0; i <= 30.0; i++){
  34472. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  34473. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  34474. index3d = floor(index3d + 0.5);
  34475. float index = 4.0 * index3d.x + 2.0 * index3d.y + index3d.z;
  34476. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  34477. float mask = value.r * 255.0;
  34478. if(isBitSet(mask, index)){
  34479. // there are more visible child nodes at this position
  34480. iOffset = iOffset + value.g * 255.0 * 256.0 + value.b * 255.0 + numberOfOnes(mask, index - 1.0);
  34481. depth++;
  34482. }else{
  34483. // no more visible child nodes at this position
  34484. return depth;
  34485. }
  34486. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  34487. }
  34488. return depth;
  34489. }
  34490. #endif
  34491. float getPointSize(){
  34492. float pointSize = 1.0;
  34493. float slope = tan(fov / 2.0);
  34494. float projFactor = -0.5 * uScreenHeight / (slope * vViewPosition.z);
  34495. float r = uOctreeSpacing * 1.5;
  34496. vRadius = r;
  34497. #if defined fixed_point_size
  34498. pointSize = size;
  34499. #elif defined attenuated_point_size
  34500. if(uUseOrthographicCamera){
  34501. pointSize = size;
  34502. }else{
  34503. pointSize = pointSize * projFactor;
  34504. }
  34505. #elif defined adaptive_point_size
  34506. if(uUseOrthographicCamera) {
  34507. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  34508. pointSize = (worldSpaceSize / uOrthoWidth) * uScreenWidth;
  34509. } else {
  34510. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  34511. pointSize = worldSpaceSize * projFactor;
  34512. }
  34513. #endif
  34514. pointSize = max(minSize, pointSize);
  34515. pointSize = min(maxSize, pointSize);
  34516. vRadius = pointSize / projFactor;
  34517. return pointSize;
  34518. }
  34519. void main() {
  34520. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  34521. vLinearDepth = gl_Position.w;
  34522. float pointSize = getPointSize();
  34523. gl_PointSize = pointSize;
  34524. }
  34525. `;
  34526. Shaders["pointcloud_sm.fs"] = `
  34527. precision mediump float;
  34528. precision mediump int;
  34529. varying vec3 vColor;
  34530. varying float vLinearDepth;
  34531. void main() {
  34532. //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  34533. //gl_FragColor = vec4(vColor, 1.0);
  34534. //gl_FragColor = vec4(vLinearDepth, pow(vLinearDepth, 2.0), 0.0, 1.0);
  34535. gl_FragColor = vec4(vLinearDepth, vLinearDepth / 30.0, vLinearDepth / 30.0, 1.0);
  34536. }
  34537. `;
  34538. Shaders["normalize.vs"] = `
  34539. precision mediump float;
  34540. precision mediump int;
  34541. attribute vec3 position;
  34542. attribute vec2 uv;
  34543. uniform mat4 projectionMatrix;
  34544. uniform mat4 modelViewMatrix;
  34545. varying vec2 vUv;
  34546. void main() {
  34547. vUv = uv;
  34548. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  34549. }`;
  34550. Shaders["normalize.fs"] = `
  34551. #extension GL_EXT_frag_depth : enable
  34552. precision mediump float;
  34553. precision mediump int;
  34554. uniform sampler2D uWeightMap;
  34555. uniform sampler2D uDepthMap;
  34556. varying vec2 vUv;
  34557. void main() {
  34558. float depth = texture2D(uDepthMap, vUv).r;
  34559. if(depth >= 1.0){
  34560. discard;
  34561. }
  34562. gl_FragColor = vec4(depth, 1.0, 0.0, 1.0);
  34563. vec4 color = texture2D(uWeightMap, vUv);
  34564. color = color / color.w;
  34565. gl_FragColor = vec4(color.xyz, 1.0);
  34566. gl_FragDepthEXT = depth;
  34567. }`;
  34568. Shaders["normalize_and_edl.fs"] = `
  34569. #extension GL_EXT_frag_depth : enable
  34570. //
  34571. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  34572. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  34573. //
  34574. precision mediump float;
  34575. precision mediump int;
  34576. uniform sampler2D uWeightMap;
  34577. uniform sampler2D uEDLMap;
  34578. uniform sampler2D uDepthMap;
  34579. uniform float screenWidth;
  34580. uniform float screenHeight;
  34581. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  34582. uniform float edlStrength;
  34583. uniform float radius;
  34584. varying vec2 vUv;
  34585. float response(float depth){
  34586. vec2 uvRadius = radius / vec2(screenWidth, screenHeight);
  34587. float sum = 0.0;
  34588. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  34589. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  34590. float neighbourDepth = texture2D(uEDLMap, uvNeighbor).a;
  34591. if(neighbourDepth != 0.0){
  34592. if(depth == 0.0){
  34593. sum += 100.0;
  34594. }else{
  34595. sum += max(0.0, depth - neighbourDepth);
  34596. }
  34597. }
  34598. }
  34599. return sum / float(NEIGHBOUR_COUNT);
  34600. }
  34601. void main() {
  34602. float edlDepth = texture2D(uEDLMap, vUv).a;
  34603. float res = response(edlDepth);
  34604. float shade = exp(-res * 300.0 * edlStrength);
  34605. float depth = texture2D(uDepthMap, vUv).r;
  34606. if(depth >= 1.0 && res == 0.0){
  34607. discard;
  34608. }
  34609. vec4 color = texture2D(uWeightMap, vUv);
  34610. color = color / color.w;
  34611. color = color * shade;
  34612. gl_FragColor = vec4(color.xyz, 1.0);
  34613. gl_FragDepthEXT = depth;
  34614. }`;
  34615. Shaders["edl.vs"] = `
  34616. precision mediump float;
  34617. precision mediump int;
  34618. attribute vec3 position;
  34619. attribute vec2 uv;
  34620. uniform mat4 projectionMatrix;
  34621. uniform mat4 modelViewMatrix;
  34622. varying vec2 vUv;
  34623. void main() {
  34624. vUv = uv;
  34625. vec4 mvPosition = modelViewMatrix * vec4(position,1.0);
  34626. gl_Position = projectionMatrix * mvPosition;
  34627. }`;
  34628. Shaders["edl.fs"] = `
  34629. #extension GL_EXT_frag_depth : enable
  34630. //
  34631. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  34632. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  34633. //
  34634. precision mediump float;
  34635. precision mediump int;
  34636. //uniform float screenWidth;
  34637. //uniform float screenHeight;
  34638. uniform vec2 resolution;
  34639. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  34640. uniform float edlStrength;
  34641. uniform float radius;
  34642. uniform float opacity;
  34643. //uniform float uNear;
  34644. //uniform float uFar;
  34645. uniform mat4 uProj;
  34646. uniform sampler2D uEDLColor;
  34647. uniform sampler2D uEDLDepth;
  34648. varying vec2 vUv;
  34649. uniform int useEDL;
  34650. float response(float depth){
  34651. vec2 uvRadius = radius / resolution; //vec2(screenWidth, screenHeight);
  34652. float sum = 0.0;
  34653. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  34654. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  34655. //获取周围八个格子的值
  34656. float neighbourDepth = texture2D(uEDLColor, uvNeighbor).a;
  34657. neighbourDepth = (neighbourDepth == 1.0) ? 0.0 : neighbourDepth;
  34658. if(neighbourDepth != 0.0){
  34659. //if(depth == 0.0){
  34660. // sum += 100.0;
  34661. //}else{
  34662. sum += max(0.0, depth - neighbourDepth); //获取差值
  34663. //}
  34664. }
  34665. }
  34666. return sum / float(NEIGHBOUR_COUNT);
  34667. }
  34668. void main(){
  34669. vec4 cEDL = texture2D(uEDLColor, vUv);
  34670. float depth = cEDL.a;
  34671. depth = (depth == 1.0) ? 0.0 : depth;
  34672. if(depth == 0.0){ //去掉这句就能在无点云像素的地方渲染outline,但会遮住其他mesh
  34673. discard;
  34674. }
  34675. if(useEDL == 1){
  34676. float res = response(depth);
  34677. //if(depth == 0.0 && res == 0.0){ //test
  34678. // discard;
  34679. //}
  34680. float shade = exp(-res * 300.0 * edlStrength); //自然常数e为底的指数函数
  34681. gl_FragColor = vec4(cEDL.rgb * shade, opacity);
  34682. //const vec3 outlineColor = vec3(1.0,0.0,0.0);//test -outline
  34683. //gl_FragColor = vec4(mix(cEDL.rgb, outlineColor, -res), opacity );
  34684. }else{//加 不改颜色的情况
  34685. gl_FragColor = vec4(cEDL.rgb, opacity);
  34686. }
  34687. { // write regular hyperbolic depth values to depth buffer 修改深度
  34688. float dl = pow(2.0, depth);
  34689. vec4 dp = uProj * vec4(0.0, 0.0, -dl, 1.0);
  34690. float pz = dp.z / dp.w;
  34691. float fragDepth = (pz + 1.0) / 2.0;
  34692. gl_FragDepthEXT = fragDepth;
  34693. }
  34694. }
  34695. `;
  34696. Shaders["blur.vs"] = `
  34697. varying vec2 vUv;
  34698. void main() {
  34699. vUv = uv;
  34700. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  34701. }`;
  34702. Shaders["blur.fs"] = `
  34703. uniform mat4 projectionMatrix;
  34704. uniform float screenWidth;
  34705. uniform float screenHeight;
  34706. uniform float near;
  34707. uniform float far;
  34708. uniform sampler2D map;
  34709. varying vec2 vUv;
  34710. void main() {
  34711. float dx = 1.0 / screenWidth;
  34712. float dy = 1.0 / screenHeight;
  34713. vec3 color = vec3(0.0, 0.0, 0.0);
  34714. color += texture2D(map, vUv + vec2(-dx, -dy)).rgb;
  34715. color += texture2D(map, vUv + vec2( 0, -dy)).rgb;
  34716. color += texture2D(map, vUv + vec2(+dx, -dy)).rgb;
  34717. color += texture2D(map, vUv + vec2(-dx, 0)).rgb;
  34718. color += texture2D(map, vUv + vec2( 0, 0)).rgb;
  34719. color += texture2D(map, vUv + vec2(+dx, 0)).rgb;
  34720. color += texture2D(map, vUv + vec2(-dx, dy)).rgb;
  34721. color += texture2D(map, vUv + vec2( 0, dy)).rgb;
  34722. color += texture2D(map, vUv + vec2(+dx, dy)).rgb;
  34723. color = color / 9.0;
  34724. gl_FragColor = vec4(color, 1.0);
  34725. }`;
  34726. Shaders["depthBasic.vs"] = `
  34727. varying vec2 vUv;
  34728. void main() {
  34729. vUv = uv;
  34730. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34731. }
  34732. `;
  34733. Shaders["depthBasic.fs"] = `varying vec2 vUv;
  34734. uniform float opacity;
  34735. uniform vec3 baseColor;
  34736. uniform vec3 backColor;
  34737. uniform float occlusionDistance;
  34738. uniform float clipDistance;
  34739. uniform float maxClipFactor;
  34740. #if defined use_map
  34741. uniform sampler2D map;
  34742. #endif
  34743. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  34744. //似乎通过gl.getExtension('EXT_frag_depth')得到的GL_EXT_frag_depth
  34745. uniform sampler2D depthTexture;
  34746. uniform float nearPlane;
  34747. uniform float farPlane;
  34748. uniform vec2 resolution;
  34749. uniform vec2 viewportOffset; // viewportOffset 范围从0-整个画布的像素
  34750. float convertToLinear(float zValue)
  34751. {
  34752. float z = zValue * 2.0 - 1.0;
  34753. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  34754. }
  34755. #endif
  34756. void main() {
  34757. vec4 color = vec4(baseColor, opacity);
  34758. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  34759. // mixFactor and clipFactor define the color mixing proportion between the states of
  34760. // full visibility and occluded visibility
  34761. // and
  34762. // full visibility and total invisibility
  34763. float mixFactor = 0.0;
  34764. float clipFactor = 0.0;
  34765. // The linear depth value of the current fragment
  34766. float fragDepth = convertToLinear(gl_FragCoord.z);
  34767. // The coordinates of the current fragment in the depth texture
  34768. vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  34769. // The linear depth value of the pixel occupied by this fragment in the depth buffer
  34770. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  34771. // The difference between the two depths
  34772. float delta = fragDepth - textureDepth;
  34773. if (delta > 0.0)//差距
  34774. {
  34775. // occlusionDistance and clipDistance define the width of the respective zones and
  34776. // mixFactor and clipFactor express the interpolation between the two colors depending on the position
  34777. // of the current fragment withing those zones.
  34778. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  34779. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  34780. }
  34781. // If the fragment is totally transparent, don't bother drawing it
  34782. if (clipFactor == 1.0)
  34783. {
  34784. discard;
  34785. }else{
  34786. #if defined use_map
  34787. color = texture2D(map, vUv) * color;
  34788. #endif
  34789. color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));
  34790. }
  34791. #else
  34792. #if defined use_map
  34793. color = texture2D(map, vUv) * color;
  34794. #endif
  34795. #endif
  34796. gl_FragColor = color;
  34797. }
  34798. `;
  34799. Shaders["copyCubeMap.vs"] = `varying vec3 vWorldPos;
  34800. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  34801. {
  34802. float y = direction.y;
  34803. direction.y = direction.z;
  34804. direction.z = -y;
  34805. return direction;
  34806. }
  34807. void main() {
  34808. vWorldPos = vec3(-position.x, -position.y, position.z);
  34809. //vWorldPos = transformAxis(vWorldPos);
  34810. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34811. }
  34812. `;
  34813. Shaders["copyCubeMap.fs"] = `varying vec3 vWorldPos;
  34814. uniform float alpha;
  34815. uniform samplerCube tDiffuse;
  34816. void main() {
  34817. vec4 texColor = textureCube(tDiffuse, vWorldPos);
  34818. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  34819. }
  34820. `;
  34821. Shaders["basicTextured.vs"] = `varying vec2 vUv;
  34822. void main() {
  34823. vUv = uv;
  34824. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34825. }
  34826. `;
  34827. Shaders["basicTextured.fs"] = `varying vec2 vUv;
  34828. uniform float alpha;
  34829. uniform sampler2D tDiffuse;
  34830. void main() {
  34831. vec4 texColor = texture2D(tDiffuse, vUv);
  34832. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  34833. }
  34834. `;
  34835. let ftCanvas = document.createElement('canvas');
  34836. const Features = (function () {
  34837. let gl = ftCanvas.getContext('webgl') || ftCanvas.getContext('experimental-webgl');
  34838. if (gl === null){
  34839. return null;
  34840. }
  34841. // -- code taken from THREE.WebGLRenderer --
  34842. let _vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT);
  34843. let _vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT);
  34844. // Unused: let _vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
  34845. let _fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  34846. let _fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT);
  34847. // Unused: let _fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT);
  34848. let highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  34849. let mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  34850. // -----------------------------------------
  34851. let precision;
  34852. if (highpAvailable) {
  34853. precision = 'highp';
  34854. } else if (mediumpAvailable) {
  34855. precision = 'mediump';
  34856. } else {
  34857. precision = 'lowp';
  34858. }
  34859. return {
  34860. SHADER_INTERPOLATION: {
  34861. isSupported: function () {
  34862. let supported = true;
  34863. supported = supported && gl.getExtension('EXT_frag_depth');
  34864. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34865. return supported;
  34866. }
  34867. },
  34868. SHADER_SPLATS: {
  34869. isSupported: function () {
  34870. let supported = true;
  34871. supported = supported && gl.getExtension('EXT_frag_depth');
  34872. supported = supported && gl.getExtension('OES_texture_float');
  34873. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34874. return supported;
  34875. }
  34876. },
  34877. SHADER_EDL: {
  34878. isSupported: function () {
  34879. let supported = true;
  34880. supported = supported && gl.getExtension('EXT_frag_depth');
  34881. supported = supported && gl.getExtension('OES_texture_float');
  34882. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34883. //supported = supported || (gl instanceof WebGL2RenderingContext);
  34884. return supported;
  34885. }
  34886. },
  34887. //add:
  34888. EXT_DEPTH:{
  34889. isSupported: function () {
  34890. if(browser.detectIOS()){
  34891. let {major,minor,patch} = browser.iosVersion();
  34892. if(major == 15 && minor == 4 && patch == 1){
  34893. console.warn('检测到是ios15.4.1, 关闭EXT_frag_depth');//该版本ext_depth有问题,导致clear错乱。没有解决办法先关闭。
  34894. return false
  34895. }
  34896. }
  34897. return gl.getExtension('EXT_frag_depth'); //shader中的GL_EXT_frag_depth需要判断一下detectIOS吗。。
  34898. }
  34899. },
  34900. //WEBGL2: {
  34901. // isSupported: function(){
  34902. // return gl instanceof WebGL2RenderingContext;
  34903. // }
  34904. //},
  34905. precision: precision
  34906. };
  34907. }());
  34908. class DepthBasicMaterial extends ShaderMaterial{
  34909. constructor(o={}){
  34910. let {width, height} = viewer.renderer.getSize(new Vector2$1());
  34911. let uniforms = {
  34912. resolution: { type: 'v2', value: new Vector2$1(width, height ) },
  34913. viewportOffset: { type: 'v2', value: new Vector2$1(0, 0 ) }, //left, top
  34914. nearPlane: { type: 'f', value: 0.1 },
  34915. farPlane: { type: 'f', value: 10000 },
  34916. depthTexture: { type: 't', value: null },
  34917. opacity: { type: 'f', value: 1 },
  34918. map: { type: 't', value: o.map },
  34919. baseColor: {type:'v3', value: o.color ? new Color(o.color) : new Color("#ffffff")},
  34920. backColor: {type:'v3', value: o.backColor ? new Color(o.backColor) : new Color("#ddd")},
  34921. clipDistance : { type: 'f', value:o.clipDistance || 4}, //消失距离
  34922. occlusionDistance : { type: 'f', value: o.occlusionDistance || 1 }, //变为backColor距离
  34923. maxClipFactor : { type: 'f', value: o.maxClipFactor || 1 }, //0-1
  34924. };
  34925. let defines = {};
  34926. let useDepth = o.useDepth && Features.EXT_DEPTH.isSupported();/* && Potree.settings.matUseDepth */
  34927. if(useDepth )defines.useDepth = '';
  34928. if(o.map)defines.use_map = '';
  34929. super({
  34930. uniforms,
  34931. vertexShader: Shaders['depthBasic.vs'],
  34932. fragmentShader: Shaders['depthBasic.fs'],
  34933. depthWrite: !1,
  34934. depthTest: !1,
  34935. transparent: o.transparent == void 0 ? true : o.transparent,
  34936. side: o.side || 0 /* THREE.DoubleSide */,
  34937. defines,
  34938. });
  34939. if(o.opacity != void 0){
  34940. this.opacity = o.opacity;
  34941. }
  34942. if(useDepth) this.useDepth_ = true;
  34943. if(this.useDepth){
  34944. let setSize = (e)=>{//如果出现横条状的异常,往往是viewportOffset出错
  34945. let viewport = e.viewport;
  34946. let viewportOffset = viewport.offset || new Vector2$1();
  34947. this.uniforms.resolution.value.copy(viewport.resolution2);
  34948. this.uniforms.viewportOffset.value.copy(viewportOffset);
  34949. //console.log('depth '+viewportOffset.toArray())
  34950. };
  34951. let viewport = viewer.mainViewport;
  34952. setSize( {viewport} );
  34953. viewer.addEventListener('resize',(e)=>{
  34954. if(!this.useDepth || !e.viewport || e.viewport.camera.isPerspectiveCamera){//地图不需要
  34955. setSize(e);
  34956. }
  34957. });
  34958. /* viewer.addEventListener('camera_changed', (e)=>{
  34959. if(e.viewport.name != 'mapViewport') this.updateDepthParams(e)
  34960. }) */
  34961. viewer.addEventListener("render.begin", (e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  34962. if(e.viewport.camera.isPerspectiveCamera) this.updateDepthParams(e);
  34963. });
  34964. this.updateDepthParams();
  34965. }
  34966. //点云变化时要一直触发updateDepthParams??
  34967. //viewer.once("render.pass.end",this.updateDepthParams.bind(this))
  34968. }
  34969. updateDepthParams(e={}){//主要用于点云遮住mesh
  34970. if(this.useDepth){
  34971. var viewport = e.viewport || viewer.mainViewport;
  34972. var camera = viewport.camera;
  34973. /* if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.depthTex){
  34974. this.uniforms.depthTexture.value = viewer.images360.currentPano.depthTex
  34975. }else{ */
  34976. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  34977. //}
  34978. this.uniforms.nearPlane.value = camera.near;
  34979. this.uniforms.farPlane.value = camera.far;
  34980. }
  34981. }
  34982. set map(map){
  34983. this.uniforms.map.value = map;
  34984. }
  34985. get useDepth(){
  34986. return this.useDepth_
  34987. }
  34988. set useDepth(value){//如果不支持 EXT_DEPTH 的话会失效
  34989. if(this.useDepth_ != value){
  34990. if(value && Features.EXT_DEPTH.isSupported()){
  34991. this.defines.useDepth = '';
  34992. this.updateDepthParams();
  34993. }else {
  34994. delete this.defines.useDepth;
  34995. }
  34996. this.useDepth_ = value;
  34997. this.needsUpdate = true;
  34998. }
  34999. }
  35000. get opacity(){
  35001. return this.uniforms.opacity.value
  35002. }
  35003. set opacity(o){
  35004. this.uniforms && (this.uniforms.opacity.value = o);
  35005. }
  35006. /* dispose(){
  35007. super.dispose()
  35008. viewer.depthBasic
  35009. } */
  35010. }
  35011. const geo = new PlaneBufferGeometry(1,1);
  35012. class Sprite$1 extends Mesh{
  35013. constructor(options){
  35014. super(geo, options.mat || new DepthBasicMaterial({map:options.map, useDepth:options.useDepth}));
  35015. this.root = options.root || this;
  35016. this.renderOrder = options.renderOrder != void 0 ? options.renderOrder : 4;
  35017. this.pickOrder = options.pickOrder || 0;
  35018. this.sizeInfo = options.sizeInfo;
  35019. this.dontFixOrient = options.dontFixOrient;
  35020. this.root.matrixAutoUpdate = false;
  35021. this.matrixMap = new Map();
  35022. this.name = options.name || 'sprite';
  35023. this.useViewport = null;
  35024. this.viewports = options.viewports;//指定更新的viewports
  35025. this.visible_ = true;
  35026. let update = (e)=>{
  35027. this.update(e);
  35028. };
  35029. viewer.mapViewer && viewer.mapViewer.addEventListener("camera_changed", update);
  35030. viewer.addEventListener("camera_changed", update);
  35031. /* if(viewer.viewports.length == 1){//直接更新。如果有多个不在这更新,在"render.begin"
  35032. this.update(e)
  35033. } */
  35034. let applyMatrix = (e)=>{
  35035. this.applyMatrix(e);
  35036. };
  35037. viewer.addEventListener("raycaster", applyMatrix); //before render
  35038. viewer.addEventListener("render.begin", applyMatrix); //before render //magnifier时要禁止吗
  35039. this.addEventListener('dispose', ()=>{
  35040. viewer.mapViewer && viewer.mapViewer.removeEventListener("camera_changed", update);
  35041. viewer.removeEventListener("camera_changed", update);
  35042. viewer.removeEventListener("raycaster", applyMatrix); //before render
  35043. viewer.removeEventListener("render.begin", applyMatrix);
  35044. this.dispose();
  35045. });
  35046. }
  35047. set visible(v){
  35048. this.visible_ = v;
  35049. if(v){
  35050. this.update();
  35051. }
  35052. }
  35053. get visible(){
  35054. return this.visible_
  35055. }
  35056. realVisible(){
  35057. let parent = this;
  35058. let v;
  35059. while(parent){
  35060. if(parent.visible === false){
  35061. v = false;
  35062. break;
  35063. }
  35064. parent = parent.parent;
  35065. }
  35066. v = true;
  35067. if(!this.latestRealVisi && v){//变为可见后先update
  35068. this.latestRealVisi = true;
  35069. setTimeout(()=>{
  35070. this.update();
  35071. },1);//延迟 防止无限调用
  35072. return false
  35073. }
  35074. this.latestRealVisi = v;
  35075. return v;
  35076. }
  35077. update(e){
  35078. if(!e){
  35079. (this.viewports || viewer.viewports).forEach(view=>{
  35080. this.update({viewport:view});
  35081. });
  35082. return;
  35083. }
  35084. if(!this.root || ! this.realVisible() /* this.visible */ )return
  35085. if(this.viewports && !this.viewports.includes(e.viewport) )return
  35086. if(e.viewport.name == 'magnifier')return
  35087. let camera = e.viewport.camera;
  35088. //rotation
  35089. this.dontFixOrient || this.root.quaternion.copy(camera.quaternion);
  35090. //scale
  35091. var info = this.sizeInfo;
  35092. if(info){
  35093. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  35094. this.root.updateMatrixWorld(true);
  35095. var scale;
  35096. if(info.restricMeshScale){//仅限制最大或最小的话,不判断像素大小,直接限制mesh的scale
  35097. var dis = camera.position.distanceTo(this.root.getWorldPosition(new Vector3()));
  35098. if(dis < info.nearBound){
  35099. scale = info.scale * dis / info.nearBound;
  35100. }else {
  35101. scale = info.scale;
  35102. }
  35103. }else {
  35104. scale = math.getScaleForConstantSize($.extend(info,{//规定下最小最大像素
  35105. camera , position:this.root.getWorldPosition(new Vector3()) ,
  35106. resolution: e.viewport.resolution//2
  35107. }));
  35108. }
  35109. if(!isNaN(scale)){
  35110. this.root.scale.set(scale, scale, scale);
  35111. }
  35112. }
  35113. this.root.updateMatrix();
  35114. this.root.updateMatrixWorld(true);
  35115. this.matrixMap.set(e.viewport, this.root.matrix.clone());
  35116. this.useViewport = e.viewport;
  35117. }
  35118. applyMatrix(e){
  35119. if(!e)e = {viewport:viewer.mainViewport};//随便写一个viewport
  35120. if(e.viewport.name == 'magnifier')return
  35121. if(this.viewports && !this.viewports.includes(e.viewport) )return
  35122. if( !this.root || !this.realVisible() )return
  35123. var matrix = this.matrixMap.get(e.viewport);
  35124. if(!matrix){
  35125. this.update(e);
  35126. matrix = this.matrixMap.get(e.viewport);
  35127. }
  35128. if(e.viewport == this.useViewport){
  35129. return
  35130. }
  35131. this.useViewport = e.viewport;
  35132. this.root.matrix.copy(matrix);
  35133. this.root.updateMatrixWorld(true);
  35134. //console.log(this.root.name + e.viewport.name + " : "+this.root.matrixWorld.elements)
  35135. }
  35136. setUniforms(name,value){
  35137. this.material.setUniforms(name,value);
  35138. }
  35139. dispose(){
  35140. this.removeAllListeners();
  35141. this.parent && this.parent.remove(this);
  35142. }
  35143. }
  35144. //可能还是要用html写,因为要加按钮和图片
  35145. class TextSprite extends Object3D{
  35146. //注:为了分两层控制scale,不直接extend Sprite
  35147. constructor( options={}){
  35148. super();
  35149. let map = new Texture();
  35150. map.minFilter = LinearFilter;
  35151. map.magFilter = LinearFilter;
  35152. this.sprite = new Sprite$1( Object.assign({
  35153. root:this
  35154. }
  35155. ,options,
  35156. {
  35157. map,
  35158. })
  35159. );
  35160. this.add(this.sprite);
  35161. this.fontWeight = options.fontWeight == void 0 ? 'Bold' : options.fontWeight;
  35162. this.rectBorderThick = options.rectBorderThick || 0;
  35163. this.textBorderThick = options.textBorderThick || 0;
  35164. this.fontface = 'Arial';
  35165. this.fontsize = options.fontsize || 16;
  35166. this.textBorderColor = options.textBorderColor || { r: 0, g: 0, b: 0, a: 0.0 };
  35167. this.backgroundColor = options.backgroundColor || { r: 255, g: 255, b: 255, a: 1.0 };
  35168. this.textColor = options.textColor || {r: 0, g: 0, b: 0, a: 1.0};
  35169. this.borderColor = options.borderColor || { r: 0, g: 0, b: 0, a: 0.0 };
  35170. this.borderRadius = options.borderRadius || 6;
  35171. if(options.text != void 0)this.setText(options.text);
  35172. this.name = options.name;
  35173. //this.setText(text);
  35174. this.addEventListener('dispose', this.dispose.bind(this));
  35175. }
  35176. setText(text){
  35177. if (this.text !== text){
  35178. this.text = text + '';
  35179. this.updateTexture();
  35180. }
  35181. }
  35182. setTextColor(color){
  35183. this.textColor = color;
  35184. this.updateTexture();
  35185. }
  35186. setBorderColor(color){
  35187. this.borderColor = color;
  35188. this.updateTexture();
  35189. }
  35190. setBackgroundColor(color){
  35191. this.backgroundColor = color;
  35192. this.updateTexture();
  35193. }
  35194. setPos(pos){
  35195. this.position.copy(pos);
  35196. this.sprite.update();
  35197. }
  35198. update(){
  35199. this.sprite.update();
  35200. }
  35201. setVisible(v){
  35202. this.visible = v;
  35203. }
  35204. setUniforms(name,value){
  35205. this.sprite.setUniforms(name,value);
  35206. }
  35207. updateTexture(){
  35208. let canvas = document.createElement('canvas');
  35209. let context = canvas.getContext('2d');
  35210. context.font = this.fontWeight + ' ' + this.fontsize + 'px ' + this.fontface;
  35211. //context["font-weight"] = 100; //语法与 CSS font 属性相同。
  35212. // get size data (height depends only on font size)
  35213. //this.text = '啊啊啊啊啊啊fag'
  35214. let metrics = context.measureText(this.text );
  35215. let textWidth = metrics.width;
  35216. let margin = new Vector2$1(this.fontsize, Math.max( this.fontsize*0.4, 10) );
  35217. let spriteWidth = 2 * margin.x + textWidth + 2 * this.rectBorderThick;
  35218. let spriteHeight = 2 * margin.y + this.fontsize + 2 * this.rectBorderThick;
  35219. context.canvas.width = spriteWidth;
  35220. context.canvas.height = spriteHeight;
  35221. context.font = this.fontWeight + ' ' + this.fontsize + 'px ' + this.fontface;
  35222. let diff = 2;//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
  35223. context.textBaseline = "middle";
  35224. // border color
  35225. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' +
  35226. this.borderColor.b + ',' + this.borderColor.a + ')';
  35227. context.lineWidth = this.rectBorderThick;
  35228. // background color
  35229. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' +
  35230. this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  35231. this.roundRect(context, this.rectBorderThick / 2, this.rectBorderThick / 2,
  35232. spriteWidth - this.rectBorderThick, spriteHeight - this.rectBorderThick, this.borderRadius);
  35233. // text color
  35234. if(this.textBorderThick){
  35235. context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' +
  35236. this.textBorderColor.b + ',' + this.textBorderColor.a + ')';
  35237. context.lineWidth = this.textBorderThick;
  35238. context.strokeText(this.text , this.rectBorderThick + margin.x,spriteHeight/2 + diff );
  35239. }
  35240. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' +
  35241. this.textColor.b + ',' + this.textColor.a + ')';
  35242. context.fillText(this.text , this.rectBorderThick + margin.x, spriteHeight/2 + diff );//x,y
  35243. let texture = new Texture(canvas);
  35244. texture.minFilter = LinearFilter;
  35245. texture.magFilter = LinearFilter;
  35246. texture.needsUpdate = true;
  35247. //this.material.needsUpdate = true;
  35248. if(this.sprite.material.map){
  35249. this.sprite.material.map.dispose();
  35250. }
  35251. this.sprite.material.map = texture;
  35252. this.sprite.scale.set(spriteWidth * 0.01, spriteHeight * 0.01, 1.0);
  35253. }
  35254. roundRect(ctx, x, y, w, h, r){
  35255. ctx.beginPath();
  35256. ctx.moveTo(x + r, y);
  35257. ctx.lineTo(x + w - r, y);
  35258. ctx.arcTo(x + w, y, x + w, y + r, r );//圆弧。前四个参数同quadraticCurveTo
  35259. //ctx.quadraticCurveTo(x + w, y, x + w, y + r); //二次贝塞尔曲线需要两个点。第一个点是用于二次贝塞尔计算中的控制点,第二个点是曲线的结束点。
  35260. ctx.lineTo(x + w, y + h - r);
  35261. ctx.arcTo(x + w, y + h, x + w - r, y + h, r );
  35262. ctx.lineTo(x + r, y + h);
  35263. ctx.arcTo(x, y + h, x, y + h - r, r );
  35264. ctx.lineTo(x, y + r);
  35265. ctx.arcTo(x, y, x + r, y, r );
  35266. ctx.closePath();
  35267. ctx.fill();
  35268. ctx.stroke();
  35269. }
  35270. dispose(){
  35271. this.sprite.material.uniforms.map.value.dispose();
  35272. this.parent && this.parent.remove(this);
  35273. this.sprite.dispatchEvent({type:'dispose'});
  35274. this.removeAllListeners();
  35275. }
  35276. }
  35277. class Volume extends Object3D {
  35278. constructor (args = {}) {
  35279. super();
  35280. if(this.constructor.name === "Volume"){
  35281. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  35282. }
  35283. //console.log(this);
  35284. //console.log(this.constructor);
  35285. //console.log(this.constructor.name);
  35286. this._clip = args.clip || false;
  35287. this._visible = true;
  35288. this._modifiable = args.modifiable || true;
  35289. { // event listeners
  35290. this.addEventListener('select', e => {});
  35291. this.addEventListener('deselect', e => {});
  35292. }
  35293. }
  35294. get visible(){
  35295. return this._visible;
  35296. }
  35297. set visible(value){
  35298. if(this._visible !== value){
  35299. this._visible = value;
  35300. this.dispatchEvent({type: "visibility_changed", object: this});
  35301. }
  35302. }
  35303. getVolume () {
  35304. console.warn("override this in subclass");
  35305. }
  35306. update () {
  35307. };
  35308. raycast (raycaster, intersects) {
  35309. }
  35310. get clip () {
  35311. return this._clip;
  35312. }
  35313. set clip (value) {
  35314. if(this._clip !== value){
  35315. this._clip = value;
  35316. this.update();
  35317. this.dispatchEvent({
  35318. type: "clip_changed",
  35319. object: this
  35320. });
  35321. }
  35322. }
  35323. get modifieable () {
  35324. return this._modifiable;
  35325. }
  35326. set modifieable (value) {
  35327. this._modifiable = value;
  35328. this.update();
  35329. }
  35330. };
  35331. class BoxVolume extends Volume{
  35332. constructor(args = {}){
  35333. super(args);
  35334. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35335. this.name = 'box_' + this.constructor.counter;
  35336. let boxGeometry = new BoxGeometry(1, 1, 1);
  35337. boxGeometry.computeBoundingBox();
  35338. let boxFrameGeometry = new Geometry();
  35339. {
  35340. let Vector3$1 = Vector3;
  35341. boxFrameGeometry.vertices.push(
  35342. // bottom
  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. new Vector3$1(-0.5, -0.5, 0.5),
  35351. // top
  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. new Vector3$1(-0.5, 0.5, 0.5),
  35360. // sides
  35361. new Vector3$1(-0.5, -0.5, 0.5),
  35362. new Vector3$1(-0.5, 0.5, 0.5),
  35363. new Vector3$1(0.5, -0.5, 0.5),
  35364. new Vector3$1(0.5, 0.5, 0.5),
  35365. new Vector3$1(0.5, -0.5, -0.5),
  35366. new Vector3$1(0.5, 0.5, -0.5),
  35367. new Vector3$1(-0.5, -0.5, -0.5),
  35368. new Vector3$1(-0.5, 0.5, -0.5),
  35369. );
  35370. }
  35371. this.material = new MeshBasicMaterial({
  35372. color: 0x00ff00,
  35373. transparent: true,
  35374. opacity: 0.3,
  35375. depthTest: true,
  35376. depthWrite: false});
  35377. this.box = new Mesh(boxGeometry, this.material);
  35378. this.box.geometry.computeBoundingBox();
  35379. this.boundingBox = this.box.geometry.boundingBox;
  35380. this.add(this.box);
  35381. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  35382. // this.frame.mode = THREE.Lines;
  35383. this.add(this.frame);
  35384. viewer.setObjectLayers(this, 'volume' );
  35385. this.update();
  35386. }
  35387. update(){
  35388. this.boundingBox = this.box.geometry.boundingBox;
  35389. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35390. if (this._clip) {
  35391. this.box.visible = false;
  35392. } else {
  35393. this.box.visible = true;
  35394. }
  35395. }
  35396. raycast (raycaster, intersects) {
  35397. let is = [];
  35398. this.box.raycast(raycaster, is);
  35399. if (is.length > 0) {
  35400. let I = is[0];
  35401. intersects.push({
  35402. distance: I.distance,
  35403. object: this,
  35404. point: I.point.clone()
  35405. });
  35406. }
  35407. }
  35408. getVolume(){
  35409. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  35410. }
  35411. };
  35412. class SphereVolume extends Volume{
  35413. constructor(args = {}){
  35414. super(args);
  35415. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35416. this.name = 'sphere_' + this.constructor.counter;
  35417. let sphereGeometry = new SphereGeometry(1, 32, 32);
  35418. sphereGeometry.computeBoundingBox();
  35419. this.material = new MeshBasicMaterial({
  35420. color: 0x00ff00,
  35421. transparent: true,
  35422. opacity: 0.3,
  35423. depthTest: true,
  35424. depthWrite: false});
  35425. this.sphere = new Mesh(sphereGeometry, this.material);
  35426. this.sphere.visible = false;
  35427. this.sphere.geometry.computeBoundingBox();
  35428. this.boundingBox = this.sphere.geometry.boundingBox;
  35429. this.add(this.sphere);
  35430. let frameGeometry = new Geometry();
  35431. {
  35432. let steps = 64;
  35433. let uSegments = 8;
  35434. let vSegments = 5;
  35435. let r = 1;
  35436. for(let uSegment = 0; uSegment < uSegments; uSegment++){
  35437. let alpha = (uSegment / uSegments) * Math.PI * 2;
  35438. let dirx = Math.cos(alpha);
  35439. let diry = Math.sin(alpha);
  35440. for(let i = 0; i <= steps; i++){
  35441. let v = (i / steps) * Math.PI * 2;
  35442. let vNext = v + 2 * Math.PI / steps;
  35443. let height = Math.sin(v);
  35444. let xyAmount = Math.cos(v);
  35445. let heightNext = Math.sin(vNext);
  35446. let xyAmountNext = Math.cos(vNext);
  35447. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  35448. frameGeometry.vertices.push(vertex);
  35449. let vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  35450. frameGeometry.vertices.push(vertexNext);
  35451. }
  35452. }
  35453. // creates rings at poles, just because it's easier to implement
  35454. for(let vSegment = 0; vSegment <= vSegments + 1; vSegment++){
  35455. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  35456. let uh = (vSegment / (vSegments + 1)); // -1 to 1
  35457. uh = (1 - uh) * (-Math.PI / 2) + uh *(Math.PI / 2);
  35458. let height = Math.sin(uh);
  35459. console.log(uh, height);
  35460. for(let i = 0; i <= steps; i++){
  35461. let u = (i / steps) * Math.PI * 2;
  35462. let uNext = u + 2 * Math.PI / steps;
  35463. let dirx = Math.cos(u);
  35464. let diry = Math.sin(u);
  35465. let dirxNext = Math.cos(uNext);
  35466. let diryNext = Math.sin(uNext);
  35467. let xyAmount = Math.sqrt(1 - height * height);
  35468. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  35469. frameGeometry.vertices.push(vertex);
  35470. let vertexNext = new Vector3(dirxNext * xyAmount, diryNext * xyAmount, height);
  35471. frameGeometry.vertices.push(vertexNext);
  35472. }
  35473. }
  35474. }
  35475. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({color: 0x000000}));
  35476. this.add(this.frame);
  35477. let frameMaterial = new MeshBasicMaterial({wireframe: true, color: 0x000000});
  35478. this.frame = new Mesh(sphereGeometry, frameMaterial);
  35479. //this.add(this.frame);
  35480. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  35481. // this.frame.mode = THREE.Lines;
  35482. //this.add(this.frame);
  35483. this.update();
  35484. }
  35485. update(){
  35486. this.boundingBox = this.sphere.geometry.boundingBox;
  35487. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35488. }
  35489. raycast (raycaster, intersects) {
  35490. let is = [];
  35491. this.sphere.raycast(raycaster, is);
  35492. if (is.length > 0) {
  35493. let I = is[0];
  35494. intersects.push({
  35495. distance: I.distance,
  35496. object: this,
  35497. point: I.point.clone()
  35498. });
  35499. }
  35500. }
  35501. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  35502. getVolume(){
  35503. return (4 / 3) * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  35504. }
  35505. };
  35506. class Profile extends Object3D{
  35507. constructor () {
  35508. super();
  35509. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35510. this.name = 'Profile_' + this.constructor.counter;
  35511. this.points = [];
  35512. this.spheres = [];
  35513. this.edges = [];
  35514. this.boxes = [];
  35515. this.width = 1;
  35516. this.height = 20;
  35517. this._modifiable = true;
  35518. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  35519. this.color = new Color(0xff0000);
  35520. this.lineColor = new Color(0xff0000);
  35521. }
  35522. createSphereMaterial () {
  35523. let sphereMaterial = new MeshLambertMaterial({
  35524. //shading: THREE.SmoothShading,
  35525. color: 0xff0000,
  35526. depthTest: false,
  35527. depthWrite: false}
  35528. );
  35529. return sphereMaterial;
  35530. };
  35531. getSegments () {
  35532. let segments = [];
  35533. for (let i = 0; i < this.points.length - 1; i++) {
  35534. let start = this.points[i].clone();
  35535. let end = this.points[i + 1].clone();
  35536. segments.push({start: start, end: end});
  35537. }
  35538. return segments;
  35539. }
  35540. getSegmentMatrices () {
  35541. let segments = this.getSegments();
  35542. let matrices = [];
  35543. for (let segment of segments) {
  35544. let {start, end} = segment;
  35545. let box = new Object3D();
  35546. let length;
  35547. if(window.axisYup){
  35548. length = start.clone().setY(0).distanceTo(end.clone().setY(0));
  35549. box.scale.set(length, 10000, this.width); //???
  35550. }else {
  35551. length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35552. box.scale.set(length, 10000, this.width);
  35553. box.up.set(0, 0, 1);
  35554. }
  35555. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35556. let diff = new Vector3().subVectors(end, start);
  35557. let target = new Vector3(diff.y, -diff.x, 0);
  35558. box.position.set(0, 0, 0);
  35559. box.lookAt(target);
  35560. box.position.copy(center);
  35561. box.updateMatrixWorld();
  35562. matrices.push(box.matrixWorld);
  35563. }
  35564. return matrices;
  35565. }
  35566. addMarker (point) {
  35567. this.points.push(point);
  35568. let sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  35569. this.add(sphere);
  35570. this.spheres.push(sphere);
  35571. // edges & boxes
  35572. if (this.points.length > 1) {
  35573. let lineGeometry = new Geometry();
  35574. lineGeometry.vertices.push(new Vector3(), new Vector3());
  35575. lineGeometry.colors.push(this.lineColor, this.lineColor, this.lineColor);
  35576. let lineMaterial = new LineBasicMaterial({
  35577. vertexColors: VertexColors,
  35578. lineWidth: 2,
  35579. transparent: true,
  35580. opacity: 0.4
  35581. });
  35582. lineMaterial.depthTest = false;
  35583. let edge = new Line(lineGeometry, lineMaterial);
  35584. edge.visible = false;
  35585. this.add(edge);
  35586. this.edges.push(edge);
  35587. let boxGeometry = new BoxGeometry(1, 1, 1);
  35588. let boxMaterial = new MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: 0.2});
  35589. let box = new Mesh(boxGeometry, boxMaterial);
  35590. box.visible = false;
  35591. this.add(box);
  35592. this.boxes.push(box);
  35593. }
  35594. { // event listeners
  35595. let drag = (e) => {
  35596. let I = Utils.getMousePointCloudIntersection(
  35597. e.drag.end,
  35598. e.viewer.scene.getActiveCamera(),
  35599. e.viewer,
  35600. e.viewer.scene.pointclouds);
  35601. if (I) {
  35602. let i = this.spheres.indexOf(e.drag.object);
  35603. if (i !== -1) {
  35604. this.setPosition(i, I.location);
  35605. //this.dispatchEvent({
  35606. // 'type': 'marker_moved',
  35607. // 'profile': this,
  35608. // 'index': i
  35609. //});
  35610. }
  35611. }
  35612. };
  35613. let drop = e => {
  35614. let i = this.spheres.indexOf(e.drag.object);
  35615. if (i !== -1) {
  35616. this.dispatchEvent({
  35617. 'type': 'marker_dropped',
  35618. 'profile': this,
  35619. 'index': i
  35620. });
  35621. }
  35622. };
  35623. let mouseover = (e) => e.object.material.emissive.setHex(0x888888);
  35624. let mouseleave = (e) => e.object.material.emissive.setHex(0x000000);
  35625. sphere.addEventListener('drag', drag);
  35626. sphere.addEventListener('drop', drop);
  35627. sphere.addEventListener('mouseover', mouseover);
  35628. sphere.addEventListener('mouseleave', mouseleave);
  35629. }
  35630. let event = {
  35631. type: 'marker_added',
  35632. profile: this,
  35633. sphere: sphere
  35634. };
  35635. this.dispatchEvent(event);
  35636. this.setPosition(this.points.length - 1, point);
  35637. }
  35638. removeMarker (index) {
  35639. this.points.splice(index, 1);
  35640. this.remove(this.spheres[index]);
  35641. let edgeIndex = (index === 0) ? 0 : (index - 1);
  35642. this.remove(this.edges[edgeIndex]);
  35643. this.edges.splice(edgeIndex, 1);
  35644. this.remove(this.boxes[edgeIndex]);
  35645. this.boxes.splice(edgeIndex, 1);
  35646. this.spheres.splice(index, 1);
  35647. this.update();
  35648. this.dispatchEvent({
  35649. 'type': 'marker_removed',
  35650. 'profile': this
  35651. });
  35652. }
  35653. setPosition (index, position) {
  35654. let point = this.points[index];
  35655. point.copy(position);
  35656. let event = {
  35657. type: 'marker_moved',
  35658. profile: this,
  35659. index: index,
  35660. position: point.clone()
  35661. };
  35662. this.dispatchEvent(event);
  35663. this.update();
  35664. }
  35665. setWidth (width) {
  35666. this.width = width;
  35667. let event = {
  35668. type: 'width_changed',
  35669. profile: this,
  35670. width: width
  35671. };
  35672. this.dispatchEvent(event);
  35673. this.update();
  35674. }
  35675. getWidth () {
  35676. return this.width;
  35677. }
  35678. update () {
  35679. if (this.points.length === 0) {
  35680. return;
  35681. } else if (this.points.length === 1) {
  35682. let point = this.points[0];
  35683. this.spheres[0].position.copy(point);
  35684. return;
  35685. }
  35686. let min = this.points[0].clone();
  35687. let max = this.points[0].clone();
  35688. let centroid = new Vector3();
  35689. let lastIndex = this.points.length - 1;
  35690. for (let i = 0; i <= lastIndex; i++) {
  35691. let point = this.points[i];
  35692. let sphere = this.spheres[i];
  35693. let leftIndex = (i === 0) ? lastIndex : i - 1;
  35694. // let rightIndex = (i === lastIndex) ? 0 : i + 1;
  35695. let leftVertex = this.points[leftIndex];
  35696. // let rightVertex = this.points[rightIndex];
  35697. let leftEdge = this.edges[leftIndex];
  35698. let rightEdge = this.edges[i];
  35699. let leftBox = this.boxes[leftIndex];
  35700. // rightBox = this.boxes[i];
  35701. // let leftEdgeLength = point.distanceTo(leftVertex);
  35702. // let rightEdgeLength = point.distanceTo(rightVertex);
  35703. // let leftEdgeCenter = new THREE.Vector3().addVectors(leftVertex, point).multiplyScalar(0.5);
  35704. // let rightEdgeCenter = new THREE.Vector3().addVectors(point, rightVertex).multiplyScalar(0.5);
  35705. sphere.position.copy(point);
  35706. if (this._modifiable) {
  35707. sphere.visible = true;
  35708. } else {
  35709. sphere.visible = false;
  35710. }
  35711. if (leftEdge) {
  35712. leftEdge.geometry.vertices[1].copy(point);
  35713. leftEdge.geometry.verticesNeedUpdate = true;
  35714. leftEdge.geometry.computeBoundingSphere();
  35715. }
  35716. if (rightEdge) {
  35717. rightEdge.geometry.vertices[0].copy(point);
  35718. rightEdge.geometry.verticesNeedUpdate = true;
  35719. rightEdge.geometry.computeBoundingSphere();
  35720. }
  35721. if (leftBox) {
  35722. let start = leftVertex;
  35723. let end = point;
  35724. let length;
  35725. if(window.axisYup){
  35726. length = start.clone().setY(0).distanceTo(end.clone().setY(0));
  35727. }else {
  35728. length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35729. leftBox.up.set(0, 0, 1);
  35730. }
  35731. leftBox.scale.set(length, 1000000, this.width);
  35732. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35733. let diff = new Vector3().subVectors(end, start);
  35734. let target = new Vector3(diff.y, -diff.x, 0);
  35735. leftBox.position.set(0, 0, 0);
  35736. leftBox.lookAt(target);
  35737. leftBox.position.copy(center);
  35738. }
  35739. centroid.add(point);
  35740. min.min(point);
  35741. max.max(point);
  35742. }
  35743. centroid.multiplyScalar(1 / this.points.length);
  35744. for (let i = 0; i < this.boxes.length; i++) {
  35745. let box = this.boxes[i];
  35746. box.position.z = min.z + (max.z - min.z) / 2;
  35747. }
  35748. }
  35749. raycast (raycaster, intersects) {
  35750. for (let i = 0; i < this.points.length; i++) {
  35751. let sphere = this.spheres[i];
  35752. sphere.raycast(raycaster, intersects);
  35753. }
  35754. // recalculate distances because they are not necessarely correct
  35755. // for scaled objects.
  35756. // see https://github.com/mrdoob/three.js/issues/5827
  35757. // TODO: remove this once the bug has been fixed
  35758. for (let i = 0; i < intersects.length; i++) {
  35759. let I = intersects[i];
  35760. I.distance = raycaster.ray.origin.distanceTo(I.point);
  35761. }
  35762. intersects.sort(function (a, b) { return a.distance - b.distance; });
  35763. };
  35764. get modifiable () {
  35765. return this._modifiable;
  35766. }
  35767. set modifiable (value) {
  35768. this._modifiable = value;
  35769. this.update();
  35770. }
  35771. }
  35772. class Label extends EventDispatcher{
  35773. constructor(o={}){
  35774. super();
  35775. this.position = o.pos;
  35776. this.text = o.text || '';
  35777. this.elem = $('<div class="hide"><a></a></div>');
  35778. o.className && this.elem.addClass(o.className);
  35779. this.elem.find('a').html(this.text);
  35780. $("#potree_labels").append(this.elem);
  35781. this.pos2d = new Vector3;
  35782. this.dom = o.dom || viewer.renderArea;
  35783. this.camera = o.camera || viewer.scene.getActiveCamera();
  35784. let update = (e)=>{
  35785. this.update(e);
  35786. };
  35787. viewer.addEventListener('camera_changed', update);
  35788. this.addEventListener('dispose', ()=>{
  35789. viewer.removeEventListener('camera_changed', update);
  35790. this.dispose();
  35791. });
  35792. }
  35793. update(){
  35794. if(!this.position || this.elem.hasClass('unvisible'))return
  35795. var p = Utils.getPos2d(this.position,this.camera,this.dom, viewer.mainViewport);
  35796. if(!p.trueSide){
  35797. this.elem.addClass("hide"); return;
  35798. }
  35799. this.elem.css({
  35800. left: p.pos.x +'px',
  35801. top: p.pos.y +'px'
  35802. });
  35803. this.elem.removeClass("hide");
  35804. this.pos2d = p.vector;
  35805. }
  35806. setVisible(visi){
  35807. if(!visi){
  35808. this.elem.addClass("unvisible");
  35809. }else {
  35810. this.elem.removeClass("unvisible");
  35811. this.update();
  35812. }
  35813. }
  35814. setText(text){
  35815. this.text = text || '';
  35816. this.elem.find('a').html(this.text);
  35817. }
  35818. setPos(pos){
  35819. this.position = pos;
  35820. }
  35821. dispose(){
  35822. this.elem.remove();
  35823. this.removeAllListeners();
  35824. }
  35825. }
  35826. const _box$4 = new Box3();
  35827. const _vector$d = new Vector3();
  35828. class LineSegmentsGeometry extends InstancedBufferGeometry {
  35829. constructor() {
  35830. super();
  35831. this.isLineSegmentsGeometry = true;
  35832. this.type = 'LineSegmentsGeometry';
  35833. 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 ];
  35834. const uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ];
  35835. const index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ];
  35836. this.setIndex( index );
  35837. this.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  35838. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  35839. }
  35840. applyMatrix4( matrix ) {
  35841. const start = this.attributes.instanceStart;
  35842. const end = this.attributes.instanceEnd;
  35843. if ( start !== undefined ) {
  35844. start.applyMatrix4( matrix );
  35845. end.applyMatrix4( matrix );
  35846. start.needsUpdate = true;
  35847. }
  35848. if ( this.boundingBox !== null ) {
  35849. this.computeBoundingBox();
  35850. }
  35851. if ( this.boundingSphere !== null ) {
  35852. this.computeBoundingSphere();
  35853. }
  35854. return this;
  35855. }
  35856. setPositions( array ) {
  35857. let lineSegments;
  35858. if ( array instanceof Float32Array ) {
  35859. lineSegments = array;
  35860. } else if ( Array.isArray( array ) ) {
  35861. lineSegments = new Float32Array( array );
  35862. }
  35863. const instanceBuffer = new InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz
  35864. this.setAttribute( 'instanceStart', new InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz
  35865. this.setAttribute( 'instanceEnd', new InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz
  35866. //
  35867. this.computeBoundingBox();
  35868. this.computeBoundingSphere();
  35869. return this;
  35870. }
  35871. setColors( array ) {
  35872. let colors;
  35873. if ( array instanceof Float32Array ) {
  35874. colors = array;
  35875. } else if ( Array.isArray( array ) ) {
  35876. colors = new Float32Array( array );
  35877. }
  35878. const instanceColorBuffer = new InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb
  35879. this.setAttribute( 'instanceColorStart', new InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb
  35880. this.setAttribute( 'instanceColorEnd', new InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb
  35881. return this;
  35882. }
  35883. fromWireframeGeometry( geometry ) {
  35884. this.setPositions( geometry.attributes.position.array );
  35885. return this;
  35886. }
  35887. fromEdgesGeometry( geometry ) {
  35888. this.setPositions( geometry.attributes.position.array );
  35889. return this;
  35890. }
  35891. fromMesh( mesh ) {
  35892. this.fromWireframeGeometry( new WireframeGeometry( mesh.geometry ) );
  35893. // set colors, maybe
  35894. return this;
  35895. }
  35896. fromLineSegments( lineSegments ) {
  35897. const geometry = lineSegments.geometry;
  35898. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  35899. // set colors, maybe
  35900. return this;
  35901. }
  35902. computeBoundingBox() {
  35903. if ( this.boundingBox === null ) {
  35904. this.boundingBox = new Box3();
  35905. }
  35906. const start = this.attributes.instanceStart;
  35907. const end = this.attributes.instanceEnd;
  35908. if ( start !== undefined && end !== undefined ) {
  35909. this.boundingBox.setFromBufferAttribute( start );
  35910. _box$4.setFromBufferAttribute( end );
  35911. this.boundingBox.union( _box$4 );
  35912. }
  35913. }
  35914. computeBoundingSphere() {
  35915. if ( this.boundingSphere === null ) {
  35916. this.boundingSphere = new Sphere();
  35917. }
  35918. if ( this.boundingBox === null ) {
  35919. this.computeBoundingBox();
  35920. }
  35921. const start = this.attributes.instanceStart;
  35922. const end = this.attributes.instanceEnd;
  35923. if ( start !== undefined && end !== undefined ) {
  35924. const center = this.boundingSphere.center;
  35925. this.boundingBox.getCenter( center );
  35926. let maxRadiusSq = 0;
  35927. for ( let i = 0, il = start.count; i < il; i ++ ) {
  35928. _vector$d.fromBufferAttribute( start, i );
  35929. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35930. _vector$d.fromBufferAttribute( end, i );
  35931. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35932. }
  35933. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  35934. if ( isNaN( this.boundingSphere.radius ) ) {
  35935. console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this );
  35936. }
  35937. }
  35938. }
  35939. toJSON() {
  35940. // todo
  35941. }
  35942. applyMatrix( matrix ) {
  35943. console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' );
  35944. return this.applyMatrix4( matrix );
  35945. }
  35946. }
  35947. /**
  35948. * parameters = {
  35949. * color: <hex>,
  35950. * lineWidth: <float>,
  35951. * dashed: <boolean>,
  35952. * dashScale: <float>,
  35953. * dashSize: <float>,
  35954. * dashOffset: <float>,
  35955. * gapSize: <float>,
  35956. * resolution: <Vector2>, // to be set by renderer
  35957. * }
  35958. */
  35959. UniformsLib.line = {
  35960. /*
  35961. worldUnits: { value: 1 },
  35962. lineWidth: { value: 1 },
  35963. resolution: { value: new Vector2( 1, 1 ) },
  35964. dashOffset: { value: 0 },
  35965. dashScale: { value: 1 },
  35966. dashSize: { value: 1 },
  35967. gapSize: { value: 1 } // todo FIX - maybe change to totalSize
  35968. */
  35969. worldUnits: { value: 1 },
  35970. lineWidth: { value: 1 },
  35971. resolution: { value: new Vector2$1( 1, 1 ) },
  35972. viewportOffset: { value: new Vector2$1(0, 0 ) }, //left, top
  35973. dashScale: { value: 1 },
  35974. dashSize: { value: 1 },
  35975. dashOffset: { value: 0 },
  35976. gapSize: { value: 1 },
  35977. opacity: { value: 1 },
  35978. backColor: {type:'v3', value: new Color("#ddd")},
  35979. clipDistance : { type: 'f', value: 4}, //消失距离
  35980. occlusionDistance : { type: 'f', value: 1 }, //变为backColor距离
  35981. maxClipFactor : { type: 'f', value: 1 }, //0-1
  35982. depthTexture:{ value: null },
  35983. nearPlane:{value: 0.1},
  35984. farPlane:{value: 100000},
  35985. };
  35986. ShaderLib[ 'line' ] = {
  35987. uniforms: UniformsUtils.merge( [
  35988. UniformsLib.common,
  35989. UniformsLib.fog,
  35990. UniformsLib.line
  35991. ] ),
  35992. vertexShader:
  35993. /* glsl */`
  35994. #include <common>
  35995. #include <color_pars_vertex>
  35996. #include <fog_pars_vertex>
  35997. #include <logdepthbuf_pars_vertex>
  35998. #include <clipping_planes_pars_vertex>
  35999. uniform float lineWidth;
  36000. uniform vec2 resolution;
  36001. attribute vec3 instanceStart;
  36002. attribute vec3 instanceEnd;
  36003. attribute vec3 instanceColorStart;
  36004. attribute vec3 instanceColorEnd;
  36005. #ifdef WORLD_UNITS
  36006. varying vec4 worldPos;
  36007. varying vec3 worldStart;
  36008. varying vec3 worldEnd;
  36009. #ifdef USE_DASH
  36010. varying vec2 vUv;
  36011. #endif
  36012. #else
  36013. varying vec2 vUv;
  36014. #endif
  36015. #ifdef USE_DASH
  36016. uniform float dashScale;
  36017. attribute float instanceDistanceStart;
  36018. attribute float instanceDistanceEnd;
  36019. varying float vLineDistance;
  36020. #endif
  36021. void trimSegment( const in vec4 start, inout vec4 end ) {
  36022. // trim end segment so it terminates between the camera plane and the near plane
  36023. // conservative estimate of the near plane
  36024. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  36025. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  36026. float nearEstimate = - 0.5 * b / a;
  36027. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  36028. end.xyz = mix( start.xyz, end.xyz, alpha );
  36029. }
  36030. void main() {
  36031. #ifdef USE_COLOR
  36032. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  36033. #endif
  36034. #ifdef USE_DASH
  36035. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  36036. vUv = uv;
  36037. #endif
  36038. float aspect = resolution.x / resolution.y;
  36039. // camera space
  36040. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  36041. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  36042. #ifdef WORLD_UNITS
  36043. worldStart = start.xyz;
  36044. worldEnd = end.xyz;
  36045. #else
  36046. vUv = uv;
  36047. #endif
  36048. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  36049. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  36050. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  36051. // perhaps there is a more elegant solution -- WestLangley
  36052. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  36053. if ( perspective ) {
  36054. if ( start.z < 0.0 && end.z >= 0.0 ) {
  36055. trimSegment( start, end );
  36056. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  36057. trimSegment( end, start );
  36058. }
  36059. }
  36060. // clip space
  36061. vec4 clipStart = projectionMatrix * start;
  36062. vec4 clipEnd = projectionMatrix * end;
  36063. // ndc space
  36064. vec3 ndcStart = clipStart.xyz / clipStart.w;
  36065. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  36066. // direction
  36067. vec2 dir = ndcEnd.xy - ndcStart.xy;
  36068. // account for clip-space aspect ratio
  36069. dir.x *= aspect;
  36070. dir = normalize( dir );
  36071. #ifdef WORLD_UNITS
  36072. // get the offset direction as perpendicular to the view vector
  36073. vec3 worldDir = normalize( end.xyz - start.xyz );
  36074. vec3 offset;
  36075. if ( position.y < 0.5 ) {
  36076. offset = normalize( cross( start.xyz, worldDir ) );
  36077. } else {
  36078. offset = normalize( cross( end.xyz, worldDir ) );
  36079. }
  36080. // sign flip
  36081. if ( position.x < 0.0 ) offset *= - 1.0;
  36082. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  36083. // don't extend the line if we're rendering dashes because we
  36084. // won't be rendering the endcaps
  36085. #ifndef USE_DASH
  36086. // extend the line bounds to encompass endcaps
  36087. start.xyz += - worldDir * lineWidth * 0.5;
  36088. end.xyz += worldDir * lineWidth * 0.5;
  36089. // shift the position of the quad so it hugs the forward edge of the line
  36090. offset.xy -= dir * forwardOffset;
  36091. offset.z += 0.5;
  36092. #endif
  36093. // endcaps
  36094. if ( position.y > 1.0 || position.y < 0.0 ) {
  36095. offset.xy += dir * 2.0 * forwardOffset;
  36096. }
  36097. // adjust for lineWidth
  36098. offset *= lineWidth * 0.5;
  36099. // set the world position
  36100. worldPos = ( position.y < 0.5 ) ? start : end;
  36101. worldPos.xyz += offset;
  36102. // project the worldpos
  36103. vec4 clip = projectionMatrix * worldPos;
  36104. // shift the depth of the projected points so the line
  36105. // segments overlap neatly
  36106. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  36107. clip.z = clipPose.z * clip.w;
  36108. #else
  36109. vec2 offset = vec2( dir.y, - dir.x );
  36110. // undo aspect ratio adjustment
  36111. dir.x /= aspect;
  36112. offset.x /= aspect;
  36113. // sign flip
  36114. if ( position.x < 0.0 ) offset *= - 1.0;
  36115. // endcaps
  36116. if ( position.y < 0.0 ) {
  36117. offset += - dir;
  36118. } else if ( position.y > 1.0 ) {
  36119. offset += dir;
  36120. }
  36121. // adjust for lineWidth
  36122. offset *= lineWidth;
  36123. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  36124. offset /= resolution.y;
  36125. // select end
  36126. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  36127. // back to clip space
  36128. offset *= clip.w;
  36129. clip.xy += offset;
  36130. #endif
  36131. gl_Position = clip;
  36132. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  36133. #include <logdepthbuf_vertex>
  36134. #include <clipping_planes_vertex>
  36135. #include <fog_vertex>
  36136. }
  36137. `,
  36138. fragmentShader:
  36139. /* glsl */`
  36140. uniform vec3 diffuse;
  36141. uniform float opacity;
  36142. uniform float lineWidth;
  36143. uniform vec3 backColor;
  36144. uniform float occlusionDistance;
  36145. uniform float clipDistance;
  36146. uniform float maxClipFactor;
  36147. #ifdef USE_DASH
  36148. uniform float dashOffset;
  36149. uniform float dashSize;
  36150. uniform float gapSize;
  36151. #endif
  36152. //加
  36153. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36154. uniform sampler2D depthTexture;
  36155. uniform float nearPlane;
  36156. uniform float farPlane;
  36157. uniform vec2 resolution;
  36158. uniform vec2 viewportOffset;
  36159. #endif
  36160. varying float vLineDistance;
  36161. #ifdef WORLD_UNITS
  36162. varying vec4 worldPos;
  36163. varying vec3 worldStart;
  36164. varying vec3 worldEnd;
  36165. #ifdef USE_DASH
  36166. varying vec2 vUv;
  36167. #endif
  36168. #else
  36169. varying vec2 vUv;
  36170. #endif
  36171. #include <common>
  36172. #include <color_pars_fragment>
  36173. #include <fog_pars_fragment>
  36174. #include <logdepthbuf_pars_fragment>
  36175. #include <clipping_planes_pars_fragment>
  36176. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36177. float convertToLinear(float zValue)
  36178. {
  36179. float z = zValue * 2.0 - 1.0;
  36180. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  36181. }
  36182. #endif
  36183. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  36184. float mua;
  36185. float mub;
  36186. vec3 p13 = p1 - p3;
  36187. vec3 p43 = p4 - p3;
  36188. vec3 p21 = p2 - p1;
  36189. float d1343 = dot( p13, p43 );
  36190. float d4321 = dot( p43, p21 );
  36191. float d1321 = dot( p13, p21 );
  36192. float d4343 = dot( p43, p43 );
  36193. float d2121 = dot( p21, p21 );
  36194. float denom = d2121 * d4343 - d4321 * d4321;
  36195. float numer = d1343 * d4321 - d1321 * d4343;
  36196. mua = numer / denom;
  36197. mua = clamp( mua, 0.0, 1.0 );
  36198. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  36199. mub = clamp( mub, 0.0, 1.0 );
  36200. return vec2( mua, mub );
  36201. }
  36202. void main() {
  36203. #include <clipping_planes_fragment>
  36204. /*#ifdef USE_DASH
  36205. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  36206. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  36207. #endif*/
  36208. #ifdef USE_DASH
  36209. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  36210. bool unvisible = mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize;
  36211. //加
  36212. #ifdef DASH_with_depth
  36213. #else
  36214. if (unvisible) discard; // todo - FIX
  36215. #endif
  36216. #endif
  36217. float alpha = opacity;
  36218. #ifdef WORLD_UNITS
  36219. // Find the closest points on the view ray and the line segment
  36220. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  36221. vec3 lineDir = worldEnd - worldStart;
  36222. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  36223. vec3 p1 = worldStart + lineDir * params.x;
  36224. vec3 p2 = rayEnd * params.y;
  36225. vec3 delta = p1 - p2;
  36226. float len = length( delta );
  36227. float norm = len / lineWidth;
  36228. #ifndef USE_DASH
  36229. #ifdef USE_ALPHA_TO_COVERAGE
  36230. float dnorm = fwidth( norm );
  36231. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  36232. #else
  36233. if ( norm > 0.5 ) {
  36234. discard;
  36235. }
  36236. #endif
  36237. #endif
  36238. #else
  36239. #ifdef USE_ALPHA_TO_COVERAGE
  36240. // artifacts appear on some hardware if a derivative is taken within a conditional
  36241. float a = vUv.x;
  36242. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  36243. float len2 = a * a + b * b;
  36244. float dlen = fwidth( len2 );
  36245. if ( abs( vUv.y ) > 1.0 ) {
  36246. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  36247. }
  36248. #else
  36249. if ( abs( vUv.y ) > 1.0 ) {
  36250. float a = vUv.x;
  36251. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  36252. float len2 = a * a + b * b;
  36253. if ( len2 > 1.0 ) discard;
  36254. }
  36255. #endif
  36256. #endif
  36257. vec4 diffuseColor = vec4( diffuse, alpha );
  36258. //加
  36259. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36260. float mixFactor = 0.0;
  36261. float clipFactor = 0.0;
  36262. float fragDepth = convertToLinear(gl_FragCoord.z);
  36263. vec2 depthTxtCoords = vec2(gl_FragCoord.x - viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  36264. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  36265. float delta = fragDepth - textureDepth;
  36266. if (delta > 0.0)
  36267. {
  36268. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  36269. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  36270. }
  36271. if (clipFactor == 1.0)
  36272. {
  36273. discard;
  36274. }
  36275. vec4 backColor_ = vec4(backColor, opacity); //vec4(0.8,0.8,0.8, 0.8*opacity);
  36276. #ifdef DASH_with_depth
  36277. // 只在被遮住的部分显示虚线, 所以若同时是虚线不可见部分和被遮住时, a为0
  36278. if(unvisible) backColor_.a = 0.0;
  36279. #endif
  36280. //vec4 diffuseColor = vec4(mix(diffuse, backColor_, mixFactor), opacity*(1.0 - clipFactor));
  36281. diffuseColor = mix(diffuseColor, backColor_ , mixFactor);
  36282. diffuseColor.a *= (1.0 - clipFactor);
  36283. #endif
  36284. #include <logdepthbuf_fragment>
  36285. #include <color_fragment>
  36286. //gl_FragColor = vec4( diffuseColor.rgb, alpha );
  36287. gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
  36288. #include <tonemapping_fragment>
  36289. #include <encodings_fragment>
  36290. #include <fog_fragment>
  36291. #include <premultiplied_alpha_fragment>
  36292. }
  36293. `
  36294. };
  36295. class LineMaterial extends ShaderMaterial {
  36296. constructor( parameters ) {
  36297. super( {
  36298. type: 'LineMaterial',
  36299. uniforms: UniformsUtils.clone( ShaderLib[ 'line' ].uniforms ),
  36300. vertexShader: ShaderLib[ 'line' ].vertexShader,
  36301. fragmentShader: ShaderLib[ 'line' ].fragmentShader,
  36302. clipping: true // required for clipping support
  36303. } );
  36304. this.isLineMaterial = true;
  36305. this.lineWidth_ = 0;
  36306. this.supportExtDepth = parameters.supportExtDepth;
  36307. this.depthTestWhenPick = false; //pick时是否识别点云等
  36308. if(parameters.color){
  36309. this.color = new Color(parameters.color);
  36310. }
  36311. if(parameters.backColor){
  36312. this.uniforms.backColor.value = new Color(parameters.backColor);
  36313. }
  36314. if(parameters.clipDistance){
  36315. this.uniforms.clipDistance.value = parameters.clipDistance;
  36316. }
  36317. if(parameters.occlusionDistance){
  36318. this.uniforms.occlusionDistance.value = parameters.occlusionDistance;
  36319. }
  36320. if(parameters.maxClipFactor){
  36321. this.uniforms.maxClipFactor.value = parameters.maxClipFactor;
  36322. }
  36323. Object.defineProperties( this, {
  36324. color: {
  36325. enumerable: true,
  36326. get: function () {
  36327. return this.uniforms.diffuse.value;
  36328. },
  36329. set: function ( value ) {
  36330. this.uniforms.diffuse.value = value;
  36331. }
  36332. },
  36333. worldUnits: {
  36334. enumerable: true,
  36335. get: function () {
  36336. return 'WORLD_UNITS' in this.defines;
  36337. },
  36338. set: function ( value ) {
  36339. if ( value === true ) {
  36340. this.defines.WORLD_UNITS = '';
  36341. } else {
  36342. delete this.defines.WORLD_UNITS;
  36343. }
  36344. }
  36345. },
  36346. lineWidth: {
  36347. enumerable: true,
  36348. get: function () {
  36349. return this.lineWidth_;//this.uniforms.lineWidth.value;
  36350. },
  36351. set: function ( value ) {
  36352. this.uniforms.lineWidth.value = value * window.devicePixelRatio;
  36353. this.lineWidth_ = value;
  36354. }
  36355. },
  36356. dashed: {
  36357. enumerable: true,
  36358. get: function () {
  36359. return Boolean( 'USE_DASH' in this.defines );
  36360. },
  36361. set( value ) {
  36362. if ( Boolean( value ) !== Boolean( 'USE_DASH' in this.defines ) ) {
  36363. this.needsUpdate = true;
  36364. }
  36365. if ( value === true ) {
  36366. this.defines.USE_DASH = '';
  36367. } else {
  36368. delete this.defines.USE_DASH;
  36369. }
  36370. }
  36371. },
  36372. dashScale: {
  36373. enumerable: true,
  36374. get: function () {
  36375. return this.uniforms.dashScale.value;
  36376. },
  36377. set: function ( value ) {
  36378. this.uniforms.dashScale.value = value;
  36379. }
  36380. },
  36381. dashSize: {
  36382. enumerable: true,
  36383. get: function () {
  36384. return this.uniforms.dashSize.value;
  36385. },
  36386. set: function ( value ) {
  36387. this.uniforms.dashSize.value = value;
  36388. }
  36389. },
  36390. dashOffset: {
  36391. enumerable: true,
  36392. get: function () {
  36393. return this.uniforms.dashOffset.value;
  36394. },
  36395. set: function ( value ) {
  36396. this.uniforms.dashOffset.value = value;
  36397. }
  36398. },
  36399. gapSize: {
  36400. enumerable: true,
  36401. get: function () {
  36402. return this.uniforms.gapSize.value;
  36403. },
  36404. set: function ( value ) {
  36405. this.uniforms.gapSize.value = value;
  36406. }
  36407. },
  36408. opacity: {
  36409. enumerable: true,
  36410. get: function () {
  36411. return this.uniforms.opacity.value;
  36412. },
  36413. set: function ( value ) {
  36414. this.uniforms.opacity.value = value;
  36415. }
  36416. },
  36417. resolution: {
  36418. enumerable: true,
  36419. get: function () {
  36420. return this.uniforms.resolution.value;
  36421. },
  36422. set: function ( value ) {
  36423. this.uniforms.resolution.value.copy( value );
  36424. }
  36425. },
  36426. alphaToCoverage: {
  36427. enumerable: true,
  36428. get: function () {
  36429. return Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines );
  36430. },
  36431. set: function ( value ) {
  36432. if ( Boolean( value ) !== Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines ) ) {
  36433. this.needsUpdate = true;
  36434. }
  36435. if ( value === true ) {
  36436. this.defines.USE_ALPHA_TO_COVERAGE = '';
  36437. this.extensions.derivatives = true;
  36438. } else {
  36439. delete this.defines.USE_ALPHA_TO_COVERAGE;
  36440. this.extensions.derivatives = false;
  36441. }
  36442. }
  36443. }
  36444. ,
  36445. useDepth:{//add
  36446. enumerable: true,
  36447. get: function () {
  36448. return 'useDepth' in this.defines
  36449. },
  36450. set: function ( value ) {
  36451. value = value && !!this.supportExtDepth;
  36452. if(value != this.useDepth){
  36453. if(value){
  36454. this.defines.useDepth = '';
  36455. this.updateDepthParams();
  36456. }else {
  36457. delete this.defines.useDepth;
  36458. }
  36459. this.needsUpdate = true;
  36460. }
  36461. }
  36462. },
  36463. dashWithDepth:{//add
  36464. enumerable: true,
  36465. get: function () {
  36466. return 'DASH_with_depth' in this.defines
  36467. },
  36468. set: function ( value ) {
  36469. value = value && !!this.supportExtDepth;
  36470. if(value != this.dashWithDepth){
  36471. if(value){
  36472. this.defines.DASH_with_depth = '';
  36473. }else {
  36474. delete this.defines.DASH_with_depth;
  36475. }
  36476. this.needsUpdate = true;
  36477. }
  36478. }
  36479. },
  36480. } );
  36481. this.setValues( parameters );
  36482. let setSize = (e)=>{
  36483. let viewport = e.viewport;
  36484. let viewportOffset = viewport.offset || new Vector2$1();
  36485. this.uniforms.resolution.value.copy(viewport.resolution2);
  36486. this.uniforms.viewportOffset.value.copy(viewportOffset);
  36487. this.lineWidth = this.lineWidth_;
  36488. };
  36489. let viewport = viewer.mainViewport;
  36490. setSize({viewport});
  36491. viewer.addEventListener('resize',(e)=>{
  36492. setSize(e);
  36493. });
  36494. if(this.supportExtDepth){
  36495. //add
  36496. this.updateDepthParams();
  36497. /* viewer.addEventListener('camera_changed', (e)=>{
  36498. if(e.viewport.name != 'mapViewport') this.updateDepthParams(e)
  36499. }) */
  36500. viewer.addEventListener("render.begin", (e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  36501. if(e.viewport.camera.isPerspectiveCamera) this.updateDepthParams(e);
  36502. });
  36503. }
  36504. }
  36505. updateDepthParams(e={}){
  36506. if(this.useDepth){
  36507. var viewport = e.viewport || viewer.mainViewport;
  36508. var camera = viewport.camera;
  36509. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //viewer.getPRenderer().rtEDL.depthTexture
  36510. this.uniforms.nearPlane.value = camera.near; //似乎因为这个所以对OrthographicCamera 无效
  36511. this.uniforms.farPlane.value = camera.far;
  36512. }
  36513. }
  36514. }
  36515. const _start$2 = new Vector3();
  36516. const _end$2 = new Vector3();
  36517. const _start4 = new Vector4();
  36518. const _end4 = new Vector4();
  36519. const _ssOrigin = new Vector4();
  36520. const _ssOrigin3 = new Vector3();
  36521. const _mvMatrix = new Matrix4();
  36522. const _line = new Line3();
  36523. const _closestPoint = new Vector3();
  36524. const _box$5 = new Box3();
  36525. const _sphere$4 = new Sphere();
  36526. const _clipToWorldVector = new Vector4();
  36527. let _ray$3, _instanceStart, _instanceEnd, _lineWidth;
  36528. // Returns the margin required to expand by in world space given the distance from the camera,
  36529. // line width, resolution, and camera projection
  36530. function getWorldSpaceHalfWidth( camera, distance, resolution ) {
  36531. // transform into clip space, adjust the x and y values by the pixel width offset, then
  36532. // transform back into world space to get world offset. Note clip space is [-1, 1] so full
  36533. // width does not need to be halved.
  36534. _clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
  36535. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  36536. _clipToWorldVector.x = _lineWidth / resolution.width;
  36537. _clipToWorldVector.y = _lineWidth / resolution.height;
  36538. _clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
  36539. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  36540. return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
  36541. }
  36542. function raycastWorldUnits( lineSegments, intersects ) {
  36543. for ( let i = 0, l = _instanceStart.count; i < l; i ++ ) {
  36544. _line.start.fromBufferAttribute( _instanceStart, i );
  36545. _line.end.fromBufferAttribute( _instanceEnd, i );
  36546. const pointOnLine = new Vector3();
  36547. const point = new Vector3();
  36548. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  36549. const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
  36550. if ( isInside ) {
  36551. intersects.push( {
  36552. point,
  36553. pointOnLine,
  36554. distance: _ray$3.origin.distanceTo( point ),
  36555. object: lineSegments,
  36556. face: null,
  36557. faceIndex: i,
  36558. uv: null,
  36559. uv2: null,
  36560. } );
  36561. }
  36562. }
  36563. }
  36564. function raycastScreenSpace( lineSegments, camera, intersects ) {
  36565. const projectionMatrix = camera.projectionMatrix;
  36566. const material = lineSegments.material;
  36567. const resolution = material.resolution;
  36568. const matrixWorld = lineSegments.matrixWorld;
  36569. const geometry = lineSegments.geometry;
  36570. const instanceStart = geometry.attributes.instanceStart;
  36571. const instanceEnd = geometry.attributes.instanceEnd;
  36572. const near = - camera.near;
  36573. //
  36574. // pick a point 1 unit out along the ray to avoid the ray origin
  36575. // sitting at the camera origin which will cause "w" to be 0 when
  36576. // applying the projection matrix.
  36577. _ray$3.at( 1, _ssOrigin );
  36578. // ndc space [ - 1.0, 1.0 ]
  36579. _ssOrigin.w = 1;
  36580. _ssOrigin.applyMatrix4( camera.matrixWorldInverse );
  36581. _ssOrigin.applyMatrix4( projectionMatrix );
  36582. _ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
  36583. // screen space
  36584. _ssOrigin.x *= resolution.x / 2;
  36585. _ssOrigin.y *= resolution.y / 2;
  36586. _ssOrigin.z = 0;
  36587. _ssOrigin3.copy( _ssOrigin );
  36588. _mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
  36589. for ( let i = 0, l = instanceStart.count; i < l; i ++ ) {
  36590. _start4.fromBufferAttribute( instanceStart, i );
  36591. _end4.fromBufferAttribute( instanceEnd, i );
  36592. _start4.w = 1;
  36593. _end4.w = 1;
  36594. // camera space
  36595. _start4.applyMatrix4( _mvMatrix );
  36596. _end4.applyMatrix4( _mvMatrix );
  36597. // skip the segment if it's entirely behind the camera
  36598. const isBehindCameraNear = _start4.z > near && _end4.z > near;
  36599. if ( isBehindCameraNear ) {
  36600. continue;
  36601. }
  36602. // trim the segment if it extends behind camera near
  36603. if ( _start4.z > near ) {
  36604. const deltaDist = _start4.z - _end4.z;
  36605. const t = ( _start4.z - near ) / deltaDist;
  36606. _start4.lerp( _end4, t );
  36607. } else if ( _end4.z > near ) {
  36608. const deltaDist = _end4.z - _start4.z;
  36609. const t = ( _end4.z - near ) / deltaDist;
  36610. _end4.lerp( _start4, t );
  36611. }
  36612. // clip space
  36613. _start4.applyMatrix4( projectionMatrix );
  36614. _end4.applyMatrix4( projectionMatrix );
  36615. // ndc space [ - 1.0, 1.0 ]
  36616. _start4.multiplyScalar( 1 / _start4.w );
  36617. _end4.multiplyScalar( 1 / _end4.w );
  36618. // screen space
  36619. _start4.x *= resolution.x / 2;
  36620. _start4.y *= resolution.y / 2;
  36621. _end4.x *= resolution.x / 2;
  36622. _end4.y *= resolution.y / 2;
  36623. // create 2d segment
  36624. _line.start.copy( _start4 );
  36625. _line.start.z = 0;
  36626. _line.end.copy( _end4 );
  36627. _line.end.z = 0;
  36628. // get closest point on ray to segment
  36629. const param = _line.closestPointToPointParameter( _ssOrigin3, true );
  36630. _line.at( param, _closestPoint );
  36631. // check if the intersection point is within clip space
  36632. const zPos = MathUtils.lerp( _start4.z, _end4.z, param );
  36633. const isInClipSpace = zPos >= - 1 && zPos <= 1;
  36634. const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
  36635. if ( isInClipSpace && isInside ) {
  36636. _line.start.fromBufferAttribute( instanceStart, i );
  36637. _line.end.fromBufferAttribute( instanceEnd, i );
  36638. _line.start.applyMatrix4( matrixWorld );
  36639. _line.end.applyMatrix4( matrixWorld );
  36640. const pointOnLine = new Vector3();
  36641. const point = new Vector3();
  36642. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  36643. intersects.push( {
  36644. point: point,
  36645. pointOnLine: pointOnLine,
  36646. distance: _ray$3.origin.distanceTo( point ),
  36647. object: lineSegments,
  36648. face: null,
  36649. faceIndex: i,
  36650. uv: null,
  36651. uv2: null,
  36652. } );
  36653. }
  36654. }
  36655. }
  36656. class LineSegments2 extends Mesh {
  36657. constructor( geometry = new LineSegmentsGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36658. super( geometry, material );
  36659. this.isLineSegments2 = true;
  36660. this.type = 'LineSegments2';
  36661. }
  36662. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  36663. computeLineDistances() {
  36664. const geometry = this.geometry;
  36665. const instanceStart = geometry.attributes.instanceStart;
  36666. const instanceEnd = geometry.attributes.instanceEnd;
  36667. const lineDistances = new Float32Array( 2 * instanceStart.count );
  36668. for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
  36669. _start$2.fromBufferAttribute( instanceStart, i );
  36670. _end$2.fromBufferAttribute( instanceEnd, i );
  36671. lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
  36672. lineDistances[ j + 1 ] = lineDistances[ j ] + _start$2.distanceTo( _end$2 );
  36673. }
  36674. const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
  36675. geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
  36676. geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
  36677. return this;
  36678. }
  36679. raycast( raycaster, intersects ) {
  36680. const worldUnits = this.material.worldUnits;
  36681. const camera = raycaster.camera;
  36682. if ( camera === null && ! worldUnits ) {
  36683. console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
  36684. }
  36685. const threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
  36686. _ray$3 = raycaster.ray;
  36687. const matrixWorld = this.matrixWorld;
  36688. const geometry = this.geometry;
  36689. const material = this.material;
  36690. _lineWidth = material.lineWidth + threshold;
  36691. _instanceStart = geometry.attributes.instanceStart;
  36692. _instanceEnd = geometry.attributes.instanceEnd;
  36693. // check if we intersect the sphere bounds
  36694. if ( geometry.boundingSphere === null ) {
  36695. geometry.computeBoundingSphere();
  36696. }
  36697. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
  36698. // increase the sphere bounds by the worst case line screen space width
  36699. let sphereMargin;
  36700. if ( worldUnits ) {
  36701. sphereMargin = _lineWidth * 0.5;
  36702. } else {
  36703. const distanceToSphere = Math.max( camera.near, _sphere$4.distanceToPoint( _ray$3.origin ) );
  36704. sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, material.resolution );
  36705. }
  36706. _sphere$4.radius += sphereMargin;
  36707. if ( _ray$3.intersectsSphere( _sphere$4 ) === false ) {
  36708. return;
  36709. }
  36710. // check if we intersect the box bounds
  36711. if ( geometry.boundingBox === null ) {
  36712. geometry.computeBoundingBox();
  36713. }
  36714. _box$5.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
  36715. // increase the box bounds by the worst case line width
  36716. let boxMargin;
  36717. if ( worldUnits ) {
  36718. boxMargin = _lineWidth * 0.5;
  36719. } else {
  36720. const distanceToBox = Math.max( camera.near, _box$5.distanceToPoint( _ray$3.origin ) );
  36721. boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, material.resolution );
  36722. }
  36723. _box$5.expandByScalar( boxMargin );
  36724. if ( _ray$3.intersectsBox( _box$5 ) === false ) {
  36725. return;
  36726. }
  36727. if ( worldUnits ) {
  36728. raycastWorldUnits( this, intersects );
  36729. } else {
  36730. raycastScreenSpace( this, camera, intersects );
  36731. }
  36732. }
  36733. }
  36734. class LineGeometry extends LineSegmentsGeometry {
  36735. constructor() {
  36736. super();
  36737. this.isLineGeometry = true;
  36738. this.type = 'LineGeometry';
  36739. }
  36740. setPositions( array ) {
  36741. // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
  36742. const length = array.length - 3;
  36743. const points = new Float32Array( 2 * length );
  36744. for ( let i = 0; i < length; i += 3 ) {
  36745. points[ 2 * i ] = array[ i ];
  36746. points[ 2 * i + 1 ] = array[ i + 1 ];
  36747. points[ 2 * i + 2 ] = array[ i + 2 ];
  36748. points[ 2 * i + 3 ] = array[ i + 3 ];
  36749. points[ 2 * i + 4 ] = array[ i + 4 ];
  36750. points[ 2 * i + 5 ] = array[ i + 5 ];
  36751. }
  36752. super.setPositions( points );
  36753. return this;
  36754. }
  36755. setColors( array ) {
  36756. // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
  36757. const length = array.length - 3;
  36758. const colors = new Float32Array( 2 * length );
  36759. for ( let i = 0; i < length; i += 3 ) {
  36760. colors[ 2 * i ] = array[ i ];
  36761. colors[ 2 * i + 1 ] = array[ i + 1 ];
  36762. colors[ 2 * i + 2 ] = array[ i + 2 ];
  36763. colors[ 2 * i + 3 ] = array[ i + 3 ];
  36764. colors[ 2 * i + 4 ] = array[ i + 4 ];
  36765. colors[ 2 * i + 5 ] = array[ i + 5 ];
  36766. }
  36767. super.setColors( colors );
  36768. return this;
  36769. }
  36770. fromLine( line ) {
  36771. const geometry = line.geometry;
  36772. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  36773. // set colors, maybe
  36774. return this;
  36775. }
  36776. }
  36777. class Line2 extends LineSegments2 {
  36778. constructor( geometry = new LineGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36779. super( geometry, material );
  36780. this.isLine2 = true;
  36781. this.type = 'Line2';
  36782. }
  36783. }
  36784. var defaultColor = new Color(1,1,1);//config.applicationName == "zhiHouse" ? Colors.zhiBlue : Colors.lightGreen;
  36785. var LineDraw = {
  36786. createLine: function (posArr, o={}) {
  36787. //多段普通线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  36788. var mat;
  36789. if(o.mat){
  36790. mat = o.mat;
  36791. }else {
  36792. let prop = {
  36793. lineWidth: o.lineWidth || 1,
  36794. //windows无效。 似乎mac/ios上粗细有效 ?
  36795. color: o.color || defaultColor,
  36796. transparent: o.dontAlwaysSeen ? false : true,
  36797. depthTest: o.dontAlwaysSeen ? true : false,
  36798. };
  36799. if(o.deshed ){
  36800. prop.dashSize = o.dashSize || 0.1,
  36801. prop.gapSize = o.gapSize || 0.1;
  36802. }
  36803. mat = new THREE$1[o.deshed ? "LineDashedMaterial" : "LineBasicMaterial"](prop);
  36804. }
  36805. var line = new LineSegments(new BufferGeometry, mat);
  36806. line.renderOrder = o.renderOrder || 4;
  36807. this.moveLine(line, posArr);
  36808. return line;
  36809. },
  36810. moveLine: function (line, posArr) {
  36811. if(posArr.length == 0)return
  36812. let position = [];
  36813. posArr.forEach(e=>position.push(e.x,e.y,e.z));
  36814. line.geometry.setAttribute('position', new Float32BufferAttribute(/* new Float32Array( */position/* ) */, 3));
  36815. line.geometry.attributes.position.needsUpdate = true;
  36816. line.geometry.computeBoundingSphere();
  36817. if(line.material instanceof LineDashedMaterial){
  36818. line.computeLineDistances();
  36819. //line.geometry.attributes.lineDistance.needsUpdate = true;
  36820. line.geometry.verticesNeedUpdate = true; //没用
  36821. }
  36822. }
  36823. ,
  36824. createFatLineMat : function(o){
  36825. var supportExtDepth = !!Features.EXT_DEPTH.isSupported();
  36826. let params = $.extend({}, {
  36827. //默认
  36828. lineWidth : 5,
  36829. color:0xffffff,
  36830. transparent : true, depthWrite:false, depthTest:false,
  36831. dashSize : 0.1, gapSize:0.1,
  36832. }, o, {
  36833. //修正覆盖:
  36834. dashed: o.dashWithDepth ? supportExtDepth && !!o.dashed : !!o.dashed ,
  36835. dashWithDepth:!!o.dashWithDepth,//只在被遮住的部分显示虚线
  36836. useDepth: !!o.useDepth,
  36837. supportExtDepth,
  36838. });
  36839. var mat = new LineMaterial(params);
  36840. //if(o.dashed)(mat.defines.USE_DASH = "")
  36841. return mat;
  36842. },
  36843. /*
  36844. 创建可以改变粗细的线。
  36845. */
  36846. createFatLine : function(posArr, o){
  36847. var geometry = new LineGeometry();
  36848. geometry.setColors( o.color || [1,1,1]);
  36849. var matLine = o.material || this.createFatLineMat(o);
  36850. var line = new Line2( geometry, matLine );
  36851. //line.computeLineDistances();
  36852. line.scale.set( 1, 1, 1 );
  36853. line.renderOrder = 2;
  36854. this.moveFatLine(line, posArr);
  36855. return line;
  36856. },
  36857. moveFatLine: function(line, posArr){
  36858. var geometry = line.geometry;
  36859. var positions = [];
  36860. posArr.forEach(e=>{positions.push(...e.toArray());});
  36861. if(positions.length > 0){
  36862. if(!geometry){
  36863. geometry = line.geometry = new LineGeometry();
  36864. }
  36865. if(geometry.attributes.instanceEnd && geometry.attributes.instanceEnd.data.array.length != positions.length){//positions个数改变会有部分显示不出来,所以重建
  36866. geometry.dispose();
  36867. geometry = new LineGeometry();
  36868. line.geometry = geometry;
  36869. }
  36870. geometry.setPositions( positions );
  36871. if(line.material.defines.USE_DASH != void 0){
  36872. //line.geometry.verticesNeedUpdate = true; //没用
  36873. line.geometry.computeBoundingSphere(); //for raycaster
  36874. line.computeLineDistances();
  36875. }
  36876. }else {
  36877. geometry.dispose();
  36878. line.geometry = new LineGeometry();
  36879. }
  36880. },
  36881. updateLine: function(line, posArr){
  36882. if(line instanceof Line2){
  36883. LineDraw.moveFatLine(line,posArr);
  36884. }else {
  36885. LineDraw.moveLine(line,posArr);
  36886. }
  36887. },
  36888. /*
  36889. 为line创建用于检测鼠标的透明mesh,实际是个1-2段圆台。
  36890. 由于近大远小的原因,假设没有透视畸变、创建的是等粗的圆柱的话, 所看到的线上每个位置的粗细应该和距离成反比。所以将圆柱改为根据距离线性渐变其截面半径的圆台,在最近点(相机到线的垂足)最细。如果最近点在线段上,则分成两段圆台,否则一段。
  36891. */
  36892. createBoldLine:function(points, o){
  36893. o = o || {};
  36894. var cylinder = o && o.cylinder;
  36895. var CD = points[1].clone().sub(points[0]);
  36896. var rotate = function(){//根据端点旋转好模型
  36897. cylinder.lastVector = CD;//记录本次的端点向量
  36898. var AB = new Vector3(0,-1,0);
  36899. var axisVec = AB.clone().cross(CD).normalize(); //得到垂直于它们的向量,也就是旋转轴
  36900. var rotationAngle = AB.angleTo(CD);
  36901. cylinder.quaternion.setFromAxisAngle( axisVec, rotationAngle );
  36902. };
  36903. if(o && o.type == "init"){
  36904. cylinder = new Mesh();
  36905. cylinder.material = o.mat;
  36906. if(CD.length() == 0)return cylinder;
  36907. rotate();
  36908. }
  36909. if(CD.length() == 0)return cylinder;
  36910. if(o.type != "update"){
  36911. var CDcenter = points[0].clone().add(points[1]).multiplyScalar(.5);
  36912. cylinder.position.copy(CDcenter);
  36913. if(!cylinder.lastVector || o.type == "moveAndRotate")rotate();
  36914. else if(cylinder.lastVector && CD.angleTo(cylinder.lastVector)>0) rotate();//线方向改了or线反向了 重新旋转一下模型
  36915. if(config.isEdit && !objects.mainDesign.editing )return cylinder;//节省初始加载时间?
  36916. }
  36917. //为了保证线段任何地方的可检测点击范围看起来一样大,更新圆台的结构(但是在镜头边缘会比中心看起来大)
  36918. var height = points[0].distanceTo(points[1]);
  36919. var standPos = o && o.standPos || objects.player.position;
  36920. var k = config.isMobile ? 20 : 40;
  36921. var dis1 = points[0].distanceTo(standPos);
  36922. var dis2 = points[1].distanceTo(standPos);
  36923. var foot = math.getFootPoint(standPos, points[0], points[1]);//垂足
  36924. if(o.constantBold || objects.player.mode != "panorama"){
  36925. var width = 0.1;//0.08;
  36926. var pts = [new Vector2$1(width ,height/2),new Vector2$1(width ,-height/2)];
  36927. }else if(foot.clone().sub(points[0]).dot( foot.clone().sub(points[1]) ) > 0){//foot不在线段上
  36928. var pts = [new Vector2$1(dis1 / k,height/2),new Vector2$1(dis2 / k,-height/2)];
  36929. }else {//在线段上的话,要在垂足这加一个节点,因它距离站位最近,而两端较远
  36930. var dis3 = foot.distanceTo(standPos);
  36931. var len = foot.distanceTo(points[0]);
  36932. var pts = [new Vector2$1(dis1 / k,height/2), new Vector2$1(dis3 / k,height/2-len), new Vector2$1(dis2 / k,-height/2)];
  36933. }
  36934. cylinder.geometry && cylinder.geometry.dispose();//若不删除会占用内存
  36935. cylinder.geometry = new LatheBufferGeometry( pts, 4/* Math.min(dis1,dis2)<10?4:3 */ );
  36936. cylinder.renderOrder = 2;
  36937. return cylinder;
  36938. },
  36939. updateBoldLine:function(cylinder, points, type, standPos, constantBold){
  36940. this.createBoldLine(points,{type:type, cylinder : cylinder, standPos:standPos, constantBold}); //type:move:平移 会改长短 , type:update根据距离和角度更新 不改长短
  36941. },
  36942. };
  36943. var MeshDraw = {
  36944. getShape:function(points, holes){
  36945. var shape = new Shape();
  36946. shape.moveTo( points[0].x, points[0].y );
  36947. for(var i=1,len=points.length; i<len; i++){
  36948. shape.lineTo(points[i].x, points[i].y );
  36949. }
  36950. /* var holePath = new THREE.Path()
  36951. .moveTo( 20, 10 )
  36952. .absarc( 10, 10, 10, 0, Math.PI * 2, true )
  36953. arcShape.holes.push( holePath );
  36954. */
  36955. if(holes){//挖空
  36956. holes.forEach((points)=>{
  36957. var holePath = new Path();
  36958. holePath.moveTo( points[0].x, points[0].y );
  36959. for(var i=1,len=points.length; i<len; i++){
  36960. holePath.lineTo(points[i].x, points[i].y );
  36961. }
  36962. shape.holes.push( holePath );
  36963. });
  36964. }
  36965. return shape
  36966. },
  36967. getShapeGeo: function(points, holes){//获取任意形状(多边形或弧形)的形状面 //quadraticCurveTo() 这是弧形的含函数
  36968. var geometry = new ShapeBufferGeometry( this.getShape(points, holes) ); //ShapeGeometry
  36969. /* var matrix = new THREE.Matrix4();//将竖直的面变为水平
  36970. matrix.set(//z = y
  36971. 1, 0, 0, 0,
  36972. 0, 0, 0, 0,
  36973. 0, 1, 0, 0,
  36974. 0, 0, 0, 1
  36975. )
  36976. geometry.applyMatrix(matrix) */
  36977. //geometry.computeVertexNormals();//对于光照需要的是点法线
  36978. return geometry;
  36979. },
  36980. getExtrudeGeo: function(points, holes, options={}){//获得挤出棱柱,可以选择传递height,或者extrudePath
  36981. var shape = this.getShape(points, holes); //points是横截面 [vector2,...]
  36982. if(options.extrudePath ){// 路径 :[vector3,...]
  36983. var length = extrudePath.reduce((total, currentValue, currentIndex, arr)=>{
  36984. if(currentIndex == 0)return 0
  36985. return total + currentValue.distanceTo(arr[currentIndex-1]);
  36986. },0);
  36987. options.extrudePath = new CatmullRomCurve3(extrudePath, options.closed , 'catmullrom' /* 'centripetal' */ , options.tension);
  36988. }
  36989. var extrudeSettings = $.extend(options,{
  36990. steps: options.steps != void 0 ? options.steps : ( options.extrudePath ? Math.round(length/0.3) : 1),
  36991. bevelEnabled: false, //不加的话,height为0时会有圆弧高度
  36992. //depth
  36993. });
  36994. var geometry = new ExtrudeBufferGeometry( shape, extrudeSettings );
  36995. return geometry;
  36996. },
  36997. getUnPosPlaneGeo : function(){//获取还没有赋值位置的plane geometry
  36998. var e = new Uint16Array([0, 1, 2, 0, 2, 3])
  36999. // , t = new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0])
  37000. , i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])
  37001. , g = new BufferGeometry;
  37002. g.setIndex(new BufferAttribute(e, 1)),
  37003. //g.addAttribute("position", new n.BufferAttribute(t, 3)),
  37004. g.setAttribute("uv", new BufferAttribute(i, 2));
  37005. return function(){
  37006. return g
  37007. }
  37008. }(),
  37009. getPlaneGeo : function(A,B,C,D){
  37010. var geo = this.getUnPosPlaneGeo().clone();
  37011. var pos = [
  37012. A.x, A.y, A.z,
  37013. B.x, B.y, B.z,
  37014. C.x, C.y, C.z,
  37015. D.x, D.y, D.z
  37016. ];
  37017. //geo.addAttribute("position", new THREE.BufferAttribute(pos, 3))
  37018. geo.setAttribute('position', new Float32BufferAttribute(pos, 3));
  37019. geo.computeVertexNormals();
  37020. geo.computeBoundingSphere(); //for raycaster
  37021. return geo;
  37022. },
  37023. drawPlane : function(A,B,C,D, material){
  37024. var wall = new Mesh(this.getPlaneGeo(A,B,C,D), material);
  37025. return wall;
  37026. },
  37027. movePlane: function(mesh, A,B,C,D){
  37028. var pos = new Float32Array([
  37029. A.x, A.y, A.z,
  37030. B.x, B.y, B.z,
  37031. C.x, C.y, C.z,
  37032. D.x, D.y, D.z
  37033. ]);
  37034. mesh.geometry.addAttribute("position", new BufferAttribute(pos, 3));
  37035. mesh.geometry.computeBoundingSphere();//for checkIntersect
  37036. }
  37037. ,
  37038. createGeometry:function(posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  37039. let geo = new BufferGeometry;
  37040. let positions = [];
  37041. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  37042. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  37043. if(faceArr){
  37044. let indice = [];
  37045. faceArr.forEach(f=>indice.push(...f));
  37046. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  37047. }
  37048. if(uvArr){
  37049. let uvs = [];
  37050. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  37051. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  37052. }
  37053. if(normalArr){
  37054. let normals = [];
  37055. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  37056. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  37057. }
  37058. /*
  37059. geo.computeVertexNormals()
  37060. geo.computeBoundingSphere() //for raycaster
  37061. */
  37062. return geo
  37063. },
  37064. updateGeometry:function(geo, posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  37065. let positions = [];
  37066. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  37067. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  37068. geo.attributes.position.needsUpdate = true;
  37069. if(faceArr){
  37070. let indice = [];
  37071. faceArr.forEach(f=>indice.push(...f));
  37072. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  37073. }
  37074. if(uvArr){
  37075. let uvs = [];
  37076. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  37077. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  37078. }
  37079. if(normalArr){
  37080. let normals = [];
  37081. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  37082. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  37083. }
  37084. /*
  37085. geo.computeVertexNormals()
  37086. */
  37087. geo.computeBoundingSphere(); //for raycaster and visi
  37088. return geo
  37089. }
  37090. };
  37091. const verticalLine = new Line3();
  37092. //控制点和边的合集。具有可以拖拽修改的功能,拖拽时能防止线相交。
  37093. class ctrlPolygon extends Object3D {
  37094. constructor (type, prop) {
  37095. super();
  37096. this.type = type;
  37097. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  37098. this.transformData(prop);
  37099. for(let i in prop){
  37100. this[i] = prop[i];
  37101. }
  37102. if(this.closed && this.dimension == '2d'){
  37103. this.areaPlane = this.createAreaPlane();
  37104. this.add(this.areaPlane);
  37105. }
  37106. //数据--刚开始一定是空的
  37107. this.points = [];
  37108. //mesh 不一定有
  37109. this.markers = [];
  37110. this.edges = [];
  37111. this.center;
  37112. }
  37113. initData(prop){
  37114. //开始加数据
  37115. if(Potree.settings.editType == 'merge'){ //融合页面没有地图,measure的不需要指定datasetId,每个点都有各自的datasetId,跟着各自的模型走
  37116. if(this.dataset_points){
  37117. this.dataset_points = this.dataset_points.map(e=>{
  37118. return e && new Vector3().copy(e)
  37119. });
  37120. prop.points = this.dataset_points.map((p,i)=>{
  37121. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.points_datasets[i], position: p})
  37122. });
  37123. if(prop.points.some(e=>e == void 0)){
  37124. return false
  37125. }
  37126. }else {
  37127. this.dataset_points = [];
  37128. }
  37129. }
  37130. if(prop.points){
  37131. for(const p of prop.points){
  37132. const pos = new Vector3().copy(p);
  37133. this.addMarker({point:pos});
  37134. }
  37135. if(Potree.settings.editType != 'merge'){
  37136. if(this.datasetId != void 0){//初始化位置
  37137. if(this.dataset_points){
  37138. this.dataset_points = this.dataset_points.map(e=>{
  37139. return e && new Vector3().copy(e)
  37140. });
  37141. this.transformByPointcloud(); //根据dataset_points生成points
  37142. }
  37143. }else {
  37144. if(prop.dataset_points && prop.dataset_points.some(e=>e != void 0)){
  37145. console.error('存在测量线的datasetId为空而dataset_points有值,请检查并删除:'+this.sid);//存在过的bug,原因未知,可能是后台处理dataset时替换的错误:http://192.168.0.21/index.php?m=bug&f=view&bugID=23601
  37146. console.log(this);
  37147. }
  37148. }
  37149. }
  37150. this.getFacePlane();
  37151. this.getPoint2dInfo(this.points);
  37152. this.update({ifUpdateMarkers:true});
  37153. //this.dragChange(new THREE.Vector3().copy(prop.points[prop.points.length-1]), prop.points.length-1);
  37154. this.setSelected(false );
  37155. this.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  37156. return true
  37157. }
  37158. }
  37159. addMarker(o={}){
  37160. var index = o.index == void 0 ? this.points.length : o.index; //要当第几个
  37161. this.points = [...this.points.slice(0,index), o.point, ...this.points.slice(index,this.points.length)];
  37162. //this.points.push(o.point);
  37163. if(o.marker){
  37164. this.add(o.marker);
  37165. this.markers = [...this.markers.slice(0,index), o.marker, ...this.markers.slice(index,this.markers.length)];
  37166. this.updateMarker(o.marker, o.point);
  37167. o.marker.addEventListener('drag', this.dragMarker.bind(this));
  37168. o.marker.addEventListener('drop', this.dropMarker.bind(this));
  37169. let addHoverEvent = (e)=>{
  37170. let mouseover = (e) => {
  37171. this.setMarkerSelected(e.object, 'hover', 'single');
  37172. viewer.dispatchEvent({
  37173. type : "CursorChange", action : "add", name:"markerMove"
  37174. });
  37175. };
  37176. let mouseleave = (e) => {
  37177. this.setMarkerSelected(e.object, 'unhover', 'single');
  37178. viewer.dispatchEvent({
  37179. type : "CursorChange", action : "remove", name:"markerMove"
  37180. });
  37181. };
  37182. o.marker.addEventListener('mouseover', mouseover);
  37183. o.marker.addEventListener('mouseleave', mouseleave);
  37184. o.marker.removeEventListener('addHoverEvent',addHoverEvent);
  37185. };
  37186. o.marker.addEventListener('addHoverEvent',addHoverEvent);//当非isNew时才添加事件
  37187. if(!this.isNew){
  37188. o.marker.dispatchEvent('addHoverEvent');
  37189. }
  37190. }
  37191. if(o.edge){
  37192. this.add(o.edge);
  37193. this.edges = [...this.edges.slice(0,index), o.edge, ...this.edges.slice(index,this.edges.length)];
  37194. }
  37195. }
  37196. dragMarker(e){
  37197. var I, atMap;
  37198. if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  37199. viewer.dispatchEvent({
  37200. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  37201. });
  37202. return
  37203. }
  37204. viewer.dispatchEvent({
  37205. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37206. });
  37207. atMap = e.drag.dragViewport.name == 'mapViewport';
  37208. if(atMap && this.unableDragAtMap){
  37209. e.drag.object = null; //取消拖拽
  37210. return
  37211. }
  37212. e.drag.object.isDragging = true;
  37213. I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  37214. //记录数据集
  37215. //在三维中脱离点云(在map中拉到周围都没有点云的地方)的顶点,无法拖拽怎么办
  37216. if (I) {
  37217. let i = this.markers.indexOf(e.drag.object);
  37218. if (i !== -1) {
  37219. this.dragChange(I.clone(), i, atMap);
  37220. /* if(this.points_datasets){
  37221. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id
  37222. else this.points_datasets[i] = null
  37223. } */
  37224. if(this.points_datasets){
  37225. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id;
  37226. else if(e.intersect.object) this.points_datasets[i] = e.intersect.object.dataset_id;
  37227. else this.points_datasets[i] = null;
  37228. }
  37229. }
  37230. this.editStateChange(true);
  37231. return true
  37232. }
  37233. };
  37234. dragChange(intersectPos, i, atMap){
  37235. let len = this.markers.length;
  37236. let oldPoint = this.points[i];
  37237. if(atMap){
  37238. intersectPos.setZ(oldPoint.z); //在地图上拖拽,不改变其高度。
  37239. }
  37240. let location = intersectPos.clone();
  37241. if(this.faceDirection && this.maxMarkers == 2 && len == 2){//add 固定方向的点不直接拖拽
  37242. var p1 = this.markers[0].position;
  37243. if(this.faceDirection == 'horizontal'){
  37244. var projectPos = location.clone().setZ(p1.z);
  37245. }else {
  37246. var projectPos = p1.clone().setZ(location.z);
  37247. }
  37248. //var p2 = p1.clone().add(this.direction)
  37249. //var projectPos = math.getFootPoint(location, p1, p2)
  37250. LineDraw.updateLine(this.guideLine, [location, projectPos]);
  37251. location = projectPos;
  37252. this.guideLine.visible = true;
  37253. }else if( len > 1){
  37254. var points = this.points.map(e=>e.clone());
  37255. points[i].copy(location); //算normal需要提前确认point
  37256. //若为定义了面朝向的矩形
  37257. if(this.faceDirection == 'horizontal'){
  37258. if(len == 2){
  37259. location.setZ(points[0].z);
  37260. }
  37261. if(!this.facePlane){//一个点就能确定面
  37262. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( new Vector3(0,0,1), this.points[0] );
  37263. }
  37264. }else if(this.faceDirection == 'vertical'){//当有两个点时, 有两个方向的可能
  37265. if(len == 2){
  37266. if(this.isRect){
  37267. let vec = points[0].clone().sub(location);
  37268. if(Math.sqrt(vec.x*vec.x+vec.y*vec.y) > Math.abs(vec.z) ){//水平(高度差小于水平距离时)
  37269. location.setZ(points[0].z);
  37270. //this.cannotConfirmNormal = false;//能确定面为水平方向
  37271. }else {//垂直 (当两点一样时也属于这种)
  37272. location.setX(points[0].x);
  37273. location.setY(points[0].y);
  37274. //this.cannotConfirmNormal = true; //不能确定面,因第三点可绕着纵轴线自由移动
  37275. }
  37276. }
  37277. }else {
  37278. {//判断cannotConfirmNormal. 如果前几段都在竖直线上,就不能固定出面方向。
  37279. this.cannotConfirmNormal = true;
  37280. let max = this.isRect ? 1 : len-2;
  37281. for(let i=0;i<max;i++){
  37282. let p1 = points[i].clone();
  37283. let p2 = points[i+1].clone();
  37284. let vec = p1.sub(p2);
  37285. if(vec.x != 0 || vec.y != 0){
  37286. this.cannotConfirmNormal = false;
  37287. break;
  37288. }
  37289. }
  37290. }
  37291. if(!this.facePlane || this.cannotConfirmNormal){//三个点且为水平方向时,计算面
  37292. var points_ = points.map(e=>new Vector2$1(e.x,e.y));
  37293. var points2 = getDifferentPoint(points_, 2);
  37294. if(points2){
  37295. let normal = math.getNormal2d({p1:points2[0], p2:points2[1]});
  37296. normal = new Vector3(normal.x, normal.y, 0);
  37297. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] );
  37298. }
  37299. }
  37300. }
  37301. }
  37302. if(len > 2){//area
  37303. if(!this.faceDirection){
  37304. if(len == 3 || this.isRect) this.cannotConfirmNormal = true; //当第三个点固定后(有四个点时)才能固定面
  37305. if(!this.facePlane || this.cannotConfirmNormal){
  37306. var points3 = getDifferentPoint(points, 3);//只有找到三个不同的点算拥有面和area
  37307. if(points3){
  37308. this.facePlane = new Plane().setFromCoplanarPoints(...points3 );
  37309. }
  37310. }
  37311. }
  37312. if( this.facePlane && !this.cannotConfirmNormal ){//之后加的点一定要在面上
  37313. if(atMap){
  37314. //地图上用垂直线,得到和面的交点。
  37315. verticalLine.set(location.clone().setZ(100000), location.clone().setZ(-100000));//确保长度范围覆盖所有测量面
  37316. location = this.facePlane.intersectLine(verticalLine, new Vector3() );
  37317. if(!location) return;
  37318. }else {
  37319. location = this.facePlane.projectPoint(intersectPos, new Vector3() );
  37320. }
  37321. }
  37322. points[i].copy(location);//再copy确认一次
  37323. if(this.isRect){ //是矩形 (即使没有faceDirection也能执行)
  37324. //根据前两个点计算当前和下一个点
  37325. var p1 = points[(i-2+len)%len];
  37326. var p2 = points[(i-1+len)%len];
  37327. if(p1.equals(p2)){//意外情况:重复点两次 ( bug点,改了好多遍)
  37328. if(this.faceDirection == 'vertical'){
  37329. p2.add(new Vector3(0,0,0.0001));
  37330. }else {
  37331. p2.add(new Vector3(0,0.0001,0));
  37332. }
  37333. }
  37334. //p3 : location
  37335. var foot = math.getFootPoint(location, p1, p2);//p2 修改p2到垂足的位置
  37336. var vec = foot.clone().sub(location);
  37337. var p4 = p1.clone().sub(vec);
  37338. points[(i-1+len)%len].copy(foot);
  37339. points[(i+1)%len].copy(p4);
  37340. this.setPosition((i-1+len)%len, foot);//p2
  37341. this.setPosition((i+1)%len, p4);
  37342. }
  37343. /* let points2d;
  37344. if(this.facePlane){
  37345. var originPoint0 = points[0].clone()
  37346. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,1));
  37347. points2d = points.map(e=>e.clone().applyQuaternion(qua))
  37348. } */
  37349. this.getPoint2dInfo(points);
  37350. var isIntersectSelf = !this.isRect && len > 3 && this.intersectSelf(this.point2dInfo.points2d);//检测相交
  37351. if(isIntersectSelf){
  37352. //not-allowed
  37353. viewer.dispatchEvent({
  37354. type : "CursorChange", action : "add", name:"polygon_isIntersectSelf"
  37355. });
  37356. this.isIntersectSelf = true;
  37357. return
  37358. }else {
  37359. this.isIntersectSelf = false;
  37360. viewer.dispatchEvent({
  37361. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  37362. });
  37363. /* this.facePlane && (this.point2dInfo = {
  37364. originPoint0 ,
  37365. points2d,
  37366. quaInverse : qua.clone().invert()
  37367. }) */
  37368. }
  37369. }
  37370. var showGuideLine = len>1 && (this.faceDirection || len > 3);
  37371. if(showGuideLine && this.guideLine){
  37372. LineDraw.updateLine(this.guideLine, [intersectPos, location]);
  37373. this.guideLine.visible = true;
  37374. }
  37375. //console.log(this.points.map(e=>e.toArray()))
  37376. }
  37377. if(this.restrictArea){
  37378. let holes = this.restrictArea.holes.concat(this.restrictArea.parentHoles);
  37379. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  37380. if(!math.isPointInArea(this.restrictArea.points, holesPoints, location)){
  37381. viewer.dispatchEvent({
  37382. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  37383. });
  37384. this.isAtWrongPlace = true;
  37385. return
  37386. }
  37387. //就不处理相交线了。 有个缺点:floor上的hole可以限制room,但hole不受room限制,会导致room的marker被框在hole里而动不了。只能去调整hole了
  37388. }
  37389. viewer.dispatchEvent({
  37390. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37391. });
  37392. this.isAtWrongPlace = false;
  37393. this.setPosition(i, location);
  37394. this.update();
  37395. this.dispatchEvent({type:'dragChange', index:i});
  37396. }
  37397. dropMarker(e){
  37398. //console.log('dropMarker')
  37399. if (this.isNew && e.pressDistance>Potree.config.clickMaxDragDis){//拖拽的话返回
  37400. return this.continueDrag(null,e)
  37401. }
  37402. if(e.isTouch){
  37403. if(e.hoverViewport != viewer.mainViewport && this.unableDragAtMap){
  37404. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  37405. //console.log('reticule_forbit',true)
  37406. return this.continueDrag(null,e)
  37407. }else {
  37408. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  37409. //console.log('reticule_forbit',false)
  37410. }
  37411. this.dragMarker(e); //触屏时必须先更新下点
  37412. }
  37413. if (e.button != MOUSE.RIGHT && (//右键click的话继续执行,因为会停止
  37414. this.isIntersectSelf && this.isNew //有线相交了
  37415. || this.isAtWrongPlace && this.isNew
  37416. || !e.isAtDomElement && this.isNew//如果是刚添加时在其他dom点击, 不要响应
  37417. || e.hoverViewport != viewer.mainViewport && this.unableDragAtMap //垂直的测量线不允许在地图上放点
  37418. || this.isNew && !getDifferentPoint(this.points, this.points.length ) //不允许和之前的点相同, 但这句在点云稀疏时会导致难结束
  37419. )
  37420. ){
  37421. return this.continueDrag(null,e)
  37422. }
  37423. //console.log('drop marker' )
  37424. let i = this.markers.indexOf(e.drag.object);
  37425. if (i !== -1) {
  37426. this.dispatchEvent({
  37427. 'type': 'marker_dropped',
  37428. 'index': i
  37429. });
  37430. if(this.markers.length>2 && this.facePlane)this.cannotConfirmNormal = false;
  37431. this.guideLine &&(this.guideLine.visible = false);
  37432. }
  37433. this.setMarkerSelected(e.drag.object, 'unhover', 'single');
  37434. this.editStateChange(false);
  37435. e.drag.endDragFun && e.drag.endDragFun(e);// addmarker
  37436. //if(this.changeCallBack)this.changeCallBack()
  37437. return true
  37438. };
  37439. getFacePlane(){//最普通一种get方法,根据顶点。且假设所有点已经共面,且不重合
  37440. if(this.points.length<3) return
  37441. this.facePlane = new Plane().setFromCoplanarPoints(...this.points.slice(0,3) );
  37442. }
  37443. getPoint2dInfo(points){ //在更新areaplane之前必须更新过point2dInfo
  37444. if(this.facePlane){
  37445. var originPoint0 = points[0].clone();
  37446. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  37447. let points2d = points.map(e=>e.clone().applyQuaternion(qua));
  37448. this.point2dInfo = {
  37449. originPoint0 ,
  37450. points2d,
  37451. quaInverse : qua.clone().invert()
  37452. };
  37453. }
  37454. }
  37455. setPosition (index, position) {//拖拽后设置位置
  37456. let point = this.points[index];
  37457. point.copy(position);
  37458. /* if(this.datasetId){
  37459. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.datasetId, position:point.clone()})
  37460. } */
  37461. /* if(Potree.settings.editType == 'merge'){
  37462. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true,this.points_datasets[i], position:point.clone()})
  37463. } */
  37464. let marker = this.markers[index];
  37465. this.updateMarker(marker, point);
  37466. }
  37467. updateMarker(marker, pos){
  37468. marker.position.copy(pos);
  37469. marker.update();
  37470. }
  37471. intersectSelf(points2d){//add
  37472. var len = points2d.length;
  37473. for(var i=0;i<len;i++){
  37474. for(var j=i+2;j<len;j++){
  37475. if(Math.abs(j-len-i)<2)continue;//不和邻边比
  37476. var p1 = points2d[i];
  37477. var p2 = points2d[i+1];
  37478. var p3 = points2d[j];
  37479. var p4 = points2d[(j+1)%len];
  37480. if(p1.equals(p2) || p3.equals(p4) || p1.equals(p3) || p2.equals(p3) || p1.equals(p4) || p2.equals(p4))continue
  37481. var line1 = [p1,p2];
  37482. var line2 = [p3,p4];
  37483. var intersect = math.isLineIntersect(line1, line2, false, 0.001);
  37484. if(intersect){
  37485. return true
  37486. break
  37487. }
  37488. }
  37489. }
  37490. }
  37491. removeMarker (index) {
  37492. this.points.splice(index, 1);
  37493. const marker = this.markers[index];
  37494. //this.remove(marker);
  37495. this.markers.splice(index, 1);
  37496. marker.dispatchEvent({type:'dispose'});
  37497. let edgeIndex = index; //(index === 0) ? 0 : (index - 1);
  37498. const edge = this.edges[edgeIndex];
  37499. if(edge){
  37500. this.remove(edge);
  37501. this.edges.splice(edgeIndex, 1);
  37502. edge.dispatchEvent({type:'dispose'});
  37503. }
  37504. this.point2dInfo && this.point2dInfo.points2d.splice(index, 1); //add
  37505. this.dispatchEvent({type:'removeMarker',index,marker});
  37506. }
  37507. createAreaPlane(mat){
  37508. var geometry = new Geometry();
  37509. var mesh = new Mesh(geometry, mat);
  37510. return mesh
  37511. }
  37512. updateAreaPlane(){
  37513. if(!this.point2dInfo)return
  37514. this.areaPlane.geometry.dispose();
  37515. if(this.points.length>2){
  37516. this.areaPlane.geometry = MeshDraw.getShapeGeo(this.point2dInfo.points2d);
  37517. var center = math.getCenterOfGravityPoint(this.point2dInfo.points2d); //重心
  37518. var firstPos = this.point2dInfo.points2d[0].clone();
  37519. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  37520. firstPos.applyQuaternion(this.point2dInfo.quaInverse);
  37521. var vec = this.point2dInfo.originPoint0.clone().sub(firstPos);
  37522. center = new Vector3(center.x, center.y, 0);
  37523. center.applyQuaternion(this.point2dInfo.quaInverse);
  37524. this.areaPlane.quaternion.copy(this.point2dInfo.quaInverse);
  37525. this.areaPlane.position.copy(vec);
  37526. center.add(vec);
  37527. this.center = center;
  37528. }else {
  37529. this.areaPlane.geometry = new Geometry();
  37530. }
  37531. }
  37532. update(options={}){
  37533. if(this.points.length === 0){
  37534. return;
  37535. }
  37536. let lastIndex = this.points.length - 1;
  37537. for (let index = 0; index <= lastIndex; index++) {
  37538. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  37539. let previousIndex = (index === 0) ? lastIndex : index - 1;
  37540. let point = this.points[index];
  37541. let nextPoint = this.points[nextIndex];
  37542. let previousPoint = this.points[previousIndex];
  37543. if(options.ifUpdateMarkers){
  37544. this.updateMarker(this.markers[index], point);
  37545. }
  37546. { // edges
  37547. let edge = this.edges[index];
  37548. if(edge){
  37549. LineDraw.updateLine(edge, [point, nextPoint]);
  37550. //edge.visible = index < lastIndex || this.isRect || (this.closed && !this.isNew);
  37551. }
  37552. }
  37553. }
  37554. if(this.areaPlane){
  37555. this.updateAreaPlane();
  37556. }
  37557. //this.dispatchEvent({type:'update'})
  37558. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); //暂时先这么都通知
  37559. }
  37560. dispose(){//add
  37561. this.parent.remove(this);
  37562. this.markers.concat(this.edges).forEach(e=>e.dispatchEvent({type:'dispose'}));
  37563. }
  37564. reDraw(restMarkerCount=0){//重新开始画
  37565. let pointCount = this.points.length - restMarkerCount; // restMarkerCount为需要留下的marker数量
  37566. while(pointCount > 0){
  37567. this.removeMarker(--pointCount);
  37568. }
  37569. this.point2dInfo = null;
  37570. this.facePlane = null;
  37571. }
  37572. setMarkerSelected(){}
  37573. editStateChange(state){
  37574. if(!state){
  37575. viewer.dispatchEvent({
  37576. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  37577. });
  37578. viewer.dispatchEvent({
  37579. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37580. });
  37581. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  37582. this.markers.forEach(e=>e.isDragging = false );
  37583. }
  37584. }
  37585. transformData(){}
  37586. setSelected(){}
  37587. continueDrag(marker, e){
  37588. let object = marker || e.drag.object;
  37589. object.isDragging = true;
  37590. var timer = setTimeout(()=>{//等 drag=null之后 //右键拖拽结束后需要重新得到drag
  37591. if(this.parent && object.isDragging){
  37592. //console.log('continueDrag')
  37593. viewer.inputHandler.startDragging( object ,
  37594. {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport}
  37595. );
  37596. }
  37597. },1);
  37598. return timer
  37599. }
  37600. }
  37601. function getDifferentPoint(points, count){//for facePlane
  37602. var result = [];
  37603. for(let i=0;i<points.length;i++){
  37604. var p = points[i];
  37605. if(result.find(e=>e.equals(p)))continue;
  37606. else result.push(p);
  37607. if(result.length == count)break
  37608. }
  37609. if(result.length == count)return result
  37610. }
  37611. let texLoader = new TextureLoader();
  37612. let defaultColor$1 = new Color(config$1.measure.default.color);
  37613. let highlightColor = new Color(config$1.measure.highlight.color);
  37614. let color = new Color(config$1.measure.color);
  37615. let textColor = new Color(config$1.measure.textColor);
  37616. var markerMats;
  37617. var lineMats;
  37618. var planeMats;
  37619. const lineDepthInfo = {
  37620. clipDistance : 4,//消失距离
  37621. occlusionDistance: 1,//变为backColor距离
  37622. };
  37623. const LabelDepthInfo = {
  37624. clipDistance : 6,//消失距离
  37625. occlusionDistance: 2,//变为backColor距离
  37626. };
  37627. /* const LabelDepthInfo = {
  37628. clipDistance : 0.1,//消失距离
  37629. occlusionDistance: 0.1,//变为backColor距离
  37630. } */
  37631. const markerSizeInfo = {
  37632. minSize : 25 , maxSize : 65, nearBound : 0.2, farBound : 4,
  37633. };
  37634. const labelSizeInfo = {width2d:200};
  37635. const mainLabelProp = {
  37636. backgroundColor: {r: defaultColor$1.r*255, g: defaultColor$1.g*255, b: defaultColor$1.b*255, a:config$1.measure.default.opacity},
  37637. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  37638. fontsize:16,
  37639. useDepth : true ,
  37640. renderOrder : 5, pickOrder:5,
  37641. };
  37642. const subLabelProp = {
  37643. backgroundColor: {r: 255, g: 255, b: 255, a:1},
  37644. textColor: {r: 0, g: 0, b:0, a: 1.0},
  37645. fontsize:14,
  37646. renderOrder : 4, pickOrder:4,
  37647. };
  37648. const angle = MathUtils.degToRad(5);//显示水平垂直辅助线的最小角度
  37649. const guideShowMinAngle = {min: angle, max: Math.PI/2 - angle};
  37650. class Measure extends ctrlPolygon{
  37651. constructor (prop) {
  37652. prop.dimension = '2d';
  37653. super('measure',prop);
  37654. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  37655. this.name = this.measureType + this.constructor.counter; //'Measure_' + this.constructor.counter;
  37656. this.markerLabels = [];
  37657. this.edgeLabels = [];
  37658. this.angleLabels = [];
  37659. this.coordinateLabels = [];
  37660. this.area = {value:0,string:''};
  37661. if(this.closed/* this.showArea */){
  37662. this.areaLabel = this.createAreaLabel();
  37663. this.add(this.areaLabel);
  37664. }
  37665. //add:
  37666. if(this.maxMarkers > 2 || this.faceDirection){
  37667. this.createGuideLine();
  37668. }
  37669. if(this.measureType == 'Distance'){
  37670. this.createHorVerGuideLine();
  37671. }
  37672. this.selectStates = {};
  37673. this.setUnitSystem(prop.unit || viewer.unitConvert.UnitService.defaultSystem);
  37674. viewer.setObjectLayers(this, 'measure' );
  37675. //addMarkers:
  37676. this.initData(prop);
  37677. this.points_datasets || (this.points_datasets = []); //存每个点是哪个数据集
  37678. this.addEventListener('marker_dropped',(e)=>{
  37679. this.updateDatasetBelong(e.index);
  37680. });
  37681. this.addEventListener('isVisible', ()=>{
  37682. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  37683. });
  37684. }
  37685. initData(prop){
  37686. let makeIt = super.initData(prop);
  37687. if(makeIt){
  37688. this.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  37689. }else {
  37690. this.failBuilded = true;
  37691. }
  37692. }
  37693. updateDatasetBelong(changeIndex){//更新所属数据集
  37694. if(Potree.settings.editType == "merge"){//无地图
  37695. /* this.dataset_points = this.points.map((e,i)=>{
  37696. return Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[i], position:e.clone()})
  37697. }) */
  37698. this.dataset_points[changeIndex] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[changeIndex], position:this.points[changeIndex].clone()});
  37699. return
  37700. }
  37701. let old = this.datasetId;
  37702. let maxCount = {id:null,count:0};
  37703. let datasets = {};
  37704. this.points_datasets.forEach(e=>{
  37705. if(e == void 0)return
  37706. if(datasets[e]){
  37707. datasets[e] ++;
  37708. }else {
  37709. datasets[e] = 1;
  37710. }
  37711. });
  37712. for(let i in datasets) {
  37713. if(datasets[i]>maxCount.count){
  37714. maxCount = {id:i, count:datasets[i]};
  37715. }
  37716. }
  37717. this.datasetId = maxCount.count > 0 ? maxCount.id : null;
  37718. //if(this.datasetId != old){
  37719. //this.dispatchEvent({type:'changeDatasetId'})
  37720. if(this.datasetId == void 0){
  37721. this.dataset_points = null; //可能为空或[null,null...]
  37722. }else {
  37723. this.dataset_points = this.points.map(e=>{
  37724. return Potree.Utils.datasetPosTransform({toDataset:true,datasetId:this.datasetId, position:e.clone()})
  37725. });
  37726. }
  37727. //}
  37728. }
  37729. transformByPointcloud(){//每次移动点云 or 加载测量线时要获取一下当前position //有地图时
  37730. if(this.datasetId == void 0)return
  37731. this.points = this.dataset_points.map(e=>{
  37732. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.datasetId, position:e.clone()})
  37733. });
  37734. this.getPoint2dInfo(this.points);
  37735. this.update({ifUpdateMarkers:true});
  37736. this.setSelected(false);//隐藏edgelabel
  37737. }
  37738. update(options={}) {
  37739. super.update(options);
  37740. if(this.showCoordinates && this.points.length>0){
  37741. let position = this.points[0];
  37742. this.markers[0].position.copy(position);
  37743. { // coordinate labels
  37744. let coordinateLabel = this.coordinateLabels[0];
  37745. let lonlat = viewer.transform.lonlatToLocal.inverse(position.toArray());
  37746. let EPSG4550 = viewer.transform.lonlatTo4550.forward(lonlat);
  37747. let pos = [
  37748. position.toArray(),
  37749. lonlat,
  37750. EPSG4550
  37751. ];
  37752. //let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  37753. let msg = pos.map(a=>
  37754. a.map(p => Utils.addCommas(p.toFixed(10))).join(", ")
  37755. ).join("<br>");
  37756. coordinateLabel.setText(msg);
  37757. coordinateLabel.setPos(position);
  37758. coordinateLabel.setVisible(true);//this.showCoordinates;
  37759. }
  37760. return
  37761. }
  37762. let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字
  37763. let center = new Vector3().addVectors(p1,p2).multiplyScalar(0.5);
  37764. label.setPos(center);
  37765. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  37766. var text = viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision, this.unitSystem, 0.1 , true);//distance要传0.1 这个factor
  37767. label.setText(text);
  37768. return distance
  37769. };
  37770. let lastIndex = this.points.length - 1;
  37771. for (let index = 0; index <= lastIndex; index++) {
  37772. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  37773. let previousIndex = (index === 0) ? lastIndex : index - 1;
  37774. let point = this.points[index];
  37775. let nextPoint = this.points[nextIndex];
  37776. let previousPoint = this.points[previousIndex];
  37777. if(this.showDistances){ // edge labels
  37778. let edgeLabel = this.edgeLabels[index];
  37779. let distance = point.distanceTo(nextPoint);
  37780. edgeLabel.shouldVisi = (index < lastIndex || this.isRect || this.closed && !this.isNew /* && this.points.length > 2 */) && distance>0;
  37781. /* this.closed || */edgeLabel.setVisible(edgeLabel.shouldVisi);
  37782. if(edgeLabel.visible){
  37783. setEdgeLabel(edgeLabel,point,nextPoint,distance);
  37784. }
  37785. }
  37786. }
  37787. if(this.measureType == 'Distance' && this.points.length>1){//设置水平垂直辅助线
  37788. var pTop, pBtm;
  37789. if(this.points[0].z > this.points[1].z ){
  37790. pTop = this.points[0];
  37791. pBtm = this.points[1];
  37792. }else {
  37793. pTop = this.points[1];
  37794. pBtm = this.points[0];
  37795. }
  37796. let projectPos = new Vector3(pTop.x, pTop.y, pBtm.z);//两条guideline的交点
  37797. {//倾斜角度太小的时候不显示
  37798. let tan = pTop.distanceTo(projectPos) / pBtm.distanceTo(projectPos);
  37799. let angle = Math.atan(tan);
  37800. this.shouldShowHorVerGuide = angle > guideShowMinAngle.min && angle < guideShowMinAngle.max;
  37801. }
  37802. LineDraw.updateLine(this.verGuideEdge, [pTop, projectPos]);
  37803. LineDraw.updateLine(this.horGuideEdge, [pBtm, projectPos]);
  37804. setEdgeLabel(this.verEdgeLabel,pTop,projectPos);
  37805. setEdgeLabel(this.horEdgeLabel,pBtm,projectPos);
  37806. this.verGuideEdge.visible = this.horGuideEdge.visible = this.shouldShowHorVerGuide;
  37807. this.verEdgeLabel.visible = this.horEdgeLabel.visible = this.shouldShowHorVerGuide;
  37808. }
  37809. if(this.showArea && this.point2dInfo){ // update area
  37810. /* if(this.points.length>2){
  37811. this.area = {value:0};
  37812. this.areaLabel.setVisible(false)
  37813. }else{ */
  37814. let area = Math.abs(math.getArea(this.point2dInfo.points2d));//this.getArea();
  37815. let msg = viewer.unitConvert.convert(area, 'area', Potree.settings.precision, this.unitSystem/* , 0.1 */ );
  37816. this.area = {value:area, string:msg};
  37817. this.areaLabel.setPos(this.center);
  37818. this.areaLabel.setText(msg);
  37819. this.areaLabel.setVisible(true);
  37820. //}
  37821. }
  37822. };
  37823. addMarker (o={}) {
  37824. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo, name:"measure_point"} );
  37825. viewer.setObjectLayers(marker, 'measure' );
  37826. marker.pickOrder = marker.renderOrder = 3;
  37827. marker.markerSelectStates = {};
  37828. marker.addEventListener('startDragging',(e)=>{
  37829. if(e.drag.dragViewport.name == 'MainView')viewer.inputHandler.dispatchEvent( {type: 'isMeasuring',v:true, cause:'startDragging'});
  37830. });
  37831. marker.addEventListener('drop',(e)=>{
  37832. viewer.inputHandler.dispatchEvent({type: 'isMeasuring', v:false, cause:'stopDragging'} );
  37833. });
  37834. let edge;
  37835. { // edges
  37836. edge = LineDraw.createFatLine( [ ],{material:this.getLineMat('edgeDefault')} );
  37837. edge.pickOrder = 0;
  37838. viewer.setObjectLayers(edge, 'measure' );
  37839. let addHoverEvent = ()=>{ //当非isNew时才添加事件
  37840. let mouseover = (e) => {this.setSelected(true, 'edge');};
  37841. let mouseleave = (e) => {this.setSelected(false, 'edge');};
  37842. edge.addEventListener('mouseover', mouseover);
  37843. edge.addEventListener('mouseleave', mouseleave);
  37844. edge.removeEventListener('addHoverEvent', addHoverEvent);
  37845. };
  37846. edge.addEventListener('addHoverEvent', addHoverEvent);
  37847. }
  37848. super.addMarker({point:o.point, marker:marker, edge});
  37849. if(this.showEdges){ // edge labels
  37850. const edgeLabel = this.createEdgeLabel('edgeLabel', !this.closed);
  37851. this.edgeLabels.push(edgeLabel);
  37852. }
  37853. if(this.showCoordinates){ // coordinate labels
  37854. let coordinateLabel = new Label({
  37855. className:'measure_pointPos',
  37856. camera: viewer.scene.getActiveCamera()
  37857. });
  37858. coordinateLabel.setVisible(false);
  37859. this.coordinateLabels.push(coordinateLabel);
  37860. }
  37861. let event = {
  37862. type: 'marker_added',
  37863. measurement: this,
  37864. marker: marker
  37865. };
  37866. this.dispatchEvent(event);
  37867. //this.setMarker(this.points.length - 1, point);
  37868. this.update();//更新一下倒数第二条线
  37869. return marker;//add
  37870. };
  37871. editStateChange(state){ //主要针对edgeLabels显示切换,编辑时显示
  37872. super.editStateChange(state);
  37873. if(!state){
  37874. this.editStateTimer = setTimeout(()=>{
  37875. if(!this.isEditing){
  37876. this.dispatchEvent({type:'editStateChange',state:false});
  37877. this.setEdgesDisplay(false);
  37878. }
  37879. },100);
  37880. }else {
  37881. if(!this.isEditing){
  37882. this.dispatchEvent({type:'editStateChange',state:true});
  37883. this.setEdgesDisplay(true);
  37884. clearTimeout(this.editStateTimer);
  37885. }
  37886. }
  37887. this.isEditing = state;
  37888. }
  37889. setMarkerSelected(marker, state, hoverObject){
  37890. //console.warn(marker.id , state, hoverObject)
  37891. marker.markerSelectStates[hoverObject] = state;
  37892. let absoluteState = false;
  37893. for(var i in marker.markerSelectStates){
  37894. if(marker.markerSelectStates[i] == 'hover'){
  37895. absoluteState = true; break;
  37896. }
  37897. }
  37898. if(absoluteState){
  37899. marker.material = this.getMarkerMaterial('select');
  37900. }else {
  37901. marker.material = this.getMarkerMaterial('default');
  37902. }
  37903. marker.selected = absoluteState;
  37904. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  37905. }
  37906. setEdgesDisplay(state, ignoreGuideLine){
  37907. this.closed && this.edgeLabels.forEach(e=>e.setVisible(!!(state && e.shouldVisi)) );
  37908. if(!ignoreGuideLine && this.measureType == 'Distance'){
  37909. this.horEdgeLabel.visible = this.verEdgeLabel.visible = this.horGuideEdge.visible = this.verGuideEdge.visible = !!(state && this.shouldShowHorVerGuide);
  37910. }
  37911. }
  37912. setSelected(state, hoverObject){//add
  37913. //console.log('setSelected',state, hoverObject)
  37914. hoverObject && (this.selectStates[hoverObject] = state);
  37915. let absoluteState = false;
  37916. for(var i in this.selectStates){
  37917. if(this.selectStates[i]){
  37918. absoluteState = true; break;
  37919. }
  37920. }
  37921. if(absoluteState){
  37922. this.markers.forEach(e=>this.setMarkerSelected(e, 'hover', 'selectAll' ) );
  37923. this.edges.forEach(e=>e.material = this.getLineMat('edgeSelect') );
  37924. this.areaPlane && (this.areaPlane.material = planeMats.selected);
  37925. //this.areaLabel && this.areaLabel.elem.addClass('highLight')
  37926. //this.closed || this.edgeLabels.forEach(e=>e.elem.addClass('highLight') )
  37927. this.setEdgesDisplay(true, hoverObject=="screenshot");
  37928. this.areaLabel && setLabelHightState(this.areaLabel, true);
  37929. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, true) );
  37930. }else {
  37931. this.markers.forEach(e=>this.setMarkerSelected(e, 'unhover', 'selectAll' ));
  37932. this.edges.forEach(e=>e.material = this.getLineMat('edgeDefault') );
  37933. this.areaPlane && (this.areaPlane.material = planeMats.default);
  37934. this.setEdgesDisplay(false, hoverObject=="screenshot");
  37935. //this.areaLabel && this.areaLabel.elem.removeClass('highLight')
  37936. //this.closed || this.edgeLabels.forEach(e=>e.elem.removeClass('highLight') )
  37937. this.areaLabel && setLabelHightState(this.areaLabel, false);
  37938. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, false) );
  37939. }
  37940. this.selected = absoluteState;
  37941. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  37942. if(hoverObject != 'byList'){
  37943. //this.bus && this.bus.emit('highlight', this.selected)
  37944. this.dispatchEvent({type:'highlight',state:this.selected});//列表高亮
  37945. }
  37946. }
  37947. removeMarker(index ){
  37948. super.removeMarker(index);
  37949. this.points_datasets.splice(index, 1);
  37950. this.dataset_points && this.dataset_points.splice(index, 1);
  37951. this.coordinateLabels.splice(index, 1);
  37952. let edgeIndex = index;//(index === 0) ? 0 : (index - 1);
  37953. if(this.edgeLabels[edgeIndex]){
  37954. this.edgeLabels[edgeIndex].dispose();
  37955. this.edgeLabels.splice(edgeIndex, 1);
  37956. }
  37957. this.update();
  37958. this.dispatchEvent({type: 'marker_removed', measurement: this});
  37959. }
  37960. setPosition(index, position) {
  37961. super.setPosition(index, position);
  37962. let event = {
  37963. type: 'marker_moved',
  37964. measure: this,
  37965. index: index,
  37966. position: position.clone()
  37967. };
  37968. this.dispatchEvent(event);
  37969. }
  37970. dispose(){//add
  37971. var labels = this.edgeLabels.concat(this.coordinateLabels);
  37972. this.areaLabel && labels.push(this.areaLabel);
  37973. labels.forEach(e=>e.dispatchEvent({type:'dispose'}));
  37974. super.dispose();
  37975. }
  37976. getTotalDistance () {
  37977. if (this.points.length === 0) {
  37978. return 0;
  37979. }
  37980. let distance = 0;
  37981. for (let i = 1; i < this.points.length; i++) {
  37982. let prev = this.points[i - 1];
  37983. let curr = this.points[i];
  37984. let d = prev.distanceTo(curr);
  37985. distance += d;
  37986. }
  37987. if (this.closed && this.points.length > 1) {
  37988. let first = this.points[0];
  37989. let last = this.points[this.points.length - 1];
  37990. let d = last.distanceTo(first);
  37991. distance += d;
  37992. }
  37993. return distance;
  37994. }
  37995. getAngleBetweenLines (cornerPoint, point1, point2) {
  37996. let v1 = new Vector3().subVectors(point1, cornerPoint);
  37997. let v2 = new Vector3().subVectors(point2, cornerPoint);
  37998. // avoid the error printed by threejs if denominator is 0
  37999. const denominator = Math.sqrt( v1.lengthSq() * v2.lengthSq() );
  38000. if(denominator === 0){
  38001. return 0;
  38002. }else {
  38003. return v1.angleTo(v2);
  38004. }
  38005. };
  38006. getAngle (index) {
  38007. if (this.points.length < 3 || index >= this.points.length) {
  38008. return 0;
  38009. }
  38010. let previous = (index === 0) ? this.points[this.points.length - 1] : this.points[index - 1];
  38011. let point = this.points[index];
  38012. let next = this.points[(index + 1) % (this.points.length)];
  38013. return this.getAngleBetweenLines(point, previous, next);
  38014. }
  38015. getCenter(/* update */){
  38016. if(this.points.length>=3){
  38017. return this.center.clone()
  38018. }else if(this.points.length == 2){
  38019. return this.points[0].clone().add((this.points[1])).multiplyScalar(0.5)
  38020. }else return this.points[0].clone()
  38021. }
  38022. // updateAzimuth(){
  38023. // // if(this.points.length !== 2){
  38024. // // return;
  38025. // // }
  38026. // // const azimuth = this.azimuth;
  38027. // // const [p0, p1] = this.points;
  38028. // // const r = p0.distanceTo(p1);
  38029. // }
  38030. createGuideLine(){//add 辅助线
  38031. var guideLine = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38032. guideLine.visible = false;
  38033. this.guideLine = guideLine;
  38034. this.add(guideLine);
  38035. }
  38036. createHorVerGuideLine(){//创建水平与垂直辅助线,仅距离测量有。
  38037. var verGuideEdge = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38038. verGuideEdge.visible = false;
  38039. this.verGuideEdge = verGuideEdge;
  38040. var horGuideEdge = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38041. horGuideEdge.visible = false;
  38042. this.horGuideEdge = horGuideEdge;
  38043. this.add(this.verGuideEdge);
  38044. this.add(this.horGuideEdge);
  38045. //label:
  38046. this.verEdgeLabel = this.createEdgeLabel('verGuideEdge');
  38047. this.horEdgeLabel = this.createEdgeLabel('horGuideEdge');
  38048. }
  38049. createEdgeLabel(name, hasHoverEvent){
  38050. const edgeLabel = new TextSprite(
  38051. $.extend(hasHoverEvent ? mainLabelProp : subLabelProp,{sizeInfo: labelSizeInfo, name:name||'edgeLabel'})
  38052. );
  38053. if(hasHoverEvent){
  38054. edgeLabel.addEventListener('mouseover',()=>{
  38055. this.setSelected(true, 'edgeLabel');
  38056. });
  38057. edgeLabel.addEventListener('mouseleave',()=>{
  38058. this.setSelected(false, 'edgeLabel');
  38059. });
  38060. edgeLabel.addEventListener('click',()=>{
  38061. viewer.focusOnObject(this, 'measure');
  38062. });
  38063. }
  38064. edgeLabel.visible = false;
  38065. edgeLabel.sprite.material.depthTestWhenPick = true;
  38066. viewer.setObjectLayers(edgeLabel, 'measure' );
  38067. this.add(edgeLabel);
  38068. return edgeLabel
  38069. }
  38070. createAreaLabel(){
  38071. /* const areaLabel = new Label({
  38072. className:'measure_area',
  38073. })
  38074. areaLabel.elem.on('mouseover',()=>{
  38075. this.setSelected(true, 'areaLabel')
  38076. })
  38077. areaLabel.elem.on('mouseout',()=>{
  38078. this.setSelected(false, 'areaLabel')
  38079. }) */
  38080. const areaLabel = new TextSprite(
  38081. $.extend(mainLabelProp,{sizeInfo: labelSizeInfo, name:'areaLabel_'} )
  38082. );
  38083. areaLabel.addEventListener('mouseover',()=>{
  38084. this.setSelected(true, 'areaLabel');
  38085. });
  38086. areaLabel.addEventListener('mouseleave',()=>{
  38087. this.setSelected(false, 'areaLabel');
  38088. });
  38089. areaLabel.addEventListener('click',()=>{
  38090. viewer.focusOnObject(this, 'measure');
  38091. });
  38092. viewer.setObjectLayers(areaLabel, 'measure' );
  38093. areaLabel.visible = false;
  38094. return areaLabel;
  38095. }
  38096. getMarkerMaterial(type) {
  38097. if(!markerMats){
  38098. markerMats = {
  38099. default: new DepthBasicMaterial($.extend({},lineDepthInfo,{
  38100. transparent: !0,
  38101. opacity: 1,
  38102. map: texLoader.load(Potree.resourcePath+'/textures/pic_point_s32.png' ),
  38103. useDepth:true
  38104. })),
  38105. select: new MeshBasicMaterial({
  38106. transparent: !0,
  38107. opacity: 1,
  38108. depthTest:false,
  38109. map: texLoader.load(Potree.resourcePath+'/textures/pic_point32.png'/* , null, null, { antialias: false } */),
  38110. }),
  38111. };
  38112. Measure.markerMats = markerMats;
  38113. }
  38114. return markerMats[type]
  38115. }
  38116. getLineMat(type) {
  38117. if(!Measure.lineMats){
  38118. Measure.lineMats = {
  38119. edgeDefault: LineDraw.createFatLineMat({
  38120. color: config$1.measure.default.color,
  38121. lineWidth: config$1.measure.lineWidth,
  38122. useDepth :true,
  38123. dashWithDepth :true, // 只在被遮住的部分显示虚线,因为实线容易挡住label
  38124. dashed :true,
  38125. dashSize : 0.04,
  38126. gapSize: 0.04,
  38127. transparent: true,
  38128. opacity: config$1.measure.default.opacity,
  38129. depthTestWhenPick:true,
  38130. }),
  38131. edgeSelect: LineDraw.createFatLineMat({
  38132. color: config$1.measure.highlight.color,//'#f0ff00',
  38133. dashSize: 0.5,
  38134. gapSize: 0.2,
  38135. lineWidth: config$1.measure.lineWidth ,
  38136. transparent: true,
  38137. opacity: config$1.measure.highlight.opacity
  38138. }),
  38139. guide: LineDraw.createFatLineMat({
  38140. color:config$1.measure.guide.color,
  38141. dashSize: 0.1,
  38142. gapSize: 0.02,
  38143. dashed: true,
  38144. lineWidth: config$1.measure.lineWidth
  38145. })
  38146. };
  38147. }
  38148. return Measure.lineMats[type]
  38149. }
  38150. createAreaPlane(){
  38151. planeMats || (planeMats = {
  38152. default: new DepthBasicMaterial( $.extend({},LabelDepthInfo,{
  38153. color:color,
  38154. side:DoubleSide,
  38155. opacity:0.2,
  38156. transparent:true,
  38157. useDepth:true
  38158. })),
  38159. selected: new MeshBasicMaterial({
  38160. color: color ,
  38161. side:DoubleSide,
  38162. opacity:0.3,
  38163. transparent:true,
  38164. })
  38165. },Measure.planeMats = planeMats);
  38166. return super.createAreaPlane(planeMats.default)
  38167. }
  38168. raycast (raycaster, intersects) {
  38169. for (let i = 0; i < this.points.length; i++) {
  38170. let marker = this.markers[i];
  38171. marker.raycast(raycaster, intersects);
  38172. }
  38173. // recalculate distances because they are not necessarely correct
  38174. // for scaled objects.
  38175. // see https://github.com/mrdoob/three.js/issues/5827
  38176. // TODO: remove this once the bug has been fixed
  38177. for (let i = 0; i < intersects.length; i++) {
  38178. let I = intersects[i];
  38179. I.distance = raycaster.ray.origin.distanceTo(I.point);
  38180. }
  38181. intersects.sort(function (a, b) { return a.distance - b.distance; });
  38182. };
  38183. transformData(prop){
  38184. if(prop.measureType == 'Point'){
  38185. prop.showCoordinates = true,
  38186. prop.closed = true,
  38187. prop.maxMarkers = 1,
  38188. prop.minMarkers = 1;
  38189. }else if(prop.measureType == 'Distance'){
  38190. prop.showDistances = true,
  38191. prop.closed = false,
  38192. prop.showEdges = true,
  38193. prop.maxMarkers = 2,
  38194. prop.minMarkers = 2;
  38195. }else if(prop.measureType == 'Ver Distance'){
  38196. prop.showDistances = true,
  38197. prop.closed = false,
  38198. prop.showEdges = true,
  38199. prop.maxMarkers = 2,
  38200. prop.minMarkers = 2,
  38201. prop.faceDirection = "vertical";
  38202. prop.unableDragAtMap = true;
  38203. }else if(prop.measureType == 'Hor Distance'){
  38204. prop.showDistances = true,
  38205. prop.closed = false,
  38206. prop.showEdges = true,
  38207. prop.maxMarkers = 2,
  38208. prop.minMarkers = 2,
  38209. prop.faceDirection = "horizontal";
  38210. }else if(prop.measureType == 'Area'){
  38211. prop.showDistances = true,
  38212. prop.showArea = true,
  38213. prop.showEdges = true,
  38214. prop.closed = true,
  38215. prop.minMarkers = 3;
  38216. }else if(prop.measureType == 'Hor Area'){
  38217. prop.showDistances = true,
  38218. prop.showArea = true,
  38219. prop.showEdges = true,
  38220. prop.closed = true,
  38221. prop.minMarkers = 3;
  38222. prop.faceDirection = "horizontal";
  38223. }else if(prop.measureType == 'Ver Area'){
  38224. prop.showDistances = true,
  38225. prop.showArea = true,
  38226. prop.showEdges = true,
  38227. prop.closed = true,
  38228. prop.minMarkers = 3;
  38229. prop.faceDirection = "vertical";
  38230. prop.unableDragAtMap = true;
  38231. }else if(prop.measureType == 'Rect Area'){
  38232. prop.showDistances = true,
  38233. prop.showArea = true,
  38234. prop.showEdges = true,
  38235. prop.closed = true,
  38236. prop.minMarkers = 4;
  38237. prop.maxMarkers = 4;
  38238. }else if(prop.measureType == 'Hor Rect Area'){
  38239. prop.showDistances = true,
  38240. prop.showArea = true,
  38241. prop.showEdges = true,
  38242. prop.closed = true,
  38243. prop.minMarkers = 4;
  38244. prop.maxMarkers = 4;
  38245. prop.isRect = true;
  38246. prop.faceDirection = "horizontal";
  38247. }else if(prop.measureType == 'Ver Rect Area'){
  38248. prop.showDistances = true,
  38249. prop.showArea = true,
  38250. prop.showEdges = true,
  38251. prop.closed = true,
  38252. prop.minMarkers = 4;
  38253. prop.maxMarkers = 4;
  38254. prop.isRect = true;
  38255. prop.faceDirection = "vertical";
  38256. prop.unableDragAtMap = true;
  38257. }
  38258. }
  38259. setUnitSystem(unitSystem){
  38260. //console.log(this.name +':' +this.unitSystem)
  38261. if(unitSystem != this.unitSystem){
  38262. if(unitSystem == "metric"){
  38263. }else if(unitSystem == 'imperial'){
  38264. }
  38265. this.unitSystem = unitSystem;
  38266. this.update();
  38267. }
  38268. }
  38269. reDraw(restMarkerCount=0){//重新开始画
  38270. super.reDraw(restMarkerCount);
  38271. if(this.measureType == 'Distance'){
  38272. this.shouldShowHorVerGuide = false;
  38273. this.setEdgesDisplay(false);
  38274. }
  38275. if(this.showArea){
  38276. this.area = {value:0};
  38277. this.areaLabel && this.areaLabel.setVisible(false);
  38278. }
  38279. viewer.inputHandler.dispatchEvent( {type:'isMeasuring', v:true, cause:'reDraw'} );
  38280. }
  38281. /* get showCoordinates () {
  38282. return this._showCoordinates;
  38283. }
  38284. set showCoordinates (value) {
  38285. this._showCoordinates = value;
  38286. this.update();
  38287. }
  38288. get showAngles () {
  38289. return this._showAngles;
  38290. }
  38291. set showAngles (value) {
  38292. this._showAngles = value;
  38293. this.update();
  38294. }
  38295. get showCircle () {
  38296. return this._showCircle;
  38297. }
  38298. set showCircle (value) {
  38299. this._showCircle = value;
  38300. this.update();
  38301. }
  38302. get showAzimuth(){
  38303. return this._showAzimuth;
  38304. }
  38305. set showAzimuth(value){
  38306. this._showAzimuth = value;
  38307. this.update();
  38308. }
  38309. get showEdges () {
  38310. return this._showEdges;
  38311. }
  38312. set showEdges (value) {
  38313. this._showEdges = value;
  38314. this.update();
  38315. }
  38316. get showHeight () {
  38317. return this._showHeight;
  38318. }
  38319. set showHeight (value) {
  38320. this._showHeight = value;
  38321. this.update();
  38322. }
  38323. get showArea () {
  38324. return this._showArea;
  38325. }
  38326. set showArea (value) {
  38327. this._showArea = value;
  38328. this.update();
  38329. }
  38330. get closed () {
  38331. return this._closed;
  38332. }
  38333. set closed (value) {
  38334. this._closed = value;
  38335. this.update();
  38336. }
  38337. get showDistances () {
  38338. return this._showDistances;
  38339. }
  38340. set showDistances (value) {
  38341. this._showDistances = value;
  38342. this.update();
  38343. } */
  38344. }
  38345. function setLabelHightState(label, state){
  38346. if(state){
  38347. label.backgroundColor = {r: highlightColor.r*255, g: highlightColor.g*255, b: highlightColor.b*255, a:config$1.measure.highlight.opacity},
  38348. label.backgroundColor.a = config$1.measure.highlight.opacity;
  38349. label.sprite.material.useDepth = false;
  38350. }else {
  38351. label.backgroundColor = mainLabelProp.backgroundColor;
  38352. label.backgroundColor.a = config$1.measure.default.opacity;
  38353. label.sprite.material.useDepth = true;
  38354. }
  38355. label.updateTexture();
  38356. //label.sprite.material.needsUpdate = true
  38357. }
  38358. function createCircleRadiusLabel(){
  38359. const circleRadiusLabel = new TextSprite("");
  38360. circleRadiusLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  38361. circleRadiusLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  38362. circleRadiusLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  38363. circleRadiusLabel.fontsize = 16;
  38364. circleRadiusLabel.material.depthTest = false;
  38365. circleRadiusLabel.material.opacity = 1;
  38366. circleRadiusLabel.visible = false;
  38367. return circleRadiusLabel;
  38368. }
  38369. function createCircleRadiusLine(){
  38370. /* const lineGeometry = new LineGeometry();
  38371. lineGeometry.setPositions([
  38372. 0, 0, 0,
  38373. 0, 0, 0,
  38374. ]);
  38375. const lineMaterial = new LineMaterial({
  38376. color: 0xff0000,
  38377. lineWidth: 2,
  38378. resolution: new THREE.Vector2(1000, 1000),
  38379. gapSize: 1,
  38380. dashed: true,
  38381. });
  38382. lineMaterial.depthTest = false;
  38383. const circleRadiusLine = new Line2(lineGeometry, lineMaterial);*/
  38384. var circleRadiusLine = LineDraw.createFatLine([ ],{
  38385. color:0xff0000,
  38386. dashSize: 0.5,
  38387. gapSize: 0.2,
  38388. lineWidth: config$1.measure.lineWidth
  38389. });
  38390. circleRadiusLine.visible = false;
  38391. return circleRadiusLine;
  38392. }
  38393. function createCircleLine(){
  38394. const coordinates = [];
  38395. let n = 128;
  38396. for(let i = 0; i <= n; i++){
  38397. let u0 = 2 * Math.PI * (i / n);
  38398. let u1 = 2 * Math.PI * (i + 1) / n;
  38399. let p0 = new Vector3(
  38400. Math.cos(u0),
  38401. Math.sin(u0),
  38402. 0
  38403. );
  38404. let p1 = new Vector3(
  38405. Math.cos(u1),
  38406. Math.sin(u1),
  38407. 0
  38408. );
  38409. coordinates.push(
  38410. p0,
  38411. p1
  38412. );
  38413. }
  38414. /* const geometry = new LineGeometry();
  38415. geometry.setPositions(coordinates);
  38416. const material = new LineMaterial({
  38417. color: 0xff0000,
  38418. dashSize: 5,
  38419. gapSize: 2,
  38420. lineWidth: 2,
  38421. resolution: new THREE.Vector2(1000, 1000),
  38422. });
  38423. material.depthTest = false;
  38424. const circleLine = new Line2(geometry, material);
  38425. circleLine.visible = false;
  38426. circleLine.computeLineDistances();*/
  38427. var circleLine = LineDraw.createFatLine(coordinates,{
  38428. color: 0xff0000,
  38429. dashSize: 0.5,
  38430. gapSize: 0.2,
  38431. lineWidth: config$1.measure.lineWidth
  38432. });
  38433. return circleLine;
  38434. }
  38435. /* function createCircleCenter(){
  38436. const sg = new THREE.markerGeometry(1, 32, 32);
  38437. const sm = new THREE.MeshNormalMaterial();
  38438. const circleCenter = new THREE.Mesh(sg, sm);
  38439. circleCenter.visible = false;
  38440. return circleCenter;
  38441. } */
  38442. function createLine(){
  38443. const line = LineDraw.createFatLine([ ],{
  38444. color: 0xff0000,
  38445. dashSize: 0.5,
  38446. gapSize: 0.2,
  38447. lineWidth: config$1.measure.lineWidth
  38448. });
  38449. return line;
  38450. }
  38451. function createCircle(){
  38452. const coordinates = [];
  38453. let n = 128;
  38454. for(let i = 0; i <= n; i++){
  38455. let u0 = 2 * Math.PI * (i / n);
  38456. let u1 = 2 * Math.PI * (i + 1) / n;
  38457. let p0 = new Vector3(
  38458. Math.cos(u0),
  38459. Math.sin(u0),
  38460. 0
  38461. );
  38462. let p1 = new Vector3(
  38463. Math.cos(u1),
  38464. Math.sin(u1),
  38465. 0
  38466. );
  38467. coordinates.push(
  38468. p0,
  38469. p1
  38470. );
  38471. }
  38472. var line = LineDraw.createFatLine(coordinates,{
  38473. color: 0xff0000,
  38474. dashSize: 0.5,
  38475. gapSize: 0.2,
  38476. lineWidth: config$1.measure.lineWidth
  38477. });
  38478. return line;
  38479. }
  38480. /* function createAzimuth(){
  38481. const azimuth = {
  38482. label: null,
  38483. center: null,
  38484. target: null,
  38485. north: null,
  38486. centerToNorth: null,
  38487. centerToTarget: null,
  38488. centerToTargetground: null,
  38489. targetgroundToTarget: null,
  38490. circle: null,
  38491. node: null,
  38492. };
  38493. const sg = new THREE.markerGeometry(1, 32, 32);
  38494. const sm = new THREE.MeshNormalMaterial();
  38495. {
  38496. const label = new TextSprite("");
  38497. label.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  38498. label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  38499. label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  38500. label.fontsize = 16;
  38501. label.material.depthTest = false;
  38502. label.material.opacity = 1;
  38503. azimuth.label = label;
  38504. }
  38505. azimuth.center = new THREE.Mesh(sg, sm);
  38506. azimuth.target = new THREE.Mesh(sg, sm);
  38507. azimuth.north = new THREE.Mesh(sg, sm);
  38508. azimuth.centerToNorth = createLine();
  38509. azimuth.centerToTarget = createLine();
  38510. azimuth.centerToTargetground = createLine();
  38511. azimuth.targetgroundToTarget = createLine();
  38512. azimuth.circle = createCircle();
  38513. azimuth.node = new THREE.Object3D();
  38514. azimuth.node.add(
  38515. azimuth.centerToNorth,
  38516. azimuth.centerToTarget,
  38517. azimuth.centerToTargetground,
  38518. azimuth.targetgroundToTarget,
  38519. azimuth.circle,
  38520. azimuth.label,
  38521. azimuth.center,
  38522. azimuth.target,
  38523. azimuth.north,
  38524. );
  38525. return azimuth;
  38526. } */
  38527. /*
  38528. */
  38529. class PolygonClipVolume extends Object3D{
  38530. constructor(camera){
  38531. super();
  38532. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  38533. this.name = "polygon_clip_volume_" + this.constructor.counter;
  38534. this.camera = camera.clone();
  38535. this.camera.rotation.set(...camera.rotation.toArray()); // [r85] workaround because camera.clone() doesn't work on rotation
  38536. this.camera.rotation.order = camera.rotation.order;
  38537. this.camera.updateMatrixWorld();
  38538. this.camera.updateProjectionMatrix();
  38539. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  38540. this.viewMatrix = this.camera.matrixWorldInverse.clone();
  38541. this.projMatrix = this.camera.projectionMatrix.clone();
  38542. // projected markers
  38543. this.markers = [];
  38544. this.initialized = false;
  38545. }
  38546. addMarker() {
  38547. let marker = new Mesh();
  38548. let cancel;
  38549. let drag = e => {
  38550. let size = e.viewer.renderer.getSize(new Vector2$1());
  38551. let projectedPos = new Vector3(
  38552. 2.0 * (e.drag.end.x / size.width) - 1.0,
  38553. -2.0 * (e.drag.end.y / size.height) + 1.0,
  38554. 0
  38555. );
  38556. marker.position.copy(projectedPos);
  38557. };
  38558. let drop = e => {
  38559. cancel();
  38560. };
  38561. cancel = e => {
  38562. marker.removeEventListener("drag", drag);
  38563. marker.removeEventListener("drop", drop);
  38564. };
  38565. marker.addEventListener("drag", drag);
  38566. marker.addEventListener("drop", drop);
  38567. this.markers.push(marker);
  38568. }
  38569. removeLastMarker() {
  38570. if(this.markers.length > 0) {
  38571. this.markers.splice(this.markers.length - 1, 1);
  38572. }
  38573. }
  38574. };
  38575. class Utils {
  38576. static async loadShapefileFeatures (file, callback) {
  38577. let features = [];
  38578. let handleFinish = () => {
  38579. callback(features);
  38580. };
  38581. let source = await shapefile.open(file);
  38582. while(true){
  38583. let result = await source.read();
  38584. if (result.done) {
  38585. handleFinish();
  38586. break;
  38587. }
  38588. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  38589. features.push(result.value);
  38590. }
  38591. }
  38592. }
  38593. static toString (value) {
  38594. if (value.x != null) {
  38595. return value.x.toFixed(2) + ', ' + value.y.toFixed(2) + ', ' + value.z.toFixed(2);
  38596. } else {
  38597. return '' + value + '';
  38598. }
  38599. }
  38600. static normalizeURL (url) {
  38601. let u = new URL(url);
  38602. return u.protocol + '//' + u.hostname + u.pathname.replace(/\/+/g, '/');
  38603. };
  38604. static pathExists (url) {
  38605. let req = XHRFactory.createXMLHttpRequest();
  38606. req.open('GET', url, false);
  38607. req.send(null);
  38608. if (req.status !== 200) {
  38609. return false;
  38610. }
  38611. return true;
  38612. };
  38613. static debugSphere(parent, position, scale, color){
  38614. let geometry = new SphereGeometry(1, 8, 8);
  38615. let material;
  38616. if(color !== undefined){
  38617. material = new MeshBasicMaterial({color: color});
  38618. }else {
  38619. material = new MeshNormalMaterial();
  38620. }
  38621. let sphere = new Mesh(geometry, material);
  38622. sphere.position.copy(position);
  38623. sphere.scale.set(scale, scale, scale);
  38624. parent.add(sphere);
  38625. return sphere;
  38626. }
  38627. static debugLine(parent, start, end, color){
  38628. let material = new LineBasicMaterial({ color: color });
  38629. let geometry = new Geometry();
  38630. const p1 = new Vector3(0, 0, 0);
  38631. const p2 = end.clone().sub(start);
  38632. geometry.vertices.push(p1, p2);
  38633. let tl = new Line( geometry, material );
  38634. tl.position.copy(start);
  38635. parent.add(tl);
  38636. let line = {
  38637. node: tl,
  38638. set: (start, end) => {
  38639. geometry.vertices[0].copy(start);
  38640. geometry.vertices[1].copy(end);
  38641. geometry.verticesNeedUpdate = true;
  38642. },
  38643. };
  38644. return line;
  38645. }
  38646. static debugCircle(parent, center, radius, normal, color){
  38647. let material = new LineBasicMaterial({ color: color });
  38648. let geometry = new Geometry();
  38649. let n = 32;
  38650. for(let i = 0; i <= n; i++){
  38651. let u0 = 2 * Math.PI * (i / n);
  38652. let u1 = 2 * Math.PI * (i + 1) / n;
  38653. let p0 = new Vector3(
  38654. Math.cos(u0),
  38655. Math.sin(u0),
  38656. 0
  38657. );
  38658. let p1 = new Vector3(
  38659. Math.cos(u1),
  38660. Math.sin(u1),
  38661. 0
  38662. );
  38663. geometry.vertices.push(p0, p1);
  38664. }
  38665. let tl = new Line( geometry, material );
  38666. tl.position.copy(center);
  38667. tl.scale.set(radius, radius, radius);
  38668. parent.add(tl);
  38669. }
  38670. static debugBox(parent, box, transform = new Matrix4(), color = 0xFFFF00){
  38671. let vertices = [
  38672. [box.min.x, box.min.y, box.min.z],
  38673. [box.min.x, box.min.y, box.max.z],
  38674. [box.min.x, box.max.y, box.min.z],
  38675. [box.min.x, box.max.y, box.max.z],
  38676. [box.max.x, box.min.y, box.min.z],
  38677. [box.max.x, box.min.y, box.max.z],
  38678. [box.max.x, box.max.y, box.min.z],
  38679. [box.max.x, box.max.y, box.max.z],
  38680. ].map(v => new Vector3(...v));
  38681. let edges = [
  38682. [0, 4], [4, 5], [5, 1], [1, 0],
  38683. [2, 6], [6, 7], [7, 3], [3, 2],
  38684. [0, 2], [4, 6], [5, 7], [1, 3]
  38685. ];
  38686. let center = box.getCenter(new Vector3());
  38687. let centroids = [
  38688. {position: [box.min.x, center.y, center.z], color: 0xFF0000},
  38689. {position: [box.max.x, center.y, center.z], color: 0x880000},
  38690. {position: [center.x, box.min.y, center.z], color: 0x00FF00},
  38691. {position: [center.x, box.max.y, center.z], color: 0x008800},
  38692. {position: [center.x, center.y, box.min.z], color: 0x0000FF},
  38693. {position: [center.x, center.y, box.max.z], color: 0x000088},
  38694. ];
  38695. for(let vertex of vertices){
  38696. let pos = vertex.clone().applyMatrix4(transform);
  38697. Utils.debugSphere(parent, pos, 0.1, 0xFF0000);
  38698. }
  38699. for(let edge of edges){
  38700. let start = vertices[edge[0]].clone().applyMatrix4(transform);
  38701. let end = vertices[edge[1]].clone().applyMatrix4(transform);
  38702. Utils.debugLine(parent, start, end, color);
  38703. }
  38704. for(let centroid of centroids){
  38705. let pos = new Vector3(...centroid.position).applyMatrix4(transform);
  38706. Utils.debugSphere(parent, pos, 0.1, centroid.color);
  38707. }
  38708. }
  38709. static debugPlane(parent, plane, size = 1, color = 0x0000FF){
  38710. let planehelper = new PlaneHelper(plane, size, color);
  38711. parent.add(planehelper);
  38712. }
  38713. /**
  38714. * adapted from mhluska at https://github.com/mrdoob/three.js/issues/1561
  38715. */
  38716. static computeTransformedBoundingBox (box, transform) {
  38717. let vertices = [
  38718. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  38719. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  38720. new Vector3(box.max.x, box.min.y, box.min.z).applyMatrix4(transform),
  38721. new Vector3(box.min.x, box.max.y, box.min.z).applyMatrix4(transform),
  38722. new Vector3(box.min.x, box.min.y, box.max.z).applyMatrix4(transform),
  38723. new Vector3(box.min.x, box.max.y, box.max.z).applyMatrix4(transform),
  38724. new Vector3(box.max.x, box.max.y, box.min.z).applyMatrix4(transform),
  38725. new Vector3(box.max.x, box.min.y, box.max.z).applyMatrix4(transform),
  38726. new Vector3(box.max.x, box.max.y, box.max.z).applyMatrix4(transform)
  38727. ];
  38728. let boundingBox = new Box3();
  38729. boundingBox.setFromPoints(vertices);
  38730. return boundingBox;
  38731. };
  38732. /**
  38733. * add separators to large numbers
  38734. *
  38735. * @param nStr
  38736. * @returns
  38737. */
  38738. static addCommas (nStr) {
  38739. nStr += '';
  38740. let x = nStr.split('.');
  38741. let x1 = x[0];
  38742. let x2 = x.length > 1 ? '.' + x[1] : '';
  38743. let rgx = /(\d+)(\d{3})/;
  38744. while (rgx.test(x1)) {
  38745. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  38746. }
  38747. return x1 + x2;
  38748. };
  38749. static removeCommas (str) {
  38750. return str.replace(/,/g, '');
  38751. }
  38752. /**
  38753. * create worker from a string
  38754. *
  38755. * code from http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
  38756. */
  38757. static createWorker (code) {
  38758. let blob = new Blob([code], {type: 'application/javascript'});
  38759. let worker = new Worker(URL.createObjectURL(blob));
  38760. return worker;
  38761. };
  38762. static moveTo(scene, endPosition, endTarget){
  38763. let view = scene.view;
  38764. let camera = scene.getActiveCamera();
  38765. let animationDuration = 500;
  38766. let easing = TWEEN.Easing.Quartic.Out;
  38767. { // animate camera position
  38768. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  38769. tween.easing(easing);
  38770. tween.start();
  38771. }
  38772. { // animate camera target
  38773. let camTargetDistance = camera.position.distanceTo(endTarget);
  38774. let target = new Vector3().addVectors(
  38775. camera.position,
  38776. camera.getWorldDirection(new Vector3()).clone().multiplyScalar(camTargetDistance)
  38777. );
  38778. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  38779. tween.easing(easing);
  38780. tween.onUpdate(() => {
  38781. view.lookAt(target);
  38782. });
  38783. tween.onComplete(() => {
  38784. view.lookAt(target);
  38785. });
  38786. tween.start();
  38787. }
  38788. }
  38789. static loadSkybox (path) {
  38790. let parent = new Object3D("skybox_root");
  38791. let camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  38792. if(!window.axisYup) camera.up.set(0, 0, 1);
  38793. let scene = new Scene();
  38794. let format = '.jpg';
  38795. let urls = [
  38796. path + 'px' + format, path + 'nx' + format,
  38797. path + 'py' + format, path + 'ny' + format,
  38798. path + 'pz' + format, path + 'nz' + format
  38799. ];
  38800. let materialArray = [];
  38801. {
  38802. for (let i = 0; i < 6; i++) {
  38803. let material = new MeshBasicMaterial({
  38804. map: null,
  38805. side: BackSide,
  38806. depthTest: false,
  38807. depthWrite: false,
  38808. color: 0x424556
  38809. });
  38810. materialArray.push(material);
  38811. let loader = new TextureLoader();
  38812. loader.load(urls[i],
  38813. function loaded (texture) {
  38814. material.map = texture;
  38815. material.needsUpdate = true;
  38816. material.color.setHex(0xffffff);
  38817. }, function progress (xhr) {
  38818. // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
  38819. }, function error (xhr) {
  38820. console.log('An error happened', xhr);
  38821. }
  38822. );
  38823. }
  38824. }
  38825. let skyGeometry = new BoxGeometry(700, 700, 700);
  38826. let skybox = new Mesh(skyGeometry, materialArray);
  38827. scene.add(skybox);
  38828. scene.traverse(n => n.frustumCulled = false);
  38829. // z up
  38830. scene.rotation.x = Math.PI / 2;
  38831. parent.children.push(camera);
  38832. camera.parent = parent;
  38833. return {camera, scene, parent};
  38834. };
  38835. static createGrid (width, length, spacing, color) {
  38836. let material = new LineBasicMaterial({
  38837. color: color || 0x888888
  38838. });
  38839. let geometry = new Geometry();
  38840. for (let i = 0; i <= length; i++) {
  38841. geometry.vertices.push(new Vector3(-(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  38842. geometry.vertices.push(new Vector3(+(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  38843. }
  38844. for (let i = 0; i <= width; i++) {
  38845. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, -(spacing * length) / 2, 0));
  38846. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, +(spacing * length) / 2, 0));
  38847. }
  38848. let line = new LineSegments(geometry, material, LinePieces);
  38849. line.receiveShadow = true;
  38850. return line;
  38851. }
  38852. static createBackgroundTexture (width, height) {
  38853. function gauss (x, y) {
  38854. return (1 / (2 * Math.PI)) * Math.exp(-(x * x + y * y) / 2);
  38855. };
  38856. // map.magFilter = THREE.NearestFilter;
  38857. let size = width * height;
  38858. let data = new Uint8Array(3 * size);
  38859. let chroma = [1, 1.5, 1.7];
  38860. let max = gauss(0, 0);
  38861. for (let x = 0; x < width; x++) {
  38862. for (let y = 0; y < height; y++) {
  38863. let u = 2 * (x / width) - 1;
  38864. let v = 2 * (y / height) - 1;
  38865. let i = x + width * y;
  38866. let d = gauss(2 * u, 2 * v) / max;
  38867. let r = (Math.random() + Math.random() + Math.random()) / 3;
  38868. r = (d * 0.5 + 0.5) * r * 0.03;
  38869. r = r * 0.4;
  38870. // d = Math.pow(d, 0.6);
  38871. data[3 * i + 0] = 255 * (d / 15 + 0.05 + r) * chroma[0];
  38872. data[3 * i + 1] = 255 * (d / 15 + 0.05 + r) * chroma[1];
  38873. data[3 * i + 2] = 255 * (d / 15 + 0.05 + r) * chroma[2];
  38874. }
  38875. }
  38876. let texture = new DataTexture(data, width, height, RGBFormat);
  38877. texture.needsUpdate = true;
  38878. return texture;
  38879. }
  38880. static getMousePointCloudIntersection (viewport, mouse, pointer, camera, viewer, pointclouds, pickParams = {} ) {
  38881. if(!pointclouds || pointclouds.length == 0)return
  38882. let renderer = viewer.renderer;
  38883. if(viewport){ //转换到类似整个画面时
  38884. /*let mouseInViewport = Utils.convertNDCToScreenPosition(pointer, null, viewport.resolution.x, viewport.resolution.y)
  38885. pickParams.x = mouseInViewport.x //mouse.x / viewport.width;
  38886. pickParams.y = mouseInViewport.y //renderer.domElement.clientHeight - mouse.y / viewport.height; */
  38887. pickParams.x = mouse.x;
  38888. pickParams.y = viewport.resolution.y - mouse.y;
  38889. }else {
  38890. pickParams.x = mouse.x;
  38891. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  38892. }
  38893. //console.log('getMousePointCloudIntersection')
  38894. /* if(!raycaster){
  38895. raycaster = new THREE.Raycaster();
  38896. raycaster.setFromCamera(pointer, camera);
  38897. } */
  38898. let raycaster = new Raycaster();
  38899. raycaster.setFromCamera(pointer, camera);
  38900. let ray = raycaster.ray;
  38901. let selectedPointcloud = null;
  38902. let closestDistance = Infinity;
  38903. let closestIntersection = null;
  38904. let closestPoint = null;
  38905. let density;
  38906. let sizeType;
  38907. let size = new Map();
  38908. if(pickParams.isMeasuring || Potree.settings.displayMode == 'showPanos'){ //测量或全景模式提高精准度
  38909. density = Potree.settings.pointDensity;
  38910. Potree.settings.pointDensity = 'magnifier';
  38911. pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  38912. size.set(e, e.temp.pointSize);
  38913. sizeType = e.material.pointSizeType;
  38914. e.material.pointSizeType = Potree.config.material.pointSizeType;
  38915. e.changePointSize(Potree.config.material.realPointSize*2, true);//更改点云大小到能铺满为止,否则容易识别不到
  38916. });
  38917. Potree.updatePointClouds(pointclouds, camera, viewport.resolution );
  38918. }else {
  38919. if(viewer.viewports.filter(e=>!e.noPointcloud && e.active).length>1 || pickParams.cameraChanged){
  38920. viewport.beforeRender && viewport.beforeRender();
  38921. Potree.updatePointClouds(pointclouds, camera, viewport.resolution ); //不加这句的话hover久了会不准 因node是错的
  38922. //但依旧需要camera真的移动到那个位置才能加载出点云
  38923. }
  38924. }
  38925. let allPointclouds = [];
  38926. for(let pointcloud of pointclouds){
  38927. let point = pointcloud.pick(viewer, viewport, camera, ray, pickParams );
  38928. if(!point){
  38929. continue;
  38930. }
  38931. allPointclouds.push(pointcloud);
  38932. let distance = camera.position.distanceTo(point.position);
  38933. if (distance < closestDistance) {
  38934. closestDistance = distance;
  38935. selectedPointcloud = pointcloud;
  38936. closestIntersection = point.position;
  38937. closestPoint = point;
  38938. }
  38939. }
  38940. if(pickParams.isMeasuring || Potree.settings.displayMode == 'showPanos'){
  38941. Potree.settings.pointDensity = density;
  38942. pointclouds.forEach(e=>{
  38943. e.material.pointSizeType = sizeType;
  38944. e.changePointSize(size.get(e));
  38945. });
  38946. }else {
  38947. /* if(viewer.viewports.filter(e=>!e.noPointcloud).length>1){
  38948. viewport.afterRender && viewport.afterRender()
  38949. } */
  38950. }
  38951. if (selectedPointcloud) {
  38952. return {
  38953. location: closestIntersection,
  38954. distance: closestDistance,
  38955. pointcloud: selectedPointcloud,
  38956. point: closestPoint,
  38957. pointclouds: allPointclouds, //add
  38958. normal: new Vector3().fromArray(closestPoint.normal )//add
  38959. };
  38960. } else {
  38961. return null;
  38962. }
  38963. }
  38964. static renderTargetToDataUrl(renderTarget, width, height, renderer, compressRatio = 0.7){
  38965. let pixelCount = width * height;
  38966. let buffer = new Uint8Array(4 * pixelCount);
  38967. renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer);
  38968. var dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio);
  38969. return dataUrl
  38970. }
  38971. static pixelsArrayToDataUrl(pixels, width, height, compressRatio = 0.7) {
  38972. let canvas = document.createElement('canvas');
  38973. canvas.width = width;
  38974. canvas.height = height;
  38975. let context = canvas.getContext('2d');
  38976. pixels = new pixels.constructor(pixels);
  38977. /* for (let i = 0; i < pixels.length; i++) {
  38978. pixels[i * 4 + 3] = 255;
  38979. } */
  38980. // flip vertically
  38981. let bytesPerLine = width * 4;
  38982. for(let i = 0; i < parseInt(height / 2); i++){
  38983. let j = height - i - 1;
  38984. let lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  38985. let lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  38986. pixels.set(lineJ, i * bytesPerLine);
  38987. pixels.set(lineI, j * bytesPerLine);
  38988. }
  38989. let imageData = context.createImageData(width, height);
  38990. imageData.data.set(pixels);
  38991. context.putImageData(imageData, 0, 0);
  38992. let dataURL = canvas.toDataURL(compressRatio);
  38993. return dataURL;
  38994. }
  38995. static removeListeners(dispatcher, type){
  38996. if (dispatcher._listeners === undefined) {
  38997. return;
  38998. }
  38999. if (dispatcher._listeners[ type ]) {
  39000. delete dispatcher._listeners[ type ];
  39001. }
  39002. }
  39003. /* static mouseToRay(mouse, camera, width, height){
  39004. let normalizedMouse = {
  39005. x: (mouse.x / width) * 2 - 1,
  39006. y: -(mouse.y / height) * 2 + 1
  39007. };
  39008. let vector = new THREE.Vector3(normalizedMouse.x, normalizedMouse.y, 0.5);
  39009. let origin = camera.position.clone();
  39010. vector.unproject(camera);
  39011. let direction = new THREE.Vector3().subVectors(vector, origin).normalize();
  39012. let ray = new THREE.Ray(origin, direction);
  39013. return ray;
  39014. } */
  39015. static mouseToRay(pointer, camera ){
  39016. let vector = new Vector3(pointer.x, pointer.y, 1);
  39017. let origin = new Vector3(pointer.x, pointer.y, -1); //不能用camera.position,在orbitCamera时不准
  39018. vector.unproject(camera);
  39019. origin.unproject(camera);
  39020. let direction = new Vector3().subVectors(vector, origin).normalize();
  39021. let ray = new Ray(origin, direction);
  39022. return ray;
  39023. }
  39024. static getPos2d(point, camera, dom, viewport){//获取一个三维坐标对应屏幕中的二维坐标
  39025. var pos;
  39026. if(math.closeTo(camera.position, point, 1e-5) ){ //和相机位置重合时显示会四处飘,看是要改成一直显示中间还是隐藏?
  39027. pos = new Vector3(0,0,1.5); //1.5是为了不可见
  39028. }else {
  39029. pos = point.clone().project(camera); //比之前hotspot的计算方式写得简单 project用于3转2(求法同shader); unproject用于2转3 :new r.Vector3(e.x, e.y, -1).unproject(this.camera);
  39030. }
  39031. var x,y,left,top;
  39032. x = (pos.x + 1) / 2 * dom.clientWidth * viewport.width;
  39033. y = (1 - (pos.y + 1) / 2) * dom.clientHeight * viewport.height;
  39034. left = viewport.left * dom.clientWidth;
  39035. top = (1- viewport.bottom - viewport.height) * dom.clientHeight;
  39036. var inSight = pos.x <= 1 && pos.x >= -1 //是否在屏幕中
  39037. && pos.x <= 1 && pos.y >= -1;
  39038. return {
  39039. pos: new Vector2$1(left+x,top+y) ,// 屏幕像素坐标
  39040. vector: pos, //(范围 -1 ~ 1)
  39041. trueSide : pos.z<1, //trueSide为false时,即使在屏幕范围内可见,也是反方向的另一个不可以被渲染的点 参见Tag.update
  39042. inSight : inSight, //在屏幕范围内可见,
  39043. posInViewport: new Vector2$1(x,y)
  39044. };
  39045. }
  39046. static projectedRadius(radius, camera, distance, screenWidth, screenHeight){
  39047. if(camera instanceof OrthographicCamera){
  39048. return Utils.projectedRadiusOrtho(radius, camera.projectionMatrix, screenWidth, screenHeight);
  39049. }else if(camera instanceof PerspectiveCamera){
  39050. return Utils.projectedRadiusPerspective(radius, camera.fov * Math.PI / 180, distance, screenHeight);
  39051. }else {
  39052. throw new Error("invalid parameters");
  39053. }
  39054. }
  39055. static projectedRadiusPerspective(radius, fov, distance, screenHeight) {
  39056. let projFactor = (1 / Math.tan(fov / 2)) / distance;
  39057. projFactor = projFactor * screenHeight / 2;
  39058. return radius * projFactor;
  39059. }
  39060. static projectedRadiusOrtho(radius, proj, screenWidth, screenHeight) {
  39061. let p1 = new Vector4(0);
  39062. let p2 = new Vector4(radius);
  39063. p1.applyMatrix4(proj);
  39064. p2.applyMatrix4(proj);
  39065. p1 = new Vector3(p1.x, p1.y, p1.z);
  39066. p2 = new Vector3(p2.x, p2.y, p2.z);
  39067. p1.x = (p1.x + 1.0) * 0.5 * screenWidth;
  39068. p1.y = (p1.y + 1.0) * 0.5 * screenHeight;
  39069. p2.x = (p2.x + 1.0) * 0.5 * screenWidth;
  39070. p2.y = (p2.y + 1.0) * 0.5 * screenHeight;
  39071. return p1.distanceTo(p2);
  39072. }
  39073. static topView(camera, node){
  39074. camera.position.set(0, 1, 0);
  39075. camera.rotation.set(-Math.PI / 2, 0, 0);
  39076. camera.zoomTo(node, 1);
  39077. }
  39078. static frontView (camera, node) {
  39079. camera.position.set(0, 0, 1);
  39080. camera.rotation.set(0, 0, 0);
  39081. camera.zoomTo(node, 1);
  39082. }
  39083. static leftView (camera, node) {
  39084. camera.position.set(-1, 0, 0);
  39085. camera.rotation.set(0, -Math.PI / 2, 0);
  39086. camera.zoomTo(node, 1);
  39087. }
  39088. static rightView (camera, node) {
  39089. camera.position.set(1, 0, 0);
  39090. camera.rotation.set(0, Math.PI / 2, 0);
  39091. camera.zoomTo(node, 1);
  39092. }
  39093. static findClosestGpsTime(target, viewer){
  39094. const start = performance.now();
  39095. const nodes = [];
  39096. for(const pc of viewer.scene.pointclouds){
  39097. nodes.push(pc.root);
  39098. for(const child of pc.root.children){
  39099. if(child){
  39100. nodes.push(child);
  39101. }
  39102. }
  39103. }
  39104. let closestNode = null;
  39105. let closestIndex = Infinity;
  39106. let closestDistance = Infinity;
  39107. let closestValue = 0;
  39108. for(const node of nodes){
  39109. const isOkay = node.geometryNode != null
  39110. && node.geometryNode.geometry != null
  39111. && node.sceneNode != null;
  39112. if(!isOkay){
  39113. continue;
  39114. }
  39115. let geometry = node.geometryNode.geometry;
  39116. let gpsTime = geometry.attributes["gps-time"];
  39117. let range = gpsTime.potree.range;
  39118. for(let i = 0; i < gpsTime.array.length; i++){
  39119. let value = gpsTime.array[i];
  39120. value = value * (range[1] - range[0]) + range[0];
  39121. const distance = Math.abs(target - value);
  39122. if(distance < closestDistance){
  39123. closestIndex = i;
  39124. closestDistance = distance;
  39125. closestValue = value;
  39126. closestNode = node;
  39127. //console.log("found a closer one: " + value);
  39128. }
  39129. }
  39130. }
  39131. const geometry = closestNode.geometryNode.geometry;
  39132. const position = new Vector3(
  39133. geometry.attributes.position.array[3 * closestIndex + 0],
  39134. geometry.attributes.position.array[3 * closestIndex + 1],
  39135. geometry.attributes.position.array[3 * closestIndex + 2],
  39136. );
  39137. position.applyMatrix4(closestNode.sceneNode.matrixWorld);
  39138. const end = performance.now();
  39139. const duration = (end - start);
  39140. console.log(`duration: ${duration.toFixed(3)}ms`);
  39141. return {
  39142. node: closestNode,
  39143. index: closestIndex,
  39144. position: position,
  39145. };
  39146. }
  39147. /**
  39148. *
  39149. * 0: no intersection
  39150. * 1: intersection
  39151. * 2: fully inside
  39152. */
  39153. static frustumSphereIntersection (frustum, sphere) {
  39154. let planes = frustum.planes;
  39155. let center = sphere.center;
  39156. let negRadius = -sphere.radius;
  39157. let minDistance = Number.MAX_VALUE;
  39158. for (let i = 0; i < 6; i++) {
  39159. let distance = planes[ i ].distanceToPoint(center);
  39160. if (distance < negRadius) {
  39161. return 0;
  39162. }
  39163. minDistance = Math.min(minDistance, distance);
  39164. }
  39165. return (minDistance >= sphere.radius) ? 2 : 1;
  39166. }
  39167. // code taken from three.js
  39168. // ImageUtils - generateDataTexture()
  39169. static generateDataTexture (width, height, color) {
  39170. let size = width * height;
  39171. let data = new Uint8Array(4 * width * height);
  39172. let r = Math.floor(color.r * 255);
  39173. let g = Math.floor(color.g * 255);
  39174. let b = Math.floor(color.b * 255);
  39175. for (let i = 0; i < size; i++) {
  39176. data[ i * 3 ] = r;
  39177. data[ i * 3 + 1 ] = g;
  39178. data[ i * 3 + 2 ] = b;
  39179. }
  39180. let texture = new DataTexture(data, width, height, RGBAFormat);
  39181. texture.needsUpdate = true;
  39182. texture.magFilter = NearestFilter;
  39183. return texture;
  39184. }
  39185. // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
  39186. static getParameterByName (name) {
  39187. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  39188. let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  39189. let results = regex.exec(document.location.search);
  39190. return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
  39191. }
  39192. static setParameter (name, value) {
  39193. // value = encodeURIComponent(value);
  39194. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  39195. let regex = new RegExp('([\\?&])(' + name + '=([^&#]*))');
  39196. let results = regex.exec(document.location.search);
  39197. let url = window.location.href;
  39198. if (results === null) {
  39199. if (window.location.search.length === 0) {
  39200. url = url + '?';
  39201. } else {
  39202. url = url + '&';
  39203. }
  39204. url = url + name + '=' + value;
  39205. } else {
  39206. let newValue = name + '=' + value;
  39207. url = url.replace(results[2], newValue);
  39208. }
  39209. window.history.replaceState({}, '', url);
  39210. }
  39211. static createChildAABB(aabb, index){
  39212. let min = aabb.min.clone();
  39213. let max = aabb.max.clone();
  39214. let size = new Vector3().subVectors(max, min);
  39215. if ((index & 0b0001) > 0) {
  39216. min.z += size.z / 2;
  39217. } else {
  39218. max.z -= size.z / 2;
  39219. }
  39220. if ((index & 0b0010) > 0) {
  39221. min.y += size.y / 2;
  39222. } else {
  39223. max.y -= size.y / 2;
  39224. }
  39225. if ((index & 0b0100) > 0) {
  39226. min.x += size.x / 2;
  39227. } else {
  39228. max.x -= size.x / 2;
  39229. }
  39230. return new Box3(min, max);
  39231. }
  39232. // see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
  39233. static clipboardCopy(text){
  39234. let textArea = document.createElement("textarea");
  39235. textArea.style.position = 'fixed';
  39236. textArea.style.top = 0;
  39237. textArea.style.left = 0;
  39238. textArea.style.width = '2em';
  39239. textArea.style.height = '2em';
  39240. textArea.style.padding = 0;
  39241. textArea.style.border = 'none';
  39242. textArea.style.outline = 'none';
  39243. textArea.style.boxShadow = 'none';
  39244. textArea.style.background = 'transparent';
  39245. textArea.value = text;
  39246. document.body.appendChild(textArea);
  39247. textArea.select();
  39248. try {
  39249. let success = document.execCommand('copy');
  39250. if(success){
  39251. console.log("copied text to clipboard");
  39252. }else {
  39253. console.log("copy to clipboard failed");
  39254. }
  39255. } catch (err) {
  39256. console.log("error while trying to copy to clipboard");
  39257. }
  39258. document.body.removeChild(textArea);
  39259. }
  39260. static getMeasurementIcon(measurement){
  39261. if (measurement instanceof Measure) {
  39262. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  39263. return `${Potree.resourcePath}/icons/distance.svg`;
  39264. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  39265. return `${Potree.resourcePath}/icons/area.svg`;
  39266. } else if (measurement.maxMarkers === 1) {
  39267. return `${Potree.resourcePath}/icons/point.svg`;
  39268. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  39269. return `${Potree.resourcePath}/icons/angle.png`;
  39270. } else if (measurement.showHeight) {
  39271. return `${Potree.resourcePath}/icons/height.svg`;
  39272. } else {
  39273. return `${Potree.resourcePath}/icons/distance.svg`;
  39274. }
  39275. } else if (measurement instanceof Profile) {
  39276. return `${Potree.resourcePath}/icons/profile.svg`;
  39277. } else if (measurement instanceof Volume) {
  39278. return `${Potree.resourcePath}/icons/volume.svg`;
  39279. } else if (measurement instanceof PolygonClipVolume) {
  39280. return `${Potree.resourcePath}/icons/clip-polygon.svg`;
  39281. }
  39282. }
  39283. static lineToLineIntersection(P0, P1, P2, P3){
  39284. const P = [P0, P1, P2, P3];
  39285. const d = (m, n, o, p) => {
  39286. let result =
  39287. (P[m].x - P[n].x) * (P[o].x - P[p].x)
  39288. + (P[m].y - P[n].y) * (P[o].y - P[p].y)
  39289. + (P[m].z - P[n].z) * (P[o].z - P[p].z);
  39290. return result;
  39291. };
  39292. const mua = (d(0, 2, 3, 2) * d(3, 2, 1, 0) - d(0, 2, 1, 0) * d(3, 2, 3, 2))
  39293. /**-----------------------------------------------------------------**/ /
  39294. (d(1, 0, 1, 0) * d(3, 2, 3, 2) - d(3, 2, 1, 0) * d(3, 2, 1, 0));
  39295. const mub = (d(0, 2, 3, 2) + mua * d(3, 2, 1, 0))
  39296. /**--------------------------------------**/ /
  39297. d(3, 2, 3, 2);
  39298. const P01 = P1.clone().sub(P0);
  39299. const P23 = P3.clone().sub(P2);
  39300. const Pa = P0.clone().add(P01.multiplyScalar(mua));
  39301. const Pb = P2.clone().add(P23.multiplyScalar(mub));
  39302. const center = Pa.clone().add(Pb).multiplyScalar(0.5);
  39303. return center;
  39304. }
  39305. static computeCircleCenter(A, B, C){
  39306. const AB = B.clone().sub(A);
  39307. const AC = C.clone().sub(A);
  39308. const N = AC.clone().cross(AB).normalize();
  39309. const ab_dir = AB.clone().cross(N).normalize();
  39310. const ac_dir = AC.clone().cross(N).normalize();
  39311. const ab_origin = A.clone().add(B).multiplyScalar(0.5);
  39312. const ac_origin = A.clone().add(C).multiplyScalar(0.5);
  39313. const P0 = ab_origin;
  39314. const P1 = ab_origin.clone().add(ab_dir);
  39315. const P2 = ac_origin;
  39316. const P3 = ac_origin.clone().add(ac_dir);
  39317. const center = Utils.lineToLineIntersection(P0, P1, P2, P3);
  39318. return center;
  39319. // Potree.Utils.debugLine(viewer.scene.scene, P0, P1, 0x00ff00);
  39320. // Potree.Utils.debugLine(viewer.scene.scene, P2, P3, 0x0000ff);
  39321. // Potree.Utils.debugSphere(viewer.scene.scene, center, 0.03, 0xff00ff);
  39322. // const radius = center.distanceTo(A);
  39323. // Potree.Utils.debugCircle(viewer.scene.scene, center, radius, new THREE.Vector3(0, 0, 1), 0xff00ff);
  39324. }
  39325. static getNorthVec(p1, distance, projection){
  39326. if(projection){
  39327. // if there is a projection, transform coordinates to WGS84
  39328. // and compute angle to north there
  39329. proj4.defs("pointcloud", projection);
  39330. const transform = proj4("pointcloud", "WGS84");
  39331. const llP1 = transform.forward(p1.toArray());
  39332. let llP2 = transform.forward([p1.x, p1.y + distance]);
  39333. const polarRadius = Math.sqrt((llP2[0] - llP1[0]) ** 2 + (llP2[1] - llP1[1]) ** 2);
  39334. llP2 = [llP1[0], llP1[1] + polarRadius];
  39335. const northVec = transform.inverse(llP2);
  39336. return new Vector3(...northVec, p1.z).sub(p1);
  39337. }else {
  39338. // if there is no projection, assume [0, 1, 0] as north direction
  39339. const vec = new Vector3(0, 1, 0).multiplyScalar(distance);
  39340. return vec;
  39341. }
  39342. }
  39343. static computeAzimuth(p1, p2, projection){
  39344. let azimuth = 0;
  39345. if(projection){
  39346. // if there is a projection, transform coordinates to WGS84
  39347. // and compute angle to north there
  39348. let transform;
  39349. if (projection.includes('EPSG')) {
  39350. transform = proj4(projection, "WGS84");
  39351. } else {
  39352. proj4.defs("pointcloud", projection);
  39353. transform = proj4("pointcloud", "WGS84");
  39354. }
  39355. const llP1 = transform.forward(p1.toArray());
  39356. const llP2 = transform.forward(p2.toArray());
  39357. const dir = [
  39358. llP2[0] - llP1[0],
  39359. llP2[1] - llP1[1],
  39360. ];
  39361. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  39362. }else {
  39363. // if there is no projection, assume [0, 1, 0] as north direction
  39364. const dir = [p2.x - p1.x, p2.y - p1.y];
  39365. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  39366. }
  39367. // make clockwise
  39368. azimuth = -azimuth;
  39369. return azimuth;
  39370. }
  39371. static async loadScript(url){
  39372. return new Promise( resolve => {
  39373. const element = document.getElementById(url);
  39374. if(element){
  39375. resolve();
  39376. }else {
  39377. const script = document.createElement("script");
  39378. script.id = url;
  39379. script.onload = () => {
  39380. resolve();
  39381. };
  39382. script.src = url;
  39383. document.body.appendChild(script);
  39384. }
  39385. });
  39386. }
  39387. static createSvgGradient(scheme){
  39388. // this is what we are creating:
  39389. //
  39390. //<svg width="1em" height="3em" xmlns="http://www.w3.org/2000/svg">
  39391. // <defs>
  39392. // <linearGradient id="gradientID" gradientTransform="rotate(90)">
  39393. // <stop offset="0%" stop-color="rgb(93, 78, 162)" />
  39394. // ...
  39395. // <stop offset="100%" stop-color="rgb(157, 0, 65)" />
  39396. // </linearGradient>
  39397. // </defs>
  39398. //
  39399. // <rect width="100%" height="100%" fill="url('#myGradient')" stroke="black" stroke-width="0.1em"/>
  39400. //</svg>
  39401. const gradientId = `${Math.random()}_${Date.now()}`;
  39402. const svgn = "http://www.w3.org/2000/svg";
  39403. const svg = document.createElementNS(svgn, "svg");
  39404. svg.setAttributeNS(null, "width", "2em");
  39405. svg.setAttributeNS(null, "height", "3em");
  39406. { // <defs>
  39407. const defs = document.createElementNS(svgn, "defs");
  39408. const linearGradient = document.createElementNS(svgn, "linearGradient");
  39409. linearGradient.setAttributeNS(null, "id", gradientId);
  39410. linearGradient.setAttributeNS(null, "gradientTransform", "rotate(90)");
  39411. for(let i = scheme.length - 1; i >= 0; i--){
  39412. const stopVal = scheme[i];
  39413. const percent = parseInt(100 - stopVal[0] * 100);
  39414. const [r, g, b] = stopVal[1].toArray().map(v => parseInt(v * 255));
  39415. const stop = document.createElementNS(svgn, "stop");
  39416. stop.setAttributeNS(null, "offset", `${percent}%`);
  39417. stop.setAttributeNS(null, "stop-color", `rgb(${r}, ${g}, ${b})`);
  39418. linearGradient.appendChild(stop);
  39419. }
  39420. defs.appendChild(linearGradient);
  39421. svg.appendChild(defs);
  39422. }
  39423. const rect = document.createElementNS(svgn, "rect");
  39424. rect.setAttributeNS(null, "width", `100%`);
  39425. rect.setAttributeNS(null, "height", `100%`);
  39426. rect.setAttributeNS(null, "fill", `url("#${gradientId}")`);
  39427. rect.setAttributeNS(null, "stroke", `black`);
  39428. rect.setAttributeNS(null, "stroke-width", `0.1em`);
  39429. svg.appendChild(rect);
  39430. return svg;
  39431. }
  39432. static async waitAny(promises){
  39433. return new Promise( (resolve) => {
  39434. promises.map( promise => {
  39435. promise.then( () => {
  39436. resolve();
  39437. });
  39438. });
  39439. });
  39440. }
  39441. }
  39442. Utils.screenPass = new function () {
  39443. this.screenScene = new Scene();
  39444. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  39445. this.screenQuad.material.depthTest = true;
  39446. this.screenQuad.material.depthWrite = true;
  39447. this.screenQuad.material.transparent = true;
  39448. this.screenScene.add(this.screenQuad);
  39449. this.camera = new Camera();
  39450. this.render = function (renderer, material, target) {
  39451. this.screenQuad.material = material;
  39452. if (typeof target === 'undefined') {
  39453. renderer.render(this.screenScene, this.camera);
  39454. } else {
  39455. renderer.setRenderTarget(target);
  39456. renderer.render(this.screenScene, this.camera);
  39457. }
  39458. };
  39459. }();
  39460. //add
  39461. Utils.computePointcloudsBound = function(pointclouds){
  39462. var boundingBox = new Box3();
  39463. pointclouds.forEach(pointcloud=>{
  39464. pointcloud.updateBound();
  39465. boundingBox.union(pointcloud.bound);
  39466. });
  39467. var boundSize = boundingBox.getSize(new Vector3);
  39468. var center = boundingBox.getCenter(new Vector3);
  39469. return {boundSize, center, boundingBox}
  39470. };
  39471. Utils.convertScreenPositionToNDC = function(pointer, mouse, width, height) {
  39472. return pointer = pointer || new Vector2$1,
  39473. pointer.x = mouse.x / width * 2 - 1,
  39474. pointer.y = 2 * -(mouse.y / height) + 1,
  39475. pointer
  39476. };
  39477. Utils.convertNDCToScreenPosition = function(pointer, mouse, width, height) {
  39478. return mouse = mouse || new Vector2$1,
  39479. mouse.x = Math.round((pointer.x + 1 ) / 2 * width),
  39480. mouse.y = Math.round(-(pointer.y - 1 ) / 2 * height),
  39481. mouse
  39482. };
  39483. Utils.getOrthoCameraMoveVec = function(pointerDelta, camera ){//获取当camera为Ortho型时 屏幕点1 到 屏幕点2 的三维距离
  39484. let cameraViewWidth = camera.right / camera.zoom;
  39485. let cameraViewHeight = camera.top / camera.zoom;
  39486. let moveVec = new Vector3;
  39487. moveVec.set( pointerDelta.x * cameraViewWidth , pointerDelta.y * cameraViewHeight , 0).applyQuaternion(camera.quaternion);
  39488. return moveVec
  39489. };
  39490. Utils.VectorFactory = {
  39491. fromArray : function(t) {
  39492. if (t) {
  39493. if (t.length < 2 || t.length > 3)
  39494. console.error("Wrong number of ordinates for a point!");
  39495. return 3 === t.length ? (new Vector3).fromArray(t) : (new Vector2$1).fromArray(t)
  39496. }
  39497. },
  39498. fromArray3 : function(t) {
  39499. if (t) {
  39500. if (3 !== t.length)
  39501. console.error("Wrong number of ordinates for a point!");
  39502. return (new Vector3).fromArray(t)
  39503. }
  39504. },
  39505. fromArray2 : function(t) {
  39506. if (t) {
  39507. if (2 !== t.length)
  39508. console.error("Wrong number of ordinates for a point!");
  39509. return (new Vector2$1).fromArray(t)
  39510. }
  39511. },
  39512. toString : function(t) {
  39513. return t.x.toFixed(8) + "," + t.y.toFixed(8) + "," + t.z.toFixed(3)
  39514. }
  39515. };
  39516. Utils.QuaternionFactory = {
  39517. rot90 : (new Quaternion).setFromAxisAngle(new Vector3(0,0,1), MathUtils.degToRad(-90)),
  39518. fromArray : function(t) {
  39519. if (t) {
  39520. if (4 !== t.length)
  39521. console.error("Wrong number of ordinates for a quaternion!");
  39522. return new Quaternion(t[1],t[2],t[3],t[0]).multiply(this.rot90)
  39523. }
  39524. }
  39525. ,
  39526. toArray : function(t) {
  39527. if (t) {
  39528. var e = t.clone().multiply(a).toArray();
  39529. return [e[3], e[0], e[1], e[2]]
  39530. }
  39531. }
  39532. ,
  39533. fromLonLat : function(t) {
  39534. if (t)
  39535. return (new Quaternion).setFromEuler(new Euler(t.lon,t.lat,0))
  39536. }
  39537. ,
  39538. toLonLat : function(t) {
  39539. if (t) {
  39540. var e = (new Euler).setFromQuaternion(t);
  39541. return {
  39542. lon: e.x,
  39543. lat: e.y
  39544. }
  39545. }
  39546. }
  39547. };
  39548. Utils.datasetPosTransform = function(o={}){
  39549. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  39550. let tranMatrix;
  39551. if(pointcloud){
  39552. if(Potree.settings.editType == 'merge'){
  39553. tranMatrix = o.fromDataset ? pointcloud.matrixWorld : new Matrix4().copy(pointcloud.matrixWorld).invert();
  39554. }else {
  39555. tranMatrix = o.fromDataset ? pointcloud.transformMatrix : pointcloud.transformInvMatrix;
  39556. }
  39557. }else {
  39558. if(Potree.settings.intersectOnObjs){
  39559. let object = o.object || viewer.objs.children.find(e=>e.dataset_id == o.datasetId);
  39560. if(object){
  39561. tranMatrix = o.fromDataset ? object.matrixWorld : new Matrix4().copy(object.matrixWorld).invert();
  39562. }
  39563. }
  39564. }
  39565. if(tranMatrix){
  39566. return (new Vector3).copy(o.position).applyMatrix4(tranMatrix)
  39567. }else {
  39568. if(o.datasetId != void 0){
  39569. console.error(`datasetPosTransform找不到datasetId为${o.datasetId}的数据集或模型,请检查数据, 模型未创建或删除`);
  39570. //很可能是旧的热点,需要删除
  39571. }
  39572. }
  39573. };
  39574. Utils.datasetRotTransform = function(o={}){
  39575. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  39576. if(pointcloud){
  39577. var matrix, newMatrix, result;
  39578. if(o.rotation){
  39579. matrix = new Matrix4().makeRotationFromEuler(o.rotation);
  39580. }else if(o.quaternion){
  39581. matrix = new Matrix4().makeRotationFromQuaternion(o.quaternion);
  39582. }else if(o.matrix){
  39583. matrix = o.matrix.clone();
  39584. }else {
  39585. return
  39586. }
  39587. let rotateMatrix = o.fromDataset ? pointcloud.rotateMatrix : pointcloud.rotateInvMatrix;
  39588. newMatrix = new Matrix4().multiplyMatrices(rotateMatrix, matrix );
  39589. if(o.getRotation){
  39590. result = new Euler().setFromRotationMatrix(newMatrix);
  39591. }else if(o.getQuaternion){
  39592. result = new Quaternion().setFromRotationMatrix(newMatrix);
  39593. }else if(o.getMatrix){
  39594. result = newMatrix;
  39595. }
  39596. return result
  39597. }
  39598. };
  39599. Utils.isInsideFrustum = function(bounding, camera){// boundingBox在视野范围内有可见部分
  39600. let frustumMatrix = new Matrix4;
  39601. frustumMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  39602. let frustum = new Frustum();
  39603. frustum.setFromProjectionMatrix(frustumMatrix);
  39604. if(bounding instanceof Sphere){
  39605. return frustum.intersectsSphere(bounding)
  39606. }else {
  39607. return frustum.intersectsBox(bounding)
  39608. }
  39609. };
  39610. Utils.isInsideBox = function(object, boxMatrixInverse){//object可以是点或者bounding, box原为1*1*1,但可能形变
  39611. let frustum = new Frustum();
  39612. frustum.setFromProjectionMatrix(boxMatrixInverse);
  39613. if(object instanceof Box3){
  39614. return frustum.intersectsSphere(object)
  39615. }else if(object instanceof Array){//点合集,先求Sphere setFromPoints
  39616. let sphere = new Sphere();
  39617. sphere.setFromPoints(object);
  39618. return this.isInsideBox(sphere, boxMatrixInverse)
  39619. }else if(object instanceof Sphere){
  39620. return frustum.intersectsSphere(object)
  39621. }else if(object instanceof Vector3){
  39622. return frustum.containsPoint(object)
  39623. }
  39624. /* containsPoint: ƒ containsPoint( point )
  39625. intersectsBox: ƒ intersectsBox( box )
  39626. intersectsObject: ƒ intersectsObject( object )//geo
  39627. intersectsSphere: ƒ intersectsSphere( sphere )
  39628. intersectsSprite: ƒ intersectsSprite( sprite )
  39629. */
  39630. };
  39631. Utils.getIntersect = function (camera, meshes, pointer, raycaster) {
  39632. //获取鼠标和meshes交点
  39633. camera.updateMatrixWorld();
  39634. if(!raycaster){//getMouseIntersect
  39635. raycaster = new Raycaster();
  39636. var origin = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  39637. end = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  39638. var dir = end.sub(origin).normalize();
  39639. raycaster.set(origin, dir);
  39640. }
  39641. meshes.forEach(e=>{
  39642. raycaster.layers.enable(math.getBaseLog(e.layers.mask,2));
  39643. });
  39644. var n = raycaster.intersectObjects(meshes);
  39645. if (0 === n.length) return null
  39646. return n[0]
  39647. };
  39648. var start = function(dom, mapDom, number ){ //t-Zvd3w0m
  39649. /* {
  39650. let obj = JSON.parse(localStorage.getItem('setting'))
  39651. for(let i in obj){
  39652. console.log(i + ': ' + obj[i])
  39653. }
  39654. }
  39655. */
  39656. Potree.settings.number = number || 't-o5YMR13';// 't-iksBApb'// 写在viewer前
  39657. let viewer = new Potree.Viewer(dom , mapDom);
  39658. let Alignment = viewer.modules.Alignment;
  39659. //let pointDensity = config.pointDensity.middle
  39660. viewer.setEDLEnabled(false);
  39661. viewer.setFOV(config$1.view.fov);
  39662. //viewer.setPointBudget(pointDensity.pointBudget);
  39663. viewer.loadSettingsFromURL();
  39664. if(!Potree.settings.isOfficial){
  39665. viewer.loadGUI(() => {
  39666. viewer.setLanguage('en');
  39667. //$("#menu_appearance").next().show();
  39668. $("#menu_tools").next().show();
  39669. $("#menu_scene").next().show();
  39670. $("#siteModel").show();
  39671. //$("#alignment").show();
  39672. viewer.toggleSidebar();
  39673. });
  39674. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  39675. }
  39676. Potree.loadDatasetsCallback = function(data, ifReload){
  39677. if(!data || data.length == 0)return console.error('getDataSet加载的数据为空')
  39678. Potree.datasetData = data;
  39679. viewer.transform = null;
  39680. var datasetLength = data.length;
  39681. var pointcloudLoaded = 0;
  39682. var panosLoaded = 0;
  39683. var pointcloudLoadDone = function(){//点云cloud.js加载完毕后
  39684. viewer.updateModelBound();
  39685. let {boundSize, center} = viewer.bound;
  39686. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , null, 12);
  39687. if(!Potree.settings.isOfficial){
  39688. Potree.loadMapEntity('all'); //加载floorplan
  39689. }
  39690. if(!ifReload){
  39691. viewer.scene.view.setView({
  39692. position: center.clone().add(new Vector3(10,5,10)),
  39693. target: center
  39694. });
  39695. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39696. if(!Potree.settings.UserPointDensity){
  39697. Potree.settings.UserPointDensity = 'high';//'middle'
  39698. }
  39699. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39700. }
  39701. };
  39702. var panosLoadDone = function(){
  39703. viewer.images360.loadDone();
  39704. viewer.scene.add360Images(viewer.images360);
  39705. viewer.mapViewer.addListener(viewer.images360);
  39706. {//初始位置
  39707. var urlFirstView = false;
  39708. var panoId = browser.urlHasValue('pano',true);
  39709. if(panoId !== ''){
  39710. var pos;
  39711. var pano = viewer.images360.panos.find(e=>e.id==panoId);
  39712. if(pano){
  39713. viewer.images360.focusPano({
  39714. pano,
  39715. duration:0,
  39716. callback:()=>{/* Potree.settings.displayMode = 'showPanos' */}
  39717. });
  39718. }
  39719. }else {//考虑到多数据集距离很远,或者像隧道那种场景,要使视野范围内一定能看到点云,最好初始点设置在漫游点上
  39720. let {boundSize, center} = viewer.bound;
  39721. let pano = viewer.images360.findNearestPano(center);
  39722. /* pano && viewer.scene.view.setView({
  39723. position: pano.position.clone().add(new THREE.Vector3(10,10,10)),
  39724. target: pano.position
  39725. }) */
  39726. pano && viewer.images360.flyToPano({
  39727. pano, duration:0,
  39728. target : viewer.images360.bound.center
  39729. });
  39730. }
  39731. }
  39732. viewer.addVideo();//addFire()
  39733. console.log('allLoaded');
  39734. viewer.dispatchEvent('allLoaded');
  39735. };
  39736. var transformPointcloud = (pointcloud, dataset)=>{
  39737. var locationLonLat = dataset.location.slice(0,2);
  39738. //当只有一个dataset时,无论如何transform 点云和漫游点都能对应上。
  39739. var location = viewer.transform.lonlatToLocal.forward(locationLonLat); //transform.inverse()
  39740. //初始化位置
  39741. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  39742. //dataset.orientation = 0
  39743. Alignment.rotate(pointcloud, null, dataset.orientation);
  39744. Alignment.translate(pointcloud, new Vector3(location[0], location[1], dataset.location[2]));
  39745. pointcloud.updateMatrixWorld();
  39746. Potree.Log(`点云${pointcloud.dataset_id}旋转值:${pointcloud.orientationUser}, 位置${math.toPrecision(pointcloud.translateUser.toArray(),3)}, 经纬度 ${locationLonLat}, spacing ${pointcloud.material.spacing}`, null, 17 );
  39747. //-------------------
  39748. //viewer.mapView.showSources(false);
  39749. };
  39750. if(!Potree.settings.originDatasetId)Potree.settings.originDatasetId = data[0].id;
  39751. var originDataset = data.find(e=>e.id == Potree.settings.originDatasetId);
  39752. {//拿初始数据集作为基准。它的位置是000
  39753. var locationLonLat = originDataset.location.slice(0,2);
  39754. proj4.defs("NAVVIS:TMERC", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  39755. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  39756. let transform1 = proj4("WGS84", "NAVVIS:TMERC"); //这个ok TMERC是展开的平面投影
  39757. 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;");
  39758. viewer.transform = {
  39759. lonlatToLocal : transform1,
  39760. lonlatTo4550 : transform2 // 转大地坐标EPSG:4550
  39761. };
  39762. viewer.mapViewer && viewer.mapViewer.mapLayer.maps[0].updateProjection();
  39763. }
  39764. data.forEach((dataset,index)=>{
  39765. if(!ifReload){
  39766. var datasetCode = dataset.sceneCode || dataset.name; //对应4dkk的场景码
  39767. var cloudPath = `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${datasetCode}/data/${datasetCode}/webcloud/cloud.js`;
  39768. var timeStamp = dataset.createTime ? dataset.createTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随createTime更新一次
  39769. //console.warn(dataset.name, 'timeStamp', timeStamp)
  39770. Potree.loadPointCloud(cloudPath, dataset.name ,datasetCode, timeStamp, e => {
  39771. let scene = viewer.scene;
  39772. let pointcloud = e.pointcloud;
  39773. let config = Potree.config.material;
  39774. let material = pointcloud.material;
  39775. pointcloud.hasDepthTex = Potree.settings.useDepthTex && (!!dataset.has_depth || Potree.settings.isLocalhost && Potree.settings.number == 'SS-t-7DUfWAUZ3V'); //test
  39776. material.minSize = config.minSize;
  39777. material.maxSize = config.maxSize;
  39778. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39779. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  39780. pointcloud.changePointOpacity(1);
  39781. material.shape = Potree.PointShape.SQUARE;
  39782. pointcloud.color = pointcloud.material.color = dataset.color;
  39783. pointcloud.dataset_id = dataset.id;//供漫游点找到属于的dataset点云
  39784. pointcloud.timeStamp = timeStamp;
  39785. transformPointcloud(pointcloud,dataset);
  39786. scene.addPointCloud(pointcloud);
  39787. if(!Potree.settings.isOfficial){
  39788. Potree.settings.floorplanEnables[dataset.id] = true;
  39789. Potree.settings.floorplanType[dataset.id] = 'default';
  39790. }
  39791. pointcloudLoaded ++;
  39792. if(pointcloudLoaded == datasetLength)pointcloudLoadDone();
  39793. Potree.loadPanos(dataset.id, (data) => {
  39794. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  39795. viewer.images360.addPanoData(data, dataset.id );
  39796. panosLoaded ++;
  39797. if(panosLoaded == datasetLength){
  39798. panosLoadDone();
  39799. }
  39800. });
  39801. });
  39802. }else {
  39803. let pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == dataset.id);
  39804. if(!pointcloud){
  39805. Potree.Log('数据集id变了,自动使用第一个','#500');
  39806. pointcloud = viewer.scene.pointclouds[0];
  39807. }
  39808. //先归零
  39809. Alignment.translate(pointcloud, pointcloud.translateUser.clone().negate());
  39810. Alignment.rotate(pointcloud, null, - pointcloud.orientationUser);
  39811. transformPointcloud(pointcloud, dataset);
  39812. }
  39813. });
  39814. if(ifReload){
  39815. //loadDone()
  39816. }
  39817. };
  39818. Potree.loadDatasets(Potree.loadDatasetsCallback);
  39819. window.testTransform = function(locationLonLat, location1, location2){
  39820. proj4.defs("NAVVIS:test", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  39821. let transform = proj4("WGS84", "NAVVIS:test"); //这个ok navvis里也是这两种转换 见proj4Factory
  39822. if(location1){//经纬度
  39823. return transform.forward(location1)
  39824. }else {
  39825. return transform.inverse(location2)
  39826. }
  39827. };
  39828. window.THREE = THREE$1;
  39829. window.buttonFunction = function(){
  39830. viewer.scene.pointclouds.forEach(e=>e.predictNodeMaxLevel());
  39831. /*
  39832. viewer.startScreenshot({type:'measure', measurement:viewer.scene.measurements[0]})
  39833. viewer.modules.RouteGuider.routeStart = new THREE.Vector3(0,0,-1.3)
  39834. viewer.modules.RouteGuider.routeEnd = new THREE.Vector3(-10,0,-1.3)
  39835. */
  39836. };
  39837. if(Potree.settings.isLocalhost){
  39838. let before = {};
  39839. viewer.inputHandler.addEventListener('keydown',e=>{ //测试的代码
  39840. if(e.event.key == 't'){
  39841. viewer.images360.cube.visible = true;
  39842. viewer.images360.cube.material.wireframe = true;
  39843. }else if(e.event.key == 'y'){
  39844. viewer.images360.cube.material.wireframe = false;
  39845. viewer.images360.cube.visible = Potree.settings.displayMode == 'showPanos';
  39846. }
  39847. });
  39848. }
  39849. };
  39850. //=======================================================================
  39851. /*
  39852. 漫游点编辑
  39853. */
  39854. //=======================================================================
  39855. var panoEditStart = function(dom, number, fileServer){
  39856. Potree.settings.editType = 'pano';
  39857. Potree.settings.number = number;
  39858. Potree.settings.unableNavigate = true;
  39859. let viewer = new Potree.Viewer(dom);
  39860. let Alignment = viewer.modules.Alignment;
  39861. viewer.setEDLEnabled(false);
  39862. viewer.setFOV(config$1.view.fov);
  39863. viewer.loadSettingsFromURL();
  39864. let datasetLoaded = 0;
  39865. if(!Potree.settings.isOfficial){
  39866. viewer.loadGUI(() => {
  39867. viewer.setLanguage('en');
  39868. $("#menu_tools").next().show();
  39869. $("#panos").show();
  39870. $("#alignment").show();
  39871. viewer.toggleSidebar();
  39872. });
  39873. Potree.settings.sizeFitToLevel = true;
  39874. }
  39875. var pointcloudLoadDone = function( ){//所有点云cloud.js加载完毕后
  39876. viewer.scene.pointclouds.forEach(c=>{
  39877. transformPointcloud(c);
  39878. });
  39879. viewer.images360.loadDone();
  39880. viewer.scene.add360Images(viewer.images360);
  39881. viewer.updateModelBound();
  39882. let {boundSize, center} = viewer.bound;
  39883. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , null, 12);
  39884. viewer.scene.view.setView({
  39885. position: center.clone().add(new Vector3(10,5,10)),
  39886. target: center
  39887. });
  39888. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39889. if(!Potree.settings.UserPointDensity){
  39890. Potree.settings.UserPointDensity = 'panoEdit';//'middle'
  39891. }
  39892. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39893. viewer.dispatchEvent('allLoaded');
  39894. };
  39895. var transformPointcloud = (pointcloud )=>{ //初始化位置
  39896. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  39897. let orientation = pointcloud.panos[0].dataRotation.z + Math.PI;
  39898. let location = pointcloud.panos[0].dataPosition.clone();//.negate()
  39899. Alignment.rotate(pointcloud, null, orientation );
  39900. Alignment.translate(pointcloud, location );
  39901. pointcloud.updateMatrixWorld();
  39902. };
  39903. let loadPanosDone = Potree.loadPanosDone = (datasetId, panoData )=>{ //一个数据集获取到它的panos后
  39904. Potree.settings.datasetsPanos[datasetId] = {panoData, panos:[]};
  39905. console.log('panoData', datasetId, panoData);
  39906. let panoCount = panoData.length;
  39907. let pointcloudLoaded = 0;
  39908. let datasetsCount = Object.keys(Potree.settings.datasetsPanos).length;
  39909. panoData.forEach((pano, index)=>{
  39910. //let cloudPath = `${Potree.scriptPath}/data/panoEdit/uuidcloud/${pano.uuid}/cloud.js`
  39911. let cloudPath = `https://laser-oss.4dkankan.com/${Potree.settings.webSite}/${Potree.settings.number}/data/bundle_${Potree.settings.number}/building/uuidcloud/${pano.uuid}/cloud.js`;
  39912. let name = datasetId + '-'+pano.uuid;
  39913. let timeStamp = 0;
  39914. pano.index = index; //注意:index不等于uuid,因为有的uuid缺失。但是visibles中存的是下标!
  39915. Potree.loadPointCloud(cloudPath, name , name, timeStamp, e => { //开始加载点云
  39916. let scene = viewer.scene;
  39917. let pointcloud = e.pointcloud;
  39918. let config = Potree.config.material;
  39919. let material = pointcloud.material;
  39920. material.minSize = config.minSize;
  39921. material.maxSize = config.maxSize;
  39922. material.pointSizeType = /* 'ADAPTIVE'// */config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39923. pointcloud.changePointSize( 0.1 /* config.realPointSize */ ); //material.size = config.pointSize;
  39924. pointcloud.changePointOpacity(1);
  39925. material.shape = Potree.PointShape.SQUARE;
  39926. pointcloud.color = config.pointColor;
  39927. pointcloud.dataset_id = datasetId; //多个点云指向一个datasetId
  39928. pointcloud.panoUuid = pano.uuid;
  39929. pointcloud.timeStamp = timeStamp;
  39930. //transformPointcloud(pointcloud, pano)
  39931. scene.addPointCloud(pointcloud);
  39932. pointcloudLoaded ++;
  39933. if(pointcloudLoaded == panoCount ){
  39934. datasetLoaded ++;
  39935. viewer.images360.addPanoData(panoData , datasetId );
  39936. if(datasetLoaded == datasetsCount){
  39937. pointcloudLoadDone();
  39938. }
  39939. }
  39940. });
  39941. });
  39942. };
  39943. if(!Potree.settings.isOfficial){
  39944. Potree.settings.datasetsPano = {'testDataset':null};
  39945. Potree.loadPanosInfo( data=>{loadPanosDone('testDataset', data.sweepLocations);} );
  39946. }
  39947. };
  39948. var mergeEditStart = function(dom){
  39949. Potree.settings.editType = 'merge';
  39950. Potree.settings.intersectOnObjs = true;
  39951. Potree.settings.boundAddObjs = true;
  39952. Potree.settings.unableNavigate = true;
  39953. let viewer = new Potree.Viewer(dom );
  39954. let Alignment = viewer.modules.Alignment;
  39955. viewer.setEDLEnabled(false);
  39956. viewer.setFOV(config$1.view.fov);
  39957. viewer.loadSettingsFromURL();
  39958. {
  39959. viewer.mainViewport.view.position.set(30,30,30);
  39960. viewer.mainViewport.view.lookAt(0,0,0);
  39961. viewer.updateModelBound();//init
  39962. //this.bound = new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1))
  39963. viewer.transformationTool.setModeEnable('scale',false);
  39964. viewer.ssaaRenderPass.sampleLevel = 1; // sampleLevel为1 的话,ground就不会变黑
  39965. viewer.inputHandler.fixSelection = true; //不通过点击屏幕而切换transfrom选中状态
  39966. }
  39967. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  39968. Potree.loadPointCloudScene = function(sceneCode, type, id, done, onError){//对应4dkk的场景码
  39969. let loadCloud = (cloudPath, sceneName, sceneCode, timeStamp, color)=>{
  39970. Potree.loadPointCloud(cloudPath, sceneName , sceneCode, timeStamp, e => {
  39971. let scene = viewer.scene;
  39972. let pointcloud = e.pointcloud;
  39973. let config = Potree.config.material;
  39974. let material = pointcloud.material;
  39975. material.minSize = config.minSize;
  39976. material.maxSize = config.maxSize;
  39977. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39978. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  39979. pointcloud.changePointOpacity(1);
  39980. material.shape = Potree.PointShape.SQUARE;
  39981. color && (pointcloud.color = pointcloud.material.color = color);
  39982. pointcloud.timeStamp = timeStamp;
  39983. //transformPointcloud(pointcloud, originDataset)
  39984. scene.addPointCloud(pointcloud);
  39985. {
  39986. viewer.updateModelBound();
  39987. let {boundSize, center} = viewer.bound;
  39988. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39989. if(!Potree.settings.UserPointDensity){
  39990. Potree.settings.UserPointDensity = 'high';//'middle'
  39991. }
  39992. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39993. }
  39994. /* Potree.loadPanos(dataset.id, (data) => { //暂时不加载panos了,因为没有id
  39995. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  39996. viewer.images360.addPanoData(data, dataset.id )
  39997. viewer.images360.loadDone()
  39998. viewer.scene.add360Images(viewer.images360); */
  39999. viewer.dispatchEvent('allLoaded');
  40000. done(pointcloud);
  40001. },onError);
  40002. };
  40003. if(type == 'laser'){
  40004. Potree.loadDatasets((data)=>{
  40005. let originDataset = data.find(e=>e.sceneCode == sceneCode);//只加载初始数据集
  40006. let timeStamp = originDataset.createTime ? originDataset.createTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随createTime更新一次
  40007. let cloudPath = `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${sceneCode}/data/${sceneCode}/webcloud/cloud.js`;
  40008. loadCloud(cloudPath, originDataset.sceneName, sceneCode, timeStamp, originDataset.color);
  40009. }, sceneCode, onError);
  40010. }else {//las or ply
  40011. let name = type + '|' + id;
  40012. let cloudPath = sceneCode + '/cloud.js';
  40013. loadCloud(cloudPath, name, name, '' );
  40014. }
  40015. };
  40016. let setMatrix = (pointcloud)=>{//为了漫游点变换,要算一下 类似setMatrix
  40017. /* pointcloud.transformMatrix = new THREE.Matrix4().multiplyMatrices(pointcloud.matrix, pointcloud.pos1MatrixInvert)//还原一点位移
  40018. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert()
  40019. pointcloud.rotateMatrix = new THREE.Matrix4().makeRotationFromEuler(pointcloud.rotation);
  40020. pointcloud.rotateInvMatrix.copy(pointcloud.rotateMatrix).invert()
  40021. pointcloud.panos.forEach(e=>e.transformByPointcloud()) */
  40022. //pointcloud.updateBound()
  40023. //pointcloud.getPanosBound()
  40024. viewer.updateModelBound();
  40025. };
  40026. let moveModel = (e)=>{//根据鼠标移动的位置改变位置
  40027. let camera = viewer.mainViewport.camera;
  40028. var origin = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera),
  40029. end = new Vector3(e.pointer.x, e.pointer.y, 1).unproject(camera);
  40030. var dir = end.sub(origin);
  40031. let planeZ = 0;
  40032. let r = (planeZ - origin.z)/dir.z;
  40033. let x = r * dir.x + origin.x;
  40034. let y = r * dir.y + origin.y;
  40035. //过后改为根据intersect的点来设置底部高度;这样的话,需要发送高度
  40036. /*let pos = new THREE.Vector3(x,y, planeZ )
  40037. modelEditing.updateMatrixWorld()
  40038. let boundCenter = modelEditing.boundingBox.getCenter(new THREE.Vector3).applyMatrix4(modelEditing.matrixWorld);
  40039. */
  40040. MergeEditor.moveBoundCenterTo(modelEditing,new Vector3(x,y, modelEditing.boundCenter.z)); //使模型中心的xy在鼠标所在位置
  40041. modelEditing.dispatchEvent("position_changed");
  40042. };
  40043. let cancelMove = ()=>{
  40044. modelEditing = null;
  40045. viewer.removeEventListener('global_mousemove', moveModel);
  40046. viewer.removeEventListener('global_click', confirmPos);
  40047. };
  40048. let confirmPos = ()=>{
  40049. MergeEditor.focusOn(modelEditing);
  40050. cancelMove();
  40051. return {stopContinue:true}
  40052. };
  40053. let modelType, modelEditing, MergeEditor = viewer.modules.MergeEditor;
  40054. Potree.addModel = function(prop, done, onProgress, onError){ //加载模型
  40055. let loadDone = (model)=>{
  40056. model.dataset_id = prop.id; //唯一标识
  40057. if(prop.position){
  40058. model.position.copy(prop.position);
  40059. }
  40060. if(prop.rotation){
  40061. model.rotation.setFromVector3(prop.rotation);
  40062. }
  40063. if(prop.scale){
  40064. model.scale.set(prop.scale,prop.scale,prop.scale);
  40065. }
  40066. if(model.isPointcloud){
  40067. model.renderOrder = Potree.config.renderOrders.model; //same as glb
  40068. }
  40069. /* {//transform --------维持离地高度和中心点的版本
  40070. let updateBound = ()=>{
  40071. model.updateMatrixWorld()
  40072. viewer.updateModelBound()
  40073. }
  40074. let maintainBtmZAndCenter = ()=>{
  40075. MergeEditor.maintainBoundXY(model)
  40076. MergeEditor.setModelBtmHeight(model)
  40077. updateBound()
  40078. model.dispatchEvent('transformChanged')
  40079. }
  40080. model.addEventListener('position_changed', ()=>{
  40081. updateBound()
  40082. MergeEditor.getBoundCenter(model);//更新boundcenter
  40083. MergeEditor.computeBtmHeight(model)
  40084. if(prop.bottomRange && (model.btmHeight > prop.bottomRange.max || model.btmHeight < prop.bottomRange.min)){
  40085. model.btmHeight = THREE.Math.clamp(model.btmHeight, prop.bottomRange.min, prop.bottomRange.max)
  40086. MergeEditor.setModelBtmHeight(model)
  40087. updateBound()
  40088. }
  40089. model.dispatchEvent('transformChanged')
  40090. })
  40091. model.addEventListener("rotation_changed", maintainBtmZAndCenter )
  40092. model.addEventListener("scale_changed", maintainBtmZAndCenter )
  40093. model.addEventListener('transformChanged', ()=>{
  40094. MergeEditor.modelTransformCallback(model)
  40095. })
  40096. //离地高度只是boundingbox在transform后的最低点的高度,而非模型transform后的最低点的高度,所以旋转过后看起来不太准确
  40097. } */
  40098. {//transform --------维持中心点的版本
  40099. let updateBound = ()=>{
  40100. model.updateMatrixWorld();
  40101. viewer.updateModelBound();
  40102. };
  40103. let maintainCenter = ()=>{
  40104. //MergeEditor.maintainBoundXY(model)
  40105. MergeEditor.maintainBoundCenter(model);
  40106. updateBound();
  40107. model.dispatchEvent('transformChanged');
  40108. };
  40109. model.addEventListener('position_changed', ()=>{
  40110. updateBound();
  40111. MergeEditor.getBoundCenter(model);//更新boundcenter
  40112. model.dispatchEvent('transformChanged');
  40113. });
  40114. model.addEventListener("rotation_changed", maintainCenter );
  40115. model.addEventListener("scale_changed", maintainCenter );
  40116. model.addEventListener('transformChanged', ()=>{
  40117. MergeEditor.modelTransformCallback(model);
  40118. });
  40119. }
  40120. model.updateMatrixWorld();
  40121. viewer.updateModelBound();
  40122. MergeEditor.getBoundCenter(model); //初始化
  40123. model.lastMatrixWorld = model.matrixWorld.clone();
  40124. done(model); // 先发送成功,因为2d界面会随机执行changePosition等初始化,然后这边再将模型移到中心地面上
  40125. if(prop.isFirstLoad){
  40126. MergeEditor.moveBoundCenterTo(model, new Vector3(0,0,0));
  40127. MergeEditor.setModelBtmHeight(model, 0); //初始加载设置离地高度为0
  40128. if(prop.mode != 'single'){//如果不是模型展示页,模型会随着鼠标位置移动
  40129. viewer.addEventListener('global_mousemove', moveModel);
  40130. viewer.addEventListener('global_click', confirmPos, 3);
  40131. modelEditing = model;
  40132. }
  40133. model.dispatchEvent("position_changed");
  40134. }else {
  40135. //MergeEditor.setModelBtmHeight(model, prop.bottom || 0) //默认离地高度为0
  40136. modelEditing = null;
  40137. }
  40138. };
  40139. if(prop.type == 'glb'){
  40140. let callback = (object)=>{
  40141. //focusOnSelect(object, 1000)
  40142. object.isModel = true;
  40143. //object.dataset_id = Date.now() //暂时
  40144. object.traverse(e=>e.material && (e.material.transparent = true));
  40145. /* object.addEventListener('click',(e)=>{
  40146. //只是为了能得到hoverElement识别才加这个侦听
  40147. }) */
  40148. loadDone(object);
  40149. };
  40150. let info = {
  40151. name: prop.type,
  40152. id: prop.id,
  40153. unlit:true,
  40154. /* transform : {
  40155. position : prop.position,
  40156. rotation : new THREE.Euler().setFromVector3(prop.rotation),
  40157. scale: new THREE.Vector3(prop.scale,prop.scale,prop.scale),
  40158. } */
  40159. };
  40160. if(prop.type == 'glb'){
  40161. info.glburl = prop.url;
  40162. }
  40163. viewer.loadModel(info , callback, onProgress, onError);
  40164. }else {
  40165. //else if(prop.type == 'las' || prop.type == 'ply')
  40166. Potree.loadPointCloudScene(prop.url, prop.type, prop.modelId, (pointcloud)=>{
  40167. pointcloud.matrixAutoUpdate = true;
  40168. pointcloud.initialPosition = pointcloud.position.clone();
  40169. pointcloud.pos1MatrixInvert = new Matrix4().setPosition(pointcloud.initialPosition).invert();
  40170. /* let maintainBtmZ = ()=>{
  40171. MergeEditor.setModelBtmHeight(pointcloud)
  40172. updateMatrix()
  40173. }
  40174. let updateMatrix = ()=>{
  40175. setMatrix(pointcloud)
  40176. pointcloud.dispatchEvent('transformChanged')
  40177. }
  40178. pointcloud.addEventListener('position_changed', updateMatrix )
  40179. pointcloud.addEventListener("orientation_changed", maintainBtmZ )
  40180. pointcloud.addEventListener("scale_changed", maintainBtmZ ) */
  40181. loadDone(pointcloud);
  40182. /* pointcloud.addEventListener('select',(e)=>{
  40183. if(Potree.settings.displayMode == 'showPanos')return
  40184. console.log('select',e)
  40185. //viewer.setControls(viewer.orbitControls)
  40186. MergeEditor.focusOnSelect(pointcloud)
  40187. viewer.outlinePass.selectedObjects = [pointcloud]
  40188. return {stopContinue:true}
  40189. },1)
  40190. pointcloud.addEventListener('deselect',(e)=>{
  40191. console.log('deselect',e)
  40192. //viewer.setControls(viewer.fpControls)
  40193. viewer.outlinePass.selectedObjects = []
  40194. }) */
  40195. }, onError);
  40196. }
  40197. };
  40198. return {THREE: THREE$1}
  40199. };
  40200. /*
  40201. 坐标转换问题:
  40202. 由于控制点可以随便输入,所以本地和地理位置的转换也是可拉伸的。而navvis的转换是等比由中心展开,
  40203. 所以对比两种转化方式时误差较大。
  40204. 另外地理注册控制点是有参考数据集的,若参考数据集和我放置在0,0,0的数据集一致,就可直接使用,否则要转换。
  40205. */
  40206. class Action extends EventDispatcher {
  40207. constructor (args = {}) {
  40208. super();
  40209. this.icon = args.icon || '';
  40210. this.tooltip = args.tooltip;
  40211. if (args.onclick !== undefined) {
  40212. this.onclick = args.onclick;
  40213. }
  40214. }
  40215. onclick (event) {
  40216. }
  40217. pairWith (object) {
  40218. }
  40219. setIcon (newIcon) {
  40220. let oldIcon = this.icon;
  40221. if (newIcon === oldIcon) {
  40222. return;
  40223. }
  40224. this.icon = newIcon;
  40225. this.dispatchEvent({
  40226. type: 'icon_changed',
  40227. action: this,
  40228. icon: newIcon,
  40229. oldIcon: oldIcon
  40230. });
  40231. }
  40232. };
  40233. //Potree.Actions = {};
  40234. //
  40235. //Potree.Actions.ToggleAnnotationVisibility = class ToggleAnnotationVisibility extends Potree.Action {
  40236. // constructor (args = {}) {
  40237. // super(args);
  40238. //
  40239. // this.icon = Potree.resourcePath + '/icons/eye.svg';
  40240. // this.showIn = 'sidebar';
  40241. // this.tooltip = 'toggle visibility';
  40242. // }
  40243. //
  40244. // pairWith (annotation) {
  40245. // if (annotation.visible) {
  40246. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40247. // } else {
  40248. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40249. // }
  40250. //
  40251. // annotation.addEventListener('visibility_changed', e => {
  40252. // let annotation = e.annotation;
  40253. //
  40254. // if (annotation.visible) {
  40255. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40256. // } else {
  40257. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40258. // }
  40259. // });
  40260. // }
  40261. //
  40262. // onclick (event) {
  40263. // let annotation = event.annotation;
  40264. //
  40265. // annotation.visible = !annotation.visible;
  40266. //
  40267. // if (annotation.visible) {
  40268. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40269. // } else {
  40270. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40271. // }
  40272. // }
  40273. //};
  40274. class PathAnimation{
  40275. constructor(path, start, end, speed, callback){
  40276. this.path = path;
  40277. this.length = this.path.spline.getLength();
  40278. this.speed = speed;
  40279. this.callback = callback;
  40280. this.tween = null;
  40281. this.startPoint = Math.max(start, 0);
  40282. this.endPoint = Math.min(end, this.length);
  40283. this.t = 0.0;
  40284. }
  40285. start(resume = false){
  40286. if(this.tween){
  40287. this.tween.stop();
  40288. this.tween = null;
  40289. }
  40290. let tStart;
  40291. if(resume){
  40292. tStart = this.t;
  40293. }else {
  40294. tStart = this.startPoint / this.length;
  40295. }
  40296. let tEnd = this.endPoint / this.length;
  40297. let animationDuration = (tEnd - tStart) * this.length * 1000 / this.speed;
  40298. let progress = {t: tStart};
  40299. this.tween = new TWEEN.Tween(progress).to({t: tEnd}, animationDuration);
  40300. this.tween.easing(TWEEN.Easing.Linear.None);
  40301. this.tween.onUpdate((e) => {
  40302. this.t = progress.t;
  40303. this.callback(progress.t);
  40304. });
  40305. this.tween.onComplete(() => {
  40306. if(this.repeat){
  40307. this.start();
  40308. }
  40309. });
  40310. setTimeout(() => {
  40311. this.tween.start();
  40312. }, 0);
  40313. }
  40314. stop(){
  40315. if(!this.tween){
  40316. return;
  40317. }
  40318. this.tween.stop();
  40319. this.tween = null;
  40320. this.t = 0;
  40321. }
  40322. pause(){
  40323. if(!this.tween){
  40324. return;
  40325. }
  40326. this.tween.stop();
  40327. TWEEN.remove(this.tween);
  40328. this.tween = null;
  40329. }
  40330. resume(){
  40331. this.start(true);
  40332. }
  40333. getPoint(t){
  40334. return this.path.spline.getPoint(t);
  40335. }
  40336. }
  40337. class AnimationPath{
  40338. constructor (points = []) {
  40339. this.points = points;
  40340. this.spline = new CatmullRomCurve3(points);
  40341. //this.spline.reparametrizeByArcLength(1 / this.spline.getLength().total);
  40342. }
  40343. get (t) {
  40344. return this.spline.getPoint(t);
  40345. }
  40346. getLength () {
  40347. return this.spline.getLength();
  40348. }
  40349. animate (start, end, speed, callback) {
  40350. let animation = new PathAnimation(this, start, end, speed, callback);
  40351. animation.start();
  40352. return animation;
  40353. }
  40354. pause () {
  40355. if (this.tween) {
  40356. this.tween.stop();
  40357. }
  40358. }
  40359. resume () {
  40360. if (this.tween) {
  40361. this.tween.start();
  40362. }
  40363. }
  40364. getGeometry () {
  40365. let geometry = new Geometry();
  40366. let samples = 500;
  40367. let i = 0;
  40368. for (let u = 0; u <= 1; u += 1 / samples) {
  40369. let position = this.spline.getPoint(u);
  40370. geometry.vertices[i] = new Vector3(position.x, position.y, position.z);
  40371. i++;
  40372. }
  40373. if(this.closed){
  40374. let position = this.spline.getPoint(0);
  40375. geometry.vertices[i] = new Vector3(position.x, position.y, position.z);
  40376. }
  40377. return geometry;
  40378. }
  40379. get closed(){
  40380. return this.spline.closed;
  40381. }
  40382. set closed(value){
  40383. this.spline.closed = value;
  40384. }
  40385. }
  40386. class Annotation extends EventDispatcher {
  40387. constructor (args = {}) {
  40388. super();
  40389. this.scene = null;
  40390. this._title = args.title || 'No Title';
  40391. this._description = args.description || '';
  40392. this.offset = new Vector3();
  40393. this.uuid = MathUtils.generateUUID();
  40394. if (!args.position) {
  40395. this.position = null;
  40396. } else if (args.position.x != null) {
  40397. this.position = args.position;
  40398. } else {
  40399. this.position = new Vector3(...args.position);
  40400. }
  40401. this.cameraPosition = (args.cameraPosition instanceof Array)
  40402. ? new Vector3().fromArray(args.cameraPosition) : args.cameraPosition;
  40403. this.cameraTarget = (args.cameraTarget instanceof Array)
  40404. ? new Vector3().fromArray(args.cameraTarget) : args.cameraTarget;
  40405. if(!this.cameraTarget && this.position){//add
  40406. this.cameraTarget = this.position.clone();
  40407. }
  40408. this.radius = args.radius;
  40409. this.view = args.view || null;
  40410. this.keepOpen = false;
  40411. this.descriptionVisible = false;
  40412. this.showDescription = true;
  40413. this.actions = args.actions || [];
  40414. this.isHighlighted = false;
  40415. this._visible = true;
  40416. this.__visible = true;
  40417. this._display = true;
  40418. this._expand = false;
  40419. this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined);
  40420. this.children = [];
  40421. this.parent = null;
  40422. this.boundingBox = new Box3();
  40423. let iconClose = exports.resourcePath + '/icons/close.svg';
  40424. this.domElement = $(`
  40425. <div class="annotation" oncontextmenu="return false;">
  40426. <div class="annotation-titlebar">
  40427. <span class="annotation-label"></span>
  40428. </div>
  40429. <div class="annotation-description">
  40430. <span class="annotation-description-close">
  40431. <img src="${iconClose}" width="16px">
  40432. </span>
  40433. <span class="annotation-description-content">${this._description}</span>
  40434. </div>
  40435. </div>
  40436. `);
  40437. this.elTitlebar = this.domElement.find('.annotation-titlebar');
  40438. this.elTitle = this.elTitlebar.find('.annotation-label');
  40439. this.elTitle.append(this._title);
  40440. this.elDescription = this.domElement.find('.annotation-description');
  40441. this.elDescriptionClose = this.elDescription.find('.annotation-description-close');
  40442. // this.elDescriptionContent = this.elDescription.find(".annotation-description-content");
  40443. this.clickTitle = () => {
  40444. //if(this.hasView()){
  40445. this.moveHere(this.scene.getActiveCamera());
  40446. //}
  40447. this.dispatchEvent({type: 'click', target: this});
  40448. viewer.renderer.domElement.focus();//add 使得方向键可用
  40449. };
  40450. this.elTitle.click(this.clickTitle);
  40451. this.actions = this.actions.map(a => {
  40452. if (a instanceof Action) {
  40453. return a;
  40454. } else {
  40455. return new Action(a);
  40456. }
  40457. });
  40458. for (let action of this.actions) {
  40459. action.pairWith(this);
  40460. }
  40461. let actions = this.actions.filter(
  40462. a => a.showIn === undefined || a.showIn.includes('scene'));
  40463. for (let action of actions) {
  40464. let elButton = $(`<img src="${action.icon}" class="annotation-action-icon">`);
  40465. this.elTitlebar.append(elButton);
  40466. elButton.click(() => action.onclick({annotation: this}));
  40467. }
  40468. this.elDescriptionClose.hover(
  40469. e => this.elDescriptionClose.css('opacity', '1'),
  40470. e => this.elDescriptionClose.css('opacity', '0.5')
  40471. );
  40472. this.elDescriptionClose.click(e => this.setHighlighted(false));
  40473. // this.elDescriptionContent.html(this._description);
  40474. this.domElement.mouseenter(e => this.setHighlighted(true));
  40475. this.domElement.mouseleave(e => this.setHighlighted(false));
  40476. this.domElement.on('touchstart', e => {
  40477. this.setHighlighted(!this.isHighlighted);
  40478. });
  40479. this.display = false;
  40480. //this.display = true;
  40481. }
  40482. installHandles(viewer){
  40483. if(this.handles !== undefined){
  40484. return;
  40485. }
  40486. let domElement = $(`
  40487. <div style="position: absolute; left: 300; top: 200; pointer-events: none">
  40488. <svg width="300" height="600">
  40489. <line x1="0" y1="0" x2="1200" y2="200" style="stroke: black; stroke-width:2" />
  40490. <circle cx="50" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  40491. <circle cx="150" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  40492. </svg>
  40493. </div>
  40494. `);
  40495. let svg = domElement.find("svg")[0];
  40496. let elLine = domElement.find("line")[0];
  40497. let elStart = domElement.find("circle")[0];
  40498. let elEnd = domElement.find("circle")[1];
  40499. let setCoordinates = (start, end) => {
  40500. elStart.setAttribute("cx", `${start.x}`);
  40501. elStart.setAttribute("cy", `${start.y}`);
  40502. elEnd.setAttribute("cx", `${end.x}`);
  40503. elEnd.setAttribute("cy", `${end.y}`);
  40504. elLine.setAttribute("x1", start.x);
  40505. elLine.setAttribute("y1", start.y);
  40506. elLine.setAttribute("x2", end.x);
  40507. elLine.setAttribute("y2", end.y);
  40508. let box = svg.getBBox();
  40509. svg.setAttribute("width", `${box.width}`);
  40510. svg.setAttribute("height", `${box.height}`);
  40511. svg.setAttribute("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`);
  40512. let ya = start.y - end.y;
  40513. let xa = start.x - end.x;
  40514. if(ya > 0){
  40515. start.y = start.y - ya;
  40516. }
  40517. if(xa > 0){
  40518. start.x = start.x - xa;
  40519. }
  40520. domElement.css("left", `${start.x}px`);
  40521. domElement.css("top", `${start.y}px`);
  40522. };
  40523. $(viewer.renderArea).append(domElement);
  40524. let annotationStartPos = this.position.clone();
  40525. let annotationStartOffset = this.offset.clone();
  40526. $(this.domElement).draggable({
  40527. start: (event, ui) => {
  40528. annotationStartPos = this.position.clone();
  40529. annotationStartOffset = this.offset.clone();
  40530. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none");
  40531. console.log($(this.domElement).find(".annotation-titlebar"));
  40532. },
  40533. stop: () => {
  40534. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "");
  40535. },
  40536. drag: (event, ui ) => {
  40537. let renderAreaWidth = viewer.renderer.getSize(new Vector2$1()).width;
  40538. //let renderAreaHeight = viewer.renderer.getSize().height;
  40539. let diff = {
  40540. x: ui.originalPosition.left - ui.position.left,
  40541. y: ui.originalPosition.top - ui.position.top
  40542. };
  40543. let nDiff = {
  40544. x: -(diff.x / renderAreaWidth) * 2,
  40545. y: (diff.y / renderAreaWidth) * 2
  40546. };
  40547. let camera = viewer.scene.getActiveCamera();
  40548. let oldScreenPos = new Vector3()
  40549. .addVectors(annotationStartPos, annotationStartOffset)
  40550. .project(camera);
  40551. let newScreenPos = oldScreenPos.clone();
  40552. newScreenPos.x += nDiff.x;
  40553. newScreenPos.y += nDiff.y;
  40554. let newPos = newScreenPos.clone();
  40555. newPos.unproject(camera);
  40556. let newOffset = new Vector3().subVectors(newPos, this.position);
  40557. this.offset.copy(newOffset);
  40558. }
  40559. });
  40560. let updateCallback = () => {
  40561. let position = this.position;
  40562. let scene = viewer.scene;
  40563. const renderAreaSize = viewer.renderer.getSize(new Vector2$1());
  40564. let renderAreaWidth = renderAreaSize.width;
  40565. let renderAreaHeight = renderAreaSize.height;
  40566. let start = this.position.clone();
  40567. let end = new Vector3().addVectors(this.position, this.offset);
  40568. let toScreen = (position) => {
  40569. let camera = scene.getActiveCamera();
  40570. let screenPos = new Vector3();
  40571. let worldView = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  40572. let ndc = new Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView);
  40573. // limit w to small positive value, in case position is behind the camera
  40574. ndc.w = Math.max(ndc.w, 0.1);
  40575. ndc.divideScalar(ndc.w);
  40576. screenPos.copy(ndc);
  40577. screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2;
  40578. screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2);
  40579. return screenPos;
  40580. };
  40581. start = toScreen(start);
  40582. end = toScreen(end);
  40583. setCoordinates(start, end);
  40584. };
  40585. viewer.addEventListener("update", updateCallback);
  40586. this.handles = {
  40587. domElement: domElement,
  40588. setCoordinates: setCoordinates,
  40589. updateCallback: updateCallback
  40590. };
  40591. }
  40592. removeHandles(viewer){
  40593. if(this.handles === undefined){
  40594. return;
  40595. }
  40596. //$(viewer.renderArea).remove(this.handles.domElement);
  40597. this.handles.domElement.remove();
  40598. viewer.removeEventListener("update", this.handles.updateCallback);
  40599. delete this.handles;
  40600. }
  40601. get visible () {
  40602. return this._visible;
  40603. }
  40604. set visible (value) {
  40605. if (this._visible === value) {
  40606. return;
  40607. }
  40608. this._visible = value;
  40609. //this.traverse(node => {
  40610. // node.display = value;
  40611. //});
  40612. this.dispatchEvent({
  40613. type: 'visibility_changed',
  40614. annotation: this
  40615. });
  40616. }
  40617. get display () {
  40618. return this._display;
  40619. }
  40620. set display (display) {
  40621. if (this._display === display) {
  40622. return;
  40623. }
  40624. this._display = display;
  40625. if (display) {
  40626. // this.domElement.fadeIn(200);
  40627. this.domElement.show();
  40628. } else {
  40629. // this.domElement.fadeOut(200);
  40630. this.domElement.hide();
  40631. }
  40632. }
  40633. get expand () {
  40634. return this._expand;
  40635. }
  40636. set expand (expand) {
  40637. if (this._expand === expand) {
  40638. return;
  40639. }
  40640. if (expand) {
  40641. this.display = false;
  40642. } else {
  40643. this.display = true;
  40644. this.traverseDescendants(node => {
  40645. node.display = false;
  40646. });
  40647. }
  40648. this._expand = expand;
  40649. }
  40650. get title () {
  40651. return this._title;
  40652. }
  40653. set title (title) {
  40654. if (this._title === title) {
  40655. return;
  40656. }
  40657. this._title = title;
  40658. this.elTitle.empty();
  40659. this.elTitle.append(this._title);
  40660. this.dispatchEvent({
  40661. type: "annotation_changed",
  40662. annotation: this,
  40663. });
  40664. }
  40665. get description () {
  40666. return this._description;
  40667. }
  40668. set description (description) {
  40669. if (this._description === description) {
  40670. return;
  40671. }
  40672. this._description = description;
  40673. const elDescriptionContent = this.elDescription.find(".annotation-description-content");
  40674. elDescriptionContent.empty();
  40675. elDescriptionContent.append(this._description);
  40676. this.dispatchEvent({
  40677. type: "annotation_changed",
  40678. annotation: this,
  40679. });
  40680. }
  40681. add (annotation) {
  40682. if (!this.children.includes(annotation)) {
  40683. this.children.push(annotation);
  40684. annotation.parent = this;
  40685. let descendants = [];
  40686. annotation.traverse(a => { descendants.push(a); });
  40687. for (let descendant of descendants) {
  40688. let c = this;
  40689. while (c !== null) {
  40690. c.dispatchEvent({
  40691. 'type': 'annotation_added',
  40692. 'annotation': descendant
  40693. });
  40694. c = c.parent;
  40695. }
  40696. }
  40697. }
  40698. }
  40699. level () {
  40700. if (this.parent === null) {
  40701. return 0;
  40702. } else {
  40703. return this.parent.level() + 1;
  40704. }
  40705. }
  40706. hasChild(annotation) {
  40707. return this.children.includes(annotation);
  40708. }
  40709. remove (annotation) {
  40710. if (this.hasChild(annotation)) {
  40711. annotation.removeAllChildren();
  40712. annotation.dispose();
  40713. this.children = this.children.filter(e => e !== annotation);
  40714. annotation.parent = null;
  40715. }
  40716. }
  40717. removeAllChildren() {
  40718. this.children.forEach((child) => {
  40719. if (child.children.length > 0) {
  40720. child.removeAllChildren();
  40721. }
  40722. this.remove(child);
  40723. });
  40724. }
  40725. updateBounds () {
  40726. let box = new Box3();
  40727. if (this.position) {
  40728. box.expandByPoint(this.position);
  40729. }
  40730. for (let child of this.children) {
  40731. child.updateBounds();
  40732. box.union(child.boundingBox);
  40733. }
  40734. this.boundingBox.copy(box);
  40735. }
  40736. traverse (handler) {
  40737. let expand = handler(this);
  40738. if (expand === undefined || expand === true) {
  40739. for (let child of this.children) {
  40740. child.traverse(handler);
  40741. }
  40742. }
  40743. }
  40744. traverseDescendants (handler) {
  40745. for (let child of this.children) {
  40746. child.traverse(handler);
  40747. }
  40748. }
  40749. flatten () {
  40750. let annotations = [];
  40751. this.traverse(annotation => {
  40752. annotations.push(annotation);
  40753. });
  40754. return annotations;
  40755. }
  40756. descendants () {
  40757. let annotations = [];
  40758. this.traverse(annotation => {
  40759. if (annotation !== this) {
  40760. annotations.push(annotation);
  40761. }
  40762. });
  40763. return annotations;
  40764. }
  40765. setHighlighted (highlighted) {
  40766. if (highlighted) {
  40767. this.domElement.css('opacity', '0.8');
  40768. this.elTitlebar.css('box-shadow', '0 0 5px #fff');
  40769. this.domElement.css('z-index', '1000');
  40770. if (this._description) {
  40771. this.descriptionVisible = true;
  40772. this.elDescription.fadeIn(200);
  40773. this.elDescription.css('position', 'relative');
  40774. }
  40775. } else {
  40776. this.domElement.css('opacity', '0.5');
  40777. this.elTitlebar.css('box-shadow', '');
  40778. this.domElement.css('z-index', '100');
  40779. this.descriptionVisible = false;
  40780. this.elDescription.css('display', 'none');
  40781. }
  40782. this.isHighlighted = highlighted;
  40783. }
  40784. hasView () {
  40785. let hasPosTargetView = this.cameraTarget.x != null;
  40786. hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null;
  40787. let hasRadiusView = this.radius !== undefined;
  40788. let hasView = hasPosTargetView || hasRadiusView;
  40789. return hasView;
  40790. };
  40791. moveHere (camera) {
  40792. if (!this.hasView()) {
  40793. return;
  40794. }
  40795. let view = this.scene.view;
  40796. let animationDuration = 500;
  40797. let easing = TWEEN.Easing.Quartic.Out;
  40798. let endTarget;
  40799. if (this.cameraTarget) {
  40800. endTarget = this.cameraTarget;
  40801. } else if (this.position) {
  40802. endTarget = this.position;
  40803. } else {
  40804. endTarget = this.boundingBox.getCenter(new Vector3());
  40805. }
  40806. if (this.cameraPosition) {
  40807. let endPosition = this.cameraPosition;
  40808. Utils.moveTo(this.scene, endPosition, endTarget);
  40809. } else if (this.radius) {
  40810. let direction = view.direction;
  40811. let endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius));
  40812. let startRadius = view.radius;
  40813. let endRadius = this.radius;
  40814. { // animate camera position
  40815. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  40816. tween.easing(easing);
  40817. tween.start();
  40818. }
  40819. { // animate radius
  40820. let t = {x: 0};
  40821. let tween = new TWEEN.Tween(t)
  40822. .to({x: 1}, animationDuration)
  40823. .onUpdate(function () {
  40824. view.radius = this.x * endRadius + (1 - this.x) * startRadius;
  40825. });
  40826. tween.easing(easing);
  40827. tween.start();
  40828. }
  40829. }
  40830. };
  40831. dispose () {
  40832. if (this.domElement.parentElement) {
  40833. this.domElement.parentElement.removeChild(this.domElement);
  40834. }
  40835. };
  40836. toString () {
  40837. return 'Annotation: ' + this._title;
  40838. }
  40839. };
  40840. class EnumItem{
  40841. constructor(object){
  40842. for(let key of Object.keys(object)){
  40843. this[key] = object[key];
  40844. }
  40845. }
  40846. inspect(){
  40847. return `Enum(${this.name}: ${this.value})`;
  40848. }
  40849. };
  40850. class Enum{//??????做什么用的
  40851. constructor(object){
  40852. this.object = object;
  40853. for(let key of Object.keys(object)){
  40854. let value = object[key];
  40855. if(typeof value === "object"){
  40856. value.name = key;
  40857. }else {
  40858. value = {name: key, value: value};
  40859. }
  40860. this[key] = new EnumItem(value);
  40861. }
  40862. }
  40863. fromValue(value){
  40864. for(let key of Object.keys(this.object)){
  40865. if(this[key].value === value){
  40866. return this[key];
  40867. }
  40868. }
  40869. throw new Error(`No enum for value: ${value}`);
  40870. }
  40871. };
  40872. const CameraMode = {
  40873. ORTHOGRAPHIC: 0,
  40874. PERSPECTIVE: 1,
  40875. VR: 2,
  40876. };
  40877. const ClipTask = {
  40878. NONE: 0,
  40879. HIGHLIGHT: 1,
  40880. SHOW_INSIDE: 2,
  40881. SHOW_OUTSIDE: 3
  40882. };
  40883. const ClipMethod = {
  40884. INSIDE_ANY: 0,
  40885. INSIDE_ALL: 1
  40886. };
  40887. const ElevationGradientRepeat = {
  40888. CLAMP: 0,
  40889. REPEAT: 1,
  40890. MIRRORED_REPEAT: 2,
  40891. };
  40892. const Buttons = {// MouseEvent.buttons
  40893. //buttons,设置按下了鼠标哪些键,是一个3个比特位的二进制值,默认为0。1表示按下主键(通常是左键),2表示按下次要键(通常是右键),4表示按下辅助键(通常是中间的键)。
  40894. NONE:0,//add
  40895. LEFT: 0b0001,
  40896. RIGHT: 0b0010,
  40897. MIDDLE: 0b0100
  40898. };
  40899. /* 如果访问的是button, 用THREE.MOUSE来判断:
  40900. button,设置按下了哪一个鼠标按键,默认为0。-1表示没有按键,0表示按下主键(通常是左键),1表示按下辅助键(通常是中间的键),2表示按下次要键(通常是右键)
  40901. */
  40902. const PointSizeType = {
  40903. FIXED: 0,
  40904. ATTENUATED: 1,
  40905. ADAPTIVE: 2
  40906. };
  40907. const PointShape = {
  40908. SQUARE: 0,
  40909. CIRCLE: 1,
  40910. PARABOLOID: 2
  40911. };
  40912. const TreeType = {
  40913. OCTREE: 0,
  40914. KDTREE: 1
  40915. };
  40916. const LengthUnits = {
  40917. METER: {code: 'm', unitspermeter: 1.0},
  40918. FEET: {code: 'ft', unitspermeter: 3.28084},
  40919. INCH: {code: '\u2033', unitspermeter: 39.3701}
  40920. };
  40921. /////////// add //////////////////////////////////
  40922. var GLCubeFaces$1 = {
  40923. GL_TEXTURE_CUBE_MAP_POSITIVE_X: 0,
  40924. GL_TEXTURE_CUBE_MAP_NEGATIVE_X: 1,
  40925. GL_TEXTURE_CUBE_MAP_POSITIVE_Y: 2,
  40926. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: 3,
  40927. GL_TEXTURE_CUBE_MAP_POSITIVE_Z: 4,
  40928. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: 5
  40929. };
  40930. var PanoSizeClass = {
  40931. BASE: 1,
  40932. STANDARD: 2,
  40933. HIGH: 3,
  40934. ULTRAHIGH: 4
  40935. };
  40936. var PanoRendererEvents = {
  40937. PanoRenderComplete: "panorama.render.complete",
  40938. TileRenderFailure: "panorama.tile.render.failed",
  40939. TileRenderSuccess: "panorama.tile.render.success",
  40940. TileUploadAttempted: "panorama.tile.upload.attempted",
  40941. UploadAttemptedForAllTiles: "panorama.upload.attempted.all.tiles",
  40942. ZoomLevelRenderStarted: "panorama.zoom.render.started"
  40943. };
  40944. var SceneRendererEvents = {
  40945. ContextCreated: "scene-renderer-context-created",
  40946. AfterRender: "after-render",
  40947. MemoryUsageUpdated: "scene-renderer-memory-usage-updated"
  40948. };
  40949. var TileDownloaderEvents = {
  40950. TileDownloadSuccess: "tiledownloader.download.success",
  40951. TileDownloadFailure: "tiledownloader.download.failure",
  40952. PanoDownloadComplete: "tiledownloader.pano.download.complete"
  40953. };
  40954. var Vectors = {
  40955. UP: new Vector3(0,1,0),
  40956. DOWN: new Vector3(0,-1,0),
  40957. LEFT: new Vector3(-1,0,0),
  40958. RIGHT: new Vector3(1,0,0),
  40959. FORWARD: new Vector3(0,0,-1),
  40960. BACK: new Vector3(0,0,1)
  40961. };
  40962. var Vectors2 = {};
  40963. for(var i in Vectors){
  40964. Vectors2[i] = math.convertVector.YupToZup(Vectors[i]);
  40965. }
  40966. var DownloadStatus = Object.freeze({
  40967. None: 0,
  40968. Queued: 1,
  40969. ForceQueued: 2,
  40970. Downloading: 3,
  40971. Downloaded: 4,
  40972. DownloadFailed: 5
  40973. });
  40974. var ModelManagerEvents = {
  40975. ModelAdded: "model-added",
  40976. ActiveModelChanged: "active-model-changed"
  40977. };
  40978. var PanoramaEvents = {
  40979. Enter: 'panorama.enter',
  40980. Exit: 'panorama.exit',
  40981. LoadComplete: "panorama.load.complete",
  40982. LoadFailed: "panorama.load.failed",
  40983. TileLoaded: "panorama.tile.loaded",
  40984. VideoRendered: "panorama.video.rendered"
  40985. };
  40986. /**
  40987. * @author mrdoob / http://mrdoob.com/ https://github.com/mrdoob/eventdispatcher.js
  40988. *
  40989. * with slight modifications by mschuetz, http://potree.org
  40990. *
  40991. */
  40992. // The MIT License
  40993. //
  40994. // Copyright (c) 2011 Mr.doob
  40995. //
  40996. // Permission is hereby granted, free of charge, to any person obtaining a copy
  40997. // of this software and associated documentation files (the "Software"), to deal
  40998. // in the Software without restriction, including without limitation the rights
  40999. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41000. // copies of the Software, and to permit persons to whom the Software is
  41001. // furnished to do so, subject to the following conditions:
  41002. //
  41003. // The above copyright notice and this permission notice shall be included in
  41004. // all copies or substantial portions of the Software.
  41005. //
  41006. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41007. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41008. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41009. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41010. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41011. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41012. // THE SOFTWARE.
  41013. class EventDispatcher$1{
  41014. constructor(){
  41015. this._listeners = {};
  41016. }
  41017. addEventListener(type, listener, importance=0 ){//add importance
  41018. const listeners = this._listeners;
  41019. if(listeners[type] === undefined){
  41020. listeners[type] = [];
  41021. }
  41022. if(listeners[type].indexOf(listener) === - 1){
  41023. listeners[type].push({ listener, importance});
  41024. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  41025. }
  41026. }
  41027. hasEventListener(type, listener){
  41028. const listeners = this._listeners;
  41029. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== - 1;
  41030. }
  41031. removeEventListener(type, listener){
  41032. let listeners = this._listeners;
  41033. let listenerArray = listeners[type];
  41034. if (listenerArray !== undefined){
  41035. /* let index = listenerArray.indexOf(listener);
  41036. if(index !== - 1){
  41037. listenerArray.splice(index, 1);
  41038. } */
  41039. let item = listenerArray.find(e=>e.listener == listener);
  41040. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  41041. }
  41042. }
  41043. removeEventListeners(type){
  41044. if(this._listeners[type] !== undefined){
  41045. delete this._listeners[type];
  41046. }
  41047. };
  41048. dispatchEvent(event){
  41049. if(typeof event == 'string'){//add
  41050. event = {type:event};
  41051. }
  41052. let listeners = this._listeners;
  41053. let listenerArray = listeners[event.type];
  41054. if ( listenerArray !== undefined ) {
  41055. event.target = this;
  41056. for(let {listener} of listenerArray.slice(0)){
  41057. let result = listener.call(this, event); //add stopContinue
  41058. if(result && result.stopContinue){
  41059. break
  41060. }
  41061. }
  41062. }
  41063. }
  41064. //add
  41065. /* emit(type){
  41066. this.dispatchEvent({type, arguments: Array.from(arguments).slice(1, arguments.length) })
  41067. }
  41068. on(type, fun){
  41069. this.addEventListener(type,(ev)=>{
  41070. fun.apply(this, ev.arguments)
  41071. })
  41072. }
  41073. off(type, fun){
  41074. this.removeEventListener(type,)
  41075. }
  41076. once(type, fun) {
  41077. function callback() {
  41078. this.removeEventListener(type, callback),
  41079. n || (n = !0, fun.apply(this, arguments))
  41080. }
  41081. var n = !1;
  41082. return callback.listener = fun,
  41083. this.on(type, callback),
  41084. this
  41085. } */
  41086. removeAllListeners(){
  41087. this._listeners = {};
  41088. }
  41089. }
  41090. const KeyCodes = {
  41091. LEFT: 37,
  41092. UP: 38,
  41093. RIGHT: 39,
  41094. BOTTOM: 40,
  41095. DELETE: 46,
  41096. BACKSPACE:8,
  41097. A: 'A'.charCodeAt(0),
  41098. S: 'S'.charCodeAt(0),
  41099. D: 'D'.charCodeAt(0),
  41100. W: 'W'.charCodeAt(0),
  41101. Q: 'Q'.charCodeAt(0),
  41102. E: 'E'.charCodeAt(0),
  41103. R: 'R'.charCodeAt(0),
  41104. F: 'F'.charCodeAt(0)
  41105. };
  41106. class LRUItem{
  41107. constructor(node){
  41108. this.previous = null;
  41109. this.next = null;
  41110. this.node = node;
  41111. }
  41112. }
  41113. /**
  41114. *
  41115. * @class A doubly-linked-list of the least recently used elements.
  41116. */
  41117. class LRU{
  41118. constructor(){
  41119. // the least recently used item
  41120. this.first = null;
  41121. // the most recently used item
  41122. this.last = null;
  41123. // a list of all items in the lru list
  41124. this.items = {};
  41125. this.elements = 0;
  41126. this.numPoints = 0;
  41127. }
  41128. size(){
  41129. return this.elements;
  41130. }
  41131. contains(node){
  41132. return this.items[node.id] == null;
  41133. }
  41134. touch(node){
  41135. if (!node.loaded) {
  41136. return;
  41137. }
  41138. let item;
  41139. if (this.items[node.id] == null) {
  41140. // add to list
  41141. item = new LRUItem(node);
  41142. item.previous = this.last;
  41143. this.last = item;
  41144. if (item.previous !== null) {
  41145. item.previous.next = item;
  41146. }
  41147. this.items[node.id] = item;
  41148. this.elements++;
  41149. if (this.first === null) {
  41150. this.first = item;
  41151. }
  41152. this.numPoints += node.numPoints;
  41153. } else {
  41154. // update in list
  41155. item = this.items[node.id];
  41156. if (item.previous === null) {
  41157. // handle touch on first element
  41158. if (item.next !== null) {
  41159. this.first = item.next;
  41160. this.first.previous = null;
  41161. item.previous = this.last;
  41162. item.next = null;
  41163. this.last = item;
  41164. item.previous.next = item;
  41165. }
  41166. } else if (item.next === null) {
  41167. // handle touch on last element
  41168. } else {
  41169. // handle touch on any other element
  41170. item.previous.next = item.next;
  41171. item.next.previous = item.previous;
  41172. item.previous = this.last;
  41173. item.next = null;
  41174. this.last = item;
  41175. item.previous.next = item;
  41176. }
  41177. }
  41178. }
  41179. remove(node){
  41180. let lruItem = this.items[node.id];
  41181. if (lruItem) {
  41182. if (this.elements === 1) {
  41183. this.first = null;
  41184. this.last = null;
  41185. } else {
  41186. if (!lruItem.previous) {
  41187. this.first = lruItem.next;
  41188. this.first.previous = null;
  41189. }
  41190. if (!lruItem.next) {
  41191. this.last = lruItem.previous;
  41192. this.last.next = null;
  41193. }
  41194. if (lruItem.previous && lruItem.next) {
  41195. lruItem.previous.next = lruItem.next;
  41196. lruItem.next.previous = lruItem.previous;
  41197. }
  41198. }
  41199. delete this.items[node.id];
  41200. this.elements--;
  41201. this.numPoints -= node.numPoints;
  41202. }
  41203. }
  41204. getLRUItem(){
  41205. if (this.first === null) {
  41206. return null;
  41207. }
  41208. let lru = this.first;
  41209. return lru.node;
  41210. }
  41211. toString(){
  41212. let string = '{ ';
  41213. let curr = this.first;
  41214. while (curr !== null) {
  41215. string += curr.node.id;
  41216. if (curr.next !== null) {
  41217. string += ', ';
  41218. }
  41219. curr = curr.next;
  41220. }
  41221. string += '}';
  41222. string += '(' + this.size() + ')';
  41223. return string;
  41224. }
  41225. freeMemory(){
  41226. if (this.elements <= 1) {
  41227. return;
  41228. }
  41229. /* while (this.numPoints > Potree.pointLoadLimit) {
  41230. let element = this.first;
  41231. let node = element.node;
  41232. this.disposeDescendants(node);
  41233. } */
  41234. //改成navvis的,使用pointBudget,否则四屏点云闪烁。
  41235. let max = /* this.pageVisible ? */viewer.viewports.length * 2 * Potree.pointBudget;// : 1000
  41236. for (; this.numPoints > max; ) {//要根据屏幕数量来增加pointBudget
  41237. var node = this.getLRUItem();
  41238. node && this.disposeSubtree(node);
  41239. }
  41240. }
  41241. disposeSubtree(t) {//add from navvis 25.js
  41242. var e = [t];
  41243. t.traverse((function(t) {
  41244. t.loaded && e.push(t);
  41245. }
  41246. ));
  41247. for (var n = 0, i = e; n < i.length; n++) {
  41248. var o = i[n];
  41249. o.dispose(),
  41250. this.remove(o);
  41251. }
  41252. }
  41253. disposeDescendants(node){
  41254. let stack = [];
  41255. stack.push(node);
  41256. while (stack.length > 0) {
  41257. let current = stack.pop();
  41258. // console.log(current);
  41259. current.dispose();
  41260. this.remove(current);
  41261. for (let key in current.children) {
  41262. if (current.children.hasOwnProperty(key)) {
  41263. let child = current.children[key];
  41264. if (child.loaded) {
  41265. stack.push(current.children[key]);
  41266. }
  41267. }
  41268. }
  41269. }
  41270. }
  41271. }
  41272. class PointCloudTreeNode extends EventDispatcher{
  41273. constructor(){
  41274. super();
  41275. this.needsTransformUpdate = true;
  41276. }
  41277. getChildren () {
  41278. throw new Error('override function');
  41279. }
  41280. getBoundingBox () {
  41281. throw new Error('override function');
  41282. }
  41283. isLoaded () {
  41284. throw new Error('override function');
  41285. }
  41286. isGeometryNode () {
  41287. throw new Error('override function');
  41288. }
  41289. isTreeNode () {
  41290. throw new Error('override function');
  41291. }
  41292. getLevel () {
  41293. throw new Error('override function');
  41294. }
  41295. getBoundingSphere () {
  41296. throw new Error('override function');
  41297. }
  41298. };
  41299. class PointCloudTree extends Object3D {
  41300. constructor () {
  41301. super();
  41302. //this.spriteGroup = new THREE.Object3D //add
  41303. }
  41304. initialized () {
  41305. return this.root !== null;
  41306. }
  41307. };
  41308. /**
  41309. * Some types of possible point attribute data formats
  41310. *
  41311. * @class
  41312. */
  41313. const PointAttributeTypes = {
  41314. DATA_TYPE_DOUBLE: {ordinal: 0, name: "double", size: 8},
  41315. DATA_TYPE_FLOAT: {ordinal: 1, name: "float", size: 4},
  41316. DATA_TYPE_INT8: {ordinal: 2, name: "int8", size: 1},
  41317. DATA_TYPE_UINT8: {ordinal: 3, name: "uint8", size: 1},
  41318. DATA_TYPE_INT16: {ordinal: 4, name: "int16", size: 2},
  41319. DATA_TYPE_UINT16: {ordinal: 5, name: "uint16", size: 2},
  41320. DATA_TYPE_INT32: {ordinal: 6, name: "int32", size: 4},
  41321. DATA_TYPE_UINT32: {ordinal: 7, name: "uint32", size: 4},
  41322. DATA_TYPE_INT64: {ordinal: 8, name: "int64", size: 8},
  41323. DATA_TYPE_UINT64: {ordinal: 9, name: "uint64", size: 8}
  41324. };
  41325. let i$1 = 0;
  41326. for (let obj in PointAttributeTypes) {
  41327. PointAttributeTypes[i$1] = PointAttributeTypes[obj];
  41328. i$1++;
  41329. }
  41330. class PointAttribute{
  41331. constructor(name, type, numElements){
  41332. this.name = name;
  41333. this.type = type;
  41334. this.numElements = numElements;
  41335. this.byteSize = this.numElements * this.type.size;
  41336. this.description = "";
  41337. this.range = [Infinity, -Infinity];
  41338. }
  41339. };
  41340. //add
  41341. const replacements = {
  41342. "COLOR_PACKED": "rgba",
  41343. "RGBA": "rgba",
  41344. "INTENSITY": "intensity",
  41345. "CLASSIFICATION": "classification",
  41346. "GPS_TIME": "gps-time",
  41347. };
  41348. const replaceOldNames = (old) => {
  41349. if(replacements[old]){
  41350. return replacements[old];
  41351. }else {
  41352. return old;
  41353. }
  41354. };
  41355. PointAttribute.POSITION_CARTESIAN = new PointAttribute(
  41356. "POSITION_CARTESIAN", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41357. PointAttribute.RGBA_PACKED = new PointAttribute(
  41358. replaceOldNames("COLOR_PACKED"), PointAttributeTypes.DATA_TYPE_INT8, 4);
  41359. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  41360. PointAttribute.RGB_PACKED = new PointAttribute(
  41361. "COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 3);
  41362. PointAttribute.NORMAL_FLOATS = new PointAttribute(
  41363. "NORMAL_FLOATS", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41364. PointAttribute.INTENSITY = new PointAttribute(
  41365. replaceOldNames("INTENSITY"), PointAttributeTypes.DATA_TYPE_UINT16, 1);
  41366. PointAttribute.CLASSIFICATION = new PointAttribute(
  41367. replaceOldNames("CLASSIFICATION"), PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41368. PointAttribute.NORMAL_SPHEREMAPPED = new PointAttribute(
  41369. "NORMAL_SPHEREMAPPED", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  41370. PointAttribute.NORMAL_OCT16 = new PointAttribute(
  41371. "NORMAL_OCT16", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  41372. PointAttribute.NORMAL = new PointAttribute(
  41373. "NORMAL", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41374. PointAttribute.RETURN_NUMBER = new PointAttribute(
  41375. "RETURN_NUMBER", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41376. PointAttribute.NUMBER_OF_RETURNS = new PointAttribute(
  41377. "NUMBER_OF_RETURNS", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41378. PointAttribute.SOURCE_ID = new PointAttribute(
  41379. "SOURCE_ID", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  41380. PointAttribute.INDICES = new PointAttribute(
  41381. "INDICES", PointAttributeTypes.DATA_TYPE_UINT32, 1);
  41382. PointAttribute.SPACING = new PointAttribute(
  41383. "SPACING", PointAttributeTypes.DATA_TYPE_FLOAT, 1);
  41384. PointAttribute.GPS_TIME = new PointAttribute(
  41385. replaceOldNames("GPS_TIME"), PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  41386. class PointAttributes{
  41387. constructor(pointAttributes){
  41388. this.attributes = [];
  41389. this.byteSize = 0;
  41390. this.size = 0;
  41391. this.vectors = [];
  41392. if (pointAttributes != null) {
  41393. for (let i = 0; i < pointAttributes.length; i++) {
  41394. let pointAttributeName = pointAttributes[i];
  41395. let pointAttribute = PointAttribute[pointAttributeName];
  41396. this.attributes.push(pointAttribute);
  41397. this.byteSize += pointAttribute.byteSize;
  41398. this.size++;
  41399. }
  41400. }
  41401. }
  41402. add(pointAttribute){
  41403. this.attributes.push(pointAttribute);
  41404. this.byteSize += pointAttribute.byteSize;
  41405. this.size++;
  41406. };
  41407. addVector(vector){
  41408. this.vectors.push(vector);
  41409. }
  41410. hasNormals(){
  41411. for (let name in this.attributes) {
  41412. let pointAttribute = this.attributes[name];
  41413. if (
  41414. pointAttribute === PointAttribute.NORMAL_SPHEREMAPPED ||
  41415. pointAttribute === PointAttribute.NORMAL_FLOATS ||
  41416. pointAttribute === PointAttribute.NORMAL ||
  41417. pointAttribute === PointAttribute.NORMAL_OCT16) {
  41418. return true;
  41419. }
  41420. }
  41421. return false;
  41422. };
  41423. }
  41424. class U {
  41425. static toVector3(v, offset) {
  41426. return new Vector3().fromArray(v, offset || 0);
  41427. }
  41428. static toBox3(b) {
  41429. return new Box3(U.toVector3(b), U.toVector3(b, 3));
  41430. };
  41431. static findDim(schema, name) {
  41432. var dim = schema.find((dim) => dim.name == name);
  41433. if (!dim) throw new Error('Failed to find ' + name + ' in schema');
  41434. return dim;
  41435. }
  41436. static sphereFrom(b) {
  41437. return b.getBoundingSphere(new Sphere());
  41438. }
  41439. };
  41440. class PointCloudEptGeometry {
  41441. constructor(url, info) {
  41442. let version = info.version;
  41443. let schema = info.schema;
  41444. let bounds = info.bounds;
  41445. let boundsConforming = info.boundsConforming;
  41446. let xyz = [
  41447. U.findDim(schema, 'X'),
  41448. U.findDim(schema, 'Y'),
  41449. U.findDim(schema, 'Z')
  41450. ];
  41451. let scale = xyz.map((d) => d.scale || 1);
  41452. let offset = xyz.map((d) => d.offset || 0);
  41453. this.eptScale = U.toVector3(scale);
  41454. this.eptOffset = U.toVector3(offset);
  41455. this.url = url;
  41456. this.info = info;
  41457. this.type = 'ept';
  41458. this.schema = schema;
  41459. this.span = info.span || info.ticks;
  41460. this.boundingBox = U.toBox3(bounds);
  41461. this.tightBoundingBox = U.toBox3(boundsConforming);
  41462. this.offset = U.toVector3([0, 0, 0]);
  41463. this.boundingSphere = U.sphereFrom(this.boundingBox);
  41464. this.tightBoundingSphere = U.sphereFrom(this.tightBoundingBox);
  41465. this.version = new Potree.Version('1.7');
  41466. this.projection = null;
  41467. this.fallbackProjection = null;
  41468. if (info.srs && info.srs.horizontal) {
  41469. this.projection = info.srs.authority + ':' + info.srs.horizontal;
  41470. }
  41471. if (info.srs.wkt) {
  41472. if (!this.projection) this.projection = info.srs.wkt;
  41473. else this.fallbackProjection = info.srs.wkt;
  41474. }
  41475. {
  41476. // TODO [mschuetz]: named projections that proj4 can't handle seem to cause problems.
  41477. // remove them for now
  41478. try{
  41479. proj4(this.projection);
  41480. }catch(e){
  41481. this.projection = null;
  41482. }
  41483. }
  41484. {
  41485. const attributes = new PointAttributes();
  41486. attributes.add(PointAttribute.POSITION_CARTESIAN);
  41487. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  41488. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  41489. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41490. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  41491. attributes.add(new PointAttribute("returnNumber", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41492. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41493. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41494. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  41495. this.pointAttributes = attributes;
  41496. }
  41497. this.spacing =
  41498. (this.boundingBox.max.x - this.boundingBox.min.x) / this.span;
  41499. let hierarchyType = info.hierarchyType || 'json';
  41500. const dataType = info.dataType;
  41501. if (dataType == 'laszip') {
  41502. this.loader = new Potree.EptLaszipLoader();
  41503. }
  41504. else if (dataType == 'binary') {
  41505. this.loader = new Potree.EptBinaryLoader();
  41506. }
  41507. else if (dataType == 'zstandard') {
  41508. this.loader = new Potree.EptZstandardLoader();
  41509. }
  41510. else {
  41511. throw new Error('Could not read data type: ' + dataType);
  41512. }
  41513. }
  41514. };
  41515. class EptKey {
  41516. constructor(ept, b, d, x, y, z) {
  41517. this.ept = ept;
  41518. this.b = b;
  41519. this.d = d;
  41520. this.x = x || 0;
  41521. this.y = y || 0;
  41522. this.z = z || 0;
  41523. }
  41524. name() {
  41525. return this.d + '-' + this.x + '-' + this.y + '-' + this.z;
  41526. }
  41527. step(a, b, c) {
  41528. let min = this.b.min.clone();
  41529. let max = this.b.max.clone();
  41530. let dst = new Vector3().subVectors(max, min);
  41531. if (a) min.x += dst.x / 2;
  41532. else max.x -= dst.x / 2;
  41533. if (b) min.y += dst.y / 2;
  41534. else max.y -= dst.y / 2;
  41535. if (c) min.z += dst.z / 2;
  41536. else max.z -= dst.z / 2;
  41537. return new Potree.EptKey(
  41538. this.ept,
  41539. new Box3(min, max),
  41540. this.d + 1,
  41541. this.x * 2 + a,
  41542. this.y * 2 + b,
  41543. this.z * 2 + c);
  41544. }
  41545. children() {
  41546. var result = [];
  41547. for (var a = 0; a < 2; ++a) {
  41548. for (var b = 0; b < 2; ++b) {
  41549. for (var c = 0; c < 2; ++c) {
  41550. var add = this.step(a, b, c).name();
  41551. if (!result.includes(add)) result = result.concat(add);
  41552. }
  41553. }
  41554. }
  41555. return result;
  41556. }
  41557. }
  41558. class PointCloudEptGeometryNode extends PointCloudTreeNode {
  41559. constructor(ept, b, d, x, y, z) {
  41560. super();
  41561. this.ept = ept;
  41562. this.key = new Potree.EptKey(
  41563. this.ept,
  41564. b || this.ept.boundingBox,
  41565. d || 0,
  41566. x,
  41567. y,
  41568. z);
  41569. this.id = PointCloudEptGeometryNode.IDCount++;
  41570. this.geometry = null;
  41571. this.boundingBox = this.key.b;
  41572. this.tightBoundingBox = this.boundingBox;
  41573. this.spacing = this.ept.spacing / Math.pow(2, this.key.d);
  41574. this.boundingSphere = U.sphereFrom(this.boundingBox);
  41575. // These are set during hierarchy loading.
  41576. this.hasChildren = false;
  41577. this.children = { };
  41578. this.numPoints = -1;
  41579. this.level = this.key.d;
  41580. this.loaded = false;
  41581. this.loading = false;
  41582. this.oneTimeDisposeHandlers = [];
  41583. let k = this.key;
  41584. this.name = this.toPotreeName(k.d, k.x, k.y, k.z);
  41585. this.index = parseInt(this.name.charAt(this.name.length - 1));
  41586. }
  41587. isGeometryNode() { return true; }
  41588. getLevel() { return this.level; }
  41589. isTreeNode() { return false; }
  41590. isLoaded() { return this.loaded; }
  41591. getBoundingSphere() { return this.boundingSphere; }
  41592. getBoundingBox() { return this.boundingBox; }
  41593. url() { return this.ept.url + 'ept-data/' + this.filename(); }
  41594. getNumPoints() { return this.numPoints; }
  41595. filename() { return this.key.name(); }
  41596. getChildren() {
  41597. let children = [];
  41598. for (let i = 0; i < 8; i++) {
  41599. if (this.children[i]) {
  41600. children.push(this.children[i]);
  41601. }
  41602. }
  41603. return children;
  41604. }
  41605. addChild(child) {
  41606. this.children[child.index] = child;
  41607. child.parent = this;
  41608. }
  41609. load() {
  41610. if (this.loaded || this.loading) return;
  41611. if (Potree.numNodesLoading >= Potree.maxNodesLoading) return;
  41612. this.loading = true;
  41613. ++Potree.numNodesLoading;
  41614. if (this.numPoints == -1) this.loadHierarchy();
  41615. this.loadPoints();
  41616. }
  41617. loadPoints(){
  41618. this.ept.loader.load(this);
  41619. }
  41620. async loadHierarchy() {
  41621. let nodes = { };
  41622. nodes[this.filename()] = this;
  41623. this.hasChildren = false;
  41624. let eptHierarchyFile =
  41625. `${this.ept.url}ept-hierarchy/${this.filename()}.json`;
  41626. let response = await fetch(eptHierarchyFile);
  41627. let hier = await response.json();
  41628. // Since we want to traverse top-down, and 10 comes
  41629. // lexicographically before 9 (for example), do a deep sort.
  41630. var keys = Object.keys(hier).sort((a, b) => {
  41631. let [da, xa, ya, za] = a.split('-').map((n) => parseInt(n, 10));
  41632. let [db, xb, yb, zb] = b.split('-').map((n) => parseInt(n, 10));
  41633. if (da < db) return -1; if (da > db) return 1;
  41634. if (xa < xb) return -1; if (xa > xb) return 1;
  41635. if (ya < yb) return -1; if (ya > yb) return 1;
  41636. if (za < zb) return -1; if (za > zb) return 1;
  41637. return 0;
  41638. });
  41639. keys.forEach((v) => {
  41640. let [d, x, y, z] = v.split('-').map((n) => parseInt(n, 10));
  41641. let a = x & 1, b = y & 1, c = z & 1;
  41642. let parentName =
  41643. (d - 1) + '-' + (x >> 1) + '-' + (y >> 1) + '-' + (z >> 1);
  41644. let parentNode = nodes[parentName];
  41645. if (!parentNode) return;
  41646. parentNode.hasChildren = true;
  41647. let key = parentNode.key.step(a, b, c);
  41648. let node = new Potree.PointCloudEptGeometryNode(
  41649. this.ept,
  41650. key.b,
  41651. key.d,
  41652. key.x,
  41653. key.y,
  41654. key.z);
  41655. node.level = d;
  41656. node.numPoints = hier[v];
  41657. parentNode.addChild(node);
  41658. nodes[key.name()] = node;
  41659. });
  41660. }
  41661. doneLoading(bufferGeometry, tightBoundingBox, np, mean) {
  41662. bufferGeometry.boundingBox = this.boundingBox;
  41663. this.geometry = bufferGeometry;
  41664. this.tightBoundingBox = tightBoundingBox;
  41665. this.numPoints = np;
  41666. this.mean = mean;
  41667. this.loaded = true;
  41668. this.loading = false;
  41669. --Potree.numNodesLoading;
  41670. }
  41671. toPotreeName(d, x, y, z) {
  41672. var name = 'r';
  41673. for (var i = 0; i < d; ++i) {
  41674. var shift = d - i - 1;
  41675. var mask = 1 << shift;
  41676. var step = 0;
  41677. if (x & mask) step += 4;
  41678. if (y & mask) step += 2;
  41679. if (z & mask) step += 1;
  41680. name += step;
  41681. }
  41682. return name;
  41683. }
  41684. dispose() {
  41685. if (this.geometry && this.parent != null) {
  41686. this.geometry.dispose();
  41687. this.geometry = null;
  41688. this.loaded = false;
  41689. // this.dispatchEvent( { type: 'dispose' } );
  41690. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  41691. let handler = this.oneTimeDisposeHandlers[i];
  41692. handler();
  41693. }
  41694. this.oneTimeDisposeHandlers = [];
  41695. }
  41696. }
  41697. }
  41698. PointCloudEptGeometryNode.IDCount = 0;
  41699. class PointCloudOctreeGeometry extends EventDispatcher{
  41700. constructor(){
  41701. super();
  41702. this.url = null;
  41703. this.octreeDir = null;
  41704. this.spacing = 0;
  41705. this.boundingBox = null;
  41706. this.root = null;
  41707. this.nodes = null;
  41708. this.pointAttributes = null;
  41709. this.hierarchyStepSize = -1;
  41710. this.loader = null;
  41711. }
  41712. }
  41713. class PointCloudOctreeGeometryNode extends PointCloudTreeNode{
  41714. constructor(name, pcoGeometry, boundingBox){
  41715. super();
  41716. this.id = PointCloudOctreeGeometryNode.IDCount++;
  41717. this.name = name;
  41718. this.index = parseInt(name.charAt(name.length - 1));
  41719. this.pcoGeometry = pcoGeometry;
  41720. this.geometry = null;
  41721. this.boundingBox = boundingBox;
  41722. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  41723. this.children = {};
  41724. this.numPoints = 0;
  41725. this.level = null;
  41726. this.loaded = false;
  41727. this.oneTimeDisposeHandlers = [];
  41728. }
  41729. isGeometryNode(){
  41730. return true;
  41731. }
  41732. getLevel(){
  41733. return this.level;
  41734. }
  41735. isTreeNode(){
  41736. return false;
  41737. }
  41738. isLoaded(){
  41739. return this.loaded;
  41740. }
  41741. getBoundingSphere(){
  41742. return this.boundingSphere;
  41743. }
  41744. getBoundingBox(){
  41745. return this.boundingBox;
  41746. }
  41747. getChildren(){
  41748. let children = [];
  41749. for (let i = 0; i < 8; i++) {
  41750. if (this.children[i]) {
  41751. children.push(this.children[i]);
  41752. }
  41753. }
  41754. return children;
  41755. }
  41756. getBoundingBox(){
  41757. return this.boundingBox;
  41758. }
  41759. getURL(){
  41760. let url = '';
  41761. let version = this.pcoGeometry.loader.version;
  41762. if (version.equalOrHigher('1.5')) {
  41763. url = this.pcoGeometry.octreeDir + '/' + this.getHierarchyPath() + '/' + this.name;
  41764. } else if (version.equalOrHigher('1.4')) {
  41765. url = this.pcoGeometry.octreeDir + '/' + this.name;
  41766. } else if (version.upTo('1.3')) {
  41767. url = this.pcoGeometry.octreeDir + '/' + this.name;
  41768. }
  41769. return url;
  41770. }
  41771. getHierarchyPath(){
  41772. let path = 'r/';
  41773. let hierarchyStepSize = this.pcoGeometry.hierarchyStepSize;
  41774. let indices = this.name.substr(1);
  41775. let numParts = Math.floor(indices.length / hierarchyStepSize);
  41776. for (let i = 0; i < numParts; i++) {
  41777. path += indices.substr(i * hierarchyStepSize, hierarchyStepSize) + '/';
  41778. }
  41779. path = path.slice(0, -1);
  41780. return path;
  41781. }
  41782. addChild(child) {
  41783. this.children[child.index] = child;
  41784. child.parent = this;
  41785. }
  41786. load(){
  41787. if (this.loading === true || this.loaded === true || Potree.numNodesLoading >= Potree.maxNodesLoading) {
  41788. return;
  41789. }
  41790. this.loading = true;
  41791. Potree.numNodesLoading++;
  41792. if (this.pcoGeometry.loader.version.equalOrHigher('1.5')) {
  41793. if ((this.level % this.pcoGeometry.hierarchyStepSize) === 0 && this.hasChildren) {
  41794. this.loadHierachyThenPoints();
  41795. } else {
  41796. this.loadPoints();
  41797. }
  41798. } else {
  41799. this.loadPoints();
  41800. }
  41801. }
  41802. loadPoints(){
  41803. this.pcoGeometry.loader.load(this);
  41804. }
  41805. loadHierachyThenPoints(pointcloud){
  41806. let node = this;
  41807. // load hierarchy
  41808. let callback = function (node, hbuffer) {
  41809. let tStart = performance.now();
  41810. let view = new DataView(hbuffer);
  41811. let stack = [];
  41812. let children = view.getUint8(0);
  41813. let numPoints = view.getUint32(1, true);
  41814. node.numPoints = numPoints;
  41815. stack.push({children: children, numPoints: numPoints, name: node.name});
  41816. let decoded = [];
  41817. let offset = 5;
  41818. while (stack.length > 0) {
  41819. let snode = stack.shift();
  41820. let mask = 1;
  41821. for (let i = 0; i < 8; i++) {
  41822. if ((snode.children & mask) !== 0) {
  41823. let childName = snode.name + i;
  41824. let childChildren = view.getUint8(offset);
  41825. let childNumPoints = view.getUint32(offset + 1, true);
  41826. stack.push({children: childChildren, numPoints: childNumPoints, name: childName});
  41827. decoded.push({children: childChildren, numPoints: childNumPoints, name: childName});
  41828. offset += 5;
  41829. }
  41830. mask = mask * 2;
  41831. }
  41832. if (offset === hbuffer.byteLength) {
  41833. break;
  41834. }
  41835. }
  41836. // console.log(decoded);
  41837. let nodes = {};
  41838. nodes[node.name] = node;
  41839. let pco = node.pcoGeometry;
  41840. for (let i = 0; i < decoded.length; i++) {
  41841. let name = decoded[i].name;
  41842. let decodedNumPoints = decoded[i].numPoints;
  41843. let index = parseInt(name.charAt(name.length - 1));
  41844. let parentName = name.substring(0, name.length - 1);
  41845. let parentNode = nodes[parentName];
  41846. let level = name.length - 1;
  41847. pco.dispatchEvent({type:'updateNodeMaxLevel',level});//add
  41848. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  41849. let currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  41850. currentNode.level = level;
  41851. currentNode.numPoints = decodedNumPoints;
  41852. currentNode.hasChildren = decoded[i].children > 0;
  41853. currentNode.spacing = pco.spacing / Math.pow(2, level);
  41854. parentNode.addChild(currentNode);
  41855. nodes[name] = currentNode;
  41856. }
  41857. let duration = performance.now() - tStart;
  41858. if(duration > 5){
  41859. /* let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`;
  41860. console.log(msg); */
  41861. }
  41862. node.loadPoints();
  41863. };
  41864. if ((node.level % node.pcoGeometry.hierarchyStepSize) === 0) {
  41865. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  41866. let hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  41867. hurl += '?m='+node.pcoGeometry.timeStamp; //add
  41868. let xhr = XHRFactory.createXMLHttpRequest();
  41869. xhr.open('GET', hurl, true);
  41870. xhr.responseType = 'arraybuffer';
  41871. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  41872. xhr.onreadystatechange = () => {
  41873. if (xhr.readyState === 4) {
  41874. if (xhr.status === 200 || xhr.status === 0) {
  41875. let hbuffer = xhr.response;
  41876. callback(node, hbuffer);
  41877. } else {
  41878. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  41879. Potree.numNodesLoading--;
  41880. }
  41881. }
  41882. };
  41883. try {
  41884. xhr.send(null);
  41885. } catch (e) {
  41886. console.log('fehler beim laden der punktwolke: ' + e);
  41887. }
  41888. }
  41889. }
  41890. getNumPoints(){
  41891. return this.numPoints;
  41892. }
  41893. dispose(){
  41894. if (this.geometry && this.parent != null) {
  41895. this.geometry.dispose();
  41896. this.geometry = null;
  41897. this.loaded = false;
  41898. this.dispatchEvent( { type: 'dispose' } );
  41899. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  41900. let handler = this.oneTimeDisposeHandlers[i];
  41901. handler();
  41902. }
  41903. this.oneTimeDisposeHandlers = [];
  41904. }
  41905. }
  41906. traverse(t, e){//add from navvis 25.js
  41907. void 0 === e && (e = !0);
  41908. for (var n, i = e ? [this] : []; void 0 !== (n = i.pop()); ) {
  41909. t(n);
  41910. for (var o = 0, r = n.children; o < r.length; o++) {
  41911. var a = r[o];
  41912. null !== a && i.push(a);
  41913. }
  41914. }
  41915. }
  41916. }
  41917. PointCloudOctreeGeometryNode.IDCount = 0;
  41918. // -------------------------------------------
  41919. // to get a ready to use gradient array from a chroma.js gradient:
  41920. // http://gka.github.io/chroma.js/
  41921. // -------------------------------------------
  41922. //
  41923. // let stops = [];
  41924. // for(let i = 0; i <= 10; i++){
  41925. // let range = chroma.scale(['yellow', 'navy']).mode('lch').domain([10,0])(i)._rgb
  41926. // .slice(0, 3)
  41927. // .map(v => (v / 255).toFixed(4))
  41928. // .join(", ");
  41929. //
  41930. // let line = `[${i / 10}, new THREE.Color(${range})],`;
  41931. //
  41932. // stops.push(line);
  41933. // }
  41934. // stops.join("\n");
  41935. //
  41936. //
  41937. //
  41938. // -------------------------------------------
  41939. // to get a ready to use gradient array from matplotlib:
  41940. // -------------------------------------------
  41941. // import matplotlib.pyplot as plt
  41942. // import matplotlib.colors as colors
  41943. //
  41944. // norm = colors.Normalize(vmin=0,vmax=1)
  41945. // cmap = plt.cm.viridis
  41946. //
  41947. // for i in range(0,11):
  41948. // u = i / 10
  41949. // rgb = cmap(norm(u))[0:3]
  41950. // rgb = ["{0:.3f}".format(v) for v in rgb]
  41951. // rgb = "[" + str(u) + ", new THREE.Color(" + ", ".join(rgb) + ")],"
  41952. // print(rgb)
  41953. let Gradients = {
  41954. // From chroma spectral http://gka.github.io/chroma.js/
  41955. SPECTRAL: [
  41956. [0, new Color(0.3686, 0.3098, 0.6353)],
  41957. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  41958. [0.2, new Color(0.4000, 0.7608, 0.6471)],
  41959. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  41960. [0.4, new Color(0.9020, 0.9608, 0.5961)],
  41961. [0.5, new Color(1.0000, 1.0000, 0.7490)],
  41962. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  41963. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  41964. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  41965. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  41966. [1, new Color(0.6196, 0.0039, 0.2588)]
  41967. ],
  41968. PLASMA: [
  41969. [0.0, new Color(0.241, 0.015, 0.610)],
  41970. [0.1, new Color(0.387, 0.001, 0.654)],
  41971. [0.2, new Color(0.524, 0.025, 0.653)],
  41972. [0.3, new Color(0.651, 0.125, 0.596)],
  41973. [0.4, new Color(0.752, 0.227, 0.513)],
  41974. [0.5, new Color(0.837, 0.329, 0.431)],
  41975. [0.6, new Color(0.907, 0.435, 0.353)],
  41976. [0.7, new Color(0.963, 0.554, 0.272)],
  41977. [0.8, new Color(0.992, 0.681, 0.195)],
  41978. [0.9, new Color(0.987, 0.822, 0.144)],
  41979. [1.0, new Color(0.940, 0.975, 0.131)]
  41980. ],
  41981. YELLOW_GREEN: [
  41982. [0, new Color(0.1647, 0.2824, 0.3451)],
  41983. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  41984. [0.2, new Color(0.0610, 0.4319, 0.4864)],
  41985. [0.3, new Color(0.0000, 0.5099, 0.5319)],
  41986. [0.4, new Color(0.0000, 0.5881, 0.5569)],
  41987. [0.5, new Color(0.1370, 0.6650, 0.5614)],
  41988. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  41989. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  41990. [0.8, new Color(0.6102, 0.8748, 0.4850)],
  41991. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  41992. [1, new Color(0.9804, 0.9804, 0.4314)]
  41993. ],
  41994. VIRIDIS: [
  41995. [0.0, new Color(0.267, 0.005, 0.329)],
  41996. [0.1, new Color(0.283, 0.141, 0.458)],
  41997. [0.2, new Color(0.254, 0.265, 0.530)],
  41998. [0.3, new Color(0.207, 0.372, 0.553)],
  41999. [0.4, new Color(0.164, 0.471, 0.558)],
  42000. [0.5, new Color(0.128, 0.567, 0.551)],
  42001. [0.6, new Color(0.135, 0.659, 0.518)],
  42002. [0.7, new Color(0.267, 0.749, 0.441)],
  42003. [0.8, new Color(0.478, 0.821, 0.318)],
  42004. [0.9, new Color(0.741, 0.873, 0.150)],
  42005. [1.0, new Color(0.993, 0.906, 0.144)]
  42006. ],
  42007. INFERNO: [
  42008. [0.0, new Color(0.077, 0.042, 0.206)],
  42009. [0.1, new Color(0.225, 0.036, 0.388)],
  42010. [0.2, new Color(0.373, 0.074, 0.432)],
  42011. [0.3, new Color(0.522, 0.128, 0.420)],
  42012. [0.4, new Color(0.665, 0.182, 0.370)],
  42013. [0.5, new Color(0.797, 0.255, 0.287)],
  42014. [0.6, new Color(0.902, 0.364, 0.184)],
  42015. [0.7, new Color(0.969, 0.516, 0.063)],
  42016. [0.8, new Color(0.988, 0.683, 0.072)],
  42017. [0.9, new Color(0.961, 0.859, 0.298)],
  42018. [1.0, new Color(0.988, 0.998, 0.645)]
  42019. ],
  42020. GRAYSCALE: [
  42021. [0, new Color(0, 0, 0)],
  42022. [1, new Color(1, 1, 1)]
  42023. ],
  42024. // 16 samples of the TURBU color scheme
  42025. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  42026. // original file licensed under Apache-2.0
  42027. TURBO: [
  42028. [0.00, new Color(0.18995, 0.07176, 0.23217)],
  42029. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  42030. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  42031. [0.20, new Color(0.25862, 0.57958, 0.99876)],
  42032. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  42033. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  42034. [0.40, new Color(0.19659, 0.94901, 0.59466)],
  42035. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  42036. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  42037. [0.60, new Color(0.80473, 0.92452, 0.20459)],
  42038. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  42039. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  42040. [0.80, new Color(0.9836, 0.49291, 0.12849)],
  42041. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  42042. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  42043. [1.00, new Color(0.66449, 0.08436, 0.00424)],
  42044. ],
  42045. RAINBOW: [
  42046. [0, new Color(0.278, 0, 0.714)],
  42047. [1 / 6, new Color(0, 0, 1)],
  42048. [2 / 6, new Color(0, 1, 1)],
  42049. [3 / 6, new Color(0, 1, 0)],
  42050. [4 / 6, new Color(1, 1, 0)],
  42051. [5 / 6, new Color(1, 0.64, 0)],
  42052. [1, new Color(1, 0, 0)]
  42053. ],
  42054. CONTOUR: [
  42055. [0.00, new Color(0, 0, 0)],
  42056. [0.03, new Color(0, 0, 0)],
  42057. [0.04, new Color(1, 1, 1)],
  42058. [1.00, new Color(1, 1, 1)]
  42059. ],
  42060. };
  42061. const ClassificationScheme = {
  42062. DEFAULT: {
  42063. 0: { visible: true, name: 'never classified' , color: [0.5, 0.5, 0.5, 1.0] },
  42064. 1: { visible: true, name: 'unclassified' , color: [0.5, 0.5, 0.5, 1.0] },
  42065. 2: { visible: true, name: 'ground' , color: [0.63, 0.32, 0.18, 1.0] },
  42066. 3: { visible: true, name: 'low vegetation' , color: [0.0, 1.0, 0.0, 1.0] },
  42067. 4: { visible: true, name: 'medium vegetation' , color: [0.0, 0.8, 0.0, 1.0] },
  42068. 5: { visible: true, name: 'high vegetation' , color: [0.0, 0.6, 0.0, 1.0] },
  42069. 6: { visible: true, name: 'building' , color: [1.0, 0.66, 0.0, 1.0] },
  42070. 7: { visible: true, name: 'low point(noise)' , color: [1.0, 0.0, 1.0, 1.0] },
  42071. 8: { visible: true, name: 'key-point' , color: [1.0, 0.0, 0.0, 1.0] },
  42072. 9: { visible: true, name: 'water' , color: [0.0, 0.0, 1.0, 1.0] },
  42073. 12: { visible: true, name: 'overlap' , color: [1.0, 1.0, 0.0, 1.0] },
  42074. DEFAULT: { visible: true, name: 'default' , color: [0.3, 0.6, 0.6, 0.5] },
  42075. }
  42076. };
  42077. Object.defineProperty(ClassificationScheme, 'RANDOM', {
  42078. get: function() {
  42079. let scheme = {};
  42080. for(let i = 0; i <= 255; i++){
  42081. scheme[i] = new Vector4(Math.random(), Math.random(), Math.random());
  42082. }
  42083. scheme["DEFAULT"] = new Vector4(Math.random(), Math.random(), Math.random());
  42084. return scheme;
  42085. }
  42086. });
  42087. //
  42088. // how to calculate the radius of a projected sphere in screen space
  42089. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  42090. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  42091. //
  42092. class PointCloudMaterial$1 extends RawShaderMaterial {
  42093. constructor (parameters = {}) {
  42094. super();
  42095. this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new Color(0xffffff));
  42096. this.visibleNodesTexture.minFilter = NearestFilter;
  42097. this.visibleNodesTexture.magFilter = NearestFilter;
  42098. let getValid = (a, b) => {
  42099. if(a !== undefined){
  42100. return a;
  42101. }else {
  42102. return b;
  42103. }
  42104. };
  42105. let pointSize = getValid(parameters.size, 1.0);
  42106. let minSize = getValid(parameters.minSize, 2.0);
  42107. let maxSize = getValid(parameters.maxSize, 1550.0);
  42108. let treeType = getValid(parameters.treeType, TreeType.OCTREE);
  42109. this._pointSizeType = PointSizeType.FIXED;
  42110. this._shape = PointShape.SQUARE;
  42111. this._useClipBox = false;
  42112. this.clipBoxes = [];
  42113. this.clipPolygons = [];
  42114. this._weighted = false;
  42115. this._gradient = Gradients.RAINBOW;//Gradients.SPECTRAL;//海拔贴图种类
  42116. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  42117. this._matcap = "matcap.jpg";
  42118. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  42119. this.lights = false;
  42120. this.fog = false;
  42121. this._treeType = treeType;
  42122. this._useEDL = false;
  42123. this.defines = new Map();
  42124. this.ranges = new Map();
  42125. this._activeAttributeName = null;
  42126. this._defaultIntensityRangeChanged = false;
  42127. this._defaultElevationRangeChanged = false;
  42128. {
  42129. const [width, height] = [256, 1];
  42130. let data = new Uint8Array(width * 4);
  42131. let texture = new DataTexture(data, width, height, RGBAFormat);
  42132. texture.magFilter = NearestFilter;
  42133. texture.needsUpdate = true;
  42134. this.classificationTexture = texture;
  42135. }
  42136. this.attributes = {
  42137. position: { type: 'fv', value: [] },
  42138. color: { type: 'fv', value: [] },
  42139. normal: { type: 'fv', value: [] },
  42140. intensity: { type: 'f', value: [] },
  42141. classification: { type: 'f', value: [] },
  42142. returnNumber: { type: 'f', value: [] },
  42143. numberOfReturns: { type: 'f', value: [] },
  42144. pointSourceID: { type: 'f', value: [] },
  42145. indices: { type: 'fv', value: [] }
  42146. };
  42147. this.uniforms = {
  42148. level: { type: "f", value: 0.0 },
  42149. vnStart: { type: "f", value: 0.0 },
  42150. spacing: { type: "f", value: 1.0 },
  42151. blendHardness: { type: "f", value: 2.0 },
  42152. blendDepthSupplement: { type: "f", value: 0.0 },
  42153. fov: { type: "f", value: 1.0 },
  42154. /* screenWidth: { type: "f", value: 1.0 },
  42155. screenHeight: { type: "f", value: 1.0 }, */
  42156. resolution: { type: 'v2', value: new Vector2$1() },
  42157. near: { type: "f", value: 0.1 },
  42158. far: { type: "f", value: 1.0 },
  42159. uColor: { type: "c", value: new Color( 0xffffff ) },
  42160. uOpacity: { type: "f", value: 1.0 },
  42161. size: { type: "f", value: pointSize },
  42162. minSize: { type: "f", value: minSize },
  42163. maxSize: { type: "f", value: maxSize },
  42164. octreeSize: { type: "f", value: 0 },
  42165. bbSize: { type: "fv", value: [0, 0, 0] },
  42166. elevationRange: { type: "2fv", value: [0, 0] },
  42167. clipBoxCount: { type: "f", value: 0 },
  42168. //clipSphereCount: { type: "f", value: 0 },
  42169. clipPolygonCount: { type: "i", value: 0 },
  42170. clipBoxes: { type: "Matrix4fv", value: [] },
  42171. //clipSpheres: { type: "Matrix4fv", value: [] },
  42172. clipPolygons: { type: "3fv", value: [] },
  42173. clipPolygonVCount: { type: "iv", value: [] },
  42174. clipPolygonVP: { type: "Matrix4fv", value: [] },
  42175. visibleNodes: { type: "t", value: this.visibleNodesTexture },
  42176. pcIndex: { type: "f", value: 0 },
  42177. gradient: { type: "t", value: this.gradientTexture },
  42178. classificationLUT: { type: "t", value: this.classificationTexture },
  42179. uHQDepthMap: { type: "t", value: null },
  42180. toModel: { type: "Matrix4f", value: [] },
  42181. diffuse: { type: "fv", value: [1, 1, 1] },
  42182. transition: { type: "f", value: 0.5 },
  42183. intensityRange: { type: "fv", value: [Infinity, -Infinity] },
  42184. intensity_gbc: { type: "fv", value: [1, 0, 0]},
  42185. uRGB_gbc: { type: "fv", value: [1, 0, 0]},
  42186. // intensityGamma: { type: "f", value: 1 },
  42187. // intensityContrast: { type: "f", value: 0 },
  42188. // intensityBrightness:{ type: "f", value: 0 },
  42189. // rgbGamma: { type: "f", value: 1 },
  42190. // rgbContrast: { type: "f", value: 0 },
  42191. // rgbBrightness: { type: "f", value: 0 },
  42192. wRGB: { type: "f", value: 1 },
  42193. wIntensity: { type: "f", value: 0 },
  42194. wElevation: { type: "f", value: 0 },
  42195. wClassification: { type: "f", value: 0 },
  42196. wReturnNumber: { type: "f", value: 0 },
  42197. wSourceID: { type: "f", value: 0 },
  42198. useOrthographicCamera: { type: "b", value: false },
  42199. elevationGradientRepat: { type: "i", value: ElevationGradientRepeat.CLAMP },
  42200. clipTask: { type: "i", value: 1 },
  42201. clipMethod: { type: "i", value: 1 },
  42202. uShadowColor: { type: "3fv", value: [0, 0, 0] },
  42203. uExtraScale: { type: "f", value: 1},
  42204. uExtraOffset: { type: "f", value: 0},
  42205. uExtraRange: { type: "2fv", value: [0, 1] },
  42206. uExtraGammaBrightContr: { type: "3fv", value: [1, 0, 0] },
  42207. uFilterReturnNumberRange: { type: "fv", value: [0, 7]},
  42208. uFilterNumberOfReturnsRange: { type: "fv", value: [0, 7]},
  42209. uFilterGPSTimeClipRange: { type: "fv", value: [0, 7]},
  42210. uFilterPointSourceIDClipRange: { type: "fv", value: [0, 65535]},
  42211. matcapTextureUniform: { type: "t", value: this.matcapTexture },
  42212. backfaceCulling: { type: "b", value: false },
  42213. ////////////////add
  42214. //usePanoMap:{ type: "i", value: 0 },
  42215. progress: {
  42216. type: "f",
  42217. value: 0
  42218. },
  42219. easeInOutRatio:{
  42220. type: "f",
  42221. value: 0.3
  42222. },
  42223. pano0Map: {
  42224. type: "t",
  42225. value: null
  42226. },
  42227. pano0Position: {
  42228. type: "v3",
  42229. value: new Vector3
  42230. },
  42231. pano0Matrix: {
  42232. type: "m4",
  42233. value: new Matrix4
  42234. },
  42235. pano1Map: {
  42236. type: "t",
  42237. value: null
  42238. },
  42239. pano1Position: {
  42240. type: "v3",
  42241. value: new Vector3
  42242. },
  42243. pano1Matrix: {
  42244. type: "m4",
  42245. value: new Matrix4
  42246. },
  42247. };
  42248. this.classification = ClassificationScheme.DEFAULT;
  42249. this.defaultAttributeValues.normal = [0, 0, 0];
  42250. this.defaultAttributeValues.classification = [0, 0, 0];
  42251. this.defaultAttributeValues.indices = [0, 0, 0, 0];
  42252. this.vertexShader = Shaders['pointcloud.vs'];
  42253. this.fragmentShader = Shaders['pointcloud.fs'];
  42254. this.vertexColors = VertexColors;
  42255. this.updateShaderSource();
  42256. }
  42257. setDefine(key, value){
  42258. if(value !== undefined && value !== null){
  42259. if(this.defines.get(key) !== value){
  42260. this.defines.set(key, value);
  42261. this.updateShaderSource();
  42262. }
  42263. }else {
  42264. this.removeDefine(key);
  42265. }
  42266. }
  42267. removeDefine(key){
  42268. this.defines.delete(key);
  42269. }
  42270. updateShaderSource () {
  42271. let vs = Shaders['pointcloud.vs'];
  42272. let fs = Shaders['pointcloud.fs'];
  42273. let definesString = this.getDefines();
  42274. let vsVersionIndex = vs.indexOf("#version ");
  42275. let fsVersionIndex = fs.indexOf("#version ");
  42276. if(vsVersionIndex >= 0){
  42277. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  42278. }else {
  42279. vs = `${definesString}\n${vs}`;
  42280. }
  42281. if(fsVersionIndex >= 0){
  42282. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  42283. }else {
  42284. fs = `${definesString}\n${fs}`;
  42285. }
  42286. this.vertexShader = vs;
  42287. this.fragmentShader = fs;
  42288. if (this.opacity === 1.0 && !this.useFilterByNormal) {//add useFilterByNormal
  42289. this.blending = NoBlending;
  42290. this.transparent = false;
  42291. this.depthTest = true;
  42292. this.depthWrite = true;
  42293. this.depthFunc = LessEqualDepth;
  42294. } else if ( (this.opacity < 1.0 ||this.useFilterByNormal) && !this.useEDL) {//add useFilterByNormal
  42295. this.blending = AdditiveBlending;
  42296. this.transparent = true;
  42297. this.depthTest = false;
  42298. this.depthWrite = true;
  42299. this.depthFunc = AlwaysDepth;
  42300. }
  42301. if (this.weighted) {
  42302. this.blending = AdditiveBlending;
  42303. this.transparent = true;
  42304. this.depthTest = true;
  42305. this.depthWrite = false;
  42306. }
  42307. this.needsUpdate = true;
  42308. }
  42309. getDefines () {
  42310. let defines = [];
  42311. if (this.pointSizeType === PointSizeType.FIXED) {
  42312. defines.push('#define fixed_point_size');
  42313. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  42314. defines.push('#define attenuated_point_size');
  42315. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  42316. defines.push('#define adaptive_point_size');
  42317. }
  42318. if(!Features.EXT_DEPTH.isSupported() && this.shape === PointShape.PARABOLOID){
  42319. this.shape = PointShape.SQUARE ;//强行替换
  42320. }
  42321. if (this.shape === PointShape.SQUARE) {
  42322. defines.push('#define square_point_shape');
  42323. } else if (this.shape === PointShape.CIRCLE) {
  42324. defines.push('#define circle_point_shape');
  42325. } else if (this.shape === PointShape.PARABOLOID) {
  42326. defines.push('#define paraboloid_point_shape');
  42327. }
  42328. //console.log('this.shape PARABOLOID', this.shape, this.shape === PointShape.PARABOLOID)
  42329. if (this._useEDL || this.fakeEDL) {
  42330. defines.push('#define use_edl');
  42331. }
  42332. if(this.activeAttributeName){
  42333. let attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  42334. defines.push(`#define color_type_${attributeName}`);
  42335. }
  42336. if(this._treeType === TreeType.OCTREE){
  42337. defines.push('#define tree_type_octree');
  42338. }else if(this._treeType === TreeType.KDTREE){
  42339. defines.push('#define tree_type_kdtree');
  42340. }
  42341. if (this.weighted) {
  42342. defines.push('#define weighted_splats');
  42343. }
  42344. for(let [key, value] of this.defines){
  42345. defines.push(value);
  42346. }
  42347. return defines.join("\n");
  42348. }
  42349. setClipBoxes (clipBoxes) {
  42350. if (!clipBoxes) {
  42351. return;
  42352. }
  42353. let doUpdate = (this.clipBoxes.length !== clipBoxes.length) && (clipBoxes.length === 0 || this.clipBoxes.length === 0);
  42354. this.uniforms.clipBoxCount.value = this.clipBoxes.length;
  42355. this.clipBoxes = clipBoxes;
  42356. if (doUpdate) {
  42357. this.updateShaderSource();
  42358. }
  42359. this.uniforms.clipBoxes.value = new Float32Array(this.clipBoxes.length * 16);
  42360. for (let i = 0; i < this.clipBoxes.length; i++) {
  42361. let box = clipBoxes[i];
  42362. this.uniforms.clipBoxes.value.set(box.inverse.elements, 16 * i);
  42363. }
  42364. for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {
  42365. if (Number.isNaN(this.uniforms.clipBoxes.value[i])) {
  42366. this.uniforms.clipBoxes.value[i] = Infinity;
  42367. }
  42368. }
  42369. }
  42370. setClipPolygons(clipPolygons, maxPolygonVertices) {
  42371. if(!clipPolygons){
  42372. return;
  42373. }
  42374. this.clipPolygons = clipPolygons;
  42375. let doUpdate = (this.clipPolygons.length !== clipPolygons.length);
  42376. if(doUpdate){
  42377. this.updateShaderSource();
  42378. }
  42379. }
  42380. get gradient(){
  42381. return this._gradient;
  42382. }
  42383. set gradient (value) {//海拔贴图
  42384. if (this._gradient !== value) {
  42385. this._gradient = value;
  42386. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  42387. this.uniforms.gradient.value = this.gradientTexture;
  42388. }
  42389. }
  42390. get matcap(){
  42391. return this._matcap;
  42392. }
  42393. set matcap (value) {
  42394. if (this._matcap !== value) {
  42395. this._matcap = value;
  42396. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  42397. this.uniforms.matcapTextureUniform.value = this.matcapTexture;
  42398. }
  42399. }
  42400. get useOrthographicCamera() {
  42401. return this.uniforms.useOrthographicCamera.value;
  42402. }
  42403. set useOrthographicCamera(value) {
  42404. if(this.uniforms.useOrthographicCamera.value !== value){
  42405. this.uniforms.useOrthographicCamera.value = value;
  42406. }
  42407. }
  42408. get backfaceCulling() {
  42409. return this.uniforms.backfaceCulling.value;
  42410. }
  42411. set backfaceCulling(value) {
  42412. if(this.uniforms.backfaceCulling.value !== value){
  42413. this.uniforms.backfaceCulling.value = value;
  42414. this.dispatchEvent({type: 'backface_changed', target: this});
  42415. }
  42416. }
  42417. recomputeClassification () {
  42418. const classification = this.classification;
  42419. const data = this.classificationTexture.image.data;
  42420. let width = 256;
  42421. const black = [1, 1, 1, 1];
  42422. let valuesChanged = false;
  42423. for (let i = 0; i < width; i++) {
  42424. let color;
  42425. let visible = true;
  42426. if (classification[i]) {
  42427. color = classification[i].color;
  42428. visible = classification[i].visible;
  42429. } else if (classification[i % 32]) {
  42430. color = classification[i % 32].color;
  42431. visible = classification[i % 32].visible;
  42432. } else if(classification.DEFAULT) {
  42433. color = classification.DEFAULT.color;
  42434. visible = classification.DEFAULT.visible;
  42435. }else {
  42436. color = black;
  42437. }
  42438. const r = parseInt(255 * color[0]);
  42439. const g = parseInt(255 * color[1]);
  42440. const b = parseInt(255 * color[2]);
  42441. const a = visible ? parseInt(255 * color[3]) : 0;
  42442. if(data[4 * i + 0] !== r){
  42443. data[4 * i + 0] = r;
  42444. valuesChanged = true;
  42445. }
  42446. if(data[4 * i + 1] !== g){
  42447. data[4 * i + 1] = g;
  42448. valuesChanged = true;
  42449. }
  42450. if(data[4 * i + 2] !== b){
  42451. data[4 * i + 2] = b;
  42452. valuesChanged = true;
  42453. }
  42454. if(data[4 * i + 3] !== a){
  42455. data[4 * i + 3] = a;
  42456. valuesChanged = true;
  42457. }
  42458. }
  42459. if(valuesChanged){
  42460. this.classificationTexture.needsUpdate = true;
  42461. this.dispatchEvent({
  42462. type: 'material_property_changed',
  42463. target: this
  42464. });
  42465. }
  42466. }
  42467. get spacing () {
  42468. return this.uniforms.spacing.value;
  42469. }
  42470. set spacing (value) {
  42471. if (this.uniforms.spacing.value !== value) { // 即 uOctreeSpacing 来自cloud.js里
  42472. this.uniforms.spacing.value = value;
  42473. }
  42474. }
  42475. get useClipBox () {
  42476. return this._useClipBox;
  42477. }
  42478. set useClipBox (value) {
  42479. if (this._useClipBox !== value) {
  42480. this._useClipBox = value;
  42481. this.updateShaderSource();
  42482. }
  42483. }
  42484. get clipTask(){
  42485. return this.uniforms.clipTask.value;
  42486. }
  42487. set clipTask(mode){
  42488. this.uniforms.clipTask.value = mode;
  42489. }
  42490. get elevationGradientRepat(){
  42491. return this.uniforms.elevationGradientRepat.value;
  42492. }
  42493. set elevationGradientRepat(mode){
  42494. this.uniforms.elevationGradientRepat.value = mode;
  42495. }
  42496. get clipMethod(){
  42497. return this.uniforms.clipMethod.value;
  42498. }
  42499. set clipMethod(mode){
  42500. this.uniforms.clipMethod.value = mode;
  42501. }
  42502. get weighted(){
  42503. return this._weighted;
  42504. }
  42505. set weighted (value) {
  42506. if (this._weighted !== value) {
  42507. this._weighted = value;
  42508. this.updateShaderSource();
  42509. }
  42510. }
  42511. get fov () {
  42512. return this.uniforms.fov.value;
  42513. }
  42514. set fov (value) {
  42515. if (this.uniforms.fov.value !== value) {
  42516. this.uniforms.fov.value = value;
  42517. // this.updateShaderSource();
  42518. }
  42519. }
  42520. /* get screenWidth () {
  42521. return this.uniforms.screenWidth.value;
  42522. }
  42523. set screenWidth (value) {
  42524. if (this.uniforms.screenWidth.value !== value) {
  42525. this.uniforms.screenWidth.value = value;
  42526. // this.updateShaderSource();
  42527. }
  42528. }
  42529. get screenHeight () {
  42530. return this.uniforms.screenHeight.value;
  42531. }
  42532. set screenHeight (value) {
  42533. if (this.uniforms.screenHeight.value !== value) {
  42534. this.uniforms.screenHeight.value = value;
  42535. // this.updateShaderSource();
  42536. }
  42537. }*/
  42538. //add--------------
  42539. get resolution(){
  42540. return this.uniforms.resolution.value
  42541. }
  42542. set resolution(value){
  42543. this.uniforms.resolution.value.copy(value);
  42544. }
  42545. //--------------
  42546. get near () {
  42547. return this.uniforms.near.value;
  42548. }
  42549. set near (value) {
  42550. if (this.uniforms.near.value !== value) {
  42551. this.uniforms.near.value = value;
  42552. }
  42553. }
  42554. get far () {
  42555. return this.uniforms.far.value;
  42556. }
  42557. set far (value) {
  42558. if (this.uniforms.far.value !== value) {
  42559. this.uniforms.far.value = value;
  42560. }
  42561. }
  42562. get opacity(){
  42563. return this.uniforms.uOpacity.value;
  42564. }
  42565. set opacity (value) {
  42566. if (this.uniforms && this.uniforms.uOpacity) {
  42567. if (this.uniforms.uOpacity.value !== value) {
  42568. this.uniforms.uOpacity.value = value;
  42569. this.updateShaderSource();
  42570. this.dispatchEvent({
  42571. type: 'opacity_changed',
  42572. target: this
  42573. });
  42574. this.dispatchEvent({
  42575. type: 'material_property_changed',
  42576. target: this
  42577. });
  42578. }
  42579. }
  42580. }
  42581. get activeAttributeName(){
  42582. return this._activeAttributeName;
  42583. }
  42584. set activeAttributeName(value){
  42585. if (this._activeAttributeName !== value) {
  42586. this._activeAttributeName = value;
  42587. this.updateShaderSource();
  42588. this.dispatchEvent({
  42589. type: 'active_attribute_changed',
  42590. target: this
  42591. });
  42592. this.dispatchEvent({
  42593. type: 'material_property_changed',
  42594. target: this
  42595. });
  42596. }
  42597. }
  42598. get pointSizeType () {
  42599. return this._pointSizeType;
  42600. }
  42601. set pointSizeType (value) {
  42602. if(typeof value == 'string' )value = PointSizeType[value];
  42603. if (this._pointSizeType !== value) {
  42604. this._pointSizeType = value;
  42605. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  42606. this.dispatchEvent({
  42607. type: 'point_size_type_changed',
  42608. target: this
  42609. });
  42610. this.dispatchEvent({
  42611. type: 'material_property_changed',
  42612. target: this
  42613. });
  42614. }
  42615. }
  42616. get useEDL(){
  42617. return this._useEDL;
  42618. }
  42619. set useEDL (value) {
  42620. if (this._useEDL !== value) {
  42621. this._useEDL = value;
  42622. this.updateShaderSource();
  42623. }
  42624. }
  42625. get fakeEDL(){
  42626. return this._fakeEDL;
  42627. }
  42628. set fakeEDL (value) {//add
  42629. if (this._fakeEDL !== value) {
  42630. this._fakeEDL = value;
  42631. this.updateShaderSource();
  42632. }
  42633. }
  42634. get color () {
  42635. return this.uniforms.uColor.value;
  42636. }
  42637. set color (value) {//改
  42638. if(value == this.color_)return
  42639. let color = value;
  42640. //if (!this.uniforms.uColor.value.equals(value)) {
  42641. if(typeof value == 'string') {
  42642. var colorArr = Potree.config.colors[value];
  42643. if(!colorArr){
  42644. //console.warn('没找到该颜色值'+ value)
  42645. }else {
  42646. color = new Color().fromArray(colorArr).multiplyScalar(1/255);
  42647. }
  42648. }
  42649. this.uniforms.uColor.value.set(color);
  42650. //this.uniforms.uColor.value.copy(value);
  42651. this.dispatchEvent({
  42652. type: 'color_changed',
  42653. target: this
  42654. });
  42655. this.dispatchEvent({
  42656. type: 'material_property_changed',
  42657. target: this
  42658. });
  42659. //}
  42660. this.color_ = value; //记录下str
  42661. }
  42662. get shape () {
  42663. return this._shape;
  42664. }
  42665. set shape (value) {
  42666. if (this._shape !== value) {
  42667. this._shape = value;
  42668. this.updateShaderSource();
  42669. this.dispatchEvent({type: 'point_shape_changed', target: this});
  42670. this.dispatchEvent({
  42671. type: 'material_property_changed',
  42672. target: this
  42673. });
  42674. }
  42675. }
  42676. get treeType () {
  42677. return this._treeType;
  42678. }
  42679. set treeType (value) {
  42680. if (this._treeType !== value) {
  42681. this._treeType = value;
  42682. this.updateShaderSource();
  42683. }
  42684. }
  42685. get bbSize () {
  42686. return this.uniforms.bbSize.value;
  42687. }
  42688. set bbSize (value) {
  42689. this.uniforms.bbSize.value = value;
  42690. }
  42691. get size () {
  42692. return this.uniforms.size.value;
  42693. }
  42694. set size (value) {
  42695. if (this.uniforms.size.value !== value) {
  42696. this.uniforms.size.value = value;
  42697. this.dispatchEvent({
  42698. type: 'point_size_changed',
  42699. target: this
  42700. });
  42701. this.dispatchEvent({
  42702. type: 'material_property_changed',
  42703. target: this
  42704. });
  42705. }
  42706. }
  42707. get minSize(){
  42708. return this.uniforms.minSize.value;
  42709. }
  42710. set minSize(value){
  42711. if (this.uniforms.minSize.value !== value) {
  42712. this.uniforms.minSize.value = value;
  42713. this.dispatchEvent({
  42714. type: 'point_size_changed',
  42715. target: this
  42716. });
  42717. this.dispatchEvent({
  42718. type: 'material_property_changed',
  42719. target: this
  42720. });
  42721. }
  42722. }
  42723. get elevationRange () {
  42724. return this.uniforms.elevationRange.value;
  42725. }
  42726. set elevationRange (value) {
  42727. let changed = this.uniforms.elevationRange.value[0] !== value[0]
  42728. || this.uniforms.elevationRange.value[1] !== value[1];
  42729. if(changed){
  42730. this.uniforms.elevationRange.value = value;
  42731. this._defaultElevationRangeChanged = true;
  42732. this.dispatchEvent({
  42733. type: 'material_property_changed',
  42734. target: this
  42735. });
  42736. }
  42737. }
  42738. get heightMin () {
  42739. return this.uniforms.elevationRange.value[0];
  42740. }
  42741. set heightMin (value) {
  42742. this.elevationRange = [value, this.elevationRange[1]];
  42743. }
  42744. get heightMax () {
  42745. return this.uniforms.elevationRange.value[1];
  42746. }
  42747. set heightMax (value) {
  42748. this.elevationRange = [this.elevationRange[0], value];
  42749. }
  42750. get transition () {
  42751. return this.uniforms.transition.value;
  42752. }
  42753. set transition (value) {
  42754. this.uniforms.transition.value = value;
  42755. }
  42756. get intensityRange () {
  42757. return this.uniforms.intensityRange.value;
  42758. }
  42759. set intensityRange (value) {
  42760. if (!(value instanceof Array && value.length === 2)) {
  42761. return;
  42762. }
  42763. if (value[0] === this.uniforms.intensityRange.value[0] &&
  42764. value[1] === this.uniforms.intensityRange.value[1]) {
  42765. return;
  42766. }
  42767. this.uniforms.intensityRange.value = value;
  42768. this._defaultIntensityRangeChanged = true;
  42769. this.dispatchEvent({
  42770. type: 'material_property_changed',
  42771. target: this
  42772. });
  42773. }
  42774. get intensityGamma () {
  42775. return this.uniforms.intensity_gbc.value[0];
  42776. }
  42777. set intensityGamma (value) {
  42778. if (this.uniforms.intensity_gbc.value[0] !== value) {
  42779. this.uniforms.intensity_gbc.value[0] = value;
  42780. this.dispatchEvent({
  42781. type: 'material_property_changed',
  42782. target: this
  42783. });
  42784. }
  42785. }
  42786. get intensityContrast () {
  42787. return this.uniforms.intensity_gbc.value[2];
  42788. }
  42789. set intensityContrast (value) {
  42790. if (this.uniforms.intensity_gbc.value[2] !== value) {
  42791. this.uniforms.intensity_gbc.value[2] = value;
  42792. this.dispatchEvent({
  42793. type: 'material_property_changed',
  42794. target: this
  42795. });
  42796. }
  42797. }
  42798. get intensityBrightness () {
  42799. return this.uniforms.intensity_gbc.value[1];
  42800. }
  42801. set intensityBrightness (value) {
  42802. if (this.uniforms.intensity_gbc.value[1] !== value) {
  42803. this.uniforms.intensity_gbc.value[1] = value;
  42804. this.dispatchEvent({
  42805. type: 'material_property_changed',
  42806. target: this
  42807. });
  42808. }
  42809. }
  42810. get rgbGamma () {
  42811. return this.uniforms.uRGB_gbc.value[0];
  42812. }
  42813. set rgbGamma (value) {
  42814. if (this.uniforms.uRGB_gbc.value[0] !== value) {
  42815. this.uniforms.uRGB_gbc.value[0] = value;
  42816. this.dispatchEvent({
  42817. type: 'material_property_changed',
  42818. target: this
  42819. });
  42820. }
  42821. }
  42822. get rgbContrast () {
  42823. return this.uniforms.uRGB_gbc.value[2];
  42824. }
  42825. set rgbContrast (value) {
  42826. if (this.uniforms.uRGB_gbc.value[2] !== value) {
  42827. this.uniforms.uRGB_gbc.value[2] = value;
  42828. this.dispatchEvent({
  42829. type: 'material_property_changed',
  42830. target: this
  42831. });
  42832. }
  42833. }
  42834. get rgbBrightness () {
  42835. return this.uniforms.uRGB_gbc.value[1];
  42836. }
  42837. set rgbBrightness (value) {
  42838. if (this.uniforms.uRGB_gbc.value[1] !== value) {
  42839. this.uniforms.uRGB_gbc.value[1] = value;
  42840. this.dispatchEvent({
  42841. type: 'material_property_changed',
  42842. target: this
  42843. });
  42844. }
  42845. }
  42846. get extraGamma () {
  42847. return this.uniforms.uExtraGammaBrightContr.value[0];
  42848. }
  42849. set extraGamma (value) {
  42850. if (this.uniforms.uExtraGammaBrightContr.value[0] !== value) {
  42851. this.uniforms.uExtraGammaBrightContr.value[0] = value;
  42852. this.dispatchEvent({
  42853. type: 'material_property_changed',
  42854. target: this
  42855. });
  42856. }
  42857. }
  42858. get extraBrightness () {
  42859. return this.uniforms.uExtraGammaBrightContr.value[1];
  42860. }
  42861. set extraBrightness (value) {
  42862. if (this.uniforms.uExtraGammaBrightContr.value[1] !== value) {
  42863. this.uniforms.uExtraGammaBrightContr.value[1] = value;
  42864. this.dispatchEvent({
  42865. type: 'material_property_changed',
  42866. target: this
  42867. });
  42868. }
  42869. }
  42870. get extraContrast () {
  42871. return this.uniforms.uExtraGammaBrightContr.value[2];
  42872. }
  42873. set extraContrast (value) {
  42874. if (this.uniforms.uExtraGammaBrightContr.value[2] !== value) {
  42875. this.uniforms.uExtraGammaBrightContr.value[2] = value;
  42876. this.dispatchEvent({
  42877. type: 'material_property_changed',
  42878. target: this
  42879. });
  42880. }
  42881. }
  42882. getRange(attributeName){
  42883. return this.ranges.get(attributeName);
  42884. }
  42885. setRange(attributeName, newRange){
  42886. let rangeChanged = false;
  42887. let oldRange = this.ranges.get(attributeName);
  42888. if(oldRange != null && newRange != null){
  42889. rangeChanged = oldRange[0] !== newRange[0] || oldRange[1] !== newRange[1];
  42890. }else {
  42891. rangeChanged = true;
  42892. }
  42893. this.ranges.set(attributeName, newRange);
  42894. if(rangeChanged){
  42895. this.dispatchEvent({
  42896. type: 'material_property_changed',
  42897. target: this
  42898. });
  42899. }
  42900. }
  42901. get extraRange () {
  42902. return this.uniforms.uExtraRange.value;
  42903. }
  42904. set extraRange (value) {
  42905. if (!(value instanceof Array && value.length === 2)) {
  42906. return;
  42907. }
  42908. if (value[0] === this.uniforms.uExtraRange.value[0] &&
  42909. value[1] === this.uniforms.uExtraRange.value[1]) {
  42910. return;
  42911. }
  42912. this.uniforms.uExtraRange.value = value;
  42913. this._defaultExtraRangeChanged = true;
  42914. this.dispatchEvent({
  42915. type: 'material_property_changed',
  42916. target: this
  42917. });
  42918. }
  42919. get weightRGB () {
  42920. return this.uniforms.wRGB.value;
  42921. }
  42922. set weightRGB (value) {
  42923. if(this.uniforms.wRGB.value !== value){
  42924. this.uniforms.wRGB.value = value;
  42925. this.dispatchEvent({
  42926. type: 'material_property_changed',
  42927. target: this
  42928. });
  42929. }
  42930. }
  42931. get weightIntensity () {
  42932. return this.uniforms.wIntensity.value;
  42933. }
  42934. set weightIntensity (value) {
  42935. if(this.uniforms.wIntensity.value !== value){
  42936. this.uniforms.wIntensity.value = value;
  42937. this.dispatchEvent({
  42938. type: 'material_property_changed',
  42939. target: this
  42940. });
  42941. }
  42942. }
  42943. get weightElevation () {
  42944. return this.uniforms.wElevation.value;
  42945. }
  42946. set weightElevation (value) {
  42947. if(this.uniforms.wElevation.value !== value){
  42948. this.uniforms.wElevation.value = value;
  42949. this.dispatchEvent({
  42950. type: 'material_property_changed',
  42951. target: this
  42952. });
  42953. }
  42954. }
  42955. get weightClassification () {
  42956. return this.uniforms.wClassification.value;
  42957. }
  42958. set weightClassification (value) {
  42959. if(this.uniforms.wClassification.value !== value){
  42960. this.uniforms.wClassification.value = value;
  42961. this.dispatchEvent({
  42962. type: 'material_property_changed',
  42963. target: this
  42964. });
  42965. }
  42966. }
  42967. get weightReturnNumber () {
  42968. return this.uniforms.wReturnNumber.value;
  42969. }
  42970. set weightReturnNumber (value) {
  42971. if(this.uniforms.wReturnNumber.value !== value){
  42972. this.uniforms.wReturnNumber.value = value;
  42973. this.dispatchEvent({
  42974. type: 'material_property_changed',
  42975. target: this
  42976. });
  42977. }
  42978. }
  42979. get weightSourceID () {
  42980. return this.uniforms.wSourceID.value;
  42981. }
  42982. set weightSourceID (value) {
  42983. if(this.uniforms.wSourceID.value !== value){
  42984. this.uniforms.wSourceID.value = value;
  42985. this.dispatchEvent({
  42986. type: 'material_property_changed',
  42987. target: this
  42988. });
  42989. }
  42990. }
  42991. static generateGradientTexture (gradient) {
  42992. let size = 64;
  42993. // create canvas
  42994. let canvas = document.createElement('canvas');
  42995. canvas.width = size;
  42996. canvas.height = size;
  42997. // get context
  42998. let context = canvas.getContext('2d');
  42999. // draw gradient
  43000. context.rect(0, 0, size, size);
  43001. let ctxGradient = context.createLinearGradient(0, 0, size, size);
  43002. for (let i = 0; i < gradient.length; i++) {
  43003. let step = gradient[i];
  43004. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  43005. }
  43006. context.fillStyle = ctxGradient;
  43007. context.fill();
  43008. //let texture = new THREE.Texture(canvas);
  43009. let texture = new CanvasTexture(canvas);
  43010. texture.needsUpdate = true;
  43011. texture.minFilter = LinearFilter;
  43012. texture.wrap = RepeatWrapping;
  43013. texture.repeat = 2;
  43014. // textureImage = texture.image;
  43015. return texture;
  43016. }
  43017. static generateMatcapTexture (matcap) {
  43018. var url = new URL(Potree.resourcePath + "/textures/matcap/" + matcap).href;
  43019. let texture = new TextureLoader().load( url );
  43020. texture.magFilter = texture.minFilter = LinearFilter;
  43021. texture.needsUpdate = true;
  43022. // 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
  43023. // Switch matcap texture on the fly : viewer.scene.pointclouds[0].material.matcap = 'matcap1.jpg';
  43024. // 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
  43025. return texture;
  43026. }
  43027. disableEvents(){
  43028. if(this._hiddenListeners === undefined){
  43029. this._hiddenListeners = this._listeners;
  43030. this._listeners = {};
  43031. }
  43032. };
  43033. enableEvents(){
  43034. this._listeners = this._hiddenListeners;
  43035. this._hiddenListeners = undefined;
  43036. };
  43037. ////////////////////////add
  43038. setProjectedPanos(pano0, pano1, progressValue, easeInOutRatio){
  43039. //this.uniforms.usePanoMap.value = 1
  43040. this.usePanoMap = true;
  43041. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  43042. //pano0.ensureSkyboxReadyForRender();
  43043. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();
  43044. this.uniforms.pano0Position.value.copy(pano0.position);
  43045. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix );
  43046. //pano1.ensureSkyboxReadyForRender();
  43047. this.uniforms.easeInOutRatio.value = easeInOutRatio || 0; //之前做点云和全景混合时加的,为了让点云颜色柔和切换到全景颜色。如不混合就0
  43048. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();
  43049. this.uniforms.pano1Position.value.copy(pano1.position);
  43050. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix );
  43051. //this.updateShaderSource()
  43052. //this.needsUpdate = true;
  43053. }
  43054. stopProjectedPanos(){
  43055. //this.uniforms.usePanoMap.value = 0
  43056. this.usePanoMap = false;
  43057. }
  43058. // copyFrom(from){
  43059. // var a = 10;
  43060. // for(let name of Object.keys(this.uniforms)){
  43061. // this.uniforms[name].value = from.uniforms[name].value;
  43062. // }
  43063. // }
  43064. // copy(from){
  43065. // this.copyFrom(from);
  43066. // }
  43067. }
  43068. var Common = {
  43069. sortByScore: function(list, request, rank){
  43070. var i = request ? Common.filterAll(list, request) : list;
  43071. return 0 === i.length ? null : i = i.map(function(e) {
  43072. return {
  43073. item: e,
  43074. score: rank.reduce(function(t, i) {
  43075. return t + i(e)
  43076. }, 0)
  43077. }
  43078. }).sort(function(e, t) {
  43079. return t.score - e.score;
  43080. })
  43081. }
  43082. ,
  43083. filterAll: function(e, t) {
  43084. return e.filter(function (e) {
  43085. return t.every(function (t) {
  43086. return t(e)
  43087. })
  43088. })
  43089. },
  43090. //---------------
  43091. find : function(list, request, rank, sortByScore ) {
  43092. if(sortByScore){
  43093. var r = this.sortByScore(list, request, rank);
  43094. return r && r[0] && r[0].item
  43095. }else {
  43096. var i = request ? Common.filterAll(list, request) : list;
  43097. return 0 === i.length ? null : (rank && rank.forEach(function(e) {
  43098. i = Common.stableSort(i, e);
  43099. }),
  43100. i[0])
  43101. }
  43102. }
  43103. ,
  43104. stableSort: function(e, f) {//用到排序函数,涉及到两个item相减
  43105. return e.map(function(e, i) {
  43106. return {
  43107. value: e,
  43108. index: i
  43109. }
  43110. }).sort(function(e, u) {
  43111. var n = f(e.value, u.value);
  43112. return 0 !== n ? n : e.index - u.index //似乎就是加多了这一步:若差距为0,按照原顺序
  43113. }).map(function(e) {
  43114. return e.value
  43115. })
  43116. },
  43117. average: function (e, t) {
  43118. if (0 === e.length)
  43119. return null;
  43120. for (var i = 0, n = 0, r = 0; r < e.length; r++) {
  43121. var o = t ? e[r][t] : e[r];
  43122. i += o,
  43123. n++;
  43124. }
  43125. return i / n
  43126. },
  43127. //---------------------------
  43128. getMixedSet : function(arr1, arr2){//交集
  43129. return arr1.filter(item=>arr2.includes(item));
  43130. },
  43131. getUnionSet : function(arr1, arr2){//并集
  43132. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  43133. },
  43134. getDifferenceSet : function(arr1, arr2){//差集 不能识别重复的,如getDifferenceSet([1,2,2],[1,1,2]) 为空
  43135. var arr11 = arr1.filter(item=>!arr2.includes(item));
  43136. var arr22 = arr2.filter(item=>!arr1.includes(item));
  43137. return arr11.concat(arr22)
  43138. },
  43139. getDifferenceSetMuti : function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  43140. var set = [];
  43141. arr.forEach(arr1=>{
  43142. arr1.forEach(item=>{
  43143. var index = set.indexOf(item);
  43144. if(index>-1){
  43145. set.splice(index, 1);
  43146. }else {
  43147. set.push(item);
  43148. }
  43149. });
  43150. });
  43151. return set;
  43152. }
  43153. ,
  43154. CloneJson : function(data){
  43155. var str = JSON.stringify(data);
  43156. return JSON.parse(str)
  43157. }
  43158. ,
  43159. CloneObject : function(copyObj, result, isSimpleCopy, simpleCopyList=[]) {
  43160. //isSimpleCopy 只复制最外层
  43161. //复制json result的可能:普通数字或字符串、普通数组、复杂对象
  43162. simpleCopyList.push(Object3D); //遇到simpleCopyList中的类直接使用不拷贝
  43163. if(!copyObj || typeof copyObj == 'number' || typeof copyObj == 'string' || copyObj instanceof Function || simpleCopyList.some(className => copyObj instanceof className)){
  43164. return copyObj
  43165. }
  43166. result = result || {};
  43167. if (copyObj instanceof Array) {
  43168. return copyObj.map(e=>{
  43169. return this.CloneObject(e)
  43170. })
  43171. }else {
  43172. if(copyObj.clone instanceof Function ){ //解决一部分
  43173. return copyObj.clone()
  43174. }
  43175. }
  43176. for (var key in copyObj) {
  43177. if (copyObj[key] instanceof Object && !isSimpleCopy)
  43178. result[key] = this.CloneObject(copyObj[key]);
  43179. else
  43180. result[key] = copyObj[key];
  43181. //如果是函数类同基本数据,即复制引用
  43182. }
  43183. return result;
  43184. }
  43185. ,
  43186. CloneClassObject :function(copyObj ){//复杂类对象
  43187. var newobj = new copyObj.constructor();
  43188. this.CopyClassObject(newobj, copyObj);
  43189. return newobj
  43190. }
  43191. ,
  43192. CopyClassObject :function(targetObj, copyObj){//复杂类对象
  43193. for(let i in copyObj){
  43194. if(i in copyObj.__proto__)break; //到函数了跳出
  43195. targetObj[i] = this.CloneObject(copyObj[i], null );
  43196. /* else if(copyObj[i].clone instanceof Function ){
  43197. targetObj[i] = copyObj[i].clone()
  43198. }else{
  43199. targetObj[i] = copyObj[i];
  43200. } */
  43201. }
  43202. }
  43203. ,
  43204. ifSame : function(object1, object2){
  43205. if(object1 == object2 )return true // 0 != undefined , 0 == ''
  43206. else if(!object1 || !object2) return false
  43207. else if(object1.constructor != object2.constructor){
  43208. return false
  43209. }else if(object1 instanceof Array ) {
  43210. if(object1.length != object2.length)return false;
  43211. var _object2 = object2.slice(0);
  43212. for(let i=0;i<object1.length;i++){
  43213. var u = _object2.find(e=>ifSame(object1[i], e));
  43214. if(u == void 0 && !_object2.includes(u) && !object1.includes(u))return false;
  43215. else {
  43216. let index = _object2.indexOf(u);
  43217. _object2.splice(index,1);
  43218. }
  43219. }
  43220. return true
  43221. }else if(object1.equals instanceof Function ){//复杂数据仅支持这种,其他的可能卡住?
  43222. return object1.equals(object2)
  43223. }else if(typeof object1 == 'number' || typeof object1 == 'string'){
  43224. if(isNaN(object1) && isNaN(object2))return true
  43225. else return object1 == object2
  43226. }else if(typeof object1 == "object"){
  43227. var keys1 = Object.keys(object1);
  43228. var keys2 = Object.keys(object2);
  43229. if(!ifSame(keys1,keys2))return false;
  43230. for(let i in object1){
  43231. var same = ifSame(object1[i], object2[i]);
  43232. if(!same)return false
  43233. }
  43234. return true
  43235. }else {
  43236. console.log('isSame出现例外');
  43237. }
  43238. }
  43239. ,
  43240. replaceAll : function (str, f, e) {
  43241. //f全部替换成e
  43242. var reg = new RegExp(f, "g"); //创建正则RegExp对象
  43243. return str.replace(reg, e);
  43244. }
  43245. ,
  43246. downloadFile : function(data, filename, cb) {
  43247. var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  43248. save_link.href = data;
  43249. save_link.download = filename;
  43250. var event = document.createEvent('MouseEvents');
  43251. event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  43252. save_link.dispatchEvent(event);
  43253. cb && cb();
  43254. },
  43255. intervalTool:{ //延时update,防止卡顿
  43256. list:[],
  43257. isWaiting:function(name, func, delayTime){
  43258. if(!this.list.includes(name)){ //如果没有该项, 则开始判断
  43259. var needWait = func(); //触发了改变,则等待一段时间后再自动判断
  43260. if(needWait){
  43261. this.list.push(name);
  43262. setTimeout(()=>{
  43263. var a = this.list.indexOf(name);
  43264. this.list.splice(a,1);
  43265. this.isWaiting(name, func, delayTime); //循环
  43266. },delayTime);
  43267. }
  43268. }
  43269. },
  43270. /* wait:function(name, delayTime){
  43271. this.list.push(name);
  43272. setTimeout(()=>{
  43273. },delayTime)
  43274. }, */
  43275. }
  43276. ,
  43277. pushToGroupAuto : function(items, groups, recognizeFunction){//自动分组。 items是将分到一起的组合。items.length = 1 or 2.
  43278. recognizeFunction = recognizeFunction || function(){};
  43279. var atGroups = groups.filter(group=>group.find(
  43280. item => items[0] == item || recognizeFunction(item, items[0]) || items[1] == item || items[1] && recognizeFunction(item, items[1])
  43281. ));
  43282. if(atGroups.length){//在不同组
  43283. //因为items是一组的,所以先都放入组1
  43284. items.forEach(item=> {if(!atGroups[0].includes(item)) atGroups[0].push(item);});
  43285. if(atGroups.length>1){//如果在不同组,说明这两个组需要合并
  43286. var combineGroup = [];
  43287. atGroups.forEach(group=>{
  43288. combineGroup = Common.getUnionSet(combineGroup, group);
  43289. groups.splice(groups.indexOf(group),1);
  43290. });
  43291. groups.push(combineGroup);
  43292. }
  43293. }else {//直接加入为一组
  43294. groups.push(items);
  43295. }
  43296. },
  43297. addOrRemoveDefine(material, defineName, type, value=''){
  43298. let defines = material.defines;
  43299. if(type == 'add'){
  43300. if(defines[defineName] != void 0 && defines[defineName] == value)return
  43301. defines[defineName] = value;
  43302. }else {
  43303. if(defines[defineName] != void 0)return;
  43304. delete defines[defineName];
  43305. }
  43306. material.needsUpdate = true;
  43307. },
  43308. makeTexDontResize(map){//避免贴图因非2的次方而缩小。小心使用
  43309. if(!map || map.image && MathUtils.isPowerOfTwo(map.image.width ) && MathUtils.isPowerOfTwo(map.image.height ))return
  43310. map.wrapS = map.wrapT = ClampToEdgeWrapping; //原默认 RepeatWrapping
  43311. map.minFilter = LinearFilter; // or THREE.NearestFilter 原默认 LinearMipmapLinearFilter
  43312. }
  43313. };
  43314. const planeGeo = new PlaneBufferGeometry(1,1);
  43315. const planeMats$1 = new Map();
  43316. let getPlaneMat = (group, removed)=>{
  43317. let mat = planeMats$1.get(group);
  43318. if(mat)return mat
  43319. var planeMat = new MeshBasicMaterial({
  43320. //color: level == 'removed' ? "#f00" : new THREE.Color(1 - level*0.2, 1,1),
  43321. color: (new Color()).setHSL(Math.random(), 0.5, 0.9) ,
  43322. //color: (new THREE.Color()).setHSL(removed ? 0 : 0.6, Math.random(), 0.9/* Math.random() */) ,
  43323. transparent:true,
  43324. side:2,
  43325. opacity: removed ? 0.3 : 0.9,
  43326. });
  43327. planeMats$1.set(group, planeMat);
  43328. return planeMat
  43329. };
  43330. class PointCloudOctreeNode extends PointCloudTreeNode {
  43331. constructor () {
  43332. super();
  43333. //this.children = {};
  43334. this.children = [];
  43335. this.sceneNode = null;
  43336. this.octree = null;
  43337. }
  43338. getNumPoints () {
  43339. return this.geometryNode.numPoints;
  43340. }
  43341. isLoaded () {
  43342. return true;
  43343. }
  43344. isTreeNode () {
  43345. return true;
  43346. }
  43347. isGeometryNode () {
  43348. return false;
  43349. }
  43350. getLevel () {
  43351. return this.geometryNode.level;
  43352. }
  43353. getBoundingSphere () {
  43354. return this.geometryNode.boundingSphere;
  43355. }
  43356. getBoundingBox () {
  43357. return this.geometryNode.boundingBox;
  43358. }
  43359. getChildren () {
  43360. let children = [];
  43361. for (let i = 0; i < 8; i++) {
  43362. if (this.children[i]) {
  43363. children.push(this.children[i]);
  43364. }
  43365. }
  43366. return children;
  43367. }
  43368. getPointsInBox(boxNode){
  43369. if(!this.sceneNode){
  43370. return null;
  43371. }
  43372. let buffer = this.geometryNode.buffer;
  43373. let posOffset = buffer.offset("position");
  43374. let stride = buffer.stride;
  43375. let view = new DataView(buffer.data);
  43376. let worldToBox = boxNode.matrixWorld.clone().invert();
  43377. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  43378. let inBox = [];
  43379. let pos = new Vector4();
  43380. for(let i = 0; i < buffer.numElements; i++){
  43381. let x = view.getFloat32(i * stride + posOffset + 0, true);
  43382. let y = view.getFloat32(i * stride + posOffset + 4, true);
  43383. let z = view.getFloat32(i * stride + posOffset + 8, true);
  43384. pos.set(x, y, z, 1);
  43385. pos.applyMatrix4(objectToBox);
  43386. if(-0.5 < pos.x && pos.x < 0.5){
  43387. if(-0.5 < pos.y && pos.y < 0.5){
  43388. if(-0.5 < pos.z && pos.z < 0.5){
  43389. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  43390. inBox.push(new Vector3(pos.x, pos.y, pos.z));
  43391. }
  43392. }
  43393. }
  43394. }
  43395. return inBox;
  43396. }
  43397. get name () {
  43398. return this.geometryNode.name;
  43399. }
  43400. };
  43401. class PointCloudOctree extends PointCloudTree {
  43402. constructor (geometry, material) {
  43403. super();
  43404. //this.pointBudget = Infinity;
  43405. this.pcoGeometry = geometry;
  43406. this.boundingBox = this.pcoGeometry.tightBoundingBox;//this.pcoGeometry.boundingBox; //boundingBox是正方体,所以换掉
  43407. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  43408. this.material = material || new PointCloudMaterial$1();
  43409. this.visiblePointsTarget = 2 * 1000 * 1000;
  43410. this.minimumNodePixelSize = 150;
  43411. this.level = 0;
  43412. this.position.copy(geometry.offset);
  43413. this.updateMatrix();
  43414. this.nodeMaxLevel = 0;//add
  43415. this.maxLevel = Infinity;
  43416. this.temp = { sizeFitToLevel:{}, opacity:{}};//add
  43417. //add
  43418. this.panos = [];
  43419. this.matrixAutoUpdate = false; //最好禁止updateMatrix 直接使用matrixWorld
  43420. this.orientationUser = 0;
  43421. this.translateUser = new Vector3;
  43422. this.rotateMatrix = new Matrix4;
  43423. this.transformMatrix = new Matrix4;// 数据集的变化矩阵
  43424. this.transformInvMatrix = new Matrix4;
  43425. this.rotateInvMatrix = new Matrix4;
  43426. this.nodeMaxLevelPredict = this.predictNodeMaxLevel();//预测maxNodeLevel
  43427. this.testMaxNodeCount = this.testMaxNodeCount2 = 0;
  43428. this.material.spacing = this.pcoGeometry.spacing;//初始化一下 以便于设置pointsize
  43429. {
  43430. let priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  43431. let selected = "rgba";
  43432. for(let attributeName of priorityQueue){
  43433. let attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  43434. if(!attribute){
  43435. continue;
  43436. }
  43437. let min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  43438. let max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  43439. let range_min = new Vector3(...min);
  43440. let range_max = new Vector3(...max);
  43441. let range = range_min.distanceTo(range_max);
  43442. if(range === 0){
  43443. continue;
  43444. }
  43445. selected = attributeName;
  43446. break;
  43447. }
  43448. this.material.activeAttributeName = selected;
  43449. }
  43450. this.showBoundingBox = false;
  43451. this.boundingBoxNodes = [];
  43452. this.loadQueue = [];
  43453. this.visibleBounds = new Box3();
  43454. this.visibleNodes = [];
  43455. this.visibleGeometry = [];
  43456. this.generateDEM = false;
  43457. this.profileRequests = [];
  43458. this.name = '';
  43459. this._visible = true;
  43460. //this._isVisible = true//add
  43461. //this.unvisibleReasons = []
  43462. {
  43463. let box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()]
  43464. .find(v => v !== undefined);
  43465. this.updateMatrixWorld(true);
  43466. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  43467. let bMin = box.min.z;
  43468. let bMax = box.max.z;
  43469. this.material.heightMin = bMin;
  43470. this.material.heightMax = bMax;
  43471. }
  43472. // TODO read projection from file instead
  43473. this.projection = geometry.projection;
  43474. this.fallbackProjection = geometry.fallbackProjection;
  43475. this.root = this.pcoGeometry.root;
  43476. this.pcoGeometry.addEventListener('updateNodeMaxLevel', this.updateNodeMaxLevel.bind(this));
  43477. this.isPointcloud = true; //add
  43478. }
  43479. /*
  43480. 注释:node的level从最大的box 0开始。
  43481. 且加载任意一个node必定也会加载它的所有祖先。(如visibleNodes中有一个level为4,则一定有3,2,1,0)
  43482. visibleNodes就是所有可见的node,比如:
  43483. 如果相机在0这个位置朝下,这时候的visibleNodes中只有一个level为0的node;
  43484. 而如果朝上看,上方的几个node如果在视野中占据足够大的位置的话,就会加载。
  43485. 如果相机在2这个位置朝上,这时候的visibleNodes中所包含的level为: 0,1,2
  43486. ________________
  43487. | | | |
  43488. |__2| | |
  43489. | 1 | 1 |
  43490. |_______|_______|
  43491. | |
  43492. | |
  43493. | 0 |
  43494. |_______________|
  43495. 查看box可在potree中开启
  43496. */
  43497. updateNodeMaxLevel(e){//目前点云包含node的最高level
  43498. var level = Math.max(e.level, this.nodeMaxLevel);
  43499. if(level != this.nodeMaxLevel){
  43500. this.nodeMaxLevel = level;
  43501. //viewer.dispatchEvent({type:'updateNodeMaxLevel', pointcloud: this, nodeMaxLevel:level})
  43502. //console.log('updateNodeMaxLevel ' + this.dataset_id + " : "+ this.nodeMaxLevel)
  43503. this.setPointLevel();//重新计算
  43504. if(!Potree.settings.sizeFitToLevel){
  43505. this.changePointSize();
  43506. }
  43507. }
  43508. }//注:在没有加载到真实的 nodeMaxLevel之前,点云会显示得偏大
  43509. //panoEdit时比预测值小很多?
  43510. testMaxNodeLevel(){//手动使maxLevel达到最高,从而迫使updateNodeMaxLevel。 因为Potree.settings.pointDensity 不为 'high'时,maxLevel不是所加载的最高,就很容易加载不出下一个层级,导致无法知道nodeMaxLevel
  43511. if(this.testMaxNodeLevelDone ) return
  43512. //if(this.nodeMaxLevel > this.nodeMaxLevelPredict.min )return
  43513. if( this.nodeMaxLevel==0 )return true
  43514. if( !viewer.atDatasets.includes(this))return true //否则老远就count++
  43515. let levels = this.visibleNodes.map(e=>e.getLevel());
  43516. let actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  43517. if(actMaxLevel < this.maxLevel)return true// 还没加载到能加载到的最高。 但在细节设置较低时,排除作用微弱。
  43518. //尝试加载出更高级的level
  43519. let old = this.maxLevel;
  43520. this.maxLevel = 12;
  43521. //var visibleNodes1 = this.visibleNodes.map(e=>e.getLevel())
  43522. //console.log('visibleNodes1',visibleNodes1)
  43523. Potree.updatePointClouds([this], viewer.scene.getActiveCamera(), viewer.mainViewport.resolution );
  43524. //不在camera可视范围内还是加载不出来。即使临时修改位置
  43525. var visibleNodes2 = this.visibleNodes.map(e=>e.getLevel());
  43526. //console.log('visibleNodes2',visibleNodes2)
  43527. this.maxLevel = old;
  43528. this.testMaxNodeCount ++;
  43529. if(this.testMaxNodeCount > 500){
  43530. console.log('testMaxNodeLevel次数超出,强制结束:',this.dataset_id, this.nodeMaxLevel, this.nodeMaxLevelPredict.min);
  43531. this.testMaxNodeLevelDone = 'moreThanMaxCount';
  43532. return; //在可以看见点云的情况下,超时,有可能是预测的max是错的
  43533. }
  43534. if(this.nodeMaxLevel < this.nodeMaxLevelPredict.min) return true //仍需要继续testMaxNodeLevel
  43535. this.testMaxNodeCount2 ++; // 已经> this.nodeMaxLevelPredict.min 后,开始计数。因为min可能低于真实nodeMaxLevel所以要再试几次
  43536. /* if(this.name == 'SS-t-CWmVgzP4XU'){
  43537. console.log('SS-t-CWmVgzP4XU count++')
  43538. } */
  43539. if(this.testMaxNodeCount2 < 50) return true //再试几次 ( 主要是细节调得低时需要多测几次才加载到
  43540. this.testMaxNodeLevelDone = true;
  43541. }
  43542. setPointLevel(){
  43543. var pointDensity = Potree.settings.pointDensity;
  43544. var config = Potree.config.pointDensity[pointDensity];
  43545. if(!config)return
  43546. /* if(this.testingMaxLevel){
  43547. this.maxLevel = 12;//先加载到最大的直到测试完毕。由于5个level为一组来加载,所以如果写4最高能加载到5,如果写5最高能加载到下一个级别的最高也就是10
  43548. //console.log('maxLevel: '+e.maxLevel + ' testingMaxLevel中 ' )
  43549. }else{ */
  43550. let percent = config.percentByUser && Potree.settings.UserDensityPercent != void 0 ? Potree.settings.UserDensityPercent : config.maxLevelPercent;
  43551. this.maxLevel = Math.round( percent * this.nodeMaxLevel);
  43552. //console.log('maxLevel: '+e.maxLevel + ', density : '+Potree.settings.pointDensity, ", percent :"+percent);
  43553. if(Potree.settings.sizeFitToLevel){
  43554. this.changePointSize();
  43555. }
  43556. this.changePointOpacity();
  43557. //}
  43558. }
  43559. //预测可能的nodeMaxLevel:
  43560. predictNodeMaxLevel(){//预测maxNodeLevel。 可能只适用于我们相机拍的点云
  43561. let spacing = {min:0.005, max:0.014};//最小节的两点间的距离 ,获得方法:spacing / Math.pow(2, nodeMaxLevel)。 目前观测的我们自己拍的这个数值的范围大概是这样
  43562. let min = Math.log2(this.material.spacing / spacing.max); //有见过最大是0.01368
  43563. let max = Math.log2(this.material.spacing / spacing.min); //大部分是 0.006
  43564. //console.log('predictNodeMaxLevel:', this.name , min, max )
  43565. return {min, max}
  43566. }
  43567. getHighestNodeSpacing(){
  43568. return this.material.spacing / Math.pow(2, this.nodeMaxLevel) //前提是这个nodeMaxLevel是准确的
  43569. }
  43570. setName (name) {
  43571. if (this.name !== name) {
  43572. this.name = name;
  43573. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  43574. }
  43575. }
  43576. getName () {
  43577. return this.name;
  43578. }
  43579. getAttribute(name){
  43580. const attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  43581. if(attribute){
  43582. return attribute;
  43583. }else {
  43584. return null;
  43585. }
  43586. }
  43587. getAttributes(){
  43588. return this.pcoGeometry.pointAttributes;
  43589. }
  43590. toTreeNode (geometryNode, parent) {
  43591. let node = new PointCloudOctreeNode();
  43592. // if(geometryNode.name === "r40206"){
  43593. // console.log("creating node for r40206");
  43594. // }
  43595. let sceneNode = new Points(geometryNode.geometry, this.material); //好像没什么用
  43596. sceneNode.name = geometryNode.name;
  43597. sceneNode.position.copy(geometryNode.boundingBox.min);
  43598. sceneNode.frustumCulled = false;
  43599. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  43600. if (material.program) {
  43601. _this.getContext().useProgram(material.program.program);
  43602. if (material.program.getUniforms().map.level) {
  43603. let level = geometryNode.getLevel();
  43604. material.uniforms.level.value = level;
  43605. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  43606. }
  43607. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  43608. let vnStart = this.visibleNodeTextureOffsets.get(node);
  43609. material.uniforms.vnStart.value = vnStart;
  43610. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  43611. }
  43612. if (material.program.getUniforms().map.pcIndex) {
  43613. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  43614. material.uniforms.pcIndex.value = i;
  43615. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  43616. }
  43617. }
  43618. };
  43619. // { // DEBUG
  43620. // let sg = new THREE.SphereGeometry(1, 16, 16);
  43621. // let sm = new THREE.MeshNormalMaterial();
  43622. // let s = new THREE.Mesh(sg, sm);
  43623. // s.scale.set(5, 5, 5);
  43624. // s.position.copy(geometryNode.mean)
  43625. // .add(this.position)
  43626. // .add(geometryNode.boundingBox.min);
  43627. //
  43628. // viewer.scene.scene.add(s);
  43629. // }
  43630. node.geometryNode = geometryNode;
  43631. node.sceneNode = sceneNode;
  43632. node.pointcloud = this;
  43633. node.children = [];
  43634. //for (let key in geometryNode.children) {
  43635. // node.children[key] = geometryNode.children[key];
  43636. //}
  43637. for(let i = 0; i < 8; i++){
  43638. node.children[i] = geometryNode.children[i];
  43639. }
  43640. if (!parent) {
  43641. this.root = node;
  43642. this.add(sceneNode);
  43643. } else {
  43644. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  43645. parent.sceneNode.add(sceneNode);
  43646. parent.children[childIndex] = node;
  43647. }
  43648. let disposeListener = function () {
  43649. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  43650. parent.sceneNode.remove(node.sceneNode);
  43651. parent.children[childIndex] = geometryNode;
  43652. };
  43653. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  43654. //this.buildTexMesh(geometryNode,sceneNode)
  43655. return node;
  43656. }
  43657. buildTexMesh11(geometryNode,sceneNode){
  43658. // viewer.scene.pointclouds.forEach(a=>a.areaPlanes.forEach(e=>e.material = viewer.images360.cube.material))
  43659. //还是无法避免不在同一个平面的点被识别到同一个面上,然后法向都算错了。 另外还有就是破面太多。虽然能算出地板也不错。或者只去算水平面和垂直面。
  43660. let startTime = Date.now();
  43661. if(!this.splitSprites){
  43662. let splitSprites = new Object3D;
  43663. splitSprites.name = 'splitSprites_'+this.name;
  43664. splitSprites.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43665. splitSprites.matrix.copy(this.matrix);
  43666. splitSprites.matrixWorld.copy(this.matrixWorld);
  43667. this.splitSprites = splitSprites;
  43668. viewer.scene.scene.add(splitSprites);
  43669. this.areaPlanes = [];
  43670. }
  43671. if(this.texMeshUseLevel == void 0 || geometryNode.level == this.texMeshUseLevel){//只需要某一层level的点
  43672. let showPointLabel = true, showCenterLabel = false;
  43673. //let spritesGeo = new THREE.BufferGeometry();
  43674. let scaleRatio = 1.4; //稍微放大些,填满缝隙
  43675. let spriteWidth1 = this.material.spacing / Math.pow(2, geometryNode.level);
  43676. if(spriteWidth1 > 3)return
  43677. let spriteWidth = spriteWidth1 * scaleRatio;
  43678. if(this.texMeshUseLevel == void 0 ){
  43679. this.texMeshUseLevel = geometryNode.level;
  43680. console.log('texMeshUseLevel ',geometryNode.level);
  43681. }
  43682. let geometry = geometryNode.geometry;
  43683. let count = geometry.attributes.position.count;
  43684. let end = Math.min(count, 6000);
  43685. let start = Math.min(5000, end);
  43686. console.warn('check points count:', end-start);
  43687. let position = geometry.attributes.position.array;
  43688. let normal = geometry.attributes.normal.array;
  43689. let i;
  43690. let up = new Vector3(0,1,0) , zeroVec = new Vector3; //up写成z向上居然结果一样
  43691. let positions = [];
  43692. let normals = [];
  43693. let newPositions = [];
  43694. let newIndices = [];
  43695. let groupMaxPointCount = 1000 ;//太多找环会崩
  43696. let minDisSquare = Math.pow(spriteWidth1 * 1.8 , 2 ); //这个数太小就连不上啦 1.65太小
  43697. let minDot = Math.cos(MathUtils.degToRad(5));//括号内是最小偏差角度, 20太大。太大的话会将立方体的相邻两面视为一个面。
  43698. //根据相邻点位置和角度是否相近来分组。有风险:两大区域可能因为一个模棱两可中间点连接在一起。
  43699. let closeGroups = [];
  43700. let groupTolerateMaxPoint = 6;//组内点<=这个数的最后会被删除
  43701. let removedCount = 0;
  43702. let useGroupCount = 0;
  43703. let splitSprites = new Object3D;
  43704. splitSprites.name = 'sub_splitSprites_'+geometryNode.name;
  43705. splitSprites.position.copy(sceneNode.position);
  43706. splitSprites.rotation.copy(sceneNode.rotation);
  43707. this.splitSprites.add(splitSprites);
  43708. for(i=start;i<end;i++){
  43709. let pos = new Vector3(position[3*i], position[3*i+1], position[3*i+2] );
  43710. let nor = new Vector3(normal[3*i],normal[3*i+1],normal[3*i+2]);
  43711. pos.nor = nor;
  43712. pos.index = i;
  43713. positions.push(pos);
  43714. normals.push(nor);
  43715. let groups = closeGroups.filter(group=>{
  43716. if(group.length>groupMaxPointCount)return //满员了
  43717. var hasClosed = group.some(p=>{
  43718. var dis = p.distanceToSquared(pos);
  43719. var dot = p.nor.dot(nor);
  43720. if(dis<minDisSquare && dot>minDot){
  43721. //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
  43722. return dis / minDisSquare - p.nor.dot(nor) < 0
  43723. }
  43724. });
  43725. return hasClosed
  43726. });
  43727. if(groups.length == 0){//创建一个新的
  43728. var newGroup = [];
  43729. closeGroups.push(newGroup);
  43730. groups = [newGroup];
  43731. }
  43732. if(groups.length == 1){//直接加入原有的
  43733. pos.belongTo = groups[0];
  43734. }else if(groups.length>1){ // comebine多个组成一个
  43735. let newBigGroup = [];
  43736. groups.forEach(e=>{
  43737. newBigGroup.push(...e);
  43738. let index = closeGroups.indexOf(e);
  43739. closeGroups.splice(index, 1);
  43740. });
  43741. closeGroups.push(newBigGroup);
  43742. pos.belongTo = newBigGroup;
  43743. newBigGroup.forEach(e=>{e.belongTo = newBigGroup;});
  43744. }
  43745. pos.belongTo.push(pos);
  43746. }
  43747. closeGroups.forEach((points,index)=>{//建造面
  43748. if(points.length <= groupTolerateMaxPoint ){
  43749. /* let sprite = new THREE.Mesh(planeGeo, getPlaneMat(pos.belongTo, true))
  43750. sprite.lookAt(nor);
  43751. sprite.position.copy(pos)
  43752. sprite.scale.set(spriteWidth,spriteWidth,spriteWidth)
  43753. sprite.name = geometryNode.name+'_index'+i
  43754. splitSprites.add(sprite)
  43755. removedCount ++; */
  43756. removedCount += points.length;
  43757. return
  43758. }
  43759. useGroupCount ++;
  43760. points.sort(function(a,b){
  43761. return a.index - b.index
  43762. });
  43763. console.log(`开始解析 ${geometryNode.name} - 第${index}组,总第${points[0].index}个点,组内有${points.length}个点`);
  43764. let planeMat = getPlaneMat(points, true);
  43765. if(showPointLabel){
  43766. points.forEach((p,i)=>{
  43767. var label = new TextSprite({
  43768. text : index+"-"+i+" ("+p.index+")"+geometryNode.name, dontFixOrient:true,
  43769. backgroundColor: {r: planeMat.color.r*255, g: planeMat.color.g*255, b: planeMat.color.b*255, a:0.6},
  43770. });
  43771. label.lookAt(p.nor);
  43772. label.position.copy(p);
  43773. label.scale.set(spriteWidth/3, spriteWidth/3, spriteWidth/3);
  43774. splitSprites.add(label);
  43775. /* let sprite = new THREE.Mesh(planeGeo,planeMat)
  43776. sprite.lookAt(p.nor);
  43777. sprite.position.copy(p)
  43778. sprite.scale.set(spriteWidth/3,spriteWidth/3,spriteWidth/3)
  43779. sprite.name = geometryNode.name+'_group'+index+"_"+ i
  43780. splitSprites.add(sprite) */
  43781. });
  43782. }
  43783. var avePos = points.reduce(function(total, currentValue){
  43784. return total.add(currentValue)
  43785. }, new Vector3).multiplyScalar(1/points.length);
  43786. let planeNormals = [];
  43787. {//获得planeNormals
  43788. //随机找两个距离远的点算normal。 按距离排序后, //抽取若干个点,然后算两两之间的法线,其中距离远的多抽取几个。
  43789. var sortPoints = points.slice(0).sort(function(a,b){
  43790. return a.distanceToSquared(avePos) - b.distanceToSquared(avePos)
  43791. });//从小到大
  43792. var pickPoints;
  43793. var length = sortPoints.length;
  43794. if(length>=7){
  43795. var ratio = [0.02,0.15,0.4,0.55,0.7,0.86,0.99];
  43796. var index = ratio.map(e=>Math.round(e * (length-1)));
  43797. //console.log('index ',index)
  43798. pickPoints = index.map(e=>sortPoints[e]);
  43799. }else {
  43800. pickPoints = sortPoints;
  43801. }
  43802. //console.log('pickPoints', pickPoints)
  43803. let num = pickPoints.length;
  43804. for(let i=0;i<num;i++){//任意一个三角形能算出一个normal
  43805. for(let j=i+1;j<num;j++){
  43806. for(let u=j+1;u<num;u++){
  43807. var p1 = pickPoints[i];
  43808. var p2 = pickPoints[j];
  43809. var p3 = pickPoints[u];
  43810. let vec1 = new Vector3().subVectors(p1,p3);
  43811. let vec2 = new Vector3().subVectors(p2,p3);
  43812. let nor = vec1.cross(vec2).normalize();
  43813. if(planeNormals[0]){
  43814. if(nor.dot(planeNormals[0])<0)nor.negate(); //反向下
  43815. }
  43816. console.log('nor',nor);
  43817. planeNormals.push(nor);
  43818. }
  43819. }
  43820. }
  43821. }
  43822. var aveNor = planeNormals.reduce(function(total, currentValue){
  43823. return total.add(currentValue)
  43824. }, new Vector3).normalize();
  43825. console.log('aveNor',aveNor, 'avePos' ,avePos, index);
  43826. if(showCenterLabel){
  43827. var label = new TextSprite({
  43828. //index+"-"+i+" ("+p.index+")"+geometryNode.name
  43829. text : `我是${index}组 ${geometryNode.name} 中心点`, dontFixOrient:true,
  43830. backgroundColor: {r: planeMat.color.r*255, g: planeMat.color.g*255, b: planeMat.color.b*255, a:0.6},
  43831. });
  43832. label.lookAt(aveNor);
  43833. label.position.copy(avePos);
  43834. label.scale.set(spriteWidth, spriteWidth, spriteWidth);
  43835. splitSprites.add(label);
  43836. }
  43837. var facePlane = new Plane().setFromNormalAndCoplanarPoint(aveNor, avePos );
  43838. var coplanarPoints = points.map(p=> facePlane.projectPoint(p, new Vector3() ));
  43839. var originPoint0 = coplanarPoints[0].clone();
  43840. var qua = math.getQuaBetween2Vector(facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  43841. let points2d = coplanarPoints.map(e=>e.clone().applyQuaternion(qua));
  43842. let quaInverse = qua.clone().invert();
  43843. //--------------------
  43844. let lines = [];
  43845. points2d.forEach((p,j)=>{
  43846. p.id = j;
  43847. for(let i=0;i<j;i++){
  43848. if(p.distanceToSquared(points2d[i])<minDisSquare*1.5){
  43849. lines.push({p1:i,p2:j});
  43850. }
  43851. }
  43852. });
  43853. console.log('points count:',points2d.length, 'lines:',lines);
  43854. var rings = searchRings({
  43855. points:points2d,
  43856. lines,
  43857. onlyGetOutRing:true,
  43858. precision: Math.max(spriteWidth1/10, 0.01)
  43859. });
  43860. console.log( 'rings:', rings );//mesh间可能重叠 但换上贴图材质应该看不出(但只要searchRings时getSliceLines就不会重叠)
  43861. if(!rings)return
  43862. let planeMat2 = planeMat.clone(); planeMat2.opacity = 0.5;
  43863. var firstPos = points2d[0].clone();
  43864. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  43865. firstPos.applyQuaternion(quaInverse);
  43866. var vec = originPoint0.clone().sub(firstPos);
  43867. rings.forEach(ring=>{
  43868. var shapeGeo = MeshDraw.getShapeGeo(ring.points);
  43869. var areaPlane = new Mesh(shapeGeo, planeMat2);
  43870. areaPlane.quaternion.copy(quaInverse);
  43871. areaPlane.position.copy(vec);
  43872. areaPlane.name = 'areaPlane_'+index;
  43873. splitSprites.add(areaPlane);
  43874. this.areaPlanes.push(areaPlane);
  43875. });
  43876. });
  43877. console.log(geometryNode.name, '中:');
  43878. console.log('removed point count: ', removedCount/* splitSprites.children.length */);
  43879. console.log(closeGroups);
  43880. console.log('comebine mesh Len:', useGroupCount);
  43881. /*
  43882. spritesGeo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(newPositions), 3));
  43883. spritesGeo.setIndex( newIndices );
  43884. let sprites = new THREE.Mesh(spritesGeo, getPlaneMat('use'))
  43885. sprites.name = geometryNode.name
  43886. sprites.position.copy(sceneNode.position)
  43887. sprites.rotation.copy(sceneNode.rotation)
  43888. sceneNode.sprites = sprites
  43889. sprites.pointsNode = sceneNode
  43890. if(geometryNode.level == 0){
  43891. let root = new THREE.Object3D;
  43892. root.name = 'spriteNodeRoot'
  43893. root.matrixAutoUpdate = false //同pointcloud一样不自动更新,直接使用
  43894. root.matrix.copy(this.matrix)
  43895. root.matrixWorld.copy(this.matrixWorld)
  43896. viewer.scene.scene.add(root)
  43897. this.spriteNodeRoot = root
  43898. }
  43899. this.spriteNodeRoot.add(sprites) */
  43900. console.log('computeTime: ' + (Date.now() - startTime));
  43901. }
  43902. //------------------
  43903. /*
  43904. viewer.scene.pointclouds[0].spriteNodeRoot.traverse(e=>e.material && (e.material = viewer.images360.cube.material))
  43905. viewer.scene.scene.children[12].visible = false
  43906. */
  43907. }
  43908. buildTexMesh(geometryNode,sceneNode){
  43909. if(geometryNode.level <= 0){
  43910. let startTime = Date.now();
  43911. let splitSprites = new Object3D;
  43912. splitSprites.name = 'splitSprites_'+geometryNode.name;
  43913. splitSprites.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43914. splitSprites.matrix.copy(this.matrix);
  43915. splitSprites.matrixWorld.copy(this.matrixWorld);
  43916. viewer.scene.scene.add(splitSprites);
  43917. let spritesGeo = new BufferGeometry();
  43918. let scaleRatio = 1.4; //稍微放大些,填满缝隙
  43919. let spriteWidth1 = this.material.spacing / Math.pow(2, geometryNode.level);
  43920. let spriteWidth = spriteWidth1 * scaleRatio;
  43921. console.log('spriteWidth:',spriteWidth);
  43922. const removeChip = false;
  43923. let geometry = geometryNode.geometry;
  43924. let count = geometry.attributes.position.count;
  43925. //count = 4000
  43926. let position = geometry.attributes.position.array;
  43927. let normal = geometry.attributes.normal.array;
  43928. let i;
  43929. let up = new Vector3(0,1,0) , zeroVec = new Vector3; //up写成z向上居然结果一样
  43930. let positions = [];
  43931. let normals = [];
  43932. let newPositions = [];
  43933. //let newNormals = [];
  43934. let newIndices = [];
  43935. let cornerPoints = [new Vector3(-1,1,0),new Vector3(1,1,0),new Vector3(-1,-1,0),new Vector3(1,-1,0) ];
  43936. let indices = [0, 2, 1, 2, 3, 1];
  43937. cornerPoints.forEach(e=>e.multiplyScalar(spriteWidth/2));
  43938. let minDisSquare = spriteWidth1 * spriteWidth1 * 1.5;
  43939. let closeGroups = [];
  43940. let groupTolerateMaxPoint = 4;//组内点<=这个数的最后会被删除
  43941. let removedCount = 0;
  43942. for(i=0;i<count;i++){
  43943. let pos = new Vector3(position[3*i], position[3*i+1], position[3*i+2] );
  43944. let nor = new Vector3(normal[3*i],normal[3*i+1],normal[3*i+2]);
  43945. pos.nor = nor;
  43946. positions.push(pos);
  43947. normals.push(nor);
  43948. if(removeChip){
  43949. let groups = closeGroups.filter(group=>{
  43950. var hasClosed = group.some(p=>{
  43951. var dis = p.distanceToSquared(pos);
  43952. if(dis<minDisSquare){
  43953. //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
  43954. return dis / minDisSquare - p.nor.dot(nor) < 0
  43955. }
  43956. });
  43957. return hasClosed
  43958. });
  43959. if(groups.length == 0){//创建一个新的
  43960. var newGroup = [];
  43961. closeGroups.push(newGroup);
  43962. groups = [newGroup];
  43963. }
  43964. if(groups.length == 1){//直接加入原有的
  43965. pos.belongTo = groups[0];
  43966. }else if(groups.length>1){ // comebine多个组成一个
  43967. let newBigGroup = [];
  43968. groups.forEach(e=>{
  43969. newBigGroup.push(...e);
  43970. let index = closeGroups.indexOf(e);
  43971. closeGroups.splice(index, 1);
  43972. });
  43973. closeGroups.push(newBigGroup);
  43974. pos.belongTo = newBigGroup;
  43975. newBigGroup.forEach(e=>{e.belongTo = newBigGroup;});
  43976. }
  43977. pos.belongTo.push(pos);
  43978. }
  43979. }
  43980. for(i=0;i<count;i++){
  43981. let pos = positions[i];
  43982. let nor = normals[i];
  43983. if(Math.abs(nor.z)>0.2)continue
  43984. if(removeChip){
  43985. if(pos.belongTo.length <= groupTolerateMaxPoint){
  43986. let sprite = new Mesh(planeGeo, getPlaneMat(pos.belongTo, true));
  43987. sprite.lookAt(nor);
  43988. sprite.position.copy(pos);
  43989. sprite.scale.set(spriteWidth,spriteWidth,spriteWidth);
  43990. sprite.name = geometryNode.name+'_index'+i;
  43991. splitSprites.add(sprite);
  43992. removedCount ++;
  43993. continue
  43994. }else {
  43995. /*
  43996. let sprite = new THREE.Mesh(planeGeo, getPlaneMat(pos.belongTo))
  43997. sprite.lookAt(nor);
  43998. sprite.position.copy(pos)
  43999. sprite.scale.set(spriteWidth/3,spriteWidth/3,spriteWidth/3)
  44000. sprite.name = geometryNode.name+'_index'+i
  44001. splitSprites.add(sprite)
  44002. */
  44003. }
  44004. }
  44005. let matrix = (new Matrix4).lookAt( nor, zeroVec, up);
  44006. matrix.elements[12] = pos.x;
  44007. matrix.elements[13] = pos.y;
  44008. matrix.elements[14] = pos.z;
  44009. cornerPoints.forEach(p=>{
  44010. let point = p.clone();
  44011. point.applyMatrix4(matrix);
  44012. newPositions.push(...point.toArray());
  44013. //newNormals
  44014. });
  44015. indices.forEach(index=>{
  44016. newIndices.push(index + i*4);
  44017. });
  44018. }
  44019. /* closeGroups.forEach(e=>{
  44020. if(e.length <= groupTolerateMaxPoint )return
  44021. }) */
  44022. console.log('removed count: ', removedCount/* splitSprites.children.length */);
  44023. console.log(closeGroups);
  44024. console.log('computeTime: ' + (Date.now() - startTime));
  44025. spritesGeo.setAttribute('position', new Float32BufferAttribute(new Float32Array(newPositions), 3));
  44026. spritesGeo.setIndex( newIndices );
  44027. let sprites = new Mesh(spritesGeo, getPlaneMat('use'));
  44028. sprites.name = geometryNode.name;
  44029. sprites.position.copy(sceneNode.position);
  44030. sprites.rotation.copy(sceneNode.rotation);
  44031. sceneNode.sprites = sprites;
  44032. sprites.pointsNode = sceneNode;
  44033. if(geometryNode.level == 0){
  44034. let root = new Object3D;
  44035. root.name = 'spriteNodeRoot';
  44036. root.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  44037. root.matrix.copy(this.matrix);
  44038. root.matrixWorld.copy(this.matrixWorld);
  44039. viewer.scene.scene.add(root);
  44040. this.spriteNodeRoot = root;
  44041. }
  44042. this.spriteNodeRoot.add(sprites);
  44043. viewer.setObjectLayers(sprites,'sceneObjects');
  44044. }
  44045. }
  44046. updateVisibleBounds () {
  44047. let leafNodes = [];
  44048. for (let i = 0; i < this.visibleNodes.length; i++) {
  44049. let node = this.visibleNodes[i];
  44050. let isLeaf = true;
  44051. for (let j = 0; j < node.children.length; j++) {
  44052. let child = node.children[j];
  44053. if (child instanceof PointCloudOctreeNode) {
  44054. isLeaf = isLeaf && !child.sceneNode.visible;
  44055. } else if (child instanceof PointCloudOctreeGeometryNode) {
  44056. isLeaf = true;
  44057. }
  44058. }
  44059. if (isLeaf) {
  44060. leafNodes.push(node);
  44061. }
  44062. }
  44063. this.visibleBounds.min = new Vector3(Infinity, Infinity, Infinity);
  44064. this.visibleBounds.max = new Vector3(-Infinity, -Infinity, -Infinity);
  44065. for (let i = 0; i < leafNodes.length; i++) {
  44066. let node = leafNodes[i];
  44067. this.visibleBounds.expandByPoint(node.getBoundingBox().min);
  44068. this.visibleBounds.expandByPoint(node.getBoundingBox().max);
  44069. }
  44070. }
  44071. updateMaterial (material, visibleNodes, camera, renderer, resolution) {
  44072. material.fov = camera.fov * (Math.PI / 180);
  44073. /* material.screenWidth = renderer.domElement.clientWidth;
  44074. material.screenHeight = renderer.domElement.clientHeight; */
  44075. material.resolution = resolution;
  44076. //material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z); //应该不需要
  44077. material.near = camera.near;
  44078. material.far = camera.far;
  44079. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  44080. }
  44081. computeVisibilityTextureData(nodes, camera){
  44082. if(Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  44083. let data = new Uint8Array(nodes.length * 4);
  44084. let visibleNodeTextureOffsets = new Map();
  44085. // copy array
  44086. nodes = nodes.slice();
  44087. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  44088. let sort = function (a, b) {
  44089. let na = a.geometryNode.name;
  44090. let nb = b.geometryNode.name;
  44091. if (na.length !== nb.length) return na.length - nb.length;
  44092. if (na < nb) return -1;
  44093. if (na > nb) return 1;
  44094. return 0;
  44095. };
  44096. nodes.sort(sort);
  44097. let worldDir = new Vector3();
  44098. let nodeMap = new Map();
  44099. let offsetsToChild = new Array(nodes.length).fill(Infinity);
  44100. for(let i = 0; i < nodes.length; i++){
  44101. let node = nodes[i];
  44102. nodeMap.set(node.name, node);
  44103. visibleNodeTextureOffsets.set(node, i);
  44104. if(i > 0){
  44105. let index = parseInt(node.name.slice(-1));
  44106. let parentName = node.name.slice(0, -1);
  44107. let parent = nodeMap.get(parentName);
  44108. let parentOffset = visibleNodeTextureOffsets.get(parent);
  44109. let parentOffsetToChild = (i - parentOffset);
  44110. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  44111. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | (1 << index);
  44112. data[parentOffset * 4 + 1] = (offsetsToChild[parentOffset] >> 8);
  44113. data[parentOffset * 4 + 2] = (offsetsToChild[parentOffset] % 256);
  44114. }
  44115. let density = node.geometryNode.density;
  44116. if(typeof density === "number"){
  44117. let lodOffset = Math.log2(density) / 2 - 1.5;
  44118. let offsetUint8 = (lodOffset + 10) * 10;
  44119. data[i * 4 + 3] = offsetUint8;
  44120. }else {
  44121. data[i * 4 + 3] = 100;
  44122. }
  44123. }
  44124. if(Potree.measureTimings){
  44125. performance.mark("computeVisibilityTextureData-end");
  44126. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  44127. }
  44128. return {
  44129. data: data,
  44130. offsets: visibleNodeTextureOffsets
  44131. };
  44132. }
  44133. nodeIntersectsProfile (node, profile) {
  44134. let bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  44135. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  44136. let intersects = false;
  44137. for (let i = 0; i < profile.points.length - 1; i++) {
  44138. let start = new Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  44139. let end = new Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  44140. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  44141. let distance = closest.distanceTo(bsWorld.center);
  44142. intersects = intersects || (distance < (bsWorld.radius + profile.width));
  44143. }
  44144. //console.log(`${node.name}: ${intersects}`);
  44145. return intersects;
  44146. }
  44147. deepestNodeAt(position){
  44148. const toObjectSpace = this.matrixWorld.clone().invert();
  44149. const objPos = position.clone().applyMatrix4(toObjectSpace);
  44150. let current = this.root;
  44151. while(true){
  44152. let containingChild = null;
  44153. for(const child of current.children){
  44154. if(child !== undefined){
  44155. if(child.getBoundingBox().containsPoint(objPos)){
  44156. containingChild = child;
  44157. }
  44158. }
  44159. }
  44160. if(containingChild !== null && containingChild instanceof PointCloudOctreeNode){
  44161. current = containingChild;
  44162. }else {
  44163. break;
  44164. }
  44165. }
  44166. const deepest = current;
  44167. return deepest;
  44168. }
  44169. nodesOnRay (nodes, ray) {
  44170. let nodesOnRay = [];
  44171. let _ray = ray.clone();
  44172. for (let i = 0; i < nodes.length; i++) {
  44173. let node = nodes[i];
  44174. let sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  44175. if (_ray.intersectsSphere(sphere)) {
  44176. nodesOnRay.push(node);
  44177. }
  44178. }
  44179. return nodesOnRay;
  44180. }
  44181. updateMatrixWorld (force) {
  44182. if (this.matrixAutoUpdate === true) this.updateMatrix();
  44183. if (this.matrixWorldNeedsUpdate === true || force === true) {
  44184. if (!this.parent) {
  44185. this.matrixWorld.copy(this.matrix);
  44186. } else {
  44187. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  44188. }
  44189. this.matrixWorldNeedsUpdate = false;
  44190. force = true;
  44191. }
  44192. }
  44193. hideDescendants (object) {
  44194. let stack = [];
  44195. for (let i = 0; i < object.children.length; i++) {
  44196. let child = object.children[i];
  44197. if (child.visible) {
  44198. stack.push(child);
  44199. }
  44200. }
  44201. while (stack.length > 0) {
  44202. let object = stack.shift();
  44203. object.visible = false;
  44204. for (let i = 0; i < object.children.length; i++) {
  44205. let child = object.children[i];
  44206. if (child.visible) {
  44207. stack.push(child);
  44208. }
  44209. }
  44210. }
  44211. }
  44212. moveToOrigin () {
  44213. this.position.set(0, 0, 0);
  44214. this.updateMatrixWorld(true);
  44215. let box = this.boundingBox;
  44216. let transform = this.matrixWorld;
  44217. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44218. this.position.set(0, 0, 0).sub(tBox.getCenter(new Vector3()));
  44219. };
  44220. moveToGroundPlane () {
  44221. this.updateMatrixWorld(true);
  44222. let box = this.boundingBox;
  44223. let transform = this.matrixWorld;
  44224. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44225. this.position.y += -tBox.min.y;
  44226. };
  44227. getBoundingBoxWorld () {
  44228. this.updateMatrixWorld(true);
  44229. let box = this.boundingBox;
  44230. let transform = this.matrixWorld;
  44231. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44232. return tBox;
  44233. };
  44234. /**
  44235. * returns points inside the profile points
  44236. *
  44237. * maxDepth: search points up to the given octree depth
  44238. *
  44239. *
  44240. * The return value is an array with all segments of the profile path
  44241. * let segment = {
  44242. * start: THREE.Vector3,
  44243. * end: THREE.Vector3,
  44244. * points: {}
  44245. * project: function()
  44246. * };
  44247. *
  44248. * The project() function inside each segment can be used to transform
  44249. * that segments point coordinates to line up along the x-axis.
  44250. *
  44251. *
  44252. */
  44253. getPointsInProfile (profile, maxDepth, callback) {
  44254. if (callback) {
  44255. let request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  44256. this.profileRequests.push(request);
  44257. return request;
  44258. }
  44259. let points = {
  44260. segments: [],
  44261. boundingBox: new Box3(),
  44262. projectedBoundingBox: new Box2()
  44263. };
  44264. // evaluate segments
  44265. for (let i = 0; i < profile.points.length - 1; i++) {
  44266. let start = profile.points[i];
  44267. let end = profile.points[i + 1];
  44268. let ps = this.getProfile(start, end, profile.width, maxDepth);
  44269. let segment = {
  44270. start: start,
  44271. end: end,
  44272. points: ps,
  44273. project: null
  44274. };
  44275. points.segments.push(segment);
  44276. points.boundingBox.expandByPoint(ps.boundingBox.min);
  44277. points.boundingBox.expandByPoint(ps.boundingBox.max);
  44278. }
  44279. // add projection functions to the segments
  44280. let mileage = new Vector3();
  44281. for (let i = 0; i < points.segments.length; i++) {
  44282. let segment = points.segments[i];
  44283. let start = segment.start;
  44284. let end = segment.end;
  44285. let project = (function (_start, _end, _mileage, _boundingBox) {
  44286. let start = _start;
  44287. let end = _end;
  44288. let mileage = _mileage;
  44289. let boundingBox = _boundingBox;
  44290. let xAxis = new Vector3(1, 0, 0);
  44291. let dir = new Vector3().subVectors(end, start);
  44292. dir.y = 0;
  44293. dir.normalize();
  44294. let alpha = Math.acos(xAxis.dot(dir));
  44295. if (dir.z > 0) {
  44296. alpha = -alpha;
  44297. }
  44298. return function (position) {
  44299. let toOrigin = new Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  44300. let alignWithX = new Matrix4().makeRotationY(-alpha);
  44301. let applyMileage = new Matrix4().makeTranslation(mileage.x, 0, 0);
  44302. let pos = position.clone();
  44303. pos.applyMatrix4(toOrigin);
  44304. pos.applyMatrix4(alignWithX);
  44305. pos.applyMatrix4(applyMileage);
  44306. return pos;
  44307. };
  44308. }(start, end, mileage.clone(), points.boundingBox.clone()));
  44309. segment.project = project;
  44310. mileage.x += new Vector3(start.x, 0, start.z).distanceTo(new Vector3(end.x, 0, end.z));
  44311. mileage.y += end.y - start.y;
  44312. }
  44313. points.projectedBoundingBox.min.x = 0;
  44314. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  44315. points.projectedBoundingBox.max.x = mileage.x;
  44316. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  44317. return points;
  44318. }
  44319. /**
  44320. * returns points inside the given profile bounds.
  44321. *
  44322. * start:
  44323. * end:
  44324. * width:
  44325. * depth: search points up to the given octree depth
  44326. * callback: if specified, points are loaded before searching
  44327. *
  44328. *
  44329. */
  44330. getProfile (start, end, width, depth, callback) {
  44331. let request = new Potree.ProfileRequest(start, end, width, depth, callback);
  44332. this.profileRequests.push(request);
  44333. };
  44334. getVisibleExtent () {
  44335. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  44336. };
  44337. intersectsPoint(position){
  44338. let rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  44339. if(!rootAvailable){
  44340. return false;
  44341. }
  44342. if(typeof this.signedDistanceField === "undefined"){
  44343. const resolution = 32;
  44344. const field = new Float32Array(resolution ** 3).fill(Infinity);
  44345. const positions = this.pcoGeometry.root.geometry.attributes.position;
  44346. const boundingBox = this.boundingBox;
  44347. const n = positions.count;
  44348. for(let i = 0; i < n; i = i + 3){
  44349. const x = positions.array[3 * i + 0];
  44350. const y = positions.array[3 * i + 1];
  44351. const z = positions.array[3 * i + 2];
  44352. const ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  44353. const iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  44354. const iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  44355. const index = ix + iy * resolution + iz * resolution * resolution;
  44356. field[index] = 0;
  44357. }
  44358. const sdf = {
  44359. resolution: resolution,
  44360. field: field,
  44361. };
  44362. this.signedDistanceField = sdf;
  44363. }
  44364. {
  44365. const sdf = this.signedDistanceField;
  44366. const boundingBox = this.boundingBox;
  44367. const toObjectSpace = this.matrixWorld.clone().invert();
  44368. const objPos = position.clone().applyMatrix4(toObjectSpace);
  44369. const resolution = sdf.resolution;
  44370. const ix = parseInt(resolution * (objPos.x / boundingBox.max.x));
  44371. const iy = parseInt(resolution * (objPos.y / boundingBox.max.y));
  44372. const iz = parseInt(resolution * (objPos.z / boundingBox.max.z));
  44373. if(ix < 0 || iy < 0 || iz < 0){
  44374. return false;
  44375. }
  44376. if(ix >= resolution || iy >= resolution || iz >= resolution){
  44377. return false;
  44378. }
  44379. const index = ix + iy * resolution + iz * resolution * resolution;
  44380. const value = sdf.field[index];
  44381. if(value === 0){
  44382. return true;
  44383. }
  44384. }
  44385. return false;
  44386. }
  44387. /**
  44388. *
  44389. *
  44390. *
  44391. * params.pickWindowSize: Look for points inside a pixel window of this size.
  44392. * Use odd values: 1, 3, 5, ...
  44393. *
  44394. *
  44395. * TODO: only draw pixels that are actually read with readPixels().
  44396. *
  44397. */
  44398. pick(viewer, viewport, camera, ray, params = {}){
  44399. let renderer = viewer.renderer;
  44400. let pRenderer = viewer.pRenderer;
  44401. performance.mark("pick-start");
  44402. let getVal = (a, b) => a != void 0 ? a : b;
  44403. let pickWindowSize_ = MathUtils.clamp( Math.round((1.1-this.maxLevel/this.nodeMaxLevel)*80), 5, 100);
  44404. let pickWindowSize = getVal(params.pickWindowSize, pickWindowSize_ ); /* 65 */ //拾取像素边长,越小越精准,但点云稀疏的话可能容易出现识别不到的情况。 另外左下侧会有缝隙无法识别到,缝隙大小和这个值有关
  44405. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  44406. let size = viewport ? viewport.resolution : renderer.getSize(new Vector2$1());
  44407. let width = Math.ceil(getVal(params.width, size.width)); //renderTarget大小。影响识别精度
  44408. let height = Math.ceil(getVal(params.height, size.height));
  44409. let screenshot = ()=>{
  44410. if(window.testScreen){
  44411. let dataUrl = Potree.Utils.renderTargetToDataUrl(pickState.renderTarget, width, height, renderer);
  44412. Common.downloadFile(dataUrl, 'screenshot.jpg'); //为什么图片上不是只有pickWindowSize区域有颜色??
  44413. window.testScreen = 0;
  44414. }
  44415. };
  44416. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  44417. let pointSize = getVal(params.pointSize, this.material.size);
  44418. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  44419. if (nodes.length === 0) {
  44420. return null;
  44421. }
  44422. //console.log('nodes.length != 0', this.name)
  44423. if (!this.pickState) {
  44424. let scene = new Scene();
  44425. let material = new Potree.PointCloudMaterial();
  44426. material.activeAttributeName = "indices";
  44427. let renderTarget = new WebGLRenderTarget(
  44428. 1, 1,
  44429. { minFilter: LinearFilter,
  44430. magFilter: NearestFilter,
  44431. format: RGBAFormat }
  44432. );
  44433. this.pickState = {
  44434. renderTarget: renderTarget,
  44435. material: material,
  44436. scene: scene
  44437. };
  44438. };
  44439. let pickState = this.pickState;
  44440. let pickMaterial = pickState.material;
  44441. { // update pick material
  44442. pickMaterial.pointSizeType = pointSizeType;
  44443. //pickMaterial.shape = this.material.shape;
  44444. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  44445. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  44446. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  44447. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  44448. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  44449. pickMaterial.activeAttributeName = "indices";
  44450. pickMaterial.size = pointSize;
  44451. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  44452. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  44453. pickMaterial.classification = this.material.classification;
  44454. pickMaterial.recomputeClassification();
  44455. if(params.pickClipped){
  44456. pickMaterial.clipBoxes = this.material.clipBoxes;
  44457. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  44458. if(this.material.clipTask === Potree.ClipTask.HIGHLIGHT){
  44459. pickMaterial.clipTask = Potree.ClipTask.NONE;
  44460. }else {
  44461. pickMaterial.clipTask = this.material.clipTask;
  44462. }
  44463. pickMaterial.clipMethod = this.material.clipMethod;
  44464. }else {
  44465. pickMaterial.clipBoxes = [];
  44466. }
  44467. this.updateMaterial(pickMaterial, nodes, camera, renderer, new Vector2$1(width, height));
  44468. }
  44469. pickState.renderTarget.setSize(width, height); //仅绘制屏幕大小的,而不乘以devicePixelRatio
  44470. let pixelPos = new Vector2$1(params.x, params.y);
  44471. let gl = renderer.getContext();
  44472. gl.enable(gl.SCISSOR_TEST);
  44473. gl.scissor( //规定渲染范围,只渲染一小块
  44474. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  44475. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  44476. parseInt(pickWindowSize), parseInt(pickWindowSize));
  44477. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  44478. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  44479. renderer.state.setBlending(NoBlending);
  44480. { // RENDER
  44481. renderer.setRenderTarget(pickState.renderTarget);
  44482. gl.clearColor(0, 0, 0, 0);
  44483. renderer.clear(true, true, true);
  44484. let tmp = this.material;
  44485. this.material = pickMaterial;
  44486. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  44487. screenshot();
  44488. this.material = tmp;
  44489. }
  44490. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  44491. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  44492. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  44493. /* let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  44494. let h = parseInt(Math.min(y + pickWindowSize, height) - y); */
  44495. let pixelCount = pickWindowSize * pickWindowSize;//w * h;
  44496. let buffer = new Uint8Array(4 * pixelCount);
  44497. //w<pickWindowSize会报错
  44498. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  44499. renderer.setRenderTarget(null);
  44500. renderer.state.reset();
  44501. renderer.setScissorTest(false);
  44502. gl.disable(gl.SCISSOR_TEST);
  44503. let pixels = buffer;
  44504. let ibuffer = new Uint32Array(buffer.buffer); //四个数整合成一个
  44505. // find closest hit inside pixelWindow boundaries
  44506. let min = Number.MAX_VALUE;
  44507. let hits = [];
  44508. for (let u = 0; u < pickWindowSize; u++) {
  44509. for (let v = 0; v < pickWindowSize; v++) {
  44510. let offset = (u + v * pickWindowSize);
  44511. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  44512. let pcIndex = pixels[4 * offset + 3];//nodes index(第四位)
  44513. pixels[4 * offset + 3] = 0; //去除nodes index后剩下的是index(前三位)
  44514. let pIndex = ibuffer[offset]; //index
  44515. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  44516. let hit = {
  44517. pIndex: pIndex,
  44518. pcIndex: pcIndex,
  44519. distanceToCenter: distance
  44520. };
  44521. if(params.all){
  44522. hits.push(hit);
  44523. }else {
  44524. if(hits.length > 0){
  44525. if(distance < hits[0].distanceToCenter){
  44526. hits[0] = hit;
  44527. }
  44528. }else {
  44529. hits.push(hit);
  44530. }
  44531. }
  44532. }
  44533. }
  44534. }
  44535. // { // DEBUG: show panel with pick image
  44536. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  44537. // let screenshot = img.src;
  44538. // if(!this.debugDIV){
  44539. // this.debugDIV = $(`
  44540. // <div id="pickDebug"
  44541. // style="position: absolute;
  44542. // right: 400px; width: 300px;
  44543. // bottom: 44px; width: 300px;
  44544. // z-index: 1000;
  44545. // "></div>`);
  44546. // $(document.body).append(this.debugDIV);
  44547. // }
  44548. // this.debugDIV.empty();
  44549. // this.debugDIV.append($(`<img src="${screenshot}"
  44550. // style="transform: scaleY(-1); width: 300px"/>`));
  44551. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  44552. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  44553. // }
  44554. for(let hit of hits){
  44555. let point = {};
  44556. if (!nodes[hit.pcIndex]) {
  44557. return null;
  44558. }
  44559. let node = nodes[hit.pcIndex];
  44560. let pc = node.sceneNode;
  44561. let geometry = node.geometryNode.geometry;
  44562. for(let attributeName in geometry.attributes){
  44563. let attribute = geometry.attributes[attributeName];
  44564. if (attributeName === 'position') {
  44565. let x = attribute.array[3 * hit.pIndex + 0];
  44566. let y = attribute.array[3 * hit.pIndex + 1];
  44567. let z = attribute.array[3 * hit.pIndex + 2];
  44568. let position = new Vector3(x, y, z);
  44569. position.applyMatrix4( pc.matrixWorld );
  44570. point[attributeName] = position;
  44571. } else if (attributeName === 'indices') {
  44572. } else {
  44573. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  44574. if(attribute.potree){
  44575. const {scale, offset} = attribute.potree;
  44576. values = values.map(v => v / scale + offset);
  44577. }
  44578. point[attributeName] = values;
  44579. //debugger;
  44580. //if (values.itemSize === 1) {
  44581. // point[attribute.name] = values.array[hit.pIndex];
  44582. //} else {
  44583. // let value = [];
  44584. // for (let j = 0; j < values.itemSize; j++) {
  44585. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  44586. // }
  44587. // point[attribute.name] = value;
  44588. //}
  44589. }
  44590. }
  44591. hit.point = point;
  44592. }
  44593. performance.mark("pick-end");
  44594. performance.measure("pick", "pick-start", "pick-end");
  44595. if(params.all){
  44596. return hits.map(hit => hit.point);
  44597. }else {
  44598. if(hits.length === 0){
  44599. return null;
  44600. }else {
  44601. return hits[0].point;
  44602. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  44603. //return sorted[0].point;
  44604. }
  44605. }
  44606. };
  44607. * getFittedBoxGen(boxNode){//???
  44608. let start = performance.now();
  44609. let shrinkedLocalBounds = new Box3();
  44610. let worldToBox = boxNode.matrixWorld.clone().invert();
  44611. for(let node of this.visibleNodes){
  44612. if(!node.sceneNode){
  44613. continue;
  44614. }
  44615. let buffer = node.geometryNode.buffer;
  44616. let posOffset = buffer.offset("position");
  44617. let stride = buffer.stride;
  44618. let view = new DataView(buffer.data);
  44619. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  44620. let pos = new Vector4();
  44621. for(let i = 0; i < buffer.numElements; i++){
  44622. let x = view.getFloat32(i * stride + posOffset + 0, true);
  44623. let y = view.getFloat32(i * stride + posOffset + 4, true);
  44624. let z = view.getFloat32(i * stride + posOffset + 8, true);
  44625. pos.set(x, y, z, 1);
  44626. pos.applyMatrix4(objectToBox);
  44627. if(-0.5 < pos.x && pos.x < 0.5){
  44628. if(-0.5 < pos.y && pos.y < 0.5){
  44629. if(-0.5 < pos.z && pos.z < 0.5){
  44630. shrinkedLocalBounds.expandByPoint(pos);
  44631. }
  44632. }
  44633. }
  44634. }
  44635. yield;
  44636. }
  44637. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  44638. let fitted = new Object3D();
  44639. fitted.position.copy(fittedPosition);
  44640. fitted.scale.copy(boxNode.scale);
  44641. fitted.rotation.copy(boxNode.rotation);
  44642. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  44643. fitted.scale.multiply(ds);
  44644. let duration = performance.now() - start;
  44645. console.log("duration: ", duration);
  44646. yield fitted;
  44647. }
  44648. getFittedBox(boxNode, maxLevel = Infinity){
  44649. maxLevel = Infinity;
  44650. let start = performance.now();
  44651. let shrinkedLocalBounds = new Box3();
  44652. let worldToBox = boxNode.matrixWorld.clone().invert();
  44653. for(let node of this.visibleNodes){
  44654. if(!node.sceneNode || node.getLevel() > maxLevel){
  44655. continue;
  44656. }
  44657. let buffer = node.geometryNode.buffer;
  44658. let posOffset = buffer.offset("position");
  44659. let stride = buffer.stride;
  44660. let view = new DataView(buffer.data);
  44661. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  44662. let pos = new Vector4();
  44663. for(let i = 0; i < buffer.numElements; i++){
  44664. let x = view.getFloat32(i * stride + posOffset + 0, true);
  44665. let y = view.getFloat32(i * stride + posOffset + 4, true);
  44666. let z = view.getFloat32(i * stride + posOffset + 8, true);
  44667. pos.set(x, y, z, 1);
  44668. pos.applyMatrix4(objectToBox);
  44669. if(-0.5 < pos.x && pos.x < 0.5){
  44670. if(-0.5 < pos.y && pos.y < 0.5){
  44671. if(-0.5 < pos.z && pos.z < 0.5){
  44672. shrinkedLocalBounds.expandByPoint(pos);
  44673. }
  44674. }
  44675. }
  44676. }
  44677. }
  44678. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  44679. let fitted = new Object3D();
  44680. fitted.position.copy(fittedPosition);
  44681. fitted.scale.copy(boxNode.scale);
  44682. fitted.rotation.copy(boxNode.rotation);
  44683. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  44684. fitted.scale.multiply(ds);
  44685. let duration = performance.now() - start;
  44686. console.log("duration: ", duration);
  44687. return fitted;
  44688. }
  44689. get progress () {
  44690. return this.visibleNodes.length / this.visibleGeometry.length;
  44691. }
  44692. find(name){
  44693. let node = null;
  44694. for(let char of name){
  44695. if(char === "r"){
  44696. node = this.root;
  44697. }else {
  44698. node = node.children[char];
  44699. }
  44700. }
  44701. return node;
  44702. }
  44703. get visible(){
  44704. return this._visible;
  44705. }
  44706. set visible(value){
  44707. if(value !== this._visible){
  44708. this._visible = value;
  44709. this.dispatchEvent({type: 'visibility_changed', pointcloud: this});
  44710. }
  44711. }
  44712. // 设置点大小
  44713. changePointSize(num, sizeFitToLevel) {
  44714. if(this.material.pointSizeType != PointSizeType.ATTENUATED){
  44715. return num && (this.material.size = num)
  44716. }
  44717. if (num == void 0) {
  44718. num = this.temp.pointSize;
  44719. } else {
  44720. this.temp.pointSize = num;
  44721. }
  44722. num /= (Potree.config.material.realPointSize / Potree.config.material.pointSize); //兼容
  44723. num = Math.pow(num, 1.05) * 6;
  44724. if(sizeFitToLevel || Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本: 近似将pointSizeType换成ADAPTIVE
  44725. let str = this.temp.pointSize+':'+this.maxLevel+':'+this.nodeMaxLevel;
  44726. let value = this.temp.sizeFitToLevel[str]; //储存。防止每次渲染(反复切换density)都要算。
  44727. if(value){
  44728. this.material.size = value;
  44729. }else {
  44730. let base = this.material.spacing / Math.pow(2, this.maxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  44731. base *= this.nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(this.maxLevel / this.nodeMaxLevel, 1.3)) : 0.1; //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙
  44732. this.material.size = base * 3 * num;/* * window.devicePixelRatio */
  44733. //在t-8BCqxQAr93 会议室 和 t-e2Kb2iU 隧道 两个场景里调节,因为它们的spacing相差较大,观察会议室墙壁的龟裂程度
  44734. this.temp.sizeFitToLevel[str] = this.material.size;
  44735. }
  44736. }else {
  44737. let base = 0.007; //let base = this.material.spacing / Math.pow(2, this.nodeMaxLevel) //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  44738. //base的数值理论上应该是右侧算出来的,但发现有的场景nodeMaxLevel和nodeMaxLevelPredict差别较大的点云显示也过大,而直接换成固定值反而可以适应所有场景。该固定值来源于 getHighestNodeSpacing 最小值,修改了下。(会不会是我们的相机其实该值是固定的,根据该值算出的spacing才是有误差的? 如果换了相机是否要改值?)
  44739. this.material.size = base * 5 * num; /* * window.devicePixelRatio */
  44740. }
  44741. //console.log('changePointSize ' + this.dataset_id + ' , num : ' + num + ' , size : ' + this.material.size, this.material.spacing)
  44742. }
  44743. // 设置点透明度
  44744. changePointOpacity(num, canMoreThanOne) {
  44745. //num:0-1 navvis用的是亮度
  44746. if (num == void 0) {
  44747. num = this.temp.pointOpacity;
  44748. } else {
  44749. this.temp.pointOpacity = num;
  44750. }
  44751. if(Potree.settings.editType == 'merge'){ //not AdditiveBlending
  44752. return this.material.opacity = num
  44753. }
  44754. if (num == 1) {
  44755. this.material.opacity = 1;
  44756. } else {
  44757. let str = (Potree.settings.sizeFitToLevel?'sizeFit:':'')+ (canMoreThanOne ? 'canMoreThanOne:':'') +this.temp.pointOpacity+':'+this.maxLevel+':'+this.nodeMaxLevel;
  44758. let value = this.temp.opacity[str]; //储存。防止每次渲染(反复切换density)都要算。
  44759. if(value){
  44760. this.material.opacity = value;
  44761. }else {
  44762. if(Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本:
  44763. let base = this.material.spacing / Math.pow(1.4, this.maxLevel); //随着level提高,点云重叠几率增多
  44764. let minBase = this.material.spacing / Math.pow(1.4, this.nodeMaxLevel);
  44765. let ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  44766. this.material.opacity = base * ratio * num;
  44767. if(!canMoreThanOne){
  44768. this.material.opacity = MathUtils.clamp(this.material.opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  44769. }
  44770. }else {
  44771. let base = this.material.spacing / Math.pow(1.8, this.maxLevel);
  44772. let minBase = this.material.spacing / Math.pow(1.8, this.nodeMaxLevel);
  44773. //console.log(1 / base, 1 / minBase / 6)
  44774. let ratio = Math.min(1 / base, 1 / minBase / 6); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  44775. this.material.opacity = base * ratio * num;
  44776. if(!canMoreThanOne){
  44777. this.material.opacity = MathUtils.clamp(this.material.opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  44778. }
  44779. }
  44780. this.temp.opacity[str] = this.material.opacity;
  44781. }
  44782. //缺点:防止颜色过亮主要是相机离远时,当在漫游点处由于离点云太近,可能会导致高质量点云看起来很暗。
  44783. }
  44784. //console.log('changePointOpacity ' + this.dataset_id + ', num : ' + num + ' , opacity : ' + this.material.opacity) //检查是否做到了低质量时num==opacity,中质量opacity稍小于num,高质量更小
  44785. }
  44786. updateBound(){
  44787. var boundingBox_ = this.pcoGeometry.tightBoundingBox.clone().applyMatrix4(this.matrixWorld);
  44788. this.bound = boundingBox_;
  44789. }
  44790. getPanosBound(){
  44791. if(this.panos.length > 0){
  44792. let minSize = new Vector3(1,1,1);
  44793. this.panosBound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  44794. }else {
  44795. this.panosBound = null;
  44796. }
  44797. }
  44798. getUnrotBoundPoint(type){//获取没有旋转的tightBounding的水平四个点
  44799. //如果alighment支持任意轴旋转,水平面上看到的可能就是六边形了,失去意义,到时候不能用这个。也可以若只绕z旋转, 使用tightBoundingBox,否则bound
  44800. let bound = this.pcoGeometry.tightBoundingBox;
  44801. if(type == 'all'){
  44802. return [new Vector3(bound.min.x, bound.min.y, bound.min.z),
  44803. new Vector3(bound.max.x, bound.min.y, bound.min.z),
  44804. new Vector3(bound.max.x, bound.max.y,bound.min.z),
  44805. new Vector3(bound.min.x, bound.max.y,bound.min.z),
  44806. new Vector3(bound.min.x, bound.min.y, bound.max.z),
  44807. new Vector3(bound.max.x, bound.min.y, bound.max.z),
  44808. new Vector3(bound.max.x, bound.max.y,bound.max.z),
  44809. new Vector3(bound.min.x, bound.max.y,bound.max.z),
  44810. ].map(e=>e.applyMatrix4(this.matrixWorld))
  44811. }else
  44812. return [new Vector3(bound.min.x, bound.min.y,0),
  44813. new Vector3(bound.max.x, bound.min.y,0),
  44814. new Vector3(bound.max.x, bound.max.y,0),
  44815. new Vector3(bound.min.x, bound.max.y,0),
  44816. ].map(e=>e.applyMatrix4(this.matrixWorld))
  44817. }
  44818. ifContainsPoint(pos){
  44819. if(!this.bound || !this.bound.containsPoint(pos))return
  44820. var points = this.getUnrotBoundPoint();
  44821. return math.isPointInArea(points, null, pos)
  44822. }
  44823. getVolume(){
  44824. var points = this.getUnrotBoundPoint();
  44825. var area = Math.abs(math.getArea(points));
  44826. return area * (this.bound.max.z - this.bound.min.z)
  44827. }
  44828. //数据集的显示影响到其下的:点云、marker .不会影响地图上的显示
  44829. /*
  44830. updateVisible(reason, ifShow){//当所有加入的条件都不为false时才显示
  44831. if(ifShow){
  44832. var index = this.unvisibleReasons.indexOf(reason);
  44833. index > -1 && this.unvisibleReasons.splice(index, 1);
  44834. if(this.unvisibleReasons.length == 0){
  44835. this.visible = true;
  44836. this.dispatchEvent({
  44837. type: 'isVisible'
  44838. visible:true
  44839. })
  44840. }
  44841. }else {
  44842. if(!this.unvisibleReasons.includes(reason)) this.unvisibleReasons.push(reason);
  44843. this.visible = false;
  44844. this.dispatchEvent({
  44845. type: 'isVisible'
  44846. visible:false
  44847. })
  44848. }
  44849. }
  44850. getVisible(reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  44851. if(this.visible)return true
  44852. else{
  44853. return !this.unvisibleReasons.includes(reason)
  44854. }
  44855. } */
  44856. /* get isVisible(){//add 手动在数据集选择是否显示(和是否全景图、隐藏点云无关)
  44857. return this._isVisible
  44858. }
  44859. set isVisible(visi){
  44860. if(!visi)this.visible = false
  44861. this._isVisible = visi
  44862. } */
  44863. }
  44864. /*
  44865. window.searchOutRing = function(points){
  44866. 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},
  44867. {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},
  44868. {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)=>{
  44869. var a = new THREE.Vector2().copy(e)
  44870. a.id = index;
  44871. return a
  44872. })
  44873. var lines = []
  44874. var minDis = 2*2
  44875. points.forEach((p,j)=>{
  44876. for(let i=0;i<j;i++){
  44877. if(p.distanceToSquared(points[i])<minDis){
  44878. lines.push({p1:i,p2:j})
  44879. }
  44880. }
  44881. })
  44882. searchRings({
  44883. points,
  44884. lines,
  44885. onlyGetOutRing:true
  44886. })
  44887. }
  44888. */
  44889. class Points$1 {
  44890. constructor () {
  44891. this.boundingBox = new Box3();
  44892. this.numPoints = 0;
  44893. this.data = {};
  44894. }
  44895. add (points) {
  44896. let currentSize = this.numPoints;
  44897. let additionalSize = points.numPoints;
  44898. let newSize = currentSize + additionalSize;
  44899. let thisAttributes = Object.keys(this.data);
  44900. let otherAttributes = Object.keys(points.data);
  44901. let attributes = new Set([...thisAttributes, ...otherAttributes]);
  44902. for (let attribute of attributes) {
  44903. if (thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  44904. // attribute in both, merge
  44905. let Type = this.data[attribute].constructor;
  44906. let merged = new Type(this.data[attribute].length + points.data[attribute].length);
  44907. merged.set(this.data[attribute], 0);
  44908. merged.set(points.data[attribute], this.data[attribute].length);
  44909. this.data[attribute] = merged;
  44910. } else if (thisAttributes.includes(attribute) && !otherAttributes.includes(attribute)) {
  44911. // attribute only in this; take over this and expand to new size
  44912. let elementsPerPoint = this.data[attribute].length / this.numPoints;
  44913. let Type = this.data[attribute].constructor;
  44914. let expanded = new Type(elementsPerPoint * newSize);
  44915. expanded.set(this.data[attribute], 0);
  44916. this.data[attribute] = expanded;
  44917. } else if (!thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  44918. // attribute only in points to be added; take over new points and expand to new size
  44919. let elementsPerPoint = points.data[attribute].length / points.numPoints;
  44920. let Type = points.data[attribute].constructor;
  44921. let expanded = new Type(elementsPerPoint * newSize);
  44922. expanded.set(points.data[attribute], elementsPerPoint * currentSize);
  44923. this.data[attribute] = expanded;
  44924. }
  44925. }
  44926. this.numPoints = newSize;
  44927. this.boundingBox.union(points.boundingBox);
  44928. }
  44929. }
  44930. /**
  44931. *
  44932. * code adapted from three.js BoxHelper.js
  44933. * https://github.com/mrdoob/three.js/blob/dev/src/helpers/BoxHelper.js
  44934. *
  44935. * @author mrdoob / http://mrdoob.com/
  44936. * @author Mugen87 / http://github.com/Mugen87
  44937. * @author mschuetz / http://potree.org
  44938. */
  44939. class Box3Helper$1 extends LineSegments {
  44940. constructor (box, color) {
  44941. if (color === undefined) color = 0xffff00;
  44942. 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 ]);
  44943. let positions = new Float32Array([
  44944. box.min.x, box.min.y, box.min.z,
  44945. box.max.x, box.min.y, box.min.z,
  44946. box.max.x, box.min.y, box.max.z,
  44947. box.min.x, box.min.y, box.max.z,
  44948. box.min.x, box.max.y, box.min.z,
  44949. box.max.x, box.max.y, box.min.z,
  44950. box.max.x, box.max.y, box.max.z,
  44951. box.min.x, box.max.y, box.max.z
  44952. ]);
  44953. let geometry = new BufferGeometry();
  44954. geometry.setIndex(new BufferAttribute(indices, 1));
  44955. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  44956. let material = new LineBasicMaterial({ color: color });
  44957. super(geometry, material);
  44958. }
  44959. }
  44960. function updatePointClouds(pointclouds,camera, areaSize /* renderer */){
  44961. for (let pointcloud of pointclouds) {
  44962. let start = performance.now();
  44963. for (let profileRequest of pointcloud.profileRequests) {
  44964. profileRequest.update();
  44965. let duration = performance.now() - start;
  44966. if(duration > 5){
  44967. break;
  44968. }
  44969. }
  44970. let duration = performance.now() - start;
  44971. }
  44972. let result = updateVisibility(pointclouds, camera, areaSize );
  44973. for (let pointcloud of pointclouds) {
  44974. //pointcloud.updateMaterial(pointcloud.material, pointcloud.visibleNodes, camera, renderer);//转移到渲染时
  44975. pointcloud.updateVisibleBounds();
  44976. }
  44977. exports.lru.freeMemory();//即Potree.lru 能看到所有在加载的node
  44978. return result;
  44979. };
  44980. function updateVisibilityStructures(pointclouds, camera, areaSize) {
  44981. let frustums = [];
  44982. let camObjPositions = [];
  44983. let priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  44984. for (let i = 0; i < pointclouds.length; i++) {
  44985. let pointcloud = pointclouds[i];
  44986. if (!pointcloud.initialized()) {
  44987. continue;
  44988. }
  44989. pointcloud.numVisibleNodes = 0;
  44990. pointcloud.numVisiblePoints = 0;
  44991. pointcloud.deepestVisibleLevel = 0;
  44992. pointcloud.visibleNodes = [];
  44993. pointcloud.visibleGeometry = [];
  44994. // frustum in object space
  44995. camera.updateMatrixWorld();
  44996. let frustum = new Frustum();
  44997. let viewI = camera.matrixWorldInverse;
  44998. let world = pointcloud.matrixWorld;
  44999. // use close near plane for frustum intersection
  45000. let frustumCam = camera.clone();
  45001. frustumCam.near = Math.min(camera.near, 0.1);
  45002. frustumCam.updateProjectionMatrix();
  45003. let proj = camera.projectionMatrix;
  45004. let fm = new Matrix4().multiply(proj).multiply(viewI).multiply(world);
  45005. frustum.setFromProjectionMatrix(fm);
  45006. frustums.push(frustum);
  45007. // camera position in object space
  45008. let view = camera.matrixWorld;
  45009. let worldI = world.clone().invert();
  45010. let camMatrixObject = new Matrix4().multiply(worldI).multiply(view);
  45011. let camObjPos = new Vector3().setFromMatrixPosition(camMatrixObject);
  45012. camObjPositions.push(camObjPos);
  45013. // 因漫游模式而隐藏的话 依旧需要加入visibleNodes,因为pick需要
  45014. /* viewer.getObjVisiByReason(pointcloud, 'datasetSelection') */
  45015. if (pointcloud.visible || pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode' && pointcloud.root !== null) {//改 visible ->
  45016. priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE});
  45017. }
  45018. // hide all previously visible nodes
  45019. // if(pointcloud.root instanceof PointCloudOctreeNode){
  45020. // pointcloud.hideDescendants(pointcloud.root.sceneNode);
  45021. // }
  45022. if (pointcloud.root.isTreeNode()) {
  45023. pointcloud.hideDescendants(pointcloud.root.sceneNode);
  45024. }
  45025. for (let j = 0; j < pointcloud.boundingBoxNodes.length; j++) {
  45026. pointcloud.boundingBoxNodes[j].visible = false;
  45027. }
  45028. }
  45029. return {
  45030. 'frustums': frustums,
  45031. 'camObjPositions': camObjPositions,
  45032. 'priorityQueue': priorityQueue
  45033. };
  45034. };
  45035. function updateVisibility(pointclouds, camera, areaSize){
  45036. let numVisibleNodes = 0;
  45037. let numVisiblePoints = 0;
  45038. let numVisiblePointsInPointclouds = new Map(pointclouds.map(pc => [pc, 0]));
  45039. let visibleNodes = [];
  45040. let visibleGeometry = [];
  45041. let unloadedGeometry = [];
  45042. let lowestSpacing = Infinity;
  45043. // calculate object space frustum and cam pos and setup priority queue
  45044. let s = updateVisibilityStructures(pointclouds, camera, areaSize);//得到相机可见范围
  45045. let frustums = s.frustums;
  45046. let camObjPositions = s.camObjPositions;
  45047. let priorityQueue = s.priorityQueue;
  45048. let loadedToGPUThisFrame = 0;
  45049. let domWidth = areaSize.x; //renderer.domElement.clientWidth;
  45050. let domHeight = areaSize.y;//renderer.domElement.clientHeight;
  45051. // check if pointcloud has been transformed
  45052. // some code will only be executed if changes have been detected
  45053. if(!Potree._pointcloudTransformVersion){
  45054. Potree._pointcloudTransformVersion = new Map();
  45055. }
  45056. let pointcloudTransformVersion = Potree._pointcloudTransformVersion;
  45057. for(let pointcloud of pointclouds){
  45058. if(!viewer.getObjVisiByReason(pointcloud, 'datasetSelection')){//改 visible ->
  45059. continue;
  45060. }
  45061. pointcloud.updateMatrixWorld();
  45062. if(!pointcloudTransformVersion.has(pointcloud)){
  45063. pointcloudTransformVersion.set(pointcloud, {number: 0, transform: pointcloud.matrixWorld.clone()});
  45064. }else {
  45065. let version = pointcloudTransformVersion.get(pointcloud);
  45066. if(!version.transform.equals(pointcloud.matrixWorld)){
  45067. version.number++;
  45068. version.transform.copy(pointcloud.matrixWorld);
  45069. pointcloud.dispatchEvent({
  45070. type: "transformation_changed",
  45071. target: pointcloud
  45072. });
  45073. }
  45074. }
  45075. }
  45076. while (priorityQueue.size() > 0) {
  45077. let element = priorityQueue.pop();//其实是拿第一个, 再把最后一个放到前面
  45078. let node = element.node;
  45079. let parent = element.parent;
  45080. let pointcloud = pointclouds[element.pointcloud];
  45081. // { // restrict to certain nodes for debugging
  45082. // let allowedNodes = ["r", "r0", "r4"];
  45083. // if(!allowedNodes.includes(node.name)){
  45084. // continue;
  45085. // }
  45086. // }
  45087. let box = node.getBoundingBox();
  45088. let frustum = frustums[element.pointcloud];
  45089. let camObjPos = camObjPositions[element.pointcloud];
  45090. let insideFrustum = frustum.intersectsBox(box);
  45091. let maxLevel = pointcloud.maxLevel == void 0 ? Infinity : pointcloud.maxLevel;
  45092. let level = node.getLevel();
  45093. let visible = insideFrustum;
  45094. visible = visible && !(numVisiblePoints + node.getNumPoints() > Potree.pointBudget);
  45095. visible = visible && !(numVisiblePointsInPointclouds.get(pointcloud) + node.getNumPoints() > pointcloud.pointBudget);
  45096. visible = visible && level <= maxLevel; //< 改为 <=
  45097. //visible = visible || node.getLevel() <= 2;
  45098. let clipBoxes = pointcloud.material.clipBoxes;
  45099. if(true && clipBoxes.length > 0){
  45100. //node.debug = false;
  45101. let numIntersecting = 0;
  45102. let numIntersectionVolumes = 0;
  45103. //if(node.name === "r60"){
  45104. // var a = 10;
  45105. //}
  45106. for(let clipBox of clipBoxes){
  45107. let pcWorldInverse = pointcloud.matrixWorld.clone().invert();
  45108. let toPCObject = pcWorldInverse.multiply(clipBox.box.matrixWorld);
  45109. let px = new Vector3(+0.5, 0, 0).applyMatrix4(pcWorldInverse);
  45110. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(pcWorldInverse);
  45111. let py = new Vector3(0, +0.5, 0).applyMatrix4(pcWorldInverse);
  45112. let ny = new Vector3(0, -0.5, 0).applyMatrix4(pcWorldInverse);
  45113. let pz = new Vector3(0, 0, +0.5).applyMatrix4(pcWorldInverse);
  45114. let nz = new Vector3(0, 0, -0.5).applyMatrix4(pcWorldInverse);
  45115. let pxN = new Vector3().subVectors(nx, px).normalize();
  45116. let nxN = pxN.clone().multiplyScalar(-1);
  45117. let pyN = new Vector3().subVectors(ny, py).normalize();
  45118. let nyN = pyN.clone().multiplyScalar(-1);
  45119. let pzN = new Vector3().subVectors(nz, pz).normalize();
  45120. let nzN = pzN.clone().multiplyScalar(-1);
  45121. let pxPlane = new Plane().setFromNormalAndCoplanarPoint(pxN, px);
  45122. let nxPlane = new Plane().setFromNormalAndCoplanarPoint(nxN, nx);
  45123. let pyPlane = new Plane().setFromNormalAndCoplanarPoint(pyN, py);
  45124. let nyPlane = new Plane().setFromNormalAndCoplanarPoint(nyN, ny);
  45125. let pzPlane = new Plane().setFromNormalAndCoplanarPoint(pzN, pz);
  45126. let nzPlane = new Plane().setFromNormalAndCoplanarPoint(nzN, nz);
  45127. //if(window.debugdraw !== undefined && window.debugdraw === true && node.name === "r60"){
  45128. // Potree.utils.debugPlane(viewer.scene.scene, pxPlane, 1, 0xFF0000);
  45129. // Potree.utils.debugPlane(viewer.scene.scene, nxPlane, 1, 0x990000);
  45130. // Potree.utils.debugPlane(viewer.scene.scene, pyPlane, 1, 0x00FF00);
  45131. // Potree.utils.debugPlane(viewer.scene.scene, nyPlane, 1, 0x009900);
  45132. // Potree.utils.debugPlane(viewer.scene.scene, pzPlane, 1, 0x0000FF);
  45133. // Potree.utils.debugPlane(viewer.scene.scene, nzPlane, 1, 0x000099);
  45134. // Potree.utils.debugBox(viewer.scene.scene, box, new THREE.Matrix4(), 0x00FF00);
  45135. // Potree.utils.debugBox(viewer.scene.scene, box, pointcloud.matrixWorld, 0xFF0000);
  45136. // Potree.utils.debugBox(viewer.scene.scene, clipBox.box.boundingBox, clipBox.box.matrixWorld, 0xFF0000);
  45137. // window.debugdraw = false;
  45138. //}
  45139. let frustum = new Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane);
  45140. let intersects = frustum.intersectsBox(box);
  45141. if(intersects){
  45142. numIntersecting++;
  45143. }
  45144. numIntersectionVolumes++;
  45145. }
  45146. let insideAny = numIntersecting > 0;
  45147. let insideAll = numIntersecting === numIntersectionVolumes;
  45148. if(pointcloud.material.clipTask === ClipTask.SHOW_INSIDE){
  45149. if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ANY && insideAny){
  45150. //node.debug = true
  45151. }else if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ALL && insideAll){
  45152. //node.debug = true;
  45153. }else {
  45154. visible = false;
  45155. }
  45156. } else if(pointcloud.material.clipTask === ClipTask.SHOW_OUTSIDE){
  45157. //if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ANY && !insideAny){
  45158. // //visible = true;
  45159. // let a = 10;
  45160. //}else if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ALL && !insideAll){
  45161. // //visible = true;
  45162. // let a = 20;
  45163. //}else{
  45164. // visible = false;
  45165. //}
  45166. }
  45167. }
  45168. // visible = ["r", "r0", "r06", "r060"].includes(node.name);
  45169. // visible = ["r"].includes(node.name);
  45170. if (node.spacing) {
  45171. lowestSpacing = Math.min(lowestSpacing, node.spacing);
  45172. } else if (node.geometryNode && node.geometryNode.spacing) {
  45173. lowestSpacing = Math.min(lowestSpacing, node.geometryNode.spacing);
  45174. }
  45175. if (numVisiblePoints + node.getNumPoints() > Potree.pointBudget) {
  45176. break;
  45177. }
  45178. if (!visible) {
  45179. continue;
  45180. }
  45181. // TODO: not used, same as the declaration?
  45182. // numVisibleNodes++;
  45183. numVisiblePoints += node.getNumPoints();
  45184. let numVisiblePointsInPointcloud = numVisiblePointsInPointclouds.get(pointcloud);
  45185. numVisiblePointsInPointclouds.set(pointcloud, numVisiblePointsInPointcloud + node.getNumPoints());
  45186. pointcloud.numVisibleNodes++;
  45187. pointcloud.numVisiblePoints += node.getNumPoints();
  45188. if (node.isGeometryNode() && (!parent || parent.isTreeNode())) {
  45189. if (node.isLoaded() && loadedToGPUThisFrame < 2) {
  45190. node = pointcloud.toTreeNode(node, parent);
  45191. loadedToGPUThisFrame++;
  45192. } else {
  45193. unloadedGeometry.push({pointcloud,node});
  45194. visibleGeometry.push(node);
  45195. }
  45196. }
  45197. if (node.isTreeNode()) {
  45198. exports.lru.touch(node.geometryNode);
  45199. node.sceneNode.visible = true;
  45200. node.sceneNode.material = pointcloud.material;
  45201. visibleNodes.push(node);
  45202. pointcloud.visibleNodes.push(node);
  45203. if(node._transformVersion === undefined){
  45204. node._transformVersion = -1;
  45205. }
  45206. let transformVersion = pointcloudTransformVersion.get(pointcloud);
  45207. if(node._transformVersion !== transformVersion.number){
  45208. node.sceneNode.updateMatrix();
  45209. //node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  45210. node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  45211. node._transformVersion = transformVersion.number;
  45212. }
  45213. if (pointcloud.showBoundingBox && !node.boundingBoxNode && node.getBoundingBox) {
  45214. let boxHelper = new Box3Helper$1(node.getBoundingBox());
  45215. boxHelper.matrixAutoUpdate = false;
  45216. pointcloud.boundingBoxNodes.push(boxHelper);
  45217. node.boundingBoxNode = boxHelper;
  45218. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  45219. } else if (pointcloud.showBoundingBox) {
  45220. node.boundingBoxNode.visible = true;
  45221. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  45222. } else if (!pointcloud.showBoundingBox && node.boundingBoxNode) {
  45223. node.boundingBoxNode.visible = false;
  45224. }
  45225. // if(node.boundingBoxNode !== undefined && exports.debug.allowedNodes !== undefined){
  45226. // if(!exports.debug.allowedNodes.includes(node.name)){
  45227. // node.boundingBoxNode.visible = false;
  45228. // }
  45229. // }
  45230. }
  45231. // add child nodes to priorityQueue
  45232. let children = node.getChildren();
  45233. for (let i = 0; i < children.length; i++) {
  45234. let child = children[i];
  45235. let weight = 0;
  45236. if(camera.isPerspectiveCamera){
  45237. let sphere = child.getBoundingSphere();
  45238. let center = sphere.center;
  45239. //let distance = sphere.center.distanceTo(camObjPos);
  45240. let dx = camObjPos.x - center.x;
  45241. let dy = camObjPos.y - center.y;
  45242. let dz = camObjPos.z - center.z;
  45243. let dd = dx * dx + dy * dy + dz * dz;
  45244. let distance = Math.sqrt(dd);
  45245. let radius = sphere.radius;
  45246. let fov = (camera.fov * Math.PI) / 180;
  45247. let slope = Math.tan(fov / 2);
  45248. let projFactor = (0.5 * domHeight) / (slope * distance);
  45249. let screenPixelRadius = radius * projFactor;
  45250. if(screenPixelRadius < pointcloud.minimumNodePixelSize){
  45251. continue;
  45252. }
  45253. weight = screenPixelRadius;
  45254. if(distance - radius < 0){
  45255. weight = Number.MAX_VALUE;
  45256. }
  45257. } else {
  45258. // TODO ortho visibility
  45259. let bb = child.getBoundingBox();
  45260. let distance = child.getBoundingSphere().center.distanceTo(camObjPos);
  45261. let diagonal = bb.max.clone().sub(bb.min).length();
  45262. //weight = diagonal / distance;
  45263. weight = diagonal;
  45264. }
  45265. priorityQueue.push({pointcloud: element.pointcloud, node: child, parent: node, weight: weight});
  45266. }
  45267. }// end priority queue loop
  45268. { // update DEM 这是什么
  45269. let maxDEMLevel = 4;
  45270. let candidates = pointclouds.filter(p => (p.generateDEM && p.dem instanceof Potree.DEM));
  45271. for (let pointcloud of candidates) {
  45272. let updatingNodes = pointcloud.visibleNodes.filter(n => n.getLevel() <= maxDEMLevel);
  45273. pointcloud.dem.update(updatingNodes);
  45274. }
  45275. }
  45276. //加载点云
  45277. for (let i = 0; i < Math.min(Potree.maxNodesLoading, unloadedGeometry.length); i++) {
  45278. unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry);
  45279. }
  45280. return {
  45281. visibleNodes: visibleNodes,
  45282. numVisiblePoints: numVisiblePoints,
  45283. lowestSpacing: lowestSpacing
  45284. };
  45285. };
  45286. //console
  45287. //viewer.scene.pointclouds[0].visibleNodes.map(e=> e && e.name )
  45288. //viewer.scene.pointclouds[0].visibleNodes.map(e=>e.children.map(e=>e && e.name))
  45289. class PointCloudArena4DNode extends PointCloudTreeNode {
  45290. constructor () {
  45291. super();
  45292. this.left = null;
  45293. this.right = null;
  45294. this.sceneNode = null;
  45295. this.kdtree = null;
  45296. }
  45297. getNumPoints () {
  45298. return this.geometryNode.numPoints;
  45299. }
  45300. isLoaded () {
  45301. return true;
  45302. }
  45303. isTreeNode () {
  45304. return true;
  45305. }
  45306. isGeometryNode () {
  45307. return false;
  45308. }
  45309. getLevel () {
  45310. return this.geometryNode.level;
  45311. }
  45312. getBoundingSphere () {
  45313. return this.geometryNode.boundingSphere;
  45314. }
  45315. getBoundingBox () {
  45316. return this.geometryNode.boundingBox;
  45317. }
  45318. toTreeNode (child) {
  45319. let geometryNode = null;
  45320. if (this.left === child) {
  45321. geometryNode = this.left;
  45322. } else if (this.right === child) {
  45323. geometryNode = this.right;
  45324. }
  45325. if (!geometryNode.loaded) {
  45326. return;
  45327. }
  45328. let node = new PointCloudArena4DNode();
  45329. let sceneNode = PointCloud(geometryNode.geometry, this.kdtree.material);
  45330. sceneNode.visible = false;
  45331. node.kdtree = this.kdtree;
  45332. node.geometryNode = geometryNode;
  45333. node.sceneNode = sceneNode;
  45334. node.parent = this;
  45335. node.left = this.geometryNode.left;
  45336. node.right = this.geometryNode.right;
  45337. }
  45338. getChildren () {
  45339. let children = [];
  45340. if (this.left) {
  45341. children.push(this.left);
  45342. }
  45343. if (this.right) {
  45344. children.push(this.right);
  45345. }
  45346. return children;
  45347. }
  45348. };
  45349. class PointCloudArena4D$1 extends PointCloudTree{
  45350. constructor (geometry) {
  45351. super();
  45352. this.root = null;
  45353. if (geometry.root) {
  45354. this.root = geometry.root;
  45355. } else {
  45356. geometry.addEventListener('hierarchy_loaded', () => {
  45357. this.root = geometry.root;
  45358. });
  45359. }
  45360. this.visiblePointsTarget = 2 * 1000 * 1000;
  45361. this.minimumNodePixelSize = 150;
  45362. this.position.sub(geometry.offset);
  45363. this.updateMatrix();
  45364. this.numVisibleNodes = 0;
  45365. this.numVisiblePoints = 0;
  45366. this.boundingBoxNodes = [];
  45367. this.loadQueue = [];
  45368. this.visibleNodes = [];
  45369. this.pcoGeometry = geometry;
  45370. this.boundingBox = this.pcoGeometry.boundingBox;
  45371. this.boundingSphere = this.pcoGeometry.boundingSphere;
  45372. this.material = new PointCloudMaterial$1({vertexColors: VertexColors, size: 0.05, treeType: TreeType.KDTREE});
  45373. this.material.sizeType = PointSizeType.ATTENUATED;
  45374. this.material.size = 0.05;
  45375. this.profileRequests = [];
  45376. this.name = '';
  45377. }
  45378. getBoundingBoxWorld () {
  45379. this.updateMatrixWorld(true);
  45380. let box = this.boundingBox;
  45381. let transform = this.matrixWorld;
  45382. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  45383. return tBox;
  45384. };
  45385. setName (name) {
  45386. if (this.name !== name) {
  45387. this.name = name;
  45388. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  45389. }
  45390. }
  45391. getName () {
  45392. return this.name;
  45393. }
  45394. getLevel () {
  45395. return this.level;
  45396. }
  45397. toTreeNode (geometryNode, parent) {
  45398. let node = new PointCloudArena4DNode();
  45399. let sceneNode = new Points(geometryNode.geometry, this.material);
  45400. sceneNode.frustumCulled = false;
  45401. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  45402. if (material.program) {
  45403. _this.getContext().useProgram(material.program.program);
  45404. if (material.program.getUniforms().map.level) {
  45405. let level = geometryNode.getLevel();
  45406. material.uniforms.level.value = level;
  45407. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  45408. }
  45409. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  45410. let vnStart = this.visibleNodeTextureOffsets.get(node);
  45411. material.uniforms.vnStart.value = vnStart;
  45412. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  45413. }
  45414. if (material.program.getUniforms().map.pcIndex) {
  45415. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  45416. material.uniforms.pcIndex.value = i;
  45417. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  45418. }
  45419. }
  45420. };
  45421. node.geometryNode = geometryNode;
  45422. node.sceneNode = sceneNode;
  45423. node.pointcloud = this;
  45424. node.left = geometryNode.left;
  45425. node.right = geometryNode.right;
  45426. if (!parent) {
  45427. this.root = node;
  45428. this.add(sceneNode);
  45429. } else {
  45430. parent.sceneNode.add(sceneNode);
  45431. if (parent.left === geometryNode) {
  45432. parent.left = node;
  45433. } else if (parent.right === geometryNode) {
  45434. parent.right = node;
  45435. }
  45436. }
  45437. let disposeListener = function () {
  45438. parent.sceneNode.remove(node.sceneNode);
  45439. if (parent.left === node) {
  45440. parent.left = geometryNode;
  45441. } else if (parent.right === node) {
  45442. parent.right = geometryNode;
  45443. }
  45444. };
  45445. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  45446. return node;
  45447. }
  45448. updateMaterial (material, visibleNodes, camera, renderer) {
  45449. material.fov = camera.fov * (Math.PI / 180);
  45450. material.screenWidth = renderer.domElement.clientWidth;
  45451. material.screenHeight = renderer.domElement.clientHeight;
  45452. material.spacing = this.pcoGeometry.spacing;
  45453. material.near = camera.near;
  45454. material.far = camera.far;
  45455. // reduce shader source updates by setting maxLevel slightly higher than actually necessary
  45456. if (this.maxLevel > material.levels) {
  45457. material.levels = this.maxLevel + 2;
  45458. }
  45459. // material.uniforms.octreeSize.value = this.boundingBox.size().x;
  45460. let bbSize = this.boundingBox.getSize(new Vector3());
  45461. material.bbSize = [bbSize.x, bbSize.y, bbSize.z];
  45462. }
  45463. updateVisibleBounds () {
  45464. }
  45465. hideDescendants (object) {
  45466. let stack = [];
  45467. for (let i = 0; i < object.children.length; i++) {
  45468. let child = object.children[i];
  45469. if (child.visible) {
  45470. stack.push(child);
  45471. }
  45472. }
  45473. while (stack.length > 0) {
  45474. let child = stack.shift();
  45475. child.visible = false;
  45476. if (child.boundingBoxNode) {
  45477. child.boundingBoxNode.visible = false;
  45478. }
  45479. for (let i = 0; i < child.children.length; i++) {
  45480. let childOfChild = child.children[i];
  45481. if (childOfChild.visible) {
  45482. stack.push(childOfChild);
  45483. }
  45484. }
  45485. }
  45486. }
  45487. updateMatrixWorld (force) {
  45488. // node.matrixWorld.multiplyMatrices( node.parent.matrixWorld, node.matrix );
  45489. if (this.matrixAutoUpdate === true) this.updateMatrix();
  45490. if (this.matrixWorldNeedsUpdate === true || force === true) {
  45491. if (this.parent === undefined) {
  45492. this.matrixWorld.copy(this.matrix);
  45493. } else {
  45494. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  45495. }
  45496. this.matrixWorldNeedsUpdate = false;
  45497. force = true;
  45498. }
  45499. }
  45500. nodesOnRay (nodes, ray) {
  45501. let nodesOnRay = [];
  45502. let _ray = ray.clone();
  45503. for (let i = 0; i < nodes.length; i++) {
  45504. let node = nodes[i];
  45505. let sphere = node.getBoundingSphere().clone().applyMatrix4(node.sceneNode.matrixWorld);
  45506. // TODO Unused: let box = node.getBoundingBox().clone().applyMatrix4(node.sceneNode.matrixWorld);
  45507. if (_ray.intersectsSphere(sphere)) {
  45508. nodesOnRay.push(node);
  45509. }
  45510. // if(_ray.isIntersectionBox(box)){
  45511. // nodesOnRay.push(node);
  45512. // }
  45513. }
  45514. return nodesOnRay;
  45515. }
  45516. pick(viewer, camera, ray, params = {}){
  45517. let renderer = viewer.renderer;
  45518. let pRenderer = viewer.pRenderer;
  45519. performance.mark("pick-start");
  45520. let getVal = (a, b) => a !== undefined ? a : b;
  45521. let pickWindowSize = getVal(params.pickWindowSize, 17);
  45522. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  45523. let size = renderer.getSize(new Vector2$1());
  45524. let width = Math.ceil(getVal(params.width, size.width));
  45525. let height = Math.ceil(getVal(params.height, size.height));
  45526. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  45527. let pointSize = getVal(params.pointSize, this.material.size);
  45528. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  45529. if (nodes.length === 0) {
  45530. return null;
  45531. }
  45532. if (!this.pickState) {
  45533. let scene = new Scene();
  45534. let material = new PointCloudMaterial$1();
  45535. material.activeAttributeName = "indices";
  45536. let renderTarget = new WebGLRenderTarget(
  45537. 1, 1,
  45538. { minFilter: LinearFilter,
  45539. magFilter: NearestFilter,
  45540. format: RGBAFormat }
  45541. );
  45542. this.pickState = {
  45543. renderTarget: renderTarget,
  45544. material: material,
  45545. scene: scene
  45546. };
  45547. };
  45548. let pickState = this.pickState;
  45549. let pickMaterial = pickState.material;
  45550. { // update pick material
  45551. pickMaterial.pointSizeType = pointSizeType;
  45552. pickMaterial.shape = this.material.shape;
  45553. pickMaterial.size = pointSize;
  45554. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  45555. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  45556. pickMaterial.classification = this.material.classification;
  45557. if(params.pickClipped){
  45558. pickMaterial.clipBoxes = this.material.clipBoxes;
  45559. if(this.material.clipTask === ClipTask.HIGHLIGHT){
  45560. pickMaterial.clipTask = ClipTask.NONE;
  45561. }else {
  45562. pickMaterial.clipTask = this.material.clipTask;
  45563. }
  45564. }else {
  45565. pickMaterial.clipBoxes = [];
  45566. }
  45567. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  45568. }
  45569. pickState.renderTarget.setSize(width, height);
  45570. let pixelPos = new Vector2$1(params.x, params.y);
  45571. let gl = renderer.getContext();
  45572. gl.enable(gl.SCISSOR_TEST);
  45573. gl.scissor(
  45574. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  45575. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  45576. parseInt(pickWindowSize), parseInt(pickWindowSize));
  45577. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  45578. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  45579. renderer.state.setBlending(NoBlending);
  45580. renderer.clearTarget(pickState.renderTarget, true, true, true);
  45581. { // RENDER
  45582. renderer.setRenderTarget(pickState.renderTarget);
  45583. gl.clearColor(0, 0, 0, 0);
  45584. renderer.clearTarget( pickState.renderTarget, true, true, true );
  45585. let tmp = this.material;
  45586. this.material = pickMaterial;
  45587. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  45588. this.material = tmp;
  45589. }
  45590. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  45591. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  45592. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  45593. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  45594. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  45595. let pixelCount = w * h;
  45596. let buffer = new Uint8Array(4 * pixelCount);
  45597. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  45598. renderer.setRenderTarget(null);
  45599. renderer.state.reset();
  45600. renderer.setScissorTest(false);
  45601. gl.disable(gl.SCISSOR_TEST);
  45602. let pixels = buffer;
  45603. let ibuffer = new Uint32Array(buffer.buffer);
  45604. // find closest hit inside pixelWindow boundaries
  45605. let min = Number.MAX_VALUE;
  45606. let hits = [];
  45607. for (let u = 0; u < pickWindowSize; u++) {
  45608. for (let v = 0; v < pickWindowSize; v++) {
  45609. let offset = (u + v * pickWindowSize);
  45610. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  45611. let pcIndex = pixels[4 * offset + 3];
  45612. pixels[4 * offset + 3] = 0;
  45613. let pIndex = ibuffer[offset];
  45614. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  45615. let hit = {
  45616. pIndex: pIndex,
  45617. pcIndex: pcIndex,
  45618. distanceToCenter: distance
  45619. };
  45620. if(params.all){
  45621. hits.push(hit);
  45622. }else {
  45623. if(hits.length > 0){
  45624. if(distance < hits[0].distanceToCenter){
  45625. hits[0] = hit;
  45626. }
  45627. }else {
  45628. hits.push(hit);
  45629. }
  45630. }
  45631. }
  45632. }
  45633. }
  45634. for(let hit of hits){
  45635. let point = {};
  45636. if (!nodes[hit.pcIndex]) {
  45637. return null;
  45638. }
  45639. let node = nodes[hit.pcIndex];
  45640. let pc = node.sceneNode;
  45641. let geometry = node.geometryNode.geometry;
  45642. for(let attributeName in geometry.attributes){
  45643. let attribute = geometry.attributes[attributeName];
  45644. if (attributeName === 'position') {
  45645. let x = attribute.array[3 * hit.pIndex + 0];
  45646. let y = attribute.array[3 * hit.pIndex + 1];
  45647. let z = attribute.array[3 * hit.pIndex + 2];
  45648. let position = new Vector3(x, y, z);
  45649. position.applyMatrix4(pc.matrixWorld);
  45650. point[attributeName] = position;
  45651. } else if (attributeName === 'indices') {
  45652. } else {
  45653. //if (values.itemSize === 1) {
  45654. // point[attribute.name] = values.array[hit.pIndex];
  45655. //} else {
  45656. // let value = [];
  45657. // for (let j = 0; j < values.itemSize; j++) {
  45658. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  45659. // }
  45660. // point[attribute.name] = value;
  45661. //}
  45662. }
  45663. }
  45664. hit.point = point;
  45665. }
  45666. performance.mark("pick-end");
  45667. performance.measure("pick", "pick-start", "pick-end");
  45668. if(params.all){
  45669. return hits.map(hit => hit.point);
  45670. }else {
  45671. if(hits.length === 0){
  45672. return null;
  45673. }else {
  45674. return hits[0].point;
  45675. }
  45676. }
  45677. }
  45678. computeVisibilityTextureData(nodes){
  45679. if(exports.measureTimings) performance.mark("computeVisibilityTextureData-start");
  45680. let data = new Uint8Array(nodes.length * 3);
  45681. let visibleNodeTextureOffsets = new Map();
  45682. // copy array
  45683. nodes = nodes.slice();
  45684. // sort by level and number
  45685. let sort = function (a, b) {
  45686. let la = a.geometryNode.level;
  45687. let lb = b.geometryNode.level;
  45688. let na = a.geometryNode.number;
  45689. let nb = b.geometryNode.number;
  45690. if (la !== lb) return la - lb;
  45691. if (na < nb) return -1;
  45692. if (na > nb) return 1;
  45693. return 0;
  45694. };
  45695. nodes.sort(sort);
  45696. let visibleNodeNames = [];
  45697. for (let i = 0; i < nodes.length; i++) {
  45698. visibleNodeNames.push(nodes[i].geometryNode.number);
  45699. }
  45700. for (let i = 0; i < nodes.length; i++) {
  45701. let node = nodes[i];
  45702. visibleNodeTextureOffsets.set(node, i);
  45703. let b1 = 0; // children
  45704. let b2 = 0; // offset to first child
  45705. let b3 = 0; // split
  45706. if (node.geometryNode.left && visibleNodeNames.indexOf(node.geometryNode.left.number) > 0) {
  45707. b1 += 1;
  45708. b2 = visibleNodeNames.indexOf(node.geometryNode.left.number) - i;
  45709. }
  45710. if (node.geometryNode.right && visibleNodeNames.indexOf(node.geometryNode.right.number) > 0) {
  45711. b1 += 2;
  45712. b2 = (b2 === 0) ? visibleNodeNames.indexOf(node.geometryNode.right.number) - i : b2;
  45713. }
  45714. if (node.geometryNode.split === 'X') {
  45715. b3 = 1;
  45716. } else if (node.geometryNode.split === 'Y') {
  45717. b3 = 2;
  45718. } else if (node.geometryNode.split === 'Z') {
  45719. b3 = 4;
  45720. }
  45721. data[i * 3 + 0] = b1;
  45722. data[i * 3 + 1] = b2;
  45723. data[i * 3 + 2] = b3;
  45724. }
  45725. if(exports.measureTimings){
  45726. performance.mark("computeVisibilityTextureData-end");
  45727. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  45728. }
  45729. return {
  45730. data: data,
  45731. offsets: visibleNodeTextureOffsets
  45732. };
  45733. }
  45734. get progress () {
  45735. if (this.pcoGeometry.root) {
  45736. return exports.numNodesLoading > 0 ? 0 : 1;
  45737. } else {
  45738. return 0;
  45739. }
  45740. }
  45741. };
  45742. // Copied from three.js: WebGLRenderer.js
  45743. function paramThreeToGL(_gl, p) {
  45744. let extension;
  45745. if (p === RepeatWrapping) return _gl.REPEAT;
  45746. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  45747. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  45748. if (p === NearestFilter) return _gl.NEAREST;
  45749. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  45750. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  45751. if (p === LinearFilter) return _gl.LINEAR;
  45752. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  45753. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  45754. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  45755. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  45756. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  45757. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  45758. if (p === ByteType) return _gl.BYTE;
  45759. if (p === ShortType) return _gl.SHORT;
  45760. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  45761. if (p === IntType) return _gl.INT;
  45762. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  45763. if (p === FloatType) return _gl.FLOAT;
  45764. if (p === HalfFloatType) {
  45765. extension = extensions.get('OES_texture_half_float');
  45766. if (extension !== null) return extension.HALF_FLOAT_OES;
  45767. }
  45768. if (p === AlphaFormat) return _gl.ALPHA;
  45769. if (p === RGBFormat) return _gl.RGB;
  45770. if (p === RGBAFormat) return _gl.RGBA;
  45771. if (p === LuminanceFormat) return _gl.LUMINANCE;
  45772. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  45773. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  45774. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  45775. if (p === AddEquation) return _gl.FUNC_ADD;
  45776. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  45777. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  45778. if (p === ZeroFactor) return _gl.ZERO;
  45779. if (p === OneFactor) return _gl.ONE;
  45780. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  45781. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  45782. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  45783. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  45784. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  45785. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  45786. if (p === DstColorFactor) return _gl.DST_COLOR;
  45787. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  45788. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  45789. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  45790. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  45791. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  45792. if (extension !== null) {
  45793. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45794. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45795. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45796. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45797. }
  45798. }
  45799. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  45800. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  45801. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  45802. if (extension !== null) {
  45803. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45804. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45805. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45806. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45807. }
  45808. }
  45809. if (p === RGB_ETC1_Format) {
  45810. extension = extensions.get('WEBGL_compressed_texture_etc1');
  45811. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  45812. }
  45813. if (p === MinEquation || p === MaxEquation) {
  45814. extension = extensions.get('EXT_blend_minmax');
  45815. if (extension !== null) {
  45816. if (p === MinEquation) return extension.MIN_EXT;
  45817. if (p === MaxEquation) return extension.MAX_EXT;
  45818. }
  45819. }
  45820. if (p === UnsignedInt248Type) {
  45821. extension = extensions.get('WEBGL_depth_texture');
  45822. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  45823. }
  45824. return 0;
  45825. };
  45826. let attributeLocations = {
  45827. "position": {name: "position", location: 0},
  45828. "color": {name: "color", location: 1},
  45829. "rgba": {name: "color", location: 1},
  45830. "intensity": {name: "intensity", location: 2},
  45831. "classification": {name: "classification", location: 3},
  45832. "returnNumber": {name: "returnNumber", location: 4},
  45833. "return number": {name: "returnNumber", location: 4},
  45834. "returns": {name: "returnNumber", location: 4},
  45835. "numberOfReturns": {name: "numberOfReturns", location: 5},
  45836. "number of returns": {name: "numberOfReturns", location: 5},
  45837. "pointSourceID": {name: "pointSourceID", location: 6},
  45838. "source id": {name: "pointSourceID", location: 6},
  45839. "point source id": {name: "pointSourceID", location: 6},
  45840. "indices": {name: "indices", location: 7},
  45841. "normal": {name: "normal", location: 8},
  45842. "spacing": {name: "spacing", location: 9},
  45843. "gps-time": {name: "gpsTime", location: 10},
  45844. "aExtra": {name: "aExtra", location: 11},
  45845. };
  45846. class Shader {
  45847. constructor(gl, name, vsSource, fsSource) {
  45848. this.gl = gl;
  45849. this.name = name;
  45850. this.vsSource = vsSource;
  45851. this.fsSource = fsSource;
  45852. this.cache = new Map();
  45853. this.vs = null;
  45854. this.fs = null;
  45855. this.program = null;
  45856. this.uniformLocations = {};
  45857. this.attributeLocations = {};
  45858. this.uniformBlockIndices = {};
  45859. this.uniformBlocks = {};
  45860. this.uniforms = {};
  45861. this.update(vsSource, fsSource);
  45862. }
  45863. update(vsSource, fsSource) {
  45864. this.vsSource = vsSource;
  45865. this.fsSource = fsSource;
  45866. this.linkProgram();
  45867. }
  45868. compileShader(shader, source){
  45869. let gl = this.gl;
  45870. gl.shaderSource(shader, source);
  45871. gl.compileShader(shader);
  45872. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  45873. if (!success) {
  45874. let info = gl.getShaderInfoLog(shader);
  45875. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  45876. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  45877. }
  45878. }
  45879. linkProgram() {
  45880. const tStart = performance.now();
  45881. let gl = this.gl;
  45882. this.uniformLocations = {};
  45883. this.attributeLocations = {};
  45884. this.uniforms = {};
  45885. gl.useProgram(null);
  45886. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  45887. if (cached) {
  45888. this.program = cached.program;
  45889. this.vs = cached.vs;
  45890. this.fs = cached.fs;
  45891. this.attributeLocations = cached.attributeLocations;
  45892. this.uniformLocations = cached.uniformLocations;
  45893. this.uniformBlocks = cached.uniformBlocks;
  45894. this.uniforms = cached.uniforms;
  45895. return;
  45896. } else {
  45897. this.vs = gl.createShader(gl.VERTEX_SHADER);
  45898. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  45899. this.program = gl.createProgram();
  45900. if( !gl.isProgram(this.program )){//创建失败 开启多个页面可能会,原因是webglcontextlost
  45901. //console.error('创建program失败');
  45902. viewer.dispatchEvent('webglError', {msg: 'potreeRenderer创建program失败'});
  45903. console.log(this.vs);
  45904. console.log(this.fs);
  45905. return;
  45906. }
  45907. for(let name of Object.keys(attributeLocations)){
  45908. let location = attributeLocations[name].location;
  45909. let glslName = attributeLocations[name].name;
  45910. gl.bindAttribLocation(this.program, location, glslName);
  45911. }
  45912. this.compileShader(this.vs, this.vsSource);
  45913. this.compileShader(this.fs, this.fsSource);
  45914. let program = this.program;
  45915. gl.attachShader(program, this.vs);
  45916. gl.attachShader(program, this.fs);
  45917. gl.linkProgram(program);
  45918. gl.detachShader(program, this.vs);
  45919. gl.detachShader(program, this.fs);
  45920. // 检测当前程序链接状态
  45921. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  45922. if (!success) {
  45923. let info = gl.getProgramInfoLog(program);
  45924. throw `could not link program ${this.name}: ${info}`;
  45925. }
  45926. { // attribute locations
  45927. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  45928. for (let i = 0; i < numAttributes; i++) {
  45929. let attribute = gl.getActiveAttrib(program, i);
  45930. let location = gl.getAttribLocation(program, attribute.name);
  45931. this.attributeLocations[attribute.name] = location;
  45932. }
  45933. }
  45934. { // uniform locations
  45935. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  45936. for (let i = 0; i < numUniforms; i++) {
  45937. let uniform = gl.getActiveUniform(program, i);
  45938. let location = gl.getUniformLocation(program, uniform.name);
  45939. this.uniformLocations[uniform.name] = location;
  45940. this.uniforms[uniform.name] = {
  45941. location: location,
  45942. value: null,
  45943. };
  45944. }
  45945. }
  45946. // uniform blocks
  45947. if( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext){ //WebGL2RenderingContext在mac的safari14以下是没有定义的
  45948. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  45949. for (let i = 0; i < numBlocks; i++) {
  45950. let blockName = gl.getActiveUniformBlockName(program, i);
  45951. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  45952. this.uniformBlockIndices[blockName] = blockIndex;
  45953. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  45954. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  45955. let uBuffer = gl.createBuffer();
  45956. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  45957. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  45958. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  45959. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  45960. this.uniformBlocks[blockName] = {
  45961. name: blockName,
  45962. index: blockIndex,
  45963. dataSize: dataSize,
  45964. buffer: uBuffer
  45965. };
  45966. }
  45967. }
  45968. let cached = {
  45969. program: this.program,
  45970. vs: this.vs,
  45971. fs: this.fs,
  45972. attributeLocations: this.attributeLocations,
  45973. uniformLocations: this.uniformLocations,
  45974. uniforms: this.uniforms,
  45975. uniformBlocks: this.uniformBlocks,
  45976. };
  45977. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  45978. }
  45979. const tEnd = performance.now();
  45980. const duration = tEnd - tStart;
  45981. //console.log(`shader compile duration: ${duration.toFixed(3)}`);
  45982. }
  45983. setUniformMatrix4(name, value) {
  45984. const gl = this.gl;
  45985. const location = this.uniformLocations[name];
  45986. if (location == null) {
  45987. return;
  45988. }
  45989. let tmp = new Float32Array(value.elements);
  45990. gl.uniformMatrix4fv(location, false, tmp);
  45991. }
  45992. setUniform1f(name, value) {
  45993. const gl = this.gl;
  45994. const uniform = this.uniforms[name];
  45995. if (uniform === undefined) {
  45996. return;
  45997. }
  45998. if(uniform.value === value){
  45999. return;
  46000. }
  46001. uniform.value = value;
  46002. gl.uniform1f(uniform.location, value);
  46003. }
  46004. setUniformBoolean(name, value) {
  46005. const gl = this.gl;
  46006. const uniform = this.uniforms[name];
  46007. if (uniform === undefined) {
  46008. return;
  46009. }
  46010. if(uniform.value === value){
  46011. return;
  46012. }
  46013. uniform.value = value;
  46014. gl.uniform1i(uniform.location, value);
  46015. }
  46016. setUniformTexture(name, value) {
  46017. const gl = this.gl;
  46018. const location = this.uniformLocations[name];
  46019. if (location == null) {
  46020. return;
  46021. }
  46022. gl.uniform1i(location, value);
  46023. }
  46024. setUniform2f(name, value) {
  46025. const gl = this.gl;
  46026. const location = this.uniformLocations[name];
  46027. if (location == null) {
  46028. return;
  46029. }
  46030. gl.uniform2f(location, value[0], value[1]);
  46031. }
  46032. setUniform3f(name, value) {
  46033. const gl = this.gl;
  46034. const location = this.uniformLocations[name];
  46035. if (location == null) {
  46036. return;
  46037. }
  46038. gl.uniform3f(location, value[0], value[1], value[2]);
  46039. }
  46040. setUniform(name, value) {
  46041. if (value.constructor === Matrix4) {
  46042. this.setUniformMatrix4(name, value);
  46043. } else if (typeof value === "number") {
  46044. this.setUniform1f(name, value);
  46045. } else if (typeof value === "boolean") {
  46046. this.setUniformBoolean(name, value);
  46047. } else if (value instanceof WebGLTexture) {
  46048. this.setUniformTexture(name, value);
  46049. } else if (value instanceof Array) {
  46050. if (value.length === 2) {
  46051. this.setUniform2f(name, value);
  46052. } else if (value.length === 3) {
  46053. this.setUniform3f(name, value);
  46054. }
  46055. } else {
  46056. console.error("unhandled uniform type: ", name, value);
  46057. }
  46058. }
  46059. setUniform1i(name, value) {
  46060. let gl = this.gl;
  46061. let location = this.uniformLocations[name];
  46062. if (location == null) {
  46063. return;
  46064. }
  46065. gl.uniform1i(location, value);
  46066. }
  46067. };
  46068. class WebGLTexture {
  46069. constructor(gl, texture) {
  46070. this.gl = gl;
  46071. this.texture = texture;
  46072. this.id = gl.createTexture();
  46073. this.target = gl.TEXTURE_2D;
  46074. this.version = -1;
  46075. this.update(texture);
  46076. }
  46077. update() {
  46078. if (!this.texture.image) {
  46079. this.version = this.texture.version;
  46080. return;
  46081. }
  46082. let gl = this.gl;
  46083. let texture = this.texture;
  46084. if (this.version === texture.version) {
  46085. return;
  46086. }
  46087. this.target = gl.TEXTURE_2D;
  46088. gl.bindTexture(this.target, this.id);
  46089. let level = 0;
  46090. let internalFormat = paramThreeToGL(gl, texture.format);
  46091. let width = texture.image.width;
  46092. let height = texture.image.height;
  46093. let border = 0;
  46094. let srcFormat = internalFormat;
  46095. let srcType = paramThreeToGL(gl, texture.type);
  46096. let data;
  46097. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  46098. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  46099. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  46100. if (texture instanceof DataTexture) {
  46101. data = texture.image.data;
  46102. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  46103. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46104. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  46105. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  46106. gl.texImage2D(this.target, level, internalFormat,
  46107. width, height, border, srcFormat, srcType,
  46108. data);
  46109. }/* else if(texture instanceof THREE.CubeTexture){//add
  46110. } */else if ((texture instanceof CanvasTexture) || (texture instanceof Texture)) {
  46111. data = texture.image;
  46112. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  46113. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  46114. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  46115. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  46116. gl.texImage2D(this.target, level, internalFormat,
  46117. internalFormat, srcType, data);
  46118. if (texture instanceof Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  46119. }
  46120. gl.bindTexture(this.target, null);
  46121. this.version = texture.version;
  46122. }
  46123. };
  46124. class WebGLBuffer {
  46125. constructor() {
  46126. this.numElements = 0;
  46127. this.vao = null;
  46128. this.vbos = new Map();
  46129. }
  46130. };
  46131. class Renderer {
  46132. constructor(threeRenderer) {
  46133. this.threeRenderer = threeRenderer;
  46134. this.gl = this.threeRenderer.getContext();
  46135. this.buffers = new Map();
  46136. this.shaders = new Map();
  46137. this.textures = new Map();
  46138. this.glTypeMapping = new Map();
  46139. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  46140. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  46141. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  46142. this.toggle = 0;
  46143. }
  46144. deleteBuffer(geometry) {
  46145. let gl = this.gl;
  46146. let webglBuffer = this.buffers.get(geometry);
  46147. if (webglBuffer != null) {
  46148. for (let attributeName in geometry.attributes) {
  46149. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  46150. }
  46151. this.buffers.delete(geometry);
  46152. }
  46153. }
  46154. createBuffer(geometry){
  46155. let gl = this.gl;
  46156. let webglBuffer = new WebGLBuffer();
  46157. webglBuffer.vao = gl.createVertexArray();
  46158. webglBuffer.numElements = geometry.attributes.position.count;
  46159. gl.bindVertexArray(webglBuffer.vao);
  46160. for(let attributeName in geometry.attributes){
  46161. let bufferAttribute = geometry.attributes[attributeName];
  46162. let vbo = gl.createBuffer();
  46163. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  46164. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  46165. let normalized = bufferAttribute.normalized;
  46166. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46167. if(attributeLocations[attributeName] === undefined){
  46168. //attributeLocation = attributeLocations["aExtra"];
  46169. }else {
  46170. let attributeLocation = attributeLocations[attributeName].location;
  46171. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46172. gl.enableVertexAttribArray(attributeLocation);
  46173. }
  46174. webglBuffer.vbos.set(attributeName, {
  46175. handle: vbo,
  46176. name: attributeName,
  46177. count: bufferAttribute.count,
  46178. itemSize: bufferAttribute.itemSize,
  46179. type: geometry.attributes.position.array.constructor,
  46180. version: 0
  46181. });
  46182. }
  46183. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46184. gl.bindVertexArray(null);
  46185. let disposeHandler = (event) => {
  46186. this.deleteBuffer(geometry);
  46187. geometry.removeEventListener("dispose", disposeHandler);
  46188. };
  46189. geometry.addEventListener("dispose", disposeHandler);
  46190. return webglBuffer;
  46191. }
  46192. updateBuffer(geometry){
  46193. let gl = this.gl;
  46194. let webglBuffer = this.buffers.get(geometry);
  46195. gl.bindVertexArray(webglBuffer.vao);
  46196. for(let attributeName in geometry.attributes){
  46197. let bufferAttribute = geometry.attributes[attributeName];
  46198. let normalized = bufferAttribute.normalized;
  46199. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46200. let vbo = null;
  46201. if(!webglBuffer.vbos.has(attributeName)){
  46202. vbo = gl.createBuffer();
  46203. webglBuffer.vbos.set(attributeName, {
  46204. handle: vbo,
  46205. name: attributeName,
  46206. count: bufferAttribute.count,
  46207. itemSize: bufferAttribute.itemSize,
  46208. type: geometry.attributes.position.array.constructor,
  46209. version: bufferAttribute.version
  46210. });
  46211. }else {
  46212. vbo = webglBuffer.vbos.get(attributeName).handle;
  46213. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  46214. }
  46215. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  46216. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  46217. if(attributeLocations[attributeName] === undefined){
  46218. //attributeLocation = attributeLocations["aExtra"];
  46219. }else {
  46220. let attributeLocation = attributeLocations[attributeName].location;
  46221. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46222. gl.enableVertexAttribArray(attributeLocation);
  46223. }
  46224. }
  46225. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46226. gl.bindVertexArray(null);
  46227. }
  46228. traverse(scene) {
  46229. let octrees = [];
  46230. let stack = [scene];
  46231. while (stack.length > 0) {
  46232. let node = stack.pop();
  46233. if (node instanceof PointCloudTree) {
  46234. octrees.push(node);
  46235. continue;
  46236. }
  46237. let visibleChildren = node.children.filter(c => c.visible);
  46238. stack.push(...visibleChildren);
  46239. }
  46240. let result = {
  46241. octrees: octrees
  46242. };
  46243. return result;
  46244. }
  46245. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  46246. if (exports.measureTimings) performance.mark("renderNodes-start");
  46247. let gl = this.gl;
  46248. let material = params.material ? params.material : octree.material;
  46249. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  46250. let view = camera.matrixWorldInverse;
  46251. if(params.viewOverride){
  46252. view = params.viewOverride;
  46253. }
  46254. let worldView = new Matrix4();
  46255. let mat4holder = new Float32Array(16);
  46256. let i = 0;
  46257. for (let node of nodes) {
  46258. if(exports.debug.allowedNodes !== undefined){
  46259. if(!exports.debug.allowedNodes.includes(node.name)){
  46260. continue;
  46261. }
  46262. }
  46263. let world = node.sceneNode.matrixWorld;
  46264. worldView.multiplyMatrices(view, world);
  46265. if (visibilityTextureData) {
  46266. let vnStart = visibilityTextureData.offsets.get(node);
  46267. shader.setUniform1f("uVNStart", vnStart);
  46268. }
  46269. let level = node.getLevel();
  46270. if(node.debug){
  46271. shader.setUniform("uDebug", true);
  46272. }else {
  46273. shader.setUniform("uDebug", false);
  46274. }
  46275. // let isLeaf = false;
  46276. // if(node instanceof PointCloudOctreeNode){
  46277. // isLeaf = Object.keys(node.children).length === 0;
  46278. // }else if(node instanceof PointCloudArena4DNode){
  46279. // isLeaf = node.geometryNode.isLeaf;
  46280. // }
  46281. // shader.setUniform("uIsLeafNode", isLeaf);
  46282. // let isLeaf = node.children.filter(n => n != null).length === 0;
  46283. // if(!isLeaf){
  46284. // continue;
  46285. // }
  46286. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  46287. const lModel = shader.uniformLocations["modelMatrix"];
  46288. if (lModel) {
  46289. mat4holder.set(world.elements);
  46290. gl.uniformMatrix4fv(lModel, false, mat4holder);
  46291. }
  46292. const lModelView = shader.uniformLocations["modelViewMatrix"];
  46293. //mat4holder.set(worldView.elements);
  46294. // faster then set in chrome 63
  46295. for(let j = 0; j < 16; j++){
  46296. mat4holder[j] = worldView.elements[j];
  46297. }
  46298. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  46299. { // Clip Polygons
  46300. if(material.clipPolygons && material.clipPolygons.length > 0){
  46301. let clipPolygonVCount = [];
  46302. let worldViewProjMatrices = [];
  46303. for(let clipPolygon of material.clipPolygons){
  46304. let view = clipPolygon.viewMatrix;
  46305. let proj = clipPolygon.projMatrix;
  46306. let worldViewProj = proj.clone().multiply(view).multiply(world);
  46307. clipPolygonVCount.push(clipPolygon.markers.length);
  46308. worldViewProjMatrices.push(worldViewProj);
  46309. }
  46310. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  46311. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  46312. for(let i = 0; i < material.clipPolygons.length; i++){
  46313. let clipPolygon = material.clipPolygons[i];
  46314. for(let j = 0; j < clipPolygon.markers.length; j++){
  46315. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  46316. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  46317. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  46318. }
  46319. }
  46320. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  46321. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  46322. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  46323. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  46324. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  46325. gl.uniform3fv(lClipPolygons, flattenedVertices);
  46326. }
  46327. }
  46328. //shader.setUniformMatrix4("modelMatrix", world);
  46329. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  46330. shader.setUniform1f("uLevel", level);
  46331. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  46332. shader.setUniform1f("uPCIndex", i);
  46333. // uBBSize
  46334. if (shadowMaps.length > 0) {
  46335. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  46336. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  46337. let bindingStart = 5;
  46338. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  46339. gl.uniform1iv(lShadowMap, bindingPoints);
  46340. for (let i = 0; i < shadowMaps.length; i++) {
  46341. let shadowMap = shadowMaps[i];
  46342. let bindingPoint = bindingPoints[i];
  46343. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  46344. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  46345. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  46346. }
  46347. {
  46348. let worldViewMatrices = shadowMaps
  46349. .map(sm => sm.camera.matrixWorldInverse)
  46350. .map(view => new Matrix4().multiplyMatrices(view, world));
  46351. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  46352. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  46353. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  46354. }
  46355. {
  46356. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  46357. const lProj = shader.uniformLocations["uShadowProj[0]"];
  46358. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  46359. }
  46360. }
  46361. const geometry = node.geometryNode.geometry;
  46362. if(geometry.attributes["gps-time"]){
  46363. const bufferAttribute = geometry.attributes["gps-time"];
  46364. const attGPS = octree.getAttribute("gps-time");
  46365. let initialRange = attGPS.initialRange;
  46366. let initialRangeSize = initialRange[1] - initialRange[0];
  46367. let globalRange = attGPS.range;
  46368. let globalRangeSize = globalRange[1] - globalRange[0];
  46369. let scale = initialRangeSize / globalRangeSize;
  46370. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  46371. scale = Number.isNaN(scale) ? 1 : scale;
  46372. offset = Number.isNaN(offset) ? 0 : offset;
  46373. shader.setUniform1f("uGpsScale", scale);
  46374. shader.setUniform1f("uGpsOffset", offset);
  46375. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  46376. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  46377. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  46378. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  46379. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  46380. let normalizedClipRange = [
  46381. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  46382. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  46383. ];
  46384. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  46385. // // ranges in full gps coordinate system
  46386. // const globalRange = attGPS.range;
  46387. // const bufferRange = bufferAttribute.potree.range;
  46388. // // ranges in [0, 1]
  46389. // // normalizedGlobalRange = [0, 1]
  46390. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  46391. // const globalWidth = globalRange[1] - globalRange[0];
  46392. // const normalizedBufferRange = [
  46393. // (bufferRange[0] - globalRange[0]) / globalWidth,
  46394. // (bufferRange[1] - globalRange[0]) / globalWidth,
  46395. // ];
  46396. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  46397. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  46398. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  46399. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  46400. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  46401. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  46402. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  46403. }
  46404. {
  46405. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  46406. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  46407. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  46408. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  46409. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  46410. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  46411. }
  46412. let webglBuffer = null;
  46413. if(!this.buffers.has(geometry)){
  46414. webglBuffer = this.createBuffer(geometry);
  46415. this.buffers.set(geometry, webglBuffer);
  46416. }else {
  46417. webglBuffer = this.buffers.get(geometry);
  46418. for(let attributeName in geometry.attributes){
  46419. let attribute = geometry.attributes[attributeName];
  46420. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  46421. this.updateBuffer(geometry);
  46422. }
  46423. }
  46424. }
  46425. gl.bindVertexArray(webglBuffer.vao);
  46426. let isExtraAttribute =
  46427. attributeLocations[material.activeAttributeName] === undefined
  46428. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  46429. if(isExtraAttribute){
  46430. const attributeLocation = attributeLocations["aExtra"].location;
  46431. for(const attributeName in geometry.attributes){
  46432. const bufferAttribute = geometry.attributes[attributeName];
  46433. const vbo = webglBuffer.vbos.get(attributeName);
  46434. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46435. gl.disableVertexAttribArray(attributeLocation);
  46436. }
  46437. const attName = material.activeAttributeName;
  46438. const bufferAttribute = geometry.attributes[attName];
  46439. const vbo = webglBuffer.vbos.get(attName);
  46440. if(bufferAttribute !== undefined && vbo !== undefined){
  46441. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46442. let normalized = bufferAttribute.normalized;
  46443. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46444. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46445. gl.enableVertexAttribArray(attributeLocation);
  46446. }
  46447. {
  46448. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  46449. .find(a => a.name === attName);
  46450. let range = material.getRange(attName);
  46451. if(!range){
  46452. range = attExtra.range;
  46453. }
  46454. if(!range){
  46455. range = [0, 1];
  46456. }
  46457. let initialRange = attExtra.initialRange;
  46458. let initialRangeSize = initialRange[1] - initialRange[0];
  46459. let globalRange = range;
  46460. let globalRangeSize = globalRange[1] - globalRange[0];
  46461. let scale = initialRangeSize / globalRangeSize;
  46462. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  46463. scale = Number.isNaN(scale) ? 1 : scale;
  46464. offset = Number.isNaN(offset) ? 0 : offset;
  46465. shader.setUniform1f("uExtraScale", scale);
  46466. shader.setUniform1f("uExtraOffset", offset);
  46467. }
  46468. }else {
  46469. for(const attributeName in geometry.attributes){
  46470. const bufferAttribute = geometry.attributes[attributeName];
  46471. const vbo = webglBuffer.vbos.get(attributeName);
  46472. if(attributeLocations[attributeName] !== undefined){
  46473. const attributeLocation = attributeLocations[attributeName].location;
  46474. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46475. let normalized = bufferAttribute.normalized;
  46476. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46477. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46478. gl.enableVertexAttribArray(attributeLocation);
  46479. }
  46480. }
  46481. }
  46482. let numPoints = webglBuffer.numElements;
  46483. gl.drawArrays(gl.POINTS, 0, numPoints);
  46484. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  46485. i++;
  46486. }
  46487. gl.bindVertexArray(null);
  46488. if (exports.measureTimings) {
  46489. performance.mark("renderNodes-end");
  46490. performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end");
  46491. }
  46492. }
  46493. renderOctree(octree, nodes, camera, target, params = {}){
  46494. let gl = this.gl;
  46495. let material = params.material ? params.material : octree.material;
  46496. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  46497. let view = camera.matrixWorldInverse;
  46498. let viewInv = camera.matrixWorld;
  46499. if(params.viewOverride){
  46500. view = params.viewOverride;
  46501. viewInv = view.clone().invert();
  46502. }
  46503. let proj = camera.projectionMatrix;
  46504. let projInv = proj.clone().invert();
  46505. //let worldView = new THREE.Matrix4();
  46506. let shader = null;
  46507. let visibilityTextureData = null;
  46508. let currentTextureBindingPoint = 0;
  46509. if (material.pointSizeType >= 0) {
  46510. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  46511. material.activeAttributeName === "level of detail") {
  46512. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  46513. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  46514. const vnt = material.visibleNodesTexture;
  46515. const data = vnt.image.data;
  46516. data.set(visibilityTextureData.data);
  46517. vnt.needsUpdate = true;
  46518. }
  46519. }
  46520. { // UPDATE SHADER AND TEXTURES
  46521. if (!this.shaders.has(material)) {
  46522. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  46523. let shader = new Shader(gl, "pointcloud", vs, fs);
  46524. this.shaders.set(material, shader);
  46525. }
  46526. shader = this.shaders.get(material);
  46527. //if(material.needsUpdate){
  46528. {
  46529. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  46530. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  46531. let numClipBoxes = (material.clipBoxes && material.clipBoxes.length) ? material.clipBoxes.length : 0;
  46532. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  46533. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  46534. let defines = [
  46535. `#define num_shadowmaps ${shadowMaps.length}`,
  46536. `#define num_snapshots ${numSnapshots}`,
  46537. `#define num_clipboxes ${numClipBoxes}`,
  46538. `#define num_clipspheres ${numClipSpheres}`,
  46539. `#define num_clippolygons ${numClipPolygons}`,
  46540. ];
  46541. //add:-----------
  46542. if(material.usePanoMap){
  46543. defines.push("#define usePanoMap");
  46544. }
  46545. if(material.useFilterByNormal){
  46546. defines.push("#define use_filter_by_normal");
  46547. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  46548. }
  46549. //---------------
  46550. if(octree.pcoGeometry.root.isLoaded()){
  46551. let attributes = octree.pcoGeometry.root.geometry.attributes;
  46552. if(attributes["gps-time"]){
  46553. defines.push("#define clip_gps_enabled");
  46554. }
  46555. if(attributes["return number"]){
  46556. defines.push("#define clip_return_number_enabled");
  46557. }
  46558. if(attributes["number of returns"]){
  46559. defines.push("#define clip_number_of_returns_enabled");
  46560. }
  46561. if(attributes["source id"] || attributes["point source id"]){
  46562. defines.push("#define clip_point_source_id_enabled");
  46563. }
  46564. }
  46565. let definesString = defines.join("\n");
  46566. let vsVersionIndex = vs.indexOf("#version ");
  46567. let fsVersionIndex = fs.indexOf("#version ");
  46568. if(vsVersionIndex >= 0){
  46569. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  46570. }else {
  46571. vs = `${definesString}\n${vs}`;
  46572. }
  46573. if(fsVersionIndex >= 0){
  46574. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  46575. }else {
  46576. fs = `${definesString}\n${fs}`;
  46577. }
  46578. shader.update(vs, fs);
  46579. material.needsUpdate = false;
  46580. }
  46581. for (let uniformName of Object.keys(material.uniforms)) {
  46582. let uniform = material.uniforms[uniformName];
  46583. if (uniform.type == "t") {
  46584. let texture = uniform.value;
  46585. if (!texture) {
  46586. continue;
  46587. }
  46588. //add
  46589. if(uniformName == 'pano0Map' || uniformName == 'pano1Map' ){ //属于cubeTex,另外设置
  46590. continue
  46591. }
  46592. if (!this.textures.has(texture)) {
  46593. let webglTexture = new WebGLTexture(gl, texture);
  46594. this.textures.set(texture, webglTexture);
  46595. }
  46596. let webGLTexture = this.textures.get(texture);
  46597. webGLTexture.update();
  46598. }
  46599. }
  46600. }
  46601. gl.useProgram(shader.program);
  46602. let transparent = false;
  46603. if(params.transparent !== undefined){
  46604. transparent = params.transparent && material.opacity < 1;
  46605. }else {
  46606. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  46607. }
  46608. if (transparent){
  46609. gl.enable(gl.BLEND);
  46610. if(params.notAdditiveBlending){
  46611. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  46612. gl.enable(gl.DEPTH_TEST);
  46613. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  46614. }else {
  46615. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  46616. gl.disable(gl.DEPTH_TEST);
  46617. gl.depthMask(false);
  46618. }
  46619. } else {
  46620. gl.disable(gl.BLEND);
  46621. gl.depthMask(true);
  46622. gl.enable(gl.DEPTH_TEST);
  46623. }
  46624. if(params.blendFunc !== undefined){
  46625. gl.enable(gl.BLEND);
  46626. gl.blendFunc(...params.blendFunc);
  46627. }
  46628. if(params.depthTest !== undefined){
  46629. if(params.depthTest === true){
  46630. gl.enable(gl.DEPTH_TEST);
  46631. }else {
  46632. gl.disable(gl.DEPTH_TEST);
  46633. }
  46634. }
  46635. if(params.depthWrite !== undefined){
  46636. if(params.depthWrite === true){
  46637. gl.depthMask(true);
  46638. }else {
  46639. gl.depthMask(false);
  46640. }
  46641. }
  46642. { // UPDATE UNIFORMS
  46643. shader.setUniformMatrix4("projectionMatrix", proj);
  46644. shader.setUniformMatrix4("viewMatrix", view);
  46645. shader.setUniformMatrix4("uViewInv", viewInv);
  46646. shader.setUniformMatrix4("uProjInv", projInv);
  46647. /* let screenWidth = target ? target.width : material.screenWidth;
  46648. let screenHeight = target ? target.height : material.screenHeight;
  46649. shader.setUniform1f("uScreenWidth", screenWidth);
  46650. shader.setUniform1f("uScreenHeight", screenHeight); */
  46651. shader.setUniform2f('resolution', material.resolution.toArray());
  46652. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  46653. shader.setUniform1f("near", camera.near);
  46654. shader.setUniform1f("far", camera.far);
  46655. if(camera instanceof OrthographicCamera){
  46656. shader.setUniform("uUseOrthographicCamera", true);
  46657. shader.setUniform("uOrthoWidth", camera.right - camera.left);
  46658. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  46659. }else {
  46660. shader.setUniform("uUseOrthographicCamera", false);
  46661. }
  46662. if(material.clipBoxes.length + material.clipPolygons.length === 0){
  46663. shader.setUniform1i("clipTask", ClipTask.NONE);
  46664. }else {
  46665. shader.setUniform1i("clipTask", material.clipTask);
  46666. }
  46667. shader.setUniform1i("clipMethod", material.clipMethod);
  46668. if (material.clipBoxes && material.clipBoxes.length > 0) {
  46669. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  46670. //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  46671. //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices);
  46672. const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  46673. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value);
  46674. }
  46675. // TODO CLIPSPHERES
  46676. if(params.clipSpheres && params.clipSpheres.length > 0){
  46677. let clipSpheres = params.clipSpheres;
  46678. let matrices = [];
  46679. for(let clipSphere of clipSpheres){
  46680. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  46681. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  46682. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  46683. let clipToWorld = clipSphere.matrixWorld;
  46684. let viewToWorld = camera.matrixWorld;
  46685. let worldToClip = clipToWorld.clone().invert();
  46686. let viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  46687. matrices.push(viewToClip);
  46688. }
  46689. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  46690. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  46691. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  46692. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  46693. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  46694. }
  46695. shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio,2) : material.size);//usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点
  46696. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  46697. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  46698. // uniform float uPCIndex
  46699. shader.setUniform1f("uOctreeSpacing", material.spacing);
  46700. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  46701. //uniform vec3 uColor;
  46702. shader.setUniform3f("uColor", material.color.toArray());
  46703. //uniform float opacity;
  46704. shader.setUniform1f("uOpacity", material.usePanoMap ? 1: material.opacity);
  46705. shader.setUniform2f("elevationRange", material.elevationRange);
  46706. shader.setUniform2f("intensityRange", material.intensityRange);
  46707. shader.setUniform3f("uIntensity_gbc", [
  46708. material.intensityGamma,
  46709. material.intensityBrightness,
  46710. material.intensityContrast
  46711. ]);
  46712. shader.setUniform3f("uRGB_gbc", [
  46713. material.rgbGamma,
  46714. material.rgbBrightness,
  46715. material.rgbContrast
  46716. ]);
  46717. shader.setUniform1f("uTransition", material.transition);
  46718. shader.setUniform1f("wRGB", material.weightRGB);
  46719. shader.setUniform1f("wIntensity", material.weightIntensity);
  46720. shader.setUniform1f("wElevation", material.weightElevation);
  46721. shader.setUniform1f("wClassification", material.weightClassification);
  46722. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  46723. shader.setUniform1f("wSourceID", material.weightSourceID);
  46724. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  46725. //==========================
  46726. //gl.TEXTURE_CUBE_MAP: 34067
  46727. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  46728. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);
  46729. if(vnWebGLTexture){
  46730. shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint);
  46731. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46732. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  46733. currentTextureBindingPoint++;
  46734. }
  46735. let gradientTexture = this.textures.get(material.gradientTexture);
  46736. shader.setUniform1i("gradient", currentTextureBindingPoint);
  46737. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46738. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  46739. const repeat = material.elevationGradientRepeat;
  46740. if(repeat === ElevationGradientRepeat.REPEAT){
  46741. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  46742. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  46743. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  46744. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  46745. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  46746. }else {
  46747. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  46748. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46749. }
  46750. currentTextureBindingPoint++;
  46751. let classificationTexture = this.textures.get(material.classificationTexture);
  46752. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  46753. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46754. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  46755. currentTextureBindingPoint++;
  46756. let matcapTexture = this.textures.get(material.matcapTexture);
  46757. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  46758. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46759. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  46760. currentTextureBindingPoint++;
  46761. if (material.snapEnabled === true) {
  46762. {
  46763. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  46764. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  46765. let bindingStart = currentTextureBindingPoint;
  46766. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  46767. let lSnapshotDepthBindingPoints = new Array(5)
  46768. .fill(1 + Math.max(...lSnapshotBindingPoints))
  46769. .map((a, i) => (a + i));
  46770. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  46771. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  46772. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  46773. for (let i = 0; i < 5; i++) {
  46774. let texture = material.uniforms[`uSnapshot`].value[i];
  46775. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  46776. if (!texture) {
  46777. break;
  46778. }
  46779. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  46780. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  46781. let bindingPoint = lSnapshotBindingPoints[i];
  46782. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  46783. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  46784. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  46785. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  46786. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  46787. }
  46788. }
  46789. {
  46790. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  46791. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  46792. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  46793. }
  46794. {
  46795. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  46796. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  46797. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  46798. }
  46799. {
  46800. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  46801. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  46802. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  46803. }
  46804. {
  46805. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  46806. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  46807. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  46808. }
  46809. }
  46810. //=============add===========
  46811. if(material.usePanoMap){//为什么pointsize失效
  46812. shader.setUniform1f("progress", material.uniforms.progress.value);
  46813. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  46814. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  46815. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  46816. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  46817. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  46818. let pano0Map = material.uniforms.pano0Map.value;
  46819. if(pano0Map){
  46820. this.threeRenderer._textures.safeSetTextureCube( pano0Map, ++currentTextureBindingPoint );
  46821. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  46822. }
  46823. let pano1Map = material.uniforms.pano1Map.value;
  46824. if(pano1Map){
  46825. this.threeRenderer._textures.safeSetTextureCube( pano1Map, ++currentTextureBindingPoint );
  46826. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  46827. }
  46828. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  46829. }
  46830. }
  46831. this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params);
  46832. gl.activeTexture(gl.TEXTURE2);
  46833. gl.bindTexture(gl.TEXTURE_2D, null);
  46834. gl.activeTexture(gl.TEXTURE0);
  46835. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  46836. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  46837. gl.disable(gl.BLEND);
  46838. gl.depthMask(true);
  46839. gl.enable(gl.DEPTH_TEST);
  46840. //DEPTH_TEST等需要恢复吗
  46841. }
  46842. render(scene, camera, target = null, params = {}) {
  46843. const gl = this.gl;
  46844. // PREPARE
  46845. if (target != null) {
  46846. this.threeRenderer.setRenderTarget(target);
  46847. }
  46848. //camera.updateProjectionMatrix();
  46849. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  46850. const traversalResult = this.traverse(scene);
  46851. //排序
  46852. if(Potree.settings.notAdditiveBlending){//add
  46853. traversalResult.octrees.forEach(tree=>{
  46854. if(tree.material.opacity==1){
  46855. tree._z = Infinity; //不透明的先渲染
  46856. }else {
  46857. let center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld);
  46858. center.project(camera);
  46859. tree._z = center.z;
  46860. }
  46861. });
  46862. traversalResult.octrees.sort((tree1,tree2)=>{
  46863. return tree2._z - tree1._z //降序 (-1 朝外)。 离屏幕近的后渲染
  46864. });
  46865. }
  46866. // RENDER
  46867. for (const octree of traversalResult.octrees) {
  46868. let nodes = octree.visibleNodes;
  46869. /* nodes.sort((node1,node2)=>{//姑且
  46870. let center = node.getBoundingSphere().center.clone().applyMatrix4(octree.matrixWorld)
  46871. return
  46872. }) */
  46873. this.renderOctree(octree, nodes, camera, target, params);
  46874. }
  46875. // CLEANUP
  46876. gl.activeTexture(gl.TEXTURE1);
  46877. gl.bindTexture(gl.TEXTURE_2D, null);
  46878. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46879. gl.bindVertexArray(null);
  46880. this.threeRenderer.resetState();
  46881. }
  46882. };
  46883. /*
  46884. 中东的链接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
  46885. geometry: 有的attributes: 属性是:
  46886. classification:
  46887. color:
  46888. indices:
  46889. normal:
  46890. position:
  46891. 最好有个spacing
  46892. */
  46893. class ProfileData {
  46894. constructor (profile) {
  46895. this.profile = profile;
  46896. this.segments = [];
  46897. this.boundingBox = new Box3();
  46898. for (let i = 0; i < profile.points.length - 1; i++) {
  46899. let start = profile.points[i];
  46900. let end = profile.points[i + 1];
  46901. let startGround = new Vector3(start.x, start.y, 0);
  46902. let endGround = new Vector3(end.x, end.y, 0);
  46903. let center = new Vector3().addVectors(endGround, startGround).multiplyScalar(0.5);
  46904. let length = startGround.distanceTo(endGround);
  46905. let side = new Vector3().subVectors(endGround, startGround).normalize();
  46906. let up = new Vector3(0, 0, 1);
  46907. let forward = new Vector3().crossVectors(side, up).normalize();
  46908. let N = forward;
  46909. let cutPlane = new Plane().setFromNormalAndCoplanarPoint(N, startGround);
  46910. let halfPlane = new Plane().setFromNormalAndCoplanarPoint(side, center);
  46911. let segment = {
  46912. start: start,
  46913. end: end,
  46914. cutPlane: cutPlane,
  46915. halfPlane: halfPlane,
  46916. length: length,
  46917. points: new Points$1()
  46918. };
  46919. this.segments.push(segment);
  46920. }
  46921. }
  46922. size () {
  46923. let size = 0;
  46924. for (let segment of this.segments) {
  46925. size += segment.points.numPoints;
  46926. }
  46927. return size;
  46928. }
  46929. };
  46930. class ProfileRequest {
  46931. constructor (pointcloud, profile, maxDepth, callback) {
  46932. this.pointcloud = pointcloud;
  46933. this.profile = profile;
  46934. this.maxDepth = maxDepth || Number.MAX_VALUE;
  46935. this.callback = callback;
  46936. this.temporaryResult = new ProfileData(this.profile);
  46937. this.pointsServed = 0;
  46938. this.highestLevelServed = 0;
  46939. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  46940. this.initialize();
  46941. }
  46942. initialize () {
  46943. this.priorityQueue.push({node: this.pointcloud.pcoGeometry.root, weight: Infinity});
  46944. };
  46945. // traverse the node and add intersecting descendants to queue
  46946. traverse (node) {
  46947. let stack = [];
  46948. for (let i = 0; i < 8; i++) {
  46949. let child = node.children[i];
  46950. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  46951. stack.push(child);
  46952. }
  46953. }
  46954. while (stack.length > 0) {
  46955. let node = stack.pop();
  46956. let weight = node.boundingSphere.radius;
  46957. this.priorityQueue.push({node: node, weight: weight});
  46958. // add children that intersect the cutting plane
  46959. if (node.level < this.maxDepth) {
  46960. for (let i = 0; i < 8; i++) {
  46961. let child = node.children[i];
  46962. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  46963. stack.push(child);
  46964. }
  46965. }
  46966. }
  46967. }
  46968. }
  46969. update(){
  46970. if(!this.updateGeneratorInstance){
  46971. this.updateGeneratorInstance = this.updateGenerator();
  46972. }
  46973. let result = this.updateGeneratorInstance.next();
  46974. if(result.done){
  46975. this.updateGeneratorInstance = null;
  46976. }
  46977. }
  46978. * updateGenerator(){
  46979. // load nodes in queue
  46980. // if hierarchy expands, also load nodes from expanded hierarchy
  46981. // once loaded, add data to this.points and remove node from queue
  46982. // only evaluate 1-50 nodes per frame to maintain responsiveness
  46983. let start = performance.now();
  46984. let maxNodesPerUpdate = 1;
  46985. let intersectedNodes = [];
  46986. for (let i = 0; i < Math.min(maxNodesPerUpdate, this.priorityQueue.size()); i++) {
  46987. let element = this.priorityQueue.pop();
  46988. let node = element.node;
  46989. if(node.level > this.maxDepth){
  46990. continue;
  46991. }
  46992. if (node.loaded) {
  46993. // add points to result
  46994. intersectedNodes.push(node);
  46995. exports.lru.touch(node);
  46996. this.highestLevelServed = Math.max(node.getLevel(), this.highestLevelServed);
  46997. var geom = node.pcoGeometry;
  46998. var hierarchyStepSize = geom ? geom.hierarchyStepSize : 1;
  46999. var doTraverse = node.getLevel() === 0 ||
  47000. (node.level % hierarchyStepSize === 0 && node.hasChildren);
  47001. if (doTraverse) {
  47002. this.traverse(node);
  47003. }
  47004. } else {
  47005. node.load();
  47006. this.priorityQueue.push(element);
  47007. }
  47008. }
  47009. if (intersectedNodes.length > 0) {
  47010. for(let done of this.getPointsInsideProfile(intersectedNodes, this.temporaryResult)){
  47011. if(!done){
  47012. //console.log("updateGenerator yields");
  47013. yield false;
  47014. }
  47015. }
  47016. if (this.temporaryResult.size() > 100) {
  47017. this.pointsServed += this.temporaryResult.size();
  47018. this.callback.onProgress({request: this, points: this.temporaryResult});
  47019. this.temporaryResult = new ProfileData(this.profile);
  47020. }
  47021. }
  47022. if (this.priorityQueue.size() === 0) {
  47023. // we're done! inform callback and remove from pending requests
  47024. if (this.temporaryResult.size() > 0) {
  47025. this.pointsServed += this.temporaryResult.size();
  47026. this.callback.onProgress({request: this, points: this.temporaryResult});
  47027. this.temporaryResult = new ProfileData(this.profile);
  47028. }
  47029. this.callback.onFinish({request: this});
  47030. let index = this.pointcloud.profileRequests.indexOf(this);
  47031. if (index >= 0) {
  47032. this.pointcloud.profileRequests.splice(index, 1);
  47033. }
  47034. }
  47035. yield true;
  47036. };
  47037. * getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage){
  47038. let checkpoint = performance.now();
  47039. let accepted = new Uint32Array(numPoints);
  47040. let mileage = new Float64Array(numPoints);
  47041. let acceptedPositions = new Float32Array(numPoints * 3);
  47042. let numAccepted = 0;
  47043. let pos = new Vector3();
  47044. let svp = new Vector3();
  47045. let view = new Float32Array(node.geometry.attributes.position.array);
  47046. for (let i = 0; i < numPoints; i++) {
  47047. pos.set(
  47048. view[i * 3 + 0],
  47049. view[i * 3 + 1],
  47050. view[i * 3 + 2]);
  47051. pos.applyMatrix4(matrix);
  47052. let distance = Math.abs(segment.cutPlane.distanceToPoint(pos));
  47053. let centerDistance = Math.abs(segment.halfPlane.distanceToPoint(pos));
  47054. if (distance < this.profile.width / 2 && centerDistance < segment.length / 2) {
  47055. svp.subVectors(pos, segment.start);
  47056. let localMileage = segmentDir.dot(svp);
  47057. accepted[numAccepted] = i;
  47058. mileage[numAccepted] = localMileage + totalMileage;
  47059. points.boundingBox.expandByPoint(pos);
  47060. pos.sub(this.pointcloud.position);
  47061. acceptedPositions[3 * numAccepted + 0] = pos.x;
  47062. acceptedPositions[3 * numAccepted + 1] = pos.y;
  47063. acceptedPositions[3 * numAccepted + 2] = pos.z;
  47064. numAccepted++;
  47065. }
  47066. if((i % 1000) === 0){
  47067. let duration = performance.now() - checkpoint;
  47068. if(duration > 4){
  47069. //console.log(`getAccepted yield after ${duration}ms`);
  47070. yield false;
  47071. checkpoint = performance.now();
  47072. }
  47073. }
  47074. }
  47075. accepted = accepted.subarray(0, numAccepted);
  47076. mileage = mileage.subarray(0, numAccepted);
  47077. acceptedPositions = acceptedPositions.subarray(0, numAccepted * 3);
  47078. //let end = performance.now();
  47079. //let duration = end - start;
  47080. //console.log("accepted duration ", duration)
  47081. //console.log(`getAccepted finished`);
  47082. yield [accepted, mileage, acceptedPositions];
  47083. }
  47084. * getPointsInsideProfile(nodes, target){
  47085. let checkpoint = performance.now();
  47086. let totalMileage = 0;
  47087. let pointsProcessed = 0;
  47088. for (let segment of target.segments) {
  47089. for (let node of nodes) {
  47090. let numPoints = node.numPoints;
  47091. let geometry = node.geometry;
  47092. if(!numPoints){
  47093. continue;
  47094. }
  47095. { // skip if current node doesn't intersect current segment
  47096. let bbWorld = node.boundingBox.clone().applyMatrix4(this.pointcloud.matrixWorld);
  47097. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  47098. let start = new Vector3(segment.start.x, segment.start.y, bsWorld.center.z);
  47099. let end = new Vector3(segment.end.x, segment.end.y, bsWorld.center.z);
  47100. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  47101. let distance = closest.distanceTo(bsWorld.center);
  47102. let intersects = (distance < (bsWorld.radius + target.profile.width));
  47103. if(!intersects){
  47104. continue;
  47105. }
  47106. }
  47107. //{// DEBUG
  47108. // console.log(node.name);
  47109. // let boxHelper = new Potree.Box3Helper(node.getBoundingBox());
  47110. // boxHelper.matrixAutoUpdate = false;
  47111. // boxHelper.matrix.copy(viewer.scene.pointclouds[0].matrixWorld);
  47112. // viewer.scene.scene.add(boxHelper);
  47113. //}
  47114. let sv = new Vector3().subVectors(segment.end, segment.start).setZ(0);
  47115. let segmentDir = sv.clone().normalize();
  47116. let points = new Points$1();
  47117. let nodeMatrix = new Matrix4().makeTranslation(...node.boundingBox.min.toArray());
  47118. let matrix = new Matrix4().multiplyMatrices(
  47119. this.pointcloud.matrixWorld, nodeMatrix);
  47120. pointsProcessed = pointsProcessed + numPoints;
  47121. let accepted = null;
  47122. let mileage = null;
  47123. let acceptedPositions = null;
  47124. for(let result of this.getAccepted(numPoints, node, matrix, segment, segmentDir, points,totalMileage)){
  47125. if(!result){
  47126. let duration = performance.now() - checkpoint;
  47127. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  47128. yield false;
  47129. checkpoint = performance.now();
  47130. }else {
  47131. [accepted, mileage, acceptedPositions] = result;
  47132. }
  47133. }
  47134. let duration = performance.now() - checkpoint;
  47135. if(duration > 4){
  47136. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  47137. yield false;
  47138. checkpoint = performance.now();
  47139. }
  47140. points.data.position = acceptedPositions;
  47141. let relevantAttributes = Object.keys(geometry.attributes).filter(a => !["position", "indices"].includes(a));
  47142. for(let attributeName of relevantAttributes){
  47143. let attribute = geometry.attributes[attributeName];
  47144. let numElements = attribute.array.length / numPoints;
  47145. if(numElements !== parseInt(numElements)){
  47146. debugger;
  47147. }
  47148. let Type = attribute.array.constructor;
  47149. let filteredBuffer = new Type(numElements * accepted.length);
  47150. let source = attribute.array;
  47151. let target = filteredBuffer;
  47152. for(let i = 0; i < accepted.length; i++){
  47153. let index = accepted[i];
  47154. let start = index * numElements;
  47155. let end = start + numElements;
  47156. let sub = source.subarray(start, end);
  47157. target.set(sub, i * numElements);
  47158. }
  47159. points.data[attributeName] = filteredBuffer;
  47160. }
  47161. points.data['mileage'] = mileage;
  47162. points.numPoints = accepted.length;
  47163. segment.points.add(points);
  47164. }
  47165. totalMileage += segment.length;
  47166. }
  47167. for (let segment of target.segments) {
  47168. target.boundingBox.union(segment.points.boundingBox);
  47169. }
  47170. //console.log(`getPointsInsideProfile finished`);
  47171. yield true;
  47172. };
  47173. finishLevelThenCancel () {
  47174. if (this.cancelRequested) {
  47175. return;
  47176. }
  47177. this.maxDepth = this.highestLevelServed;
  47178. this.cancelRequested = true;
  47179. //console.log(`maxDepth: ${this.maxDepth}`);
  47180. };
  47181. cancel () {
  47182. this.callback.onCancel();
  47183. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  47184. let index = this.pointcloud.profileRequests.indexOf(this);
  47185. if (index >= 0) {
  47186. this.pointcloud.profileRequests.splice(index, 1);
  47187. }
  47188. };
  47189. }
  47190. class Version{
  47191. constructor(version){
  47192. this.version = version;
  47193. let vmLength = (version.indexOf('.') === -1) ? version.length : version.indexOf('.');
  47194. this.versionMajor = parseInt(version.substr(0, vmLength));
  47195. this.versionMinor = parseInt(version.substr(vmLength + 1));
  47196. if (this.versionMinor.length === 0) {
  47197. this.versionMinor = 0;
  47198. }
  47199. }
  47200. newerThan(version){
  47201. let v = new Version(version);
  47202. if (this.versionMajor > v.versionMajor) {
  47203. return true;
  47204. } else if (this.versionMajor === v.versionMajor && this.versionMinor > v.versionMinor) {
  47205. return true;
  47206. } else {
  47207. return false;
  47208. }
  47209. }
  47210. equalOrHigher(version){
  47211. let v = new Version(version);
  47212. if (this.versionMajor > v.versionMajor) {
  47213. return true;
  47214. } else if (this.versionMajor === v.versionMajor && this.versionMinor >= v.versionMinor) {
  47215. return true;
  47216. } else {
  47217. return false;
  47218. }
  47219. }
  47220. upTo(version){
  47221. return !this.newerThan(version);
  47222. }
  47223. }
  47224. class WorkerPool{
  47225. constructor(){
  47226. this.workers = {};
  47227. }
  47228. getWorker(url){
  47229. if (!this.workers[url]){
  47230. this.workers[url] = [];
  47231. }
  47232. if (this.workers[url].length === 0){
  47233. let worker = new Worker(url);
  47234. this.workers[url].push(worker);
  47235. }
  47236. let worker = this.workers[url].pop();
  47237. return worker;
  47238. }
  47239. returnWorker(url, worker){
  47240. this.workers[url].push(worker);
  47241. }
  47242. };
  47243. //Potree.workerPool = new Potree.WorkerPool();
  47244. function createPointcloudData(pointcloud) {
  47245. let material = pointcloud.material;
  47246. let ranges = [];
  47247. for(let [name, value] of material.ranges){
  47248. ranges.push({
  47249. name: name,
  47250. value: value,
  47251. });
  47252. }
  47253. if(typeof material.elevationRange[0] === "number"){
  47254. ranges.push({
  47255. name: "elevationRange",
  47256. value: material.elevationRange,
  47257. });
  47258. }
  47259. if(typeof material.intensityRange[0] === "number"){
  47260. ranges.push({
  47261. name: "intensityRange",
  47262. value: material.intensityRange,
  47263. });
  47264. }
  47265. let pointSizeTypeName = Object.entries(Potree.PointSizeType).find(e => e[1] === material.pointSizeType)[0];
  47266. let jsonMaterial = {
  47267. activeAttributeName: material.activeAttributeName,
  47268. ranges: ranges,
  47269. size: material.size,
  47270. minSize: material.minSize,
  47271. pointSizeType: pointSizeTypeName,
  47272. matcap: material.matcap,
  47273. };
  47274. const pcdata = {
  47275. name: pointcloud.name,
  47276. url: pointcloud.pcoGeometry.url,
  47277. position: pointcloud.position.toArray(),
  47278. rotation: pointcloud.rotation.toArray(),
  47279. scale: pointcloud.scale.toArray(),
  47280. material: jsonMaterial,
  47281. };
  47282. return pcdata;
  47283. }
  47284. function createProfileData(profile){
  47285. const data = {
  47286. uuid: profile.uuid,
  47287. name: profile.name,
  47288. points: profile.points.map(p => p.toArray()),
  47289. height: profile.height,
  47290. width: profile.width,
  47291. };
  47292. return data;
  47293. }
  47294. function createVolumeData(volume){
  47295. const data = {
  47296. uuid: volume.uuid,
  47297. type: volume.constructor.name,
  47298. name: volume.name,
  47299. position: volume.position.toArray(),
  47300. rotation: volume.rotation.toArray(),
  47301. scale: volume.scale.toArray(),
  47302. visible: volume.visible,
  47303. clip: volume.clip,
  47304. };
  47305. return data;
  47306. }
  47307. function createCameraAnimationData(animation){
  47308. const controlPoints = animation.controlPoints.map( cp => {
  47309. const cpdata = {
  47310. position: cp.position.toArray(),
  47311. target: cp.target.toArray(),
  47312. };
  47313. return cpdata;
  47314. });
  47315. const data = {
  47316. uuid: animation.uuid,
  47317. name: animation.name,
  47318. duration: animation.duration,
  47319. t: animation.t,
  47320. curveType: animation.curveType,
  47321. visible: animation.visible,
  47322. controlPoints: controlPoints,
  47323. };
  47324. return data;
  47325. }
  47326. function createMeasurementData(measurement){
  47327. /* const data = {
  47328. uuid: measurement.uuid,
  47329. name: measurement.name,
  47330. measureType:measurement.measureType, //add
  47331. direction:measurement.direction,//add
  47332. minMarkers:measurement.minMarkers,//add
  47333. maxMarkers: measurement.maxMarkers,//add
  47334. isRect: measurement.isRect,//add
  47335. faceDirection: measurement.faceDirection,//add
  47336. points: measurement.points.map(p => p.position.toArray()),
  47337. showDistances: measurement.showDistances,
  47338. showCoordinates: measurement.showCoordinates,
  47339. showArea: measurement.showArea,
  47340. closed: measurement.closed,
  47341. showAngles: measurement.showAngles,
  47342. showHeight: measurement.showHeight,
  47343. showCircle: measurement.showCircle,
  47344. showAzimuth: measurement.showAzimuth,
  47345. showEdges: measurement.showEdges,
  47346. color: measurement.color.toArray(),
  47347. }; */
  47348. const data = {
  47349. uuid: measurement.uuid,
  47350. name: measurement.name,
  47351. measureType:measurement.measureType, //add
  47352. points: measurement.points.map(p => p.toArray()),
  47353. };
  47354. return data;
  47355. }
  47356. function createOrientedImagesData(images){
  47357. const data = {
  47358. cameraParamsPath: images.cameraParamsPath,
  47359. imageParamsPath: images.imageParamsPath,
  47360. };
  47361. return data;
  47362. }
  47363. function createGeopackageData(geopackage){
  47364. const data = {
  47365. path: geopackage.path,
  47366. };
  47367. return data;
  47368. }
  47369. function createAnnotationData(annotation){
  47370. const data = {
  47371. uuid: annotation.uuid,
  47372. title: annotation.title.toString(),
  47373. description: annotation.description,
  47374. position: annotation.position.toArray(),
  47375. offset: annotation.offset.toArray(),
  47376. children: [],
  47377. };
  47378. if(annotation.cameraPosition){
  47379. data.cameraPosition = annotation.cameraPosition.toArray();
  47380. }
  47381. if(annotation.cameraTarget){
  47382. data.cameraTarget = annotation.cameraTarget.toArray();
  47383. }
  47384. if(typeof annotation.radius !== "undefined"){
  47385. data.radius = annotation.radius;
  47386. }
  47387. return data;
  47388. }
  47389. function createAnnotationsData(viewer){
  47390. const map = new Map();
  47391. viewer.scene.annotations.traverseDescendants(a => {
  47392. const aData = createAnnotationData(a);
  47393. map.set(a, aData);
  47394. });
  47395. for(const [annotation, data] of map){
  47396. for(const child of annotation.children){
  47397. const childData = map.get(child);
  47398. data.children.push(childData);
  47399. }
  47400. }
  47401. const annotations = viewer.scene.annotations.children.map(a => map.get(a));
  47402. return annotations;
  47403. }
  47404. function createSettingsData(viewer){
  47405. return {
  47406. pointBudget: viewer.getPointBudget(),
  47407. fov: viewer.getFOV(),
  47408. edlEnabled: viewer.getEDLEnabled(),
  47409. edlRadius: viewer.getEDLRadius(),
  47410. edlStrength: viewer.getEDLStrength(),
  47411. background: viewer.getBackground(),
  47412. minNodeSize: viewer.getMinNodeSize(),
  47413. showBoundingBoxes: viewer.getShowBoundingBox(),
  47414. };
  47415. }
  47416. function createSceneContentData(viewer){
  47417. const data = [];
  47418. const potreeObjects = [];
  47419. viewer.scene.scene.traverse(node => {
  47420. if(node.potree){
  47421. potreeObjects.push(node);
  47422. }
  47423. });
  47424. for(const object of potreeObjects){
  47425. if(object.potree.file){
  47426. const saveObject = {
  47427. file: object.potree.file,
  47428. };
  47429. data.push(saveObject);
  47430. }
  47431. }
  47432. return data;
  47433. }
  47434. function createViewData(viewer){
  47435. const view = viewer.scene.view;
  47436. const data = {
  47437. position: view.position.toArray(),
  47438. target: view.getPivot().toArray(),
  47439. };
  47440. return data;
  47441. }
  47442. function createClassificationData(viewer){
  47443. const classifications = viewer.classifications;
  47444. const data = classifications;
  47445. return data;
  47446. }
  47447. function saveProject(viewer) {
  47448. const scene = viewer.scene;
  47449. const data = {
  47450. type: "Potree",
  47451. version: 1.7,
  47452. settings: createSettingsData(viewer),
  47453. view: createViewData(viewer),
  47454. classification: createClassificationData(viewer),
  47455. pointclouds: scene.pointclouds.map(createPointcloudData),
  47456. measurements: scene.measurements.map(createMeasurementData),
  47457. volumes: scene.volumes.map(createVolumeData),
  47458. cameraAnimations: scene.cameraAnimations.map(createCameraAnimationData),
  47459. profiles: scene.profiles.map(createProfileData),
  47460. annotations: createAnnotationsData(viewer),
  47461. orientedImages: scene.orientedImages.map(createOrientedImagesData),
  47462. geopackages: scene.geopackages.map(createGeopackageData),
  47463. // objects: createSceneContentData(viewer),
  47464. };
  47465. return data;
  47466. }
  47467. class HandleSvg extends EventDispatcher{
  47468. constructor(position, color){
  47469. super();
  47470. this.position = position;
  47471. this.color = '#'+new Color(color).getHexString();
  47472. this.svg = this.create();
  47473. this.visible_ = true;
  47474. let update = ()=>{
  47475. this.update();
  47476. };
  47477. viewer.addEventListener("camera_changed", update);
  47478. this.addEventListener('dispose', ()=>{
  47479. viewer.removeEventListener("camera_changed", update);
  47480. });
  47481. }
  47482. create(){
  47483. const svgns = "http://www.w3.org/2000/svg";
  47484. const svg = document.createElementNS(svgns, "svg");
  47485. svg.setAttribute("width", "2em");
  47486. svg.setAttribute("height", "2em");
  47487. svg.setAttribute("position", "absolute");
  47488. svg.style.left = "50px";
  47489. svg.style.top = "50px";
  47490. svg.style.position = "absolute";
  47491. svg.style.zIndex = "10000";
  47492. svg.style.cursor = 'grab';
  47493. svg.style.transform = 'translate(-50%,-50%)';
  47494. const circle = document.createElementNS(svgns, 'circle');
  47495. circle.setAttributeNS(null, 'cx', "1em");
  47496. circle.setAttributeNS(null, 'cy', "1em");
  47497. circle.setAttributeNS(null, 'r', "0.5em");
  47498. circle.setAttributeNS(null, 'style', 'fill: '+this.color+'; stroke: black; stroke-width: 0.2em;' );
  47499. svg.appendChild(circle);
  47500. const element = viewer.renderer.domElement.parentElement;
  47501. element.appendChild(svg);
  47502. const startDrag = (evt) => {
  47503. /* if(evt.button === THREE.MOUSE.RIGHT){
  47504. return
  47505. } */
  47506. this.selectedElement = svg;
  47507. document.addEventListener("mousemove", drag);
  47508. };
  47509. const endDrag = (evt) => {
  47510. this.selectedElement = null;
  47511. document.removeEventListener("mousemove", drag);
  47512. };
  47513. const drag = (evt) => {
  47514. if (this.selectedElement) {
  47515. evt.preventDefault();
  47516. const rect = viewer.renderer.domElement.getBoundingClientRect();
  47517. const x = evt.clientX - rect.x;
  47518. const y = evt.clientY - rect.y;
  47519. const {width, height} = viewer.renderer.getSize(new Vector2$1());
  47520. const camera = viewer.scene.getActiveCamera();
  47521. const projected = this.position.clone().project(camera);
  47522. projected.x = ((x / width) - 0.5) / 0.5;
  47523. projected.y = (-(y - height) / height - 0.5) / 0.5;
  47524. const unprojected = projected.clone().unproject(camera);
  47525. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  47526. this.update();
  47527. this.dispatchEvent({type:'dragged', position: this.position});
  47528. }
  47529. };
  47530. svg.addEventListener('mousedown', startDrag);
  47531. svg.addEventListener('mouseup', endDrag);
  47532. svg.style.display = this.visible ? "" : "none";
  47533. this.addEventListener('dispose',()=>{
  47534. svg.removeEventListener('mousedown', startDrag);
  47535. svg.removeEventListener('mouseup', endDrag);
  47536. });
  47537. return svg
  47538. }
  47539. set visible(v){
  47540. this.visible_ = v;
  47541. if(v){
  47542. this.update();
  47543. }else {
  47544. this.svg.style.display = "none";
  47545. }
  47546. }
  47547. get visible(){
  47548. return this.visible_
  47549. }
  47550. update(){
  47551. if(!this.visible)return
  47552. let camera = viewer.scene.getActiveCamera();
  47553. var p = Potree.Utils.getPos2d( this.position, camera , viewer.renderArea, viewer.mainViewport);
  47554. if(!p.trueSide){
  47555. return this.svg.style.display = 'none';
  47556. }
  47557. this.svg.style.left = p.posInViewport.x;
  47558. this.svg.style.top = p.posInViewport.y;
  47559. this.svg.style.display = '';
  47560. }
  47561. dispose(){
  47562. this.svg.remove();
  47563. this.dispatchEvent('dispose');
  47564. }
  47565. }
  47566. /*
  47567. 两种拖拽方式:
  47568. 1 只依附在点云上
  47569. 2 平行于镜头view移动 */
  47570. const geo$1 = new PlaneBufferGeometry(1,1);
  47571. class HandleSprite extends Sprite$1{
  47572. constructor(position,options={}){
  47573. options.sizeInfo = {width2d:60};
  47574. super(options);
  47575. this.position.copy(position);
  47576. this.dragStyle = options.dragStyle || 'default'; //'default'||'onPointCloud'
  47577. this.bindEvent();
  47578. }
  47579. bindEvent(){
  47580. let projectedStart, pointerStart;
  47581. const drag = (e)=>{
  47582. /* if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  47583. viewer.dispatchEvent({
  47584. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  47585. })
  47586. return
  47587. } */
  47588. const camera = viewer.scene.getActiveCamera();
  47589. if(projectedStart){
  47590. let move2d = new Vector2$1().subVectors(e.pointer, pointerStart);
  47591. let projectNow = projectedStart.clone();
  47592. projectNow.x += move2d.x;
  47593. projectNow.y += move2d.y;
  47594. let unprojected = projectNow.clone().unproject(camera);
  47595. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  47596. }else {
  47597. projectedStart = this.position.clone().project(camera);
  47598. pointerStart = e.pointer.clone();
  47599. }
  47600. this.update();
  47601. this.dispatchEvent({type:'dragged', position: this.position });
  47602. };
  47603. const drop = (e)=>{
  47604. projectedStart = null, pointerStart = null;
  47605. };
  47606. const mouseover = (e) => {
  47607. viewer.dispatchEvent({
  47608. type : "CursorChange", action : "add", name:"markerMove"
  47609. });
  47610. };
  47611. const mouseleave = (e) => {
  47612. viewer.dispatchEvent({
  47613. type : "CursorChange", action : "remove", name:"markerMove"
  47614. });
  47615. };
  47616. this.addEventListener('drag', drag);
  47617. this.addEventListener('drop', drop);
  47618. this.addEventListener('mouseover', mouseover);
  47619. this.addEventListener('mouseleave', mouseleave);
  47620. }
  47621. }
  47622. const sphere = new Mesh(new SphereBufferGeometry(0.08,0.08,3,2), new MeshBasicMaterial({color:'#f88'}));
  47623. class CurveCtrl extends Object3D {
  47624. constructor(points, lineMat, color, name, options={}){
  47625. super();
  47626. this.curve = new CatmullRomCurve3(points, false, "centripetal" /* , tension */);
  47627. this.name = name || 'curveNode';
  47628. this.handleMat = options.handleMat;
  47629. this.lineMat = lineMat;
  47630. this.createPath();
  47631. this.color = color;
  47632. this.handles = [];
  47633. this.wholeLength = 0;
  47634. this.viewports = options.viewports || [viewer.mainViewport]; //for HandleSprite
  47635. for(let i=0,j=this.points.length; i<j;i++){
  47636. this.handles.push(this.createHandle(this.points[i]));
  47637. }
  47638. this.visible_ = true;
  47639. if(Potree.settings.isTest){
  47640. this.spheres = new Object3D;
  47641. /* let i = Count+1;
  47642. while(i>0){
  47643. this.spheres.add(sphere.clone());
  47644. i--;
  47645. } */
  47646. this.add(this.spheres);
  47647. }
  47648. this.updatePath();
  47649. }
  47650. addPoint(position, index, ifUpdate){
  47651. let length = this.points.length;
  47652. if(index == void 0 ){
  47653. index = length;
  47654. }
  47655. let handle = this.createHandle(position);
  47656. this.handles = [...this.handles.slice(0,index), handle, ...this.handles.slice(index,length)];
  47657. this.points = [...this.points.slice(0,index), position, ...this.points.slice(index,length)];
  47658. ifUpdate && (this.updatePath(), this.updateHandle(index));
  47659. }
  47660. removePoint(index){
  47661. let handle = this.handles[index];
  47662. handle.dispose();
  47663. this.handles.splice(index,1);
  47664. this.points.splice(index,1);
  47665. this.updatePath();
  47666. }
  47667. createPath(){
  47668. const line = LineDraw.createFatLine( [ ],this.lineMat);
  47669. this.line = line;
  47670. this.add(line);
  47671. }
  47672. updatePath(){
  47673. this.curve.needsUpdate = true; //如果不更新,得到的点不均匀,开头点少。
  47674. let points, length = this.points.length;
  47675. this.wholeLength = this.points.reduce((total, currentValue, currentIndex, arr)=>{ //所有端点的距离总和
  47676. if(currentIndex == 0)return 0
  47677. return total + currentValue.distanceTo(arr[currentIndex-1]);
  47678. },0);
  47679. if(length > 1){
  47680. const count = MathUtils.clamp(Math.ceil(this.wholeLength * 5), 30, 500);
  47681. points = this.curve.getSpacedPoints( count );
  47682. if(this.needsPercent){ //获取每个节点在整条中的百分比,便于定位(但不精确)
  47683. this.pointsPercent = [0];
  47684. let sums = [0];
  47685. let sum = 0, last = points[0];
  47686. for(let i=1;i<length;i++){
  47687. let point = this.points[i];
  47688. sum += point.distanceTo(last); //参考getLengths函数,根据长度得到百分比
  47689. last = point;
  47690. sums.push(sum);
  47691. }
  47692. for(let i=1;i<length;i++){
  47693. this.pointsPercent.push(sum == 0 ? i/length : sums[i] / sum);
  47694. }
  47695. }
  47696. if(Potree.settings.isTest){
  47697. this.spheres.children.forEach(e=>e.visible = false);
  47698. points.forEach((e,i)=>{
  47699. let sphere1 = this.spheres.children[i];
  47700. if(!sphere1){
  47701. sphere1 = sphere.clone();
  47702. this.spheres.add(sphere1);
  47703. }
  47704. sphere1.position.copy(e);
  47705. sphere1.visible = true;
  47706. });
  47707. }
  47708. }else {
  47709. points = [];
  47710. }
  47711. LineDraw.updateLine(this.line, points);
  47712. this.dispatchEvent('updatePath');
  47713. }
  47714. createHandle(position){
  47715. if(this.handleMat){
  47716. var handle = new HandleSprite(position, {mat:this.handleMat, viewports:this.viewports});
  47717. this.add(handle);
  47718. }else {
  47719. var handle = new HandleSvg(position, this.color);
  47720. }
  47721. handle.visible = this.visible;
  47722. handle.addEventListener('dragged',(e)=>{
  47723. let index = this.handles.indexOf(handle);
  47724. this.points[index].copy(e.position);
  47725. this.updatePath();
  47726. this.dispatchEvent({type:'dragCurvePoint', index});
  47727. });
  47728. return handle
  47729. }
  47730. updateHandle(index){
  47731. if(!this.visible)return
  47732. this.handles[index].update();
  47733. }
  47734. updateHandles(){
  47735. this.handles.forEach((handle,index)=>{
  47736. this.updateHandle(index);
  47737. });
  47738. }
  47739. update(){
  47740. this.updateHandles();
  47741. this.updatePath();
  47742. }
  47743. set visible(v){
  47744. if(v != this.visible_ ){
  47745. this.visible_ = v;
  47746. this.visible = v;
  47747. if(this.handles){
  47748. this.handles.forEach(e=>e.visible = v );
  47749. if(v) this.updateHandles(); //因为不可见时没更新位置
  47750. }
  47751. }
  47752. }
  47753. get visible(){
  47754. return this.visible_
  47755. }
  47756. /* set visible(v){
  47757. this.handles.forEach(e=>e.svg.style.display = v ? "" : "none" )
  47758. if(v) this.updateHandles() //因为不可见时没更新位置
  47759. } */
  47760. get points(){
  47761. return this.curve.points;
  47762. }
  47763. set points(points){
  47764. this.curve.points = points;
  47765. }
  47766. getPointAt(t){
  47767. return this.curve.getPointAt(t)
  47768. }
  47769. getSpacedPoints(t){
  47770. return this.curve.getSpacedPoints(t)
  47771. }
  47772. dispose(){
  47773. this.parent && this.parent.remove(this);
  47774. this.handles.forEach(e=>e.dispose() );
  47775. this.line.geometry && this.line.geometry.dispose();
  47776. }
  47777. }
  47778. var easing = {};
  47779. //渐变曲线函数,反应加速度的变化
  47780. //currentTime:x轴当前时间(从0-到duration), startY:起始点, duration:总时长, wholeY:路程 (即endY-startY)
  47781. //参数基本是 x, 0, 1, 1
  47782. /*
  47783. easeOut 基本是y= m * (x-dur)^k + n, 若k为偶数,m<0, 若k为奇数,m>0; (因为偶数的话必须开口向下才能获得斜率递减的递增的那段,而奇数是对称的,单调递增. )
  47784. 根据x=0时y=0, x=dur时y=S , 得 n = S,m = -S/(-dur)^k
  47785. */
  47786. easing.getEaseOut = function(k){// k 是>=2的整数. 越大变化率越大, 相同初始速度所需要时间越久
  47787. let easeFun;
  47788. k = Math.round(k);
  47789. if(k<2){
  47790. k = Math.PI / 2;
  47791. easeFun = easing.easeOutSine;
  47792. }else {
  47793. easeFun = function(currentTime, startY, wholeY, duration) {
  47794. if(k>2){
  47795. console.log(k);
  47796. }
  47797. return -wholeY/Math.pow(-duration, k) * Math.pow(currentTime-duration, k) + wholeY
  47798. };
  47799. }
  47800. return {
  47801. k,
  47802. easeFun
  47803. }
  47804. };
  47805. easing.linearTween = function(currentTime, startY, wholeY, duration) {
  47806. return wholeY * currentTime / duration + startY
  47807. }
  47808. ,
  47809. easing.easeInQuad = function(currentTime, startY, wholeY, duration) {
  47810. return currentTime /= duration,
  47811. wholeY * currentTime * currentTime + startY
  47812. }
  47813. ,
  47814. 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
  47815. return currentTime /= duration,
  47816. -wholeY * currentTime * (currentTime - 2) + startY
  47817. }
  47818. ,
  47819. easing.easeInOutQuad = function(currentTime, startY, wholeY, duration) {
  47820. return currentTime /= duration / 2,
  47821. currentTime < 1 ? wholeY / 2 * currentTime * currentTime + startY : (currentTime--,
  47822. -wholeY / 2 * (currentTime * (currentTime - 2) - 1) + startY)
  47823. }
  47824. ,
  47825. easing.easeInCubic = function(currentTime, startY, wholeY, duration) {
  47826. return currentTime /= duration,
  47827. wholeY * currentTime * currentTime * currentTime + startY
  47828. }
  47829. ,
  47830. 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
  47831. return currentTime /= duration,
  47832. currentTime--,
  47833. wholeY * (currentTime * currentTime * currentTime + 1) + startY
  47834. }
  47835. ,
  47836. easing.easeInOutCubic = function(currentTime, startY, wholeY, duration) {
  47837. return currentTime /= duration / 2,
  47838. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47839. wholeY / 2 * (currentTime * currentTime * currentTime + 2) + startY)
  47840. }
  47841. ,
  47842. easing.easeInQuart = function(currentTime, startY, wholeY, duration) {
  47843. return currentTime /= duration,
  47844. wholeY * currentTime * currentTime * currentTime * currentTime + startY
  47845. }
  47846. ,
  47847. easing.easeOutQuart = function(currentTime, startY, wholeY, duration) {//根据上面的计算,估计0时速度应该是4S/dur吧……
  47848. return currentTime /= duration,
  47849. currentTime--,
  47850. -wholeY * (currentTime * currentTime * currentTime * currentTime - 1) + startY
  47851. }
  47852. ,
  47853. easing.easeInOutQuart = function(currentTime, startY, wholeY, duration) {
  47854. return currentTime /= duration / 2,
  47855. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47856. -wholeY / 2 * (currentTime * currentTime * currentTime * currentTime - 2) + startY)
  47857. }
  47858. ,
  47859. easing.easeInQuint = function(currentTime, startY, wholeY, duration) {
  47860. return currentTime /= duration,
  47861. wholeY * currentTime * currentTime * currentTime * currentTime * currentTime + startY
  47862. }
  47863. ,
  47864. easing.easeOutQuint = function(currentTime, startY, wholeY, duration) {
  47865. return currentTime /= duration,
  47866. currentTime--,
  47867. wholeY * (currentTime * currentTime * currentTime * currentTime * currentTime + 1) + startY
  47868. }
  47869. ,
  47870. easing.easeInOutQuint = function(currentTime, startY, wholeY, duration) {
  47871. return currentTime /= duration / 2,
  47872. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47873. wholeY / 2 * (currentTime * currentTime * currentTime * currentTime * currentTime + 2) + startY)
  47874. }
  47875. ,
  47876. easing.easeInSine = function(currentTime, startY, wholeY, duration) {
  47877. return -wholeY * Math.cos(currentTime / duration * (Math.PI / 2)) + wholeY + startY
  47878. }
  47879. ,
  47880. easing.easeOutSine = function(currentTime, startY, wholeY, duration) {// y' = S * PI / 2 / dur * cos(PI/2/dur * x)
  47881. console.log('easeOutSine');
  47882. return wholeY * Math.sin(currentTime / duration * (Math.PI / 2)) + startY
  47883. }
  47884. ,
  47885. easing.easeInOutSine = function(currentTime, startY, wholeY, duration) {
  47886. return -wholeY / 2 * (Math.cos(Math.PI * currentTime / duration) - 1) + startY
  47887. }
  47888. ,
  47889. easing.easeInExpo = function(currentTime, startY, wholeY, duration) {
  47890. return wholeY * Math.pow(2, 10 * (currentTime / duration - 1)) + startY
  47891. }
  47892. ,
  47893. easing.easeOutExpo = function(currentTime, startY, wholeY, duration) {
  47894. return wholeY * (-Math.pow(2, -10 * currentTime / duration) + 1) + startY
  47895. }
  47896. ,
  47897. easing.easeInOutExpo = function(currentTime, startY, wholeY, duration) {
  47898. return currentTime /= duration / 2,
  47899. currentTime < 1 ? wholeY / 2 * Math.pow(2, 10 * (currentTime - 1)) + startY : (currentTime--,
  47900. wholeY / 2 * (-Math.pow(2, -10 * currentTime) + 2) + startY)
  47901. }
  47902. ,
  47903. easing.easeInCirc = function(currentTime, startY, wholeY, duration) {
  47904. return currentTime /= duration,
  47905. -wholeY * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY
  47906. }
  47907. ,
  47908. easing.easeOutCirc = function(currentTime, startY, wholeY, duration) {
  47909. return currentTime /= duration,
  47910. currentTime--,
  47911. wholeY * Math.sqrt(1 - currentTime * currentTime) + startY
  47912. }
  47913. ,
  47914. easing.easeInOutCirc = function(currentTime, startY, wholeY, duration) {
  47915. return currentTime /= duration / 2,
  47916. currentTime < 1 ? -wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY : (currentTime -= 2,
  47917. wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) + 1) + startY)
  47918. }
  47919. ,
  47920. easing.easeInElastic = function(currentTime, startY, wholeY, duration) {
  47921. var r = 1.70158
  47922. , o = 0
  47923. , a = wholeY;
  47924. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  47925. a < Math.abs(wholeY) ? (a = wholeY,
  47926. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47927. -(a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY)
  47928. }
  47929. ,
  47930. easing.easeOutElastic = function(currentTime, startY, wholeY, duration) {
  47931. var r = 1.70158
  47932. , o = 0
  47933. , a = wholeY;
  47934. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  47935. a < Math.abs(wholeY) ? (a = wholeY,
  47936. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47937. a * Math.pow(2, -10 * currentTime) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) + wholeY + startY)
  47938. }
  47939. ,
  47940. easing.easeInOutElastic = function(currentTime, startY, wholeY, duration) {
  47941. var r = 1.70158
  47942. , o = 0
  47943. , a = wholeY;
  47944. return 0 === currentTime ? startY : 2 === (currentTime /= duration / 2) ? startY + wholeY : (o || (o = duration * (.3 * 1.5)),
  47945. a < Math.abs(wholeY) ? (a = wholeY,
  47946. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47947. 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)
  47948. }
  47949. ,
  47950. easing.easeInBack = function(currentTime, startY, wholeY, duration, r) {
  47951. return void 0 === r && (r = 1.70158),
  47952. wholeY * (currentTime /= duration) * currentTime * ((r + 1) * currentTime - r) + startY
  47953. }
  47954. ,
  47955. easing.easeOutBack = function(currentTime, startY, wholeY, duration, r) {
  47956. return void 0 === r && (r = 1.70158),
  47957. wholeY * ((currentTime = currentTime / duration - 1) * currentTime * ((r + 1) * currentTime + r) + 1) + startY
  47958. }
  47959. ,
  47960. easing.easeInOutBack = function(currentTime, startY, wholeY, duration, r) {
  47961. return void 0 === r && (r = 1.70158),
  47962. (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
  47963. }
  47964. ,
  47965. easing.easeOutBounce = function(currentTime, startY, wholeY, duration) {
  47966. 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
  47967. }
  47968. ,
  47969. easing.easeInBounce = function(currentTime, startY, wholeY, r) {
  47970. return wholeY - easing.easeOutBounce(r - currentTime, 0, wholeY, r) + startY
  47971. }
  47972. ,
  47973. easing.easeInOutBounce = function(currentTime, startY, wholeY, r) {
  47974. 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
  47975. };
  47976. var lerp = {
  47977. /* vector: function(currentTime, startY, f) {//xzw change, add f
  47978. var wholeY = currentTime.clone();
  47979. return startY = startY.clone(),
  47980. function(duration) {
  47981. currentTime.set(wholeY.x * (1 - duration) + startY.x * duration, wholeY.y * (1 - duration) + startY.y * duration, wholeY.z * (1 - duration) + startY.z * duration)
  47982. f && f(currentTime,duration);
  47983. }
  47984. },
  47985. quaternion: function(currentTime, startY, f) {//xzw change, add f
  47986. var wholeY = currentTime.clone();
  47987. return function(duration) {
  47988. currentTime.copy(wholeY).slerp(startY, duration);
  47989. f && f(currentTime,duration);
  47990. }
  47991. },
  47992. property: function(currentTime, startY, wholeY, duration) {
  47993. var r = currentTime[startY];
  47994. return function(o) {
  47995. currentTime[startY] = r * (1 - o) + wholeY * o,
  47996. duration && duration(currentTime[startY])
  47997. }
  47998. },
  47999. uniform: function(currentTime, startY, wholeY) {
  48000. var duration = currentTime.material.uniforms[startY].value;
  48001. return function(r) {
  48002. try{
  48003. currentTime.material.uniforms[startY] && (currentTime.material.uniforms[startY].value = duration * (1 - r) + wholeY * r)
  48004. }catch(currentTime){
  48005. console.log(1)
  48006. }
  48007. }
  48008. },
  48009. matrix4: function(currentTime, startY) {
  48010. var wholeY = currentTime.clone();
  48011. return function(duration) {
  48012. for (var r = currentTime.elements, o = wholeY.elements, a = startY.elements, s = 0; s < 16; s++)
  48013. r[s] = o[s] * (1 - duration) + a[s] * duration
  48014. }
  48015. },
  48016. allUniforms: function(currentTime, startY, wholeY) {
  48017. var duration = currentTime.map(function(currentTime) {
  48018. return this.uniform(currentTime, startY, wholeY)
  48019. }
  48020. .bind(this));
  48021. return function(currentTime) {
  48022. duration.forEach(function(startY) {
  48023. startY(currentTime)
  48024. })
  48025. }
  48026. } */
  48027. vector: function(t, i, f) {//xzw change, add f
  48028. var n = t.clone();
  48029. return i = i.clone(),
  48030. function(e) {
  48031. t.set(n.x * (1 - e) + i.x * e, n.y * (1 - e) + i.y * e, n.z * (1 - e) + i.z * e);
  48032. f && f(t,e);
  48033. }
  48034. },
  48035. quaternion: function(t, i, f) {//xzw change, add f
  48036. var n = t.clone();
  48037. return function(e) {
  48038. t.copy(n).slerp(i, e);
  48039. f && f(t,e);
  48040. }
  48041. },
  48042. property: function(t, i, n, r) {
  48043. var o = t[i];
  48044. return function(e) {
  48045. t[i] = o * (1 - e) + n * e,
  48046. r && r(t[i]);
  48047. }
  48048. },
  48049. uniform: function(t, i, n) {
  48050. var r = t.material.uniforms[i].value;
  48051. return function(e) {
  48052. t.material.uniforms[i] && (t.material.uniforms[i].value = r * (1 - e) + n * e);
  48053. }
  48054. },
  48055. matrix4: function(o, a) {
  48056. var s = o.clone();
  48057. return function(e) {
  48058. for (var t = o.elements, i = s.elements, n = a.elements, r = 0; r < 16; r++)
  48059. t[r] = i[r] * (1 - e) + n[r] * e;
  48060. }
  48061. },
  48062. allUniforms: function(e, t, i) {
  48063. var n = e.map(function(e) {
  48064. return this.uniform(e, t, i)
  48065. }
  48066. .bind(this));
  48067. return function(t) {
  48068. n.forEach(function(e) {
  48069. e(t);
  48070. });
  48071. }
  48072. }
  48073. };
  48074. /*
  48075. 渐变
  48076. */
  48077. var transitions = {
  48078. globalDone: null,
  48079. funcs: [],
  48080. counter: 0,
  48081. uniqueID: 0,
  48082. start: function(func, duration, done, delay, ease, name, id, cancelFun) {
  48083. return delay = delay || 0,
  48084. this.funcs.push({
  48085. func: func,
  48086. current: -delay * Math.abs(duration), //当前时间
  48087. duration: (1 - Math.max(delay, 0)) * Math.abs(duration), //总时长
  48088. done: done,
  48089. easing: ease || easing.linearTween, //渐变曲线
  48090. cycling: duration < 0,
  48091. running: !0,
  48092. debug: delay < 0,
  48093. name: name || "T" + this.counter,
  48094. id: void 0 === id ? this.counter : id,
  48095. paused: !1,
  48096. cancelFun : cancelFun, //取消时执行的函数
  48097. }),
  48098. func(0, 16),
  48099. this.counter += 1,
  48100. func
  48101. },
  48102. trigger: function(e) {
  48103. var t = void 0 === e.delayRatio ? 0 : e.delayRatio
  48104. , u = e.func || function() {}
  48105. , r = void 0 === e.duration ? 0 : e.duration;
  48106. void 0 !== e.cycling && e.cycling && (r = -Math.abs(r));
  48107. var o = e.done || null
  48108. , a = e.easing || easing.linearTween
  48109. , s = e.name || "R" + this.counter
  48110. , l = void 0 === e.id ? this.counter : e.id;
  48111. return this.start(u, r, o, t, a, s, l)
  48112. },
  48113. setTimeout: function(e, t, u) {
  48114. var duration = void 0 === u ? this.counter : u;
  48115. return this.trigger({
  48116. done: e,
  48117. duration: void 0 === t ? 0 : t,
  48118. name: "O" + this.counter,
  48119. id: duration
  48120. })
  48121. },
  48122. pause: function() {
  48123. this.paused = !0;
  48124. },
  48125. resume: function() {
  48126. this.paused = !1;
  48127. },
  48128. update: function(e) {
  48129. this.funcs.forEach(function(t) {
  48130. if (!(t.paused || (t.current += 1e3 * e,
  48131. t.current < 0)))
  48132. if (t.current >= t.duration && !t.cycling) {
  48133. var u = t.easing(1, 0, 1, 1);
  48134. t.func(u, 1e3 * e),
  48135. t.done && t.done(),
  48136. t.running = !1;
  48137. } else {
  48138. var duration = t.easing(t.current % t.duration / t.duration, 0, 1, 1)
  48139. , r = t.func(duration, 1e3 * e) || !1;
  48140. r && (t.done && t.done(),
  48141. t.running = !1);
  48142. }
  48143. });
  48144. var t = this.funcs.length;
  48145. this.funcs = this.funcs.filter(function(e) {
  48146. return e.running
  48147. });
  48148. var u = this.funcs.length;
  48149. if (t > 0 && 0 === u && this.globalDone) {
  48150. var duration = this.globalDone;
  48151. this.globalDone = null,
  48152. duration();
  48153. }
  48154. },
  48155. adjustSpeed: function(e, t) {
  48156. for (var u = this.getById(e), duration = 0; duration < u.length; duration++) {
  48157. var r = u[duration];
  48158. r.duration /= t,
  48159. r.current /= t;
  48160. }
  48161. },
  48162. getById: function(e) {
  48163. return this.funcs.filter(function(t) {
  48164. return e === t.id
  48165. })
  48166. },
  48167. get: function(e) {
  48168. for (var t = 0; t < this.funcs.length; t += 1)
  48169. if (this.funcs[t].func === e)
  48170. return this.funcs[t];
  48171. return null
  48172. },
  48173. isRunning: function(e) {
  48174. var t = this.get(e);
  48175. return null !== t && t.running
  48176. },
  48177. countActive: function() {
  48178. for (var e = 0, t = 0; t < this.funcs.length; t += 1)
  48179. e += this.funcs[t].running;
  48180. return e
  48181. },
  48182. listActive: function() {
  48183. for (var e = [], t = 0; t < this.funcs.length; t += 1)
  48184. this.funcs[t].running && e.push(this.funcs[t].name);
  48185. return e
  48186. },
  48187. done: function(e) {
  48188. this.globalDone = e;
  48189. },
  48190. cancelById: function(e, dealCancelFun) { //xzw add dealDone
  48191. var t = void 0 === e ? 0 : e;
  48192. let cancels = [];
  48193. this.funcs = this.funcs.filter(function(e) {
  48194. var is = e.id == t;
  48195. if(is && dealCancelFun){
  48196. e.cancelFun && cancels.push(e.cancelFun);
  48197. //e.cancelFun && e.cancelFun()
  48198. }
  48199. return !is
  48200. });
  48201. cancels.forEach(e=>{e();}); //先从funcs中去除后再执行
  48202. },
  48203. cancel: function(e) {
  48204. this.funcs = this.funcs.filter(function(t) {
  48205. return t.func !== e
  48206. });
  48207. },
  48208. getUniqueId: function() {
  48209. return this.uniqueID -= 1,
  48210. this.uniqueID
  48211. }
  48212. };
  48213. const colors = {
  48214. position: 'red',
  48215. target : 'blue'
  48216. };
  48217. let lineMats$1;
  48218. const getLineMat = function(name){
  48219. if(!lineMats$1){
  48220. lineMats$1 = {
  48221. position: LineDraw.createFatLineMat({
  48222. color: colors.position,
  48223. lineWidth: 3
  48224. }),
  48225. target : LineDraw.createFatLineMat({
  48226. color: colors.target,
  48227. lineWidth: 3
  48228. }),
  48229. frustum: LineDraw.createFatLineMat({
  48230. color: colors.position,
  48231. lineWidth: 2
  48232. }),
  48233. aimAtTarget: new LineBasicMaterial({color:colors.target})
  48234. };
  48235. }
  48236. return lineMats$1[name]
  48237. };
  48238. class CameraAnimation extends EventDispatcher{
  48239. constructor(viewer){
  48240. super();
  48241. this.viewer = viewer;
  48242. this.selectedElement = null;
  48243. //this.controlPoints = [];
  48244. this.uuid = MathUtils.generateUUID();
  48245. this.node = new Object3D();
  48246. this.node.name = "camera animation";
  48247. this.viewer.scene.scene.add(this.node);
  48248. this.frustum = this.createFrustum();
  48249. this.node.add(this.frustum);
  48250. this.name = "Camera Animation";
  48251. // "centripetal", "chordal", "catmullrom"
  48252. this.curveType = "centripetal";
  48253. this.visible = true;
  48254. this.targets = [];
  48255. this.createPath();
  48256. this.duration = 5;
  48257. this.percent = 0;
  48258. this.currentIndex = 0;
  48259. this.durations = [];
  48260. this.quaternions = [];
  48261. if(!Potree.settings.isTest){
  48262. this.setVisible(false);
  48263. }
  48264. this.addEventListener('dispose', ()=>{
  48265. this.dispose();
  48266. });
  48267. this.targetLines = new Object3D;
  48268. this.node.add(this.targetLines);
  48269. }
  48270. static defaultFromView(viewer){
  48271. const animation = new CameraAnimation(viewer);
  48272. const camera = viewer.scene.getActiveCamera();
  48273. const target = viewer.scene.view.getPivot();
  48274. const cpCenter = new Vector3(
  48275. 0.3 * camera.position.x + 0.7 * target.x,
  48276. 0.3 * camera.position.y + 0.7 * target.y,
  48277. 0.3 * camera.position.z + 0.7 * target.z,
  48278. );
  48279. const targetCenter = new Vector3(
  48280. 0.05 * camera.position.x + 0.95 * target.x,
  48281. 0.05 * camera.position.y + 0.95 * target.y,
  48282. 0.05 * camera.position.z + 0.95 * target.z,
  48283. );
  48284. const r = 2;//camera.position.distanceTo(target) * 0.3;
  48285. //const dir = target.clone().sub(camera.position).normalize();
  48286. const angle = Utils.computeAzimuth(camera.position, target);
  48287. const n = 5;
  48288. for(let i = 0; i < n; i++){
  48289. let u = 1.5 * Math.PI * (i / n) + angle;
  48290. const dx = r * Math.cos(u);
  48291. const dy = r * Math.sin(u);
  48292. const cpPos = new Vector3(
  48293. cpCenter.x + dx,
  48294. cpCenter.y + dy,
  48295. cpCenter.z,
  48296. );
  48297. const targetPos = new Vector3(
  48298. targetCenter.x + dx * 0.1,
  48299. targetCenter.y + dy * 0.1,
  48300. targetCenter.z,
  48301. );
  48302. animation.createControlPoint(null,{position:cpPos, target:targetPos});
  48303. }
  48304. animation.changeCallback();
  48305. return animation;
  48306. }
  48307. createControlPoint(index, posInfo ){
  48308. const length = this.posCurve.points.length;
  48309. const position = new Vector3;
  48310. const target = new Vector3;
  48311. if(index == void 0 ){
  48312. index = length;
  48313. }
  48314. if(!posInfo){
  48315. if(length >= 2 && index === 0){
  48316. const dir = new Vector3().subVectors(this.posCurve.points[0], this.posCurve.points[1] );
  48317. position.copy(this.posCurve.points[0]).add(dir);
  48318. const tDir = new Vector3().subVectors(this.targets[0].position, this.targets[1].position );
  48319. target.copy(this.targets[0].position).add(dir);
  48320. }else if(length >= 2 && index === length){
  48321. const dir = new Vector3().subVectors(this.posCurve.points[length-1], this.posCurve.points[length-2] );
  48322. position.copy(this.posCurve.points[length-2]).add(dir);
  48323. const tDir = new Vector3().subVectors(this.targets[length-1].position, this.targets[length-2].position );
  48324. target.copy(this.targets[length-2].position).add(dir);
  48325. }else if(length >= 2){
  48326. position.copy(this.posCurve.points[index-1].clone().add(this.posCurve.points[index]).multiplyScalar(0.5));
  48327. target.copy(this.targets[length-1].position.clone().add(this.targets[length]).multiplyScalar(0.5));
  48328. }
  48329. }else {
  48330. position.copy(posInfo.position);
  48331. target.copy(posInfo.target);
  48332. }
  48333. this.posCurve.addPoint(position, index/* , true */);
  48334. //this.targetCurve.addPoint(target, index/* , true */)
  48335. let targetSvg = new HandleSvg(target, colors.target);
  48336. targetSvg.visible = this.visible;
  48337. this.targets = [...this.targets.slice(0,index), targetSvg, ...this.targets.slice(index,length)];
  48338. if(this.useDurSlice){//不使用全局的duration,而是分段的
  48339. this.durations = [...this.durations.slice(0,index), posInfo.duration, ...this.durations.slice(index,length)];
  48340. }
  48341. this.dispatchEvent({
  48342. type: "controlpoint_added",
  48343. index
  48344. });
  48345. {
  48346. let targetLine = LineDraw.createLine([position,target] ,{mat: getLineMat('aimAtTarget')});
  48347. this.targetLines.children = [...this.targetLines.children.slice(0,index), targetLine, ...this.targetLines.children.slice(index,length)];
  48348. this.targets[index].addEventListener('dragged', (e)=>{
  48349. this.updatePathCallback();
  48350. this.dragPointCallback(e);
  48351. });
  48352. }
  48353. }
  48354. dragPointCallback(e){
  48355. let index = e.index;
  48356. if(e.index == void 0){
  48357. index = this.targets.indexOf(e.target);
  48358. }
  48359. LineDraw.moveLine(this.targetLines.children[index], [this.posCurve.points[index], this.targets[index].position] );
  48360. this.updateFrustum();
  48361. }
  48362. updatePathCallback(){
  48363. {
  48364. this.quaternions = [];
  48365. let length = this.posCurve.points.length;
  48366. for(let i=0; i<length; i++){
  48367. let quaternion = math.getQuaFromPosAim(this.posCurve.points[i], this.targets[i].position);
  48368. this.quaternions.push( quaternion);
  48369. }
  48370. }
  48371. this.reMapCurvePercent();
  48372. }
  48373. removeControlPoint(index){
  48374. this.posCurve.removePoint(index);
  48375. //this.targetCurve.removePoint(index)
  48376. this.targets[index].dispose();
  48377. this.targets.splice(index, 1);
  48378. this.dispatchEvent({
  48379. type: "controlpoint_removed",
  48380. index
  48381. });
  48382. this.targetLines.remove(this.targetLines.children[index]);
  48383. if(this.useDurSlice){
  48384. this.durations.splice(index, 1);
  48385. }
  48386. }
  48387. createPath(){
  48388. this.posCurve = new CurveCtrl([],getLineMat('position'), colors.position, 'posCurve');
  48389. //this.targetCurve = new CurveCtrl([], getLineMat('target'), colors.target, 'targetCurve', {noLine:true});
  48390. this.posCurve.needsPercent = true;
  48391. this.node.add(this.posCurve);
  48392. //this.node.add(this.targetCurve)
  48393. this.posCurve.addEventListener('dragCurvePoint', this.dragPointCallback.bind(this));
  48394. this.posCurve.addEventListener('updatePath', this.updatePathCallback.bind(this));
  48395. }
  48396. createFrustum(){
  48397. const f = 0.3;
  48398. const positions = [
  48399. new Vector3( 0, 0, 0),
  48400. new Vector3(-f, -f, +1),
  48401. new Vector3( 0, 0, 0),
  48402. new Vector3( f, -f, +1),
  48403. new Vector3( 0, 0, 0),
  48404. new Vector3( f, f, +1),
  48405. new Vector3( 0, 0, 0),
  48406. new Vector3(-f, f, +1),
  48407. new Vector3(-f, -f, +1),
  48408. new Vector3( f, -f, +1),
  48409. new Vector3( f, -f, +1),
  48410. new Vector3( f, f, +1),
  48411. new Vector3( f, f, +1),
  48412. new Vector3(-f, f, +1),
  48413. new Vector3(-f, f, +1),
  48414. new Vector3(-f, -f, +1),
  48415. ];
  48416. positions.forEach(e=>e.z *= -1); //因为得到的rotation是camera的,作用在物体上要反向,所以这里反向一下
  48417. //geometry.computeBoundingSphere();//?
  48418. const line = LineDraw.createFatLine( positions, {material:getLineMat('frustum')});
  48419. //line.scale.set(20, 20, 20);
  48420. line.visible = false;
  48421. return line;
  48422. }
  48423. reMapCurvePercent(){ //因在不同点在相同位置旋转,由于间隔仅和位置距离相关,导致时间间隔为0,采取重新调整间隔的策略。
  48424. var length = this.posCurve.points.length;
  48425. if(length<2){
  48426. return this.newPointsPercents = []
  48427. }
  48428. var newPercents = [0];
  48429. if(this.useDurSlice){ //已经设定好了每一段的duration的话
  48430. let sums = [0];
  48431. let sum = 0, last;
  48432. for(let i=0;i<length-1;i++){ //去掉最后一个duration,因为已到终点
  48433. let duration = this.durations[i];
  48434. sum += duration;
  48435. last = duration;
  48436. sums.push(sum);
  48437. }
  48438. for(let i=1;i<length;i++){
  48439. newPercents.push(sum == 0 ? i/length : sums[i] / sum);
  48440. }
  48441. }else {
  48442. const maxSpaceDur = this.duration / length; //每两点之间修改间隔时间后,最大时间
  48443. const durPerRad = 0.8; //每弧度应该占用的时间
  48444. const minSpaceDur = Math.min(0.8, maxSpaceDur);//每两点之间修改间隔时间后,最小时间
  48445. const maxAngleSpaceDur = MathUtils.clamp(durPerRad * Math.PI, minSpaceDur, maxSpaceDur );// 最大可能差距是180度
  48446. var percents = this.posCurve.pointsPercent;
  48447. for(let i=1;i<length;i++){
  48448. let diff = (percents[i] - percents[i-1]) * this.duration; //间隔时间
  48449. let percent;
  48450. let curMin = minSpaceDur;
  48451. if(diff < maxAngleSpaceDur){ //若小于最大旋转时间
  48452. let rad = this.quaternions[i].angleTo(this.quaternions[i-1]);
  48453. curMin = MathUtils.clamp(rad * durPerRad, minSpaceDur, maxSpaceDur);
  48454. }
  48455. diff = Math.max(diff, curMin);
  48456. percent = newPercents[i-1] + (diff / this.duration); //得到新的percent
  48457. newPercents.push(percent);
  48458. }
  48459. let maxPercent = newPercents[length-1]; //最后一个,若扩充过时间,就会>1
  48460. if( !math.closeTo(maxPercent, 1)){
  48461. let scale = 1 / maxPercent; //需要压缩的比例 <1 这一步会让实际得到的间隔更小
  48462. newPercents = newPercents.map(e=> e*=scale );
  48463. }
  48464. }
  48465. this.newPointsPercents = newPercents;
  48466. //console.log(newPercents)
  48467. }
  48468. at(originPercent, delta, transitionRatio){
  48469. originPercent = MathUtils.clamp(originPercent, 0, 1);
  48470. //修改第一层:起始时间
  48471. let percent = originPercent;
  48472. /* const easePercent = 0.3; //缓动占比 //如果能在所有从静止到运动的中间加缓动就好了呀:lastPos * 0.9 + currentPos * 0.1 ?
  48473. if(originPercent < easePercent){
  48474. console.log('easeIn')
  48475. percent = easing.easeInSine(originPercent, 0, easePercent, easePercent) //currentTime, startY, wholeY, duration 选了一个衔接时接近斜率1的缓动函数
  48476. }else if(originPercent > 1-easePercent){
  48477. console.log('easeOut')
  48478. percent = easing.easeOutSine(originPercent-(1-easePercent), 1-easePercent, easePercent, easePercent)
  48479. } */
  48480. let quaternion;
  48481. if(percent < 1){
  48482. //修改第二层:使用每个点的重定位的 newPointsPercents
  48483. this.currentIndex = this.newPointsPercents.findIndex(e=> e>percent ) - 1;
  48484. //假设每个节点的百分比是精确的,那么:
  48485. let curIndexPercent = this.newPointsPercents[this.currentIndex];
  48486. let nextIndexPercent = this.newPointsPercents[this.currentIndex+1];
  48487. let progress = (percent - curIndexPercent) / (nextIndexPercent - curIndexPercent);//在这两个节点间的百分比
  48488. //投影到原本的 posCurve.pointsPercent上:
  48489. let curIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex];
  48490. let nextIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex+1];
  48491. percent = curIndexOriPercent + (nextIndexOriPercent - curIndexOriPercent) * progress;
  48492. let endQuaternion = this.quaternions[this.currentIndex+1];
  48493. let startQuaternion = this.quaternions[this.currentIndex];
  48494. quaternion = (new Quaternion()).copy(startQuaternion);
  48495. lerp.quaternion(quaternion, endQuaternion)(progress);
  48496. }else {
  48497. this.currentIndex = this.posCurve.points.length - 1;
  48498. quaternion = math.getQuaFromPosAim(this.posCurve.points[this.currentIndex], this.targets[this.currentIndex].position);
  48499. }
  48500. const position = this.posCurve.getPointAt(percent); // 需要this.posCurve.points.length>1 否则报错
  48501. //console.log(this.currentIndex, originPercent)
  48502. //缓动:
  48503. var aimQua, aimPos;
  48504. if(delta != void 0 ){
  48505. if(Potree.settings.tourTestCameraMove){
  48506. aimQua = this.frustum.quaternion.clone();
  48507. aimPos = this.frustum.position.clone();
  48508. }else {
  48509. var camera = viewer.scene.getActiveCamera();
  48510. aimQua = camera.quaternion.clone();
  48511. aimPos = camera.position.clone();
  48512. }
  48513. transitionRatio = transitionRatio || 1 / Potree.settings.cameraAniSmoothRatio;//渐变系数,越小缓动程度越高,越平滑
  48514. transitionRatio *= delta * 60; //假设标准帧率为60fps,当帧率低时(delta大时)要降低缓动
  48515. //console.log(transitionRatio, delta) //画面ui变化会使delta变大
  48516. transitionRatio = MathUtils.clamp(transitionRatio, 0, 1);
  48517. lerp.quaternion(aimQua, quaternion)(transitionRatio); //每次只改变一点点
  48518. lerp.vector(aimPos, position)(transitionRatio);
  48519. }else {
  48520. aimQua = quaternion; aimPos = position;
  48521. }
  48522. let rotation = new Euler().setFromQuaternion(aimQua );
  48523. const frame = {
  48524. position: aimPos,
  48525. rotation
  48526. };
  48527. return frame;
  48528. }
  48529. set(percent){
  48530. this.percent = percent;
  48531. }
  48532. setVisible(visible){
  48533. this.node.visible = visible;
  48534. this.posCurve.visible = visible;
  48535. this.targets.forEach(e=>e.visible = visible );
  48536. this.visible = visible;
  48537. }
  48538. setDuration(duration){
  48539. if(duration != this.duration){
  48540. this.duration = duration;
  48541. if(this.quaternions.length == this.posCurve.points.length)this.reMapCurvePercent();
  48542. }
  48543. }
  48544. getDuration(duration){
  48545. return this.duration;
  48546. }
  48547. play(startOptions={}){
  48548. if(this.onUpdate){
  48549. return console.error('已经开始播放')
  48550. }
  48551. let startPercent = 0, currentIndex = 0;
  48552. if(startOptions.percent != void 0 ){
  48553. startPercent = startOptions.percent;
  48554. }else if(startOptions.index){
  48555. currentIndex = index;
  48556. //startPercent = index/(this.posCurve.points.length-1)
  48557. startPercent = this.posCurve.pointsPercent[index];
  48558. }
  48559. //const tStart = performance.now();
  48560. const duration = this.duration;
  48561. this.originalyVisible = this.visible;
  48562. Potree.settings.tourTestCameraMove || this.setVisible(false);
  48563. let tStart, startTransitionRatio = 0.2;
  48564. let startDelay = 1/startTransitionRatio / 20 ;//因为缓动所以延迟开始,前面前都是at(0),使过渡到开始点位(但是依旧不能准确停在起始点,因为缓动是乘百分比有残留。所以直接平滑衔接到开始后的位置)
  48565. let hasPlayedTime = 0;
  48566. let finishDelay = Potree.settings.cameraAniSmoothRatio / 60 * 3;//结束后还需要多久时间才能大致达到缓动的最终目标
  48567. let hasStoppedTime = 0;
  48568. this.onUpdate = (e) => {
  48569. if(this.posCurve.points.length<2){
  48570. if(this.posCurve.points.length == 1){
  48571. viewer.scene.view.position.copy(this.posCurve.points[0]);
  48572. viewer.scene.view.rotation = new Euler().setFromQuaternion(this.quaternions[0]);
  48573. }
  48574. this.pause();
  48575. return
  48576. }
  48577. let percent, transitionRatio;
  48578. if(tStart){
  48579. let tNow = performance.now();
  48580. let elapsed = (tNow - tStart) / 1000;
  48581. percent = elapsed / duration + startPercent;
  48582. }else {//从当前位置过渡到开始位置
  48583. percent = 0;
  48584. hasPlayedTime += e.delta;
  48585. transitionRatio = startTransitionRatio;
  48586. //console.log('延迟开始')
  48587. if(hasPlayedTime > startDelay){
  48588. tStart = performance.now();
  48589. }
  48590. }
  48591. this.set(percent);
  48592. const frame = this.at(percent, e.delta, transitionRatio);
  48593. if(currentIndex != this.currentIndex){
  48594. currentIndex = this.currentIndex;
  48595. console.log('updateCurrentIndex', currentIndex);
  48596. this.dispatchEvent({type:'updateCurrentIndex', currentIndex });
  48597. }
  48598. if(!Potree.settings.tourTestCameraMove){
  48599. viewer.scene.view.position.copy(frame.position);
  48600. //viewer.scene.view.lookAt(frame.target);
  48601. viewer.scene.view.rotation = frame.rotation;
  48602. }
  48603. this.updateFrustum(frame);
  48604. if(percent >= 1){
  48605. if(hasStoppedTime > finishDelay){
  48606. this.pause();
  48607. }else {
  48608. hasStoppedTime += e.delta;
  48609. //console.log('延迟结束')
  48610. }
  48611. }
  48612. };
  48613. this.viewer.addEventListener("update", this.onUpdate);
  48614. }
  48615. pause(){
  48616. this.setVisible(this.originalyVisible);
  48617. this.viewer.removeEventListener("update", this.onUpdate);
  48618. this.dispatchEvent('playDone');
  48619. this.onUpdate = null;
  48620. }
  48621. updateFrustum(frame){
  48622. const frustum = this.frustum;
  48623. if(this.posCurve.points.length>1){
  48624. frustum.visible = true;
  48625. }else {
  48626. frustum.visible = false;
  48627. return
  48628. }
  48629. frame = frame || this.at(this.percent);
  48630. frustum.position.copy(frame.position);
  48631. //frustum.lookAt(...frame.target.toArray());
  48632. frustum.rotation.copy(frame.rotation);
  48633. }
  48634. changeCallback(){
  48635. this.posCurve.update();
  48636. //this.targetCurve.update()
  48637. this.targets.forEach(e=>e.update());
  48638. this.updateFrustum();
  48639. }
  48640. dispose(){//add
  48641. this.posCurve.dispose();
  48642. //this.targetCurve.dispatchEvent({type:'dispose'})
  48643. this.targets.forEach(e=>e.dispose());
  48644. this.durations = [];
  48645. this.node.parent.remove(this.node);
  48646. }
  48647. }
  48648. //scene.removeCameraAnimation
  48649. //修改:不使用targetCurve作为target曲线,因为播放时posCuve的节点和targetCurve并没有对应,且使用target的曲线会使角度变化大的情况过渡生硬。
  48650. // 改完旋转了。但是位置也有问题。速度完全和路程相关,当在同一位置设置多点时,这段的总时长为0. (是否要设置最小时长?不过也做不到 - -)
  48651. function loadPointCloud(viewer, data){
  48652. let loadMaterial = (target) => {
  48653. if(data.material){
  48654. if(data.material.activeAttributeName != null){
  48655. target.activeAttributeName = data.material.activeAttributeName;
  48656. }
  48657. if(data.material.ranges != null){
  48658. for(let range of data.material.ranges){
  48659. if(range.name === "elevationRange"){
  48660. target.elevationRange = range.value;
  48661. }else if(range.name === "intensityRange"){
  48662. target.intensityRange = range.value;
  48663. }else {
  48664. target.setRange(range.name, range.value);
  48665. }
  48666. }
  48667. }
  48668. if(data.material.size != null){
  48669. target.size = data.material.size;
  48670. }
  48671. if(data.material.minSize != null){
  48672. target.minSize = data.material.minSize;
  48673. }
  48674. if(data.material.pointSizeType != null){
  48675. target.pointSizeType = PointSizeType[data.material.pointSizeType];
  48676. }
  48677. if(data.material.matcap != null){
  48678. target.matcap = data.material.matcap;
  48679. }
  48680. }else if(data.activeAttributeName != null){
  48681. target.activeAttributeName = data.activeAttributeName;
  48682. }else {
  48683. // no material data
  48684. }
  48685. };
  48686. const promise = new Promise((resolve) => {
  48687. const names = viewer.scene.pointclouds.map(p => p.name);
  48688. const alreadyExists = names.includes(data.name);
  48689. if(alreadyExists){
  48690. resolve();
  48691. return;
  48692. }
  48693. Potree.loadPointCloud(data.url, data.name, (e) => {
  48694. const {pointcloud} = e;
  48695. pointcloud.position.set(...data.position);
  48696. pointcloud.rotation.set(...data.rotation);
  48697. pointcloud.scale.set(...data.scale);
  48698. loadMaterial(pointcloud.material);
  48699. viewer.scene.addPointCloud(pointcloud);
  48700. resolve(pointcloud);
  48701. });
  48702. });
  48703. return promise;
  48704. }
  48705. function loadMeasurement(viewer, data){
  48706. const duplicate = viewer.scene.measurements.find(measure => measure.uuid === data.uuid);
  48707. if(duplicate){
  48708. return;
  48709. }
  48710. data.points = data.points.map(point=>new Vector3(...point));
  48711. const measure = viewer.measuringTool.createMeasureFromData(data);
  48712. }
  48713. function loadVolume(viewer, data){
  48714. const duplicate = viewer.scene.volumes.find(volume => volume.uuid === data.uuid);
  48715. if(duplicate){
  48716. return;
  48717. }
  48718. let volume = new Potree[data.type];
  48719. volume.uuid = data.uuid;
  48720. volume.name = data.name;
  48721. volume.position.set(...data.position);
  48722. volume.rotation.set(...data.rotation);
  48723. volume.scale.set(...data.scale);
  48724. volume.visible = data.visible;
  48725. volume.clip = data.clip;
  48726. viewer.scene.addVolume(volume);
  48727. }
  48728. function loadCameraAnimation(viewer, data){
  48729. const duplicate = viewer.scene.cameraAnimations.find(a => a.uuid === data.uuid);
  48730. if(duplicate){
  48731. return;
  48732. }
  48733. const animation = new CameraAnimation(viewer);
  48734. animation.uuid = data.uuid;
  48735. animation.name = data.name;
  48736. animation.duration = data.duration;
  48737. animation.t = data.t;
  48738. animation.curveType = data.curveType;
  48739. animation.visible = data.visible;
  48740. animation.controlPoints = [];
  48741. for(const cpdata of data.controlPoints){
  48742. const cp = animation.createControlPoint();
  48743. cp.position.set(...cpdata.position);
  48744. cp.target.set(...cpdata.target);
  48745. }
  48746. viewer.scene.addCameraAnimation(animation);
  48747. }
  48748. function loadOrientedImages(viewer, images){
  48749. const {cameraParamsPath, imageParamsPath} = images;
  48750. const duplicate = viewer.scene.orientedImages.find(i => i.imageParamsPath === imageParamsPath);
  48751. if(duplicate){
  48752. return;
  48753. }
  48754. Potree.OrientedImageLoader.load(cameraParamsPath, imageParamsPath, viewer).then( images => {
  48755. viewer.scene.addOrientedImages(images);
  48756. });
  48757. }
  48758. function loadGeopackage(viewer, geopackage){
  48759. const path = geopackage.path;
  48760. const duplicate = viewer.scene.geopackages.find(i => i.path === path);
  48761. if(duplicate){
  48762. return;
  48763. }
  48764. const projection = viewer.getProjection();
  48765. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  48766. proj4.defs("pointcloud", projection);
  48767. const transform = proj4("WGS84", "pointcloud");
  48768. const params = {
  48769. transform: transform,
  48770. };
  48771. Potree.GeoPackageLoader.loadUrl(path, params).then(data => {
  48772. viewer.scene.addGeopackage(data);
  48773. });
  48774. }
  48775. function loadSettings(viewer, data){
  48776. if(!data){
  48777. return;
  48778. }
  48779. viewer.setPointBudget(data.pointBudget);
  48780. viewer.setFOV(data.fov);
  48781. viewer.setEDLEnabled(data.edlEnabled);
  48782. viewer.setEDLRadius(data.edlRadius);
  48783. viewer.setEDLStrength(data.edlStrength);
  48784. viewer.setBackground(data.background);
  48785. viewer.setMinNodeSize(data.minNodeSize);
  48786. viewer.setShowBoundingBox(data.showBoundingBoxes);
  48787. }
  48788. function loadView(viewer, view){
  48789. viewer.scene.view.position.set(...view.position);
  48790. viewer.scene.view.lookAt(...view.target);
  48791. }
  48792. function loadAnnotationItem(item){
  48793. const annotation = new Annotation({
  48794. position: item.position,
  48795. title: item.title,
  48796. cameraPosition: item.cameraPosition,
  48797. cameraTarget: item.cameraTarget,
  48798. });
  48799. annotation.description = item.description;
  48800. annotation.uuid = item.uuid;
  48801. if(item.offset){
  48802. annotation.offset.set(...item.offset);
  48803. }
  48804. return annotation;
  48805. }
  48806. function loadAnnotations(viewer, data){
  48807. if(!data){
  48808. return;
  48809. }
  48810. const findDuplicate = (item) => {
  48811. let duplicate = null;
  48812. viewer.scene.annotations.traverse( a => {
  48813. if(a.uuid === item.uuid){
  48814. duplicate = a;
  48815. }
  48816. });
  48817. return duplicate;
  48818. };
  48819. const traverse = (item, parent) => {
  48820. const duplicate = findDuplicate(item);
  48821. if(duplicate){
  48822. return;
  48823. }
  48824. const annotation = loadAnnotationItem(item);
  48825. for(const childItem of item.children){
  48826. traverse(childItem, annotation);
  48827. }
  48828. parent.add(annotation);
  48829. };
  48830. for(const item of data){
  48831. traverse(item, viewer.scene.annotations);
  48832. }
  48833. }
  48834. function loadProfile(viewer, data){
  48835. const {name, points} = data;
  48836. const duplicate = viewer.scene.profiles.find(profile => profile.uuid === data.uuid);
  48837. if(duplicate){
  48838. return;
  48839. }
  48840. let profile = new Potree.Profile();
  48841. profile.name = name;
  48842. profile.uuid = data.uuid;
  48843. profile.setWidth(data.width);
  48844. for(const point of points){
  48845. profile.addMarker(new Vector3(...point));
  48846. }
  48847. viewer.scene.addProfile(profile);
  48848. }
  48849. function loadClassification(viewer, data){
  48850. if(!data){
  48851. return;
  48852. }
  48853. const classifications = data;
  48854. viewer.setClassifications(classifications);
  48855. }
  48856. async function loadProject(viewer, data, done){
  48857. if(data.type !== "Potree"){
  48858. console.error("not a valid Potree project");
  48859. return;
  48860. }
  48861. loadSettings(viewer, data.settings);
  48862. loadView(viewer, data.view);
  48863. /* const pointcloudPromises = [];
  48864. for(const pointcloud of data.pointclouds){
  48865. const promise = loadPointCloud(viewer, pointcloud);
  48866. pointcloudPromises.push(promise);
  48867. } */
  48868. for(const measure of data.measurements){
  48869. loadMeasurement(viewer, measure);
  48870. }
  48871. for(const volume of data.volumes){
  48872. loadVolume(viewer, volume);
  48873. }
  48874. for(const animation of data.cameraAnimations){
  48875. loadCameraAnimation(viewer, animation);
  48876. }
  48877. for(const profile of data.profiles){
  48878. loadProfile(viewer, profile);
  48879. }
  48880. if(data.orientedImages){
  48881. for(const images of data.orientedImages){
  48882. loadOrientedImages(viewer, images);
  48883. }
  48884. }
  48885. loadAnnotations(viewer, data.annotations);
  48886. loadClassification(viewer, data.classification);
  48887. done && done();
  48888. // need to load at least one point cloud that defines the scene projection,
  48889. // before we can load stuff in other projections such as geopackages
  48890. //await Promise.any(pointcloudPromises); // (not yet supported)
  48891. /* Utils.waitAny(pointcloudPromises).then( () => {
  48892. if(data.geopackages){
  48893. for(const geopackage of data.geopackages){
  48894. loadGeopackage(viewer, geopackage);
  48895. }
  48896. }
  48897. });
  48898. await Promise.all(pointcloudPromises); */
  48899. }
  48900. //
  48901. // Algorithm by Christian Boucheny
  48902. // shader code taken and adapted from CloudCompare
  48903. //
  48904. // see
  48905. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  48906. // http://www.kitware.com/source/home/post/9
  48907. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  48908. class EyeDomeLightingMaterial extends RawShaderMaterial{
  48909. constructor(parameters = {}){
  48910. super();
  48911. let uniforms = {
  48912. /* screenWidth: { type: 'f', value: 0 },
  48913. screenHeight: { type: 'f', value: 0 }, */
  48914. resolution: { type: 'v2', value: new Vector2$1() },
  48915. edlStrength: { type: 'f', value: 1.0 },
  48916. uNear: { type: 'f', value: 1.0 },
  48917. uFar: { type: 'f', value: 1.0 },
  48918. radius: { type: 'f', value: 1.0 },
  48919. neighbours: { type: '2fv', value: [] },
  48920. depthMap: { type: 't', value: null },
  48921. uEDLColor: { type: 't', value: null },
  48922. uEDLDepth: { type: 't', value: null },
  48923. opacity: { type: 'f', value: 1.0 },
  48924. uProj: { type: "Matrix4fv", value: [] },
  48925. useEDL: { type: 'i', value: 1 }//add
  48926. };
  48927. this.setValues({
  48928. uniforms: uniforms,
  48929. vertexShader: this.getDefines() + Shaders['edl.vs'],
  48930. fragmentShader: this.getDefines() + Shaders['edl.fs'],
  48931. lights: false
  48932. });
  48933. this.neighbourCount = 8;
  48934. }
  48935. getDefines() {
  48936. let defines = '';
  48937. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  48938. return defines;
  48939. }
  48940. updateShaderSource() {
  48941. let vs = this.getDefines() + Shaders['edl.vs'];
  48942. let fs = this.getDefines() + Shaders['edl.fs'];
  48943. this.setValues({
  48944. vertexShader: vs,
  48945. fragmentShader: fs
  48946. });
  48947. this.uniforms.neighbours.value = this.neighbours;
  48948. this.needsUpdate = true;
  48949. }
  48950. get neighbourCount(){
  48951. return this._neighbourCount;
  48952. }
  48953. set neighbourCount(value){
  48954. if (this._neighbourCount !== value) { //周围八个格子
  48955. this._neighbourCount = value;
  48956. this.neighbours = new Float32Array(this._neighbourCount * 2);
  48957. for (let c = 0; c < this._neighbourCount; c++) {
  48958. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  48959. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  48960. }
  48961. this.updateShaderSource();
  48962. }
  48963. }
  48964. }
  48965. class NormalizationEDLMaterial extends RawShaderMaterial{
  48966. constructor(parameters = {}){
  48967. super();
  48968. let uniforms = {
  48969. screenWidth: { type: 'f', value: 0 },
  48970. screenHeight: { type: 'f', value: 0 },
  48971. edlStrength: { type: 'f', value: 1.0 },
  48972. radius: { type: 'f', value: 1.0 },
  48973. neighbours: { type: '2fv', value: [] },
  48974. uEDLMap: { type: 't', value: null },
  48975. uDepthMap: { type: 't', value: null },
  48976. uWeightMap: { type: 't', value: null },
  48977. };
  48978. this.setValues({
  48979. uniforms: uniforms,
  48980. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  48981. fragmentShader: this.getDefines() + Shaders['normalize_and_edl.fs'],
  48982. });
  48983. this.neighbourCount = 8;
  48984. }
  48985. getDefines() {
  48986. let defines = '';
  48987. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  48988. return defines;
  48989. }
  48990. updateShaderSource() {
  48991. let vs = this.getDefines() + Shaders['normalize.vs'];
  48992. let fs = this.getDefines() + Shaders['normalize_and_edl.fs'];
  48993. this.setValues({
  48994. vertexShader: vs,
  48995. fragmentShader: fs
  48996. });
  48997. this.uniforms.neighbours.value = this.neighbours;
  48998. this.needsUpdate = true;
  48999. }
  49000. get neighbourCount(){
  49001. return this._neighbourCount;
  49002. }
  49003. set neighbourCount(value){
  49004. if (this._neighbourCount !== value) {
  49005. this._neighbourCount = value;
  49006. this.neighbours = new Float32Array(this._neighbourCount * 2);
  49007. for (let c = 0; c < this._neighbourCount; c++) {
  49008. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  49009. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  49010. }
  49011. this.updateShaderSource();
  49012. }
  49013. }
  49014. }
  49015. class NormalizationMaterial extends RawShaderMaterial{
  49016. constructor(parameters = {}){
  49017. super();
  49018. let uniforms = {
  49019. uDepthMap: { type: 't', value: null },
  49020. uWeightMap: { type: 't', value: null },
  49021. };
  49022. this.setValues({
  49023. uniforms: uniforms,
  49024. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  49025. fragmentShader: this.getDefines() + Shaders['normalize.fs'],
  49026. });
  49027. }
  49028. getDefines() {
  49029. let defines = '';
  49030. return defines;
  49031. }
  49032. updateShaderSource() {
  49033. let vs = this.getDefines() + Shaders['normalize.vs'];
  49034. let fs = this.getDefines() + Shaders['normalize.fs'];
  49035. this.setValues({
  49036. vertexShader: vs,
  49037. fragmentShader: fs
  49038. });
  49039. this.needsUpdate = true;
  49040. }
  49041. }
  49042. /**
  49043. * laslaz code taken and adapted from plas.io js-laslaz
  49044. * http://plas.io/
  49045. * https://github.com/verma/plasio
  49046. *
  49047. * Thanks to Uday Verma and Howard Butler
  49048. *
  49049. */
  49050. class LasLazLoader {
  49051. constructor (version, extension) {
  49052. if (typeof (version) === 'string') {
  49053. this.version = new Version(version);
  49054. } else {
  49055. this.version = version;
  49056. }
  49057. this.extension = extension;
  49058. }
  49059. static progressCB () {
  49060. }
  49061. load (node) {
  49062. if (node.loaded) {
  49063. return;
  49064. }
  49065. let url = node.getURL();
  49066. if (this.version.equalOrHigher('1.4')) {
  49067. url += `.${this.extension}`;
  49068. }
  49069. let xhr = XHRFactory.createXMLHttpRequest();
  49070. xhr.open('GET', url, true);
  49071. xhr.responseType = 'arraybuffer';
  49072. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49073. xhr.onreadystatechange = () => {
  49074. if (xhr.readyState === 4) {
  49075. if (xhr.status === 200 || xhr.status === 0) {
  49076. let buffer = xhr.response;
  49077. this.parse(node, buffer);
  49078. } else {
  49079. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url);
  49080. }
  49081. }
  49082. };
  49083. xhr.send(null);
  49084. }
  49085. async parse(node, buffer){
  49086. let lf = new LASFile(buffer);
  49087. let handler = new LasLazBatcher(node);
  49088. try{
  49089. await lf.open();
  49090. lf.isOpen = true;
  49091. }catch(e){
  49092. console.log("failed to open file. :(");
  49093. return;
  49094. }
  49095. let header = await lf.getHeader();
  49096. let skip = 1;
  49097. let totalRead = 0;
  49098. let totalToRead = (skip <= 1 ? header.pointsCount : header.pointsCount / skip);
  49099. let hasMoreData = true;
  49100. while(hasMoreData){
  49101. let data = await lf.readData(1000 * 1000, 0, skip);
  49102. handler.push(new LASDecoder(data.buffer,
  49103. header.pointsFormatId,
  49104. header.pointsStructSize,
  49105. data.count,
  49106. header.scale,
  49107. header.offset,
  49108. header.mins, header.maxs));
  49109. totalRead += data.count;
  49110. LasLazLoader.progressCB(totalRead / totalToRead);
  49111. hasMoreData = data.hasMoreData;
  49112. }
  49113. header.totalRead = totalRead;
  49114. header.versionAsString = lf.versionAsString;
  49115. header.isCompressed = lf.isCompressed;
  49116. LasLazLoader.progressCB(1);
  49117. try{
  49118. await lf.close();
  49119. lf.isOpen = false;
  49120. }catch(e){
  49121. console.error("failed to close las/laz file!!!");
  49122. throw e;
  49123. }
  49124. }
  49125. handle (node, url) {
  49126. }
  49127. };
  49128. class LasLazBatcher{
  49129. constructor (node) {
  49130. this.node = node;
  49131. }
  49132. push (lasBuffer) {
  49133. const workerPath = Potree.scriptPath + '/workers/LASDecoderWorker.js';
  49134. const worker = Potree.workerPool.getWorker(workerPath);
  49135. const node = this.node;
  49136. const pointAttributes = node.pcoGeometry.pointAttributes;
  49137. worker.onmessage = (e) => {
  49138. let geometry = new BufferGeometry();
  49139. let numPoints = lasBuffer.pointsCount;
  49140. let positions = new Float32Array(e.data.position);
  49141. let colors = new Uint8Array(e.data.color);
  49142. let intensities = new Float32Array(e.data.intensity);
  49143. let classifications = new Uint8Array(e.data.classification);
  49144. let returnNumbers = new Uint8Array(e.data.returnNumber);
  49145. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49146. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  49147. let indices = new Uint8Array(e.data.indices);
  49148. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  49149. geometry.setAttribute('color', new BufferAttribute(colors, 4, true));
  49150. geometry.setAttribute('intensity', new BufferAttribute(intensities, 1));
  49151. geometry.setAttribute('classification', new BufferAttribute(classifications, 1));
  49152. geometry.setAttribute('return number', new BufferAttribute(returnNumbers, 1));
  49153. geometry.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  49154. geometry.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1));
  49155. geometry.setAttribute('indices', new BufferAttribute(indices, 4));
  49156. geometry.attributes.indices.normalized = true;
  49157. for(const key in e.data.ranges){
  49158. const range = e.data.ranges[key];
  49159. const attribute = pointAttributes.attributes.find(a => a.name === key);
  49160. attribute.range[0] = Math.min(attribute.range[0], range[0]);
  49161. attribute.range[1] = Math.max(attribute.range[1], range[1]);
  49162. }
  49163. let tightBoundingBox = new Box3(
  49164. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49165. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49166. );
  49167. geometry.boundingBox = this.node.boundingBox;
  49168. this.node.tightBoundingBox = tightBoundingBox;
  49169. this.node.geometry = geometry;
  49170. this.node.numPoints = numPoints;
  49171. this.node.loaded = true;
  49172. this.node.loading = false;
  49173. Potree.numNodesLoading--;
  49174. this.node.mean = new Vector3(...e.data.mean);
  49175. Potree.workerPool.returnWorker(workerPath, worker);
  49176. };
  49177. let message = {
  49178. buffer: lasBuffer.arrayb,
  49179. numPoints: lasBuffer.pointsCount,
  49180. pointSize: lasBuffer.pointSize,
  49181. pointFormatID: 2,
  49182. scale: lasBuffer.scale,
  49183. offset: lasBuffer.offset,
  49184. mins: lasBuffer.mins,
  49185. maxs: lasBuffer.maxs
  49186. };
  49187. worker.postMessage(message, [message.buffer]);
  49188. };
  49189. }
  49190. //加载 解析点云
  49191. class BinaryLoader{
  49192. constructor(version, boundingBox, scale){
  49193. if (typeof (version) === 'string') {
  49194. this.version = new Version(version);
  49195. } else {
  49196. this.version = version;
  49197. }
  49198. this.boundingBox = boundingBox;
  49199. this.scale = scale;
  49200. }
  49201. load(node){
  49202. if (node.loaded) {
  49203. return;
  49204. }
  49205. let url = node.getURL();
  49206. if (this.version.equalOrHigher('1.4')) {
  49207. url += '.bin';
  49208. }
  49209. url += '?m='+node.pcoGeometry.timeStamp; //add
  49210. let xhr = XHRFactory.createXMLHttpRequest();
  49211. xhr.open('GET', url, true);
  49212. xhr.responseType = 'arraybuffer';
  49213. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49214. xhr.onreadystatechange = () => {
  49215. if (xhr.readyState === 4) {
  49216. if((xhr.status === 200 || xhr.status === 0) && xhr.response !== null){
  49217. let buffer = xhr.response;
  49218. this.parse(node, buffer);
  49219. } else {
  49220. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  49221. throw new Error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  49222. }
  49223. }
  49224. };
  49225. try {
  49226. xhr.send(null);
  49227. } catch (e) {
  49228. console.log('fehler beim laden der punktwolke: ' + e);
  49229. }
  49230. };
  49231. parse(node, buffer){ //解析点云
  49232. let pointAttributes = node.pcoGeometry.pointAttributes;
  49233. let numPoints = buffer.byteLength / node.pcoGeometry.pointAttributes.byteSize;
  49234. if (this.version.upTo('1.5')) {
  49235. node.numPoints = numPoints;
  49236. }
  49237. let workerPath = Potree.scriptPath + '/workers/BinaryDecoderWorker.js';
  49238. let worker = Potree.workerPool.getWorker(workerPath);
  49239. worker.onmessage = function (e) {
  49240. let data = e.data;
  49241. let buffers = data.attributeBuffers;
  49242. let tightBoundingBox = new Box3(
  49243. new Vector3().fromArray(data.tightBoundingBox.min),
  49244. new Vector3().fromArray(data.tightBoundingBox.max)
  49245. );
  49246. Potree.workerPool.returnWorker(workerPath, worker);
  49247. let geometry = new BufferGeometry();
  49248. for(let property in buffers){
  49249. let buffer = buffers[property].buffer;
  49250. let batchAttribute = buffers[property].attribute;
  49251. if (property === "POSITION_CARTESIAN") {
  49252. geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3));
  49253. } else if (property === "rgba") {
  49254. geometry.setAttribute("rgba", new BufferAttribute(new Uint8Array(buffer), 4, true));
  49255. } else if (property === "NORMAL_SPHEREMAPPED") {
  49256. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49257. } else if (property === "NORMAL_OCT16") {
  49258. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49259. } else if (property === "NORMAL") {
  49260. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49261. } else if (property === "INDICES") {
  49262. let bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4);
  49263. bufferAttribute.normalized = true;
  49264. geometry.setAttribute('indices', bufferAttribute);
  49265. } else if (property === "SPACING") {
  49266. let bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  49267. geometry.setAttribute('spacing', bufferAttribute);
  49268. } else {
  49269. const bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  49270. bufferAttribute.potree = {
  49271. offset: buffers[property].offset,
  49272. scale: buffers[property].scale,
  49273. preciseBuffer: buffers[property].preciseBuffer,
  49274. range: batchAttribute.range,
  49275. };
  49276. geometry.setAttribute(property, bufferAttribute);
  49277. const attribute = pointAttributes.attributes.find(a => a.name === batchAttribute.name);
  49278. attribute.range[0] = Math.min(attribute.range[0], batchAttribute.range[0]);
  49279. attribute.range[1] = Math.max(attribute.range[1], batchAttribute.range[1]);
  49280. if(node.getLevel() === 0){
  49281. attribute.initialRange = batchAttribute.range;
  49282. }
  49283. }
  49284. }
  49285. tightBoundingBox.max.sub(tightBoundingBox.min);
  49286. tightBoundingBox.min.set(0, 0, 0);
  49287. let numPoints = e.data.buffer.byteLength / pointAttributes.byteSize;
  49288. node.numPoints = numPoints;
  49289. node.geometry = geometry;
  49290. node.mean = new Vector3(...data.mean);
  49291. node.tightBoundingBox = tightBoundingBox;
  49292. node.loaded = true;
  49293. node.loading = false;
  49294. node.estimatedSpacing = data.estimatedSpacing;
  49295. Potree.numNodesLoading--;
  49296. };
  49297. let message = {
  49298. buffer: buffer,
  49299. pointAttributes: pointAttributes,
  49300. version: this.version.version,
  49301. min: [ node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z ],
  49302. offset: [node.pcoGeometry.offset.x, node.pcoGeometry.offset.y, node.pcoGeometry.offset.z],
  49303. scale: this.scale,
  49304. spacing: node.spacing,
  49305. hasChildren: node.hasChildren,
  49306. name: node.name
  49307. };
  49308. worker.postMessage(message, [message.buffer]);
  49309. };
  49310. }
  49311. var transformFrom4dkk = function(name){
  49312. var jsAttribute = PointAttribute[name];
  49313. return jsAttribute
  49314. /* if(name == "POSITION_CARTESIAN"){
  49315. jsAttribute = {
  49316. description: "",
  49317. elementSize: 4,
  49318. elements: 3,
  49319. name: "POSITION_CARTESIAN",
  49320. size: 12,
  49321. type: "int32",
  49322. }
  49323. }else if(name == "COLOR_PACKED"){
  49324. jsAttribute = {
  49325. description: "" ,
  49326. elementSize: 1,
  49327. elements: 4,
  49328. name: "RGBA",
  49329. size: 4,
  49330. type: 'int8',
  49331. }
  49332. }else if(name == "NORMAL_OCT16"){
  49333. jsAttribute = {
  49334. description: "" ,
  49335. elementSize: 4,
  49336. elements: 2,
  49337. name: "NORMAL_OCT16",
  49338. size: 12,
  49339. type: "uint8",
  49340. }
  49341. } */
  49342. /* var Q = q(L.COLOR_PACKED, K.DATA_TYPE_INT8, 4)
  49343. POSITION_CARTESIAN: q(L.POSITION_CARTESIAN, K.DATA_TYPE_FLOAT, 3),
  49344. RGBA_PACKED: Q,
  49345. COLOR_PACKED: Q,
  49346. RGB_PACKED: q(L.COLOR_PACKED, K.DATA_TYPE_INT8, 3),
  49347. NORMAL_FLOATS: q(L.NORMAL_FLOATS, K.DATA_TYPE_FLOAT, 3),
  49348. FILLER_1B: q(L.FILLER, K.DATA_TYPE_UINT8, 1),
  49349. INTENSITY: q(L.INTENSITY, K.DATA_TYPE_UINT16, 1),
  49350. CLASSIFICATION: q(L.CLASSIFICATION, K.DATA_TYPE_UINT8, 1),
  49351. NORMAL_SPHEREMAPPED: q(L.NORMAL_SPHEREMAPPED, K.DATA_TYPE_UINT8, 2),
  49352. NORMAL_OCT16: q(L.NORMAL_OCT16, K.DATA_TYPE_UINT8, 2),
  49353. NORMAL: q(L.NORMAL, K.DATA_TYPE_FLOAT, 3) */
  49354. };
  49355. function parseAttributes(cloudjs){
  49356. let version = new Version(cloudjs.version);
  49357. const replacements = {
  49358. "COLOR_PACKED": "rgba",
  49359. "RGBA": "rgba",
  49360. "INTENSITY": "intensity",
  49361. "CLASSIFICATION": "classification",
  49362. "GPS_TIME": "gps-time",
  49363. };
  49364. const replaceOldNames = (old) => {
  49365. if(replacements[old]){
  49366. return replacements[old];
  49367. }else {
  49368. return old;
  49369. }
  49370. };
  49371. const pointAttributes = [];
  49372. if(version.upTo('1.7')){
  49373. for(let attributeName of cloudjs.pointAttributes){
  49374. const oldAttribute = PointAttribute[attributeName];
  49375. const attribute = {
  49376. name: oldAttribute.name,
  49377. size: oldAttribute.byteSize,
  49378. elements: oldAttribute.numElements,
  49379. elementSize: oldAttribute.byteSize / oldAttribute.numElements,
  49380. type: oldAttribute.type.name,
  49381. description: "",
  49382. };
  49383. pointAttributes.push(attribute);
  49384. }
  49385. }else {
  49386. pointAttributes.push(...cloudjs.pointAttributes);
  49387. }
  49388. {
  49389. const attributes = new PointAttributes();
  49390. const typeConversion = {
  49391. int8: PointAttributeTypes.DATA_TYPE_INT8,
  49392. int16: PointAttributeTypes.DATA_TYPE_INT16,
  49393. int32: PointAttributeTypes.DATA_TYPE_INT32,
  49394. int64: PointAttributeTypes.DATA_TYPE_INT64,
  49395. uint8: PointAttributeTypes.DATA_TYPE_UINT8,
  49396. uint16: PointAttributeTypes.DATA_TYPE_UINT16,
  49397. uint32: PointAttributeTypes.DATA_TYPE_UINT32,
  49398. uint64: PointAttributeTypes.DATA_TYPE_UINT64,
  49399. double: PointAttributeTypes.DATA_TYPE_DOUBLE,
  49400. float: PointAttributeTypes.DATA_TYPE_FLOAT,
  49401. };
  49402. for(let jsAttribute of pointAttributes){
  49403. if(jsAttribute.name == void 0){//是来自四维看看的数据
  49404. //attribute = transformFrom4dkk(jsAttribute)
  49405. var attribute_ = PointAttribute[jsAttribute];
  49406. attributes.add(attribute_);
  49407. continue;
  49408. }
  49409. const name = replaceOldNames(jsAttribute.name);
  49410. const type = typeConversion[jsAttribute.type];
  49411. const numElements = jsAttribute.elements;
  49412. const description = jsAttribute.description;
  49413. const attribute = new PointAttribute(name, type, numElements);
  49414. attributes.add(attribute);
  49415. }
  49416. {
  49417. // check if it has normals
  49418. let hasNormals =
  49419. pointAttributes.find(a => a.name === "NormalX") !== undefined &&
  49420. pointAttributes.find(a => a.name === "NormalY") !== undefined &&
  49421. pointAttributes.find(a => a.name === "NormalZ") !== undefined;
  49422. if(hasNormals){
  49423. let vector = {
  49424. name: "NORMAL",
  49425. attributes: ["NormalX", "NormalY", "NormalZ"],
  49426. };
  49427. attributes.addVector(vector);
  49428. }
  49429. }
  49430. return attributes;
  49431. }
  49432. }
  49433. function lasLazAttributes(fMno){
  49434. const attributes = new PointAttributes();
  49435. attributes.add(PointAttribute.POSITION_CARTESIAN);
  49436. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  49437. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  49438. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49439. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  49440. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49441. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49442. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  49443. //attributes.add(new PointAttribute("pointSourceID", PointAttributeTypes.DATA_TYPE_INT8, 4));
  49444. return attributes;
  49445. }
  49446. class POCLoader {
  49447. static load(url, timeStamp, callback){ //add timeStamp
  49448. try {
  49449. let pco = new PointCloudOctreeGeometry();
  49450. pco.timeStamp = timeStamp;
  49451. pco.url = url;
  49452. let xhr = XHRFactory.createXMLHttpRequest();
  49453. xhr.open('GET', url+'?m='+timeStamp, true);
  49454. xhr.onreadystatechange = function () {
  49455. if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
  49456. let fMno = JSON.parse(xhr.responseText);
  49457. let version = new Version(fMno.version);
  49458. // assume octreeDir is absolute if it starts with http
  49459. if (fMno.octreeDir.indexOf('http') === 0) {
  49460. pco.octreeDir = fMno.octreeDir;
  49461. } else {
  49462. pco.octreeDir = url + '/../' + fMno.octreeDir;
  49463. }
  49464. pco.spacing = fMno.spacing;
  49465. pco.hierarchyStepSize = fMno.hierarchyStepSize;
  49466. pco.pointAttributes = fMno.pointAttributes;
  49467. let min = new Vector3(fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz);
  49468. let max = new Vector3(fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz);
  49469. let boundingBox = new Box3(min, max);
  49470. let tightBoundingBox = boundingBox.clone();
  49471. if (fMno.tightBoundingBox) {//这个才是真实的bounding,前面那个bounding的size是个正方体,似乎取了最长边作为边长
  49472. tightBoundingBox.min.copy(new Vector3(fMno.tightBoundingBox.lx, fMno.tightBoundingBox.ly, fMno.tightBoundingBox.lz));
  49473. tightBoundingBox.max.copy(new Vector3(fMno.tightBoundingBox.ux, fMno.tightBoundingBox.uy, fMno.tightBoundingBox.uz));
  49474. }
  49475. let offset = min.clone(); //将成为点云的position,被我用作旋转中心(但在点云中不那么居中,navvis也是这样, 这样可能是为了让模型在这数据的bounding上)
  49476. boundingBox.min.sub(offset); //点云的真实坐标的min都是0,0,0吗(我看案例是,因绕角落旋转,也就是原点)
  49477. boundingBox.max.sub(offset);
  49478. tightBoundingBox.min.sub(offset);
  49479. tightBoundingBox.max.sub(offset);
  49480. //改
  49481. //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 ",
  49482. //"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" //给地图
  49483. pco.boundingBox = boundingBox;
  49484. pco.tightBoundingBox = tightBoundingBox;
  49485. pco.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  49486. pco.tightBoundingSphere = tightBoundingBox.getBoundingSphere(new Sphere());
  49487. pco.offset = offset;
  49488. if (fMno.pointAttributes === 'LAS') {
  49489. pco.loader = new LasLazLoader(fMno.version, "las");
  49490. pco.pointAttributes = lasLazAttributes(fMno);
  49491. } else if (fMno.pointAttributes === 'LAZ') {
  49492. pco.loader = new LasLazLoader(fMno.version, "laz");
  49493. pco.pointAttributes = lasLazAttributes(fMno);
  49494. } else {
  49495. pco.loader = new BinaryLoader(fMno.version, boundingBox, fMno.scale);
  49496. pco.pointAttributes = parseAttributes(fMno);
  49497. }
  49498. let nodes = {};
  49499. { // load root
  49500. let name = 'r';
  49501. let root = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  49502. root.level = 0;
  49503. root.hasChildren = true;
  49504. root.spacing = pco.spacing;
  49505. if (version.upTo('1.5')) {
  49506. root.numPoints = fMno.hierarchy[0][1];
  49507. } else {
  49508. root.numPoints = 0;
  49509. }
  49510. pco.root = root;
  49511. pco.root.load();
  49512. nodes[name] = root;
  49513. }
  49514. // load remaining hierarchy
  49515. if (version.upTo('1.4')) {
  49516. for (let i = 1; i < fMno.hierarchy.length; i++) {
  49517. let name = fMno.hierarchy[i][0];
  49518. let numPoints = fMno.hierarchy[i][1];
  49519. let index = parseInt(name.charAt(name.length - 1));
  49520. let parentName = name.substring(0, name.length - 1);
  49521. let parentNode = nodes[parentName];
  49522. let level = name.length - 1;
  49523. //let boundingBox = POCLoader.createChildAABB(parentNode.boundingBox, index);
  49524. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  49525. let node = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  49526. node.level = level;
  49527. node.numPoints = numPoints;
  49528. node.spacing = pco.spacing / Math.pow(2, level);
  49529. parentNode.addChild(node);
  49530. nodes[name] = node;
  49531. }
  49532. }
  49533. pco.nodes = nodes;
  49534. callback(pco);
  49535. }
  49536. };
  49537. xhr.send(null);
  49538. } catch (e) {
  49539. console.log("loading failed: '" + url + "'");
  49540. console.log(e);
  49541. callback();
  49542. }
  49543. }
  49544. loadPointAttributes(mno){
  49545. let fpa = mno.pointAttributes;
  49546. let pa = new PointAttributes();
  49547. for (let i = 0; i < fpa.length; i++) {
  49548. let pointAttribute = PointAttribute[fpa[i]];
  49549. pa.add(pointAttribute);
  49550. }
  49551. return pa;
  49552. }
  49553. createChildAABB(aabb, index){
  49554. let min = aabb.min.clone();
  49555. let max = aabb.max.clone();
  49556. let size = new Vector3().subVectors(max, min);
  49557. if ((index & 0b0001) > 0) {
  49558. min.z += size.z / 2;
  49559. } else {
  49560. max.z -= size.z / 2;
  49561. }
  49562. if ((index & 0b0010) > 0) {
  49563. min.y += size.y / 2;
  49564. } else {
  49565. max.y -= size.y / 2;
  49566. }
  49567. if ((index & 0b0100) > 0) {
  49568. min.x += size.x / 2;
  49569. } else {
  49570. max.x -= size.x / 2;
  49571. }
  49572. return new Box3(min, max);
  49573. }
  49574. }
  49575. /**
  49576. * @author Connor Manning
  49577. */
  49578. class EptLoader {
  49579. static async load(file, callback) {
  49580. let response = await fetch(file);
  49581. let json = await response.json();
  49582. let url = file.substr(0, file.lastIndexOf('ept.json'));
  49583. let geometry = new Potree.PointCloudEptGeometry(url, json);
  49584. let root = new Potree.PointCloudEptGeometryNode(geometry);
  49585. geometry.root = root;
  49586. geometry.root.load();
  49587. callback(geometry);
  49588. }
  49589. };
  49590. class EptBinaryLoader {
  49591. extension() {
  49592. return '.bin';
  49593. }
  49594. workerPath() {
  49595. return Potree.scriptPath + '/workers/EptBinaryDecoderWorker.js';
  49596. }
  49597. load(node) {
  49598. if (node.loaded) return;
  49599. let url = node.url() + this.extension();
  49600. let xhr = XHRFactory.createXMLHttpRequest();
  49601. xhr.open('GET', url, true);
  49602. xhr.responseType = 'arraybuffer';
  49603. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49604. xhr.onreadystatechange = () => {
  49605. if (xhr.readyState === 4) {
  49606. if (xhr.status === 200) {
  49607. let buffer = xhr.response;
  49608. this.parse(node, buffer);
  49609. } else {
  49610. console.log('Failed ' + url + ': ' + xhr.status);
  49611. }
  49612. }
  49613. };
  49614. try {
  49615. xhr.send(null);
  49616. }
  49617. catch (e) {
  49618. console.log('Failed request: ' + e);
  49619. }
  49620. }
  49621. parse(node, buffer) {
  49622. let workerPath = this.workerPath();
  49623. let worker = Potree.workerPool.getWorker(workerPath);
  49624. worker.onmessage = function(e) {
  49625. let g = new BufferGeometry();
  49626. let numPoints = e.data.numPoints;
  49627. let position = new Float32Array(e.data.position);
  49628. g.setAttribute('position', new BufferAttribute(position, 3));
  49629. let indices = new Uint8Array(e.data.indices);
  49630. g.setAttribute('indices', new BufferAttribute(indices, 4));
  49631. if (e.data.color) {
  49632. let color = new Uint8Array(e.data.color);
  49633. g.setAttribute('color', new BufferAttribute(color, 4, true));
  49634. }
  49635. if (e.data.intensity) {
  49636. let intensity = new Float32Array(e.data.intensity);
  49637. g.setAttribute('intensity',
  49638. new BufferAttribute(intensity, 1));
  49639. }
  49640. if (e.data.classification) {
  49641. let classification = new Uint8Array(e.data.classification);
  49642. g.setAttribute('classification',
  49643. new BufferAttribute(classification, 1));
  49644. }
  49645. if (e.data.returnNumber) {
  49646. let returnNumber = new Uint8Array(e.data.returnNumber);
  49647. g.setAttribute('return number',
  49648. new BufferAttribute(returnNumber, 1));
  49649. }
  49650. if (e.data.numberOfReturns) {
  49651. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49652. g.setAttribute('number of returns',
  49653. new BufferAttribute(numberOfReturns, 1));
  49654. }
  49655. if (e.data.pointSourceId) {
  49656. let pointSourceId = new Uint16Array(e.data.pointSourceId);
  49657. g.setAttribute('source id',
  49658. new BufferAttribute(pointSourceId, 1));
  49659. }
  49660. g.attributes.indices.normalized = true;
  49661. let tightBoundingBox = new Box3(
  49662. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49663. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49664. );
  49665. node.doneLoading(
  49666. g,
  49667. tightBoundingBox,
  49668. numPoints,
  49669. new Vector3(...e.data.mean));
  49670. Potree.workerPool.returnWorker(workerPath, worker);
  49671. };
  49672. let toArray = (v) => [v.x, v.y, v.z];
  49673. let message = {
  49674. buffer: buffer,
  49675. schema: node.ept.schema,
  49676. scale: node.ept.eptScale,
  49677. offset: node.ept.eptOffset,
  49678. mins: toArray(node.key.b.min)
  49679. };
  49680. worker.postMessage(message, [message.buffer]);
  49681. }
  49682. };
  49683. /**
  49684. * laslaz code taken and adapted from plas.io js-laslaz
  49685. * http://plas.io/
  49686. * https://github.com/verma/plasio
  49687. *
  49688. * Thanks to Uday Verma and Howard Butler
  49689. *
  49690. */
  49691. class EptLaszipLoader {
  49692. load(node) {
  49693. if (node.loaded) return;
  49694. let url = node.url() + '.laz';
  49695. let xhr = XHRFactory.createXMLHttpRequest();
  49696. xhr.open('GET', url, true);
  49697. xhr.responseType = 'arraybuffer';
  49698. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49699. xhr.onreadystatechange = () => {
  49700. if (xhr.readyState === 4) {
  49701. if (xhr.status === 200) {
  49702. let buffer = xhr.response;
  49703. this.parse(node, buffer);
  49704. } else {
  49705. console.log('Failed ' + url + ': ' + xhr.status);
  49706. }
  49707. }
  49708. };
  49709. xhr.send(null);
  49710. }
  49711. async parse(node, buffer){
  49712. let lf = new LASFile(buffer);
  49713. let handler = new EptLazBatcher(node);
  49714. try{
  49715. await lf.open();
  49716. lf.isOpen = true;
  49717. const header = await lf.getHeader();
  49718. {
  49719. let i = 0;
  49720. let toArray = (v) => [v.x, v.y, v.z];
  49721. let mins = toArray(node.key.b.min);
  49722. let maxs = toArray(node.key.b.max);
  49723. let hasMoreData = true;
  49724. while(hasMoreData){
  49725. const data = await lf.readData(1000000, 0, 1);
  49726. let d = new LASDecoder(
  49727. data.buffer,
  49728. header.pointsFormatId,
  49729. header.pointsStructSize,
  49730. data.count,
  49731. header.scale,
  49732. header.offset,
  49733. mins,
  49734. maxs);
  49735. d.extraBytes = header.extraBytes;
  49736. d.pointsFormatId = header.pointsFormatId;
  49737. handler.push(d);
  49738. i += data.count;
  49739. hasMoreData = data.hasMoreData;
  49740. }
  49741. header.totalRead = i;
  49742. header.versionAsString = lf.versionAsString;
  49743. header.isCompressed = lf.isCompressed;
  49744. await lf.close();
  49745. lf.isOpen = false;
  49746. }
  49747. }catch(err){
  49748. console.error('Error reading LAZ:', err);
  49749. if (lf.isOpen) {
  49750. await lf.close();
  49751. lf.isOpen = false;
  49752. }
  49753. throw err;
  49754. }
  49755. }
  49756. };
  49757. class EptLazBatcher {
  49758. constructor(node) { this.node = node; }
  49759. push(las) {
  49760. let workerPath = Potree.scriptPath +
  49761. '/workers/EptLaszipDecoderWorker.js';
  49762. let worker = Potree.workerPool.getWorker(workerPath);
  49763. worker.onmessage = (e) => {
  49764. let g = new BufferGeometry();
  49765. let numPoints = las.pointsCount;
  49766. let positions = new Float32Array(e.data.position);
  49767. let colors = new Uint8Array(e.data.color);
  49768. let intensities = new Float32Array(e.data.intensity);
  49769. let classifications = new Uint8Array(e.data.classification);
  49770. let returnNumbers = new Uint8Array(e.data.returnNumber);
  49771. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49772. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  49773. let indices = new Uint8Array(e.data.indices);
  49774. let gpsTime = new Float32Array(e.data.gpsTime);
  49775. g.setAttribute('position',
  49776. new BufferAttribute(positions, 3));
  49777. g.setAttribute('rgba',
  49778. new BufferAttribute(colors, 4, true));
  49779. g.setAttribute('intensity',
  49780. new BufferAttribute(intensities, 1));
  49781. g.setAttribute('classification',
  49782. new BufferAttribute(classifications, 1));
  49783. g.setAttribute('return number',
  49784. new BufferAttribute(returnNumbers, 1));
  49785. g.setAttribute('number of returns',
  49786. new BufferAttribute(numberOfReturns, 1));
  49787. g.setAttribute('source id',
  49788. new BufferAttribute(pointSourceIDs, 1));
  49789. g.setAttribute('indices',
  49790. new BufferAttribute(indices, 4));
  49791. g.setAttribute('gpsTime',
  49792. new BufferAttribute(gpsTime, 1));
  49793. this.node.gpsTime = e.data.gpsMeta;
  49794. g.attributes.indices.normalized = true;
  49795. let tightBoundingBox = new Box3(
  49796. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49797. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49798. );
  49799. this.node.doneLoading(
  49800. g,
  49801. tightBoundingBox,
  49802. numPoints,
  49803. new Vector3(...e.data.mean));
  49804. Potree.workerPool.returnWorker(workerPath, worker);
  49805. };
  49806. let message = {
  49807. buffer: las.arrayb,
  49808. numPoints: las.pointsCount,
  49809. pointSize: las.pointSize,
  49810. pointFormatID: las.pointsFormatId,
  49811. scale: las.scale,
  49812. offset: las.offset,
  49813. mins: las.mins,
  49814. maxs: las.maxs
  49815. };
  49816. worker.postMessage(message, [message.buffer]);
  49817. };
  49818. };
  49819. class EptZstandardLoader extends EptBinaryLoader {
  49820. extension() {
  49821. return '.zst';
  49822. }
  49823. workerPath() {
  49824. return Potree.scriptPath + '/workers/EptZstandardDecoderWorker.js';
  49825. }
  49826. };
  49827. class ShapefileLoader{
  49828. constructor(){
  49829. this.transform = null;
  49830. }
  49831. async load(path){
  49832. const matLine = new LineMaterial( {
  49833. color: 0xff0000,
  49834. lineWidth: 3, // in pixels
  49835. resolution: new Vector2$1(1000, 1000),
  49836. dashed: false
  49837. } );
  49838. const features = await this.loadShapefileFeatures(path);
  49839. const node = new Object3D();
  49840. for(const feature of features){
  49841. const fnode = this.featureToSceneNode(feature, matLine);
  49842. node.add(fnode);
  49843. }
  49844. let setResolution = (x, y) => {
  49845. matLine.resolution.set(x, y);
  49846. };
  49847. const result = {
  49848. features: features,
  49849. node: node,
  49850. setResolution: setResolution,
  49851. };
  49852. return result;
  49853. }
  49854. featureToSceneNode(feature, matLine){
  49855. let geometry = feature.geometry;
  49856. let color = new Color(1, 1, 1);
  49857. let transform = this.transform;
  49858. if(transform === null){
  49859. transform = {forward: (v) => v};
  49860. }
  49861. if(feature.geometry.type === "Point"){
  49862. let sg = new SphereGeometry(1, 18, 18);
  49863. let sm = new MeshNormalMaterial();
  49864. let s = new Mesh(sg, sm);
  49865. let [long, lat] = geometry.coordinates;
  49866. let pos = transform.forward([long, lat]);
  49867. s.position.set(...pos, 20);
  49868. s.scale.set(10, 10, 10);
  49869. return s;
  49870. }else if(geometry.type === "LineString"){
  49871. let coordinates = [];
  49872. let min = new Vector3(Infinity, Infinity, Infinity);
  49873. for(let i = 0; i < geometry.coordinates.length; i++){
  49874. let [long, lat] = geometry.coordinates[i];
  49875. let pos = transform.forward([long, lat]);
  49876. min.x = Math.min(min.x, pos[0]);
  49877. min.y = Math.min(min.y, pos[1]);
  49878. min.z = Math.min(min.z, 20);
  49879. coordinates.push(...pos, 20);
  49880. if(i > 0 && i < geometry.coordinates.length - 1){
  49881. coordinates.push(...pos, 20);
  49882. }
  49883. }
  49884. for(let i = 0; i < coordinates.length; i += 3){
  49885. coordinates[i+0] -= min.x;
  49886. coordinates[i+1] -= min.y;
  49887. coordinates[i+2] -= min.z;
  49888. }
  49889. const lineGeometry = new LineGeometry();
  49890. lineGeometry.setPositions( coordinates );
  49891. const line = new Line2( lineGeometry, matLine );
  49892. line.computeLineDistances();
  49893. line.scale.set( 1, 1, 1 );
  49894. line.position.copy(min);
  49895. return line;
  49896. }else if(geometry.type === "Polygon"){
  49897. for(let pc of geometry.coordinates){
  49898. let coordinates = [];
  49899. let min = new Vector3(Infinity, Infinity, Infinity);
  49900. for(let i = 0; i < pc.length; i++){
  49901. let [long, lat] = pc[i];
  49902. let pos = transform.forward([long, lat]);
  49903. min.x = Math.min(min.x, pos[0]);
  49904. min.y = Math.min(min.y, pos[1]);
  49905. min.z = Math.min(min.z, 20);
  49906. coordinates.push(...pos, 20);
  49907. if(i > 0 && i < pc.length - 1){
  49908. coordinates.push(...pos, 20);
  49909. }
  49910. }
  49911. for(let i = 0; i < coordinates.length; i += 3){
  49912. coordinates[i+0] -= min.x;
  49913. coordinates[i+1] -= min.y;
  49914. coordinates[i+2] -= min.z;
  49915. }
  49916. const lineGeometry = new LineGeometry();
  49917. lineGeometry.setPositions( coordinates );
  49918. const line = new Line2( lineGeometry, matLine );
  49919. line.computeLineDistances();
  49920. line.scale.set( 1, 1, 1 );
  49921. line.position.copy(min);
  49922. return line;
  49923. }
  49924. }else {
  49925. console.log("unhandled feature: ", feature);
  49926. }
  49927. }
  49928. async loadShapefileFeatures(file){
  49929. let features = [];
  49930. let source = await shapefile.open(file);
  49931. while(true){
  49932. let result = await source.read();
  49933. if (result.done) {
  49934. break;
  49935. }
  49936. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  49937. features.push(result.value);
  49938. }
  49939. }
  49940. return features;
  49941. }
  49942. };
  49943. const defaultColors = {
  49944. "landuse": [0.5, 0.5, 0.5],
  49945. "natural": [0.0, 1.0, 0.0],
  49946. "places": [1.0, 0.0, 1.0],
  49947. "points": [0.0, 1.0, 1.0],
  49948. "roads": [1.0, 1.0, 0.0],
  49949. "waterways": [0.0, 0.0, 1.0],
  49950. "default": [0.9, 0.6, 0.1],
  49951. };
  49952. function getColor(feature){
  49953. let color = defaultColors[feature];
  49954. if(!color){
  49955. color = defaultColors["default"];
  49956. }
  49957. return color;
  49958. }
  49959. class Geopackage$1{
  49960. constructor(){
  49961. this.path = null;
  49962. this.node = null;
  49963. }
  49964. };
  49965. class GeoPackageLoader{
  49966. constructor(){
  49967. }
  49968. static async loadUrl(url, params){
  49969. await Promise.all([
  49970. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  49971. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  49972. ]);
  49973. const result = await fetch(url);
  49974. const buffer = await result.arrayBuffer();
  49975. params = params || {};
  49976. params.source = url;
  49977. return GeoPackageLoader.loadBuffer(buffer, params);
  49978. }
  49979. static async loadBuffer(buffer, params){
  49980. await Promise.all([
  49981. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  49982. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  49983. ]);
  49984. params = params || {};
  49985. const resolver = async (resolve) => {
  49986. let transform = params.transform;
  49987. if(!transform){
  49988. transform = {forward: (arg) => arg};
  49989. }
  49990. const wasmPath = `${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.wasm`;
  49991. const SQL = await initSqlJs({ locateFile: filename => wasmPath});
  49992. const u8 = new Uint8Array(buffer);
  49993. const data = await geopackage.open(u8);
  49994. window.data = data;
  49995. const geopackageNode = new Object3D();
  49996. geopackageNode.name = params.source;
  49997. geopackageNode.potree = {
  49998. source: params.source,
  49999. };
  50000. const geo = new Geopackage$1();
  50001. geo.path = params.source;
  50002. geo.node = geopackageNode;
  50003. const tables = data.getTables();
  50004. for(const table of tables.features){
  50005. const dao = data.getFeatureDao(table);
  50006. let boundingBox = dao.getBoundingBox();
  50007. boundingBox = boundingBox.projectBoundingBox(dao.projection, 'EPSG:4326');
  50008. const geoJson = data.queryForGeoJSONFeaturesInTable(table, boundingBox);
  50009. const matLine = new LineMaterial( {
  50010. color: new Color().setRGB(...getColor(table)),
  50011. lineWidth: 2,
  50012. resolution: new Vector2$1(1000, 1000),
  50013. dashed: false
  50014. } );
  50015. const node = new Object3D();
  50016. node.name = table;
  50017. geo.node.add(node);
  50018. for(const [index, feature] of Object.entries(geoJson)){
  50019. //const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, transform);
  50020. const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, dao.projection, transform);
  50021. node.add(featureNode);
  50022. }
  50023. }
  50024. resolve(geo);
  50025. };
  50026. return new Promise(resolver);
  50027. }
  50028. static featureToSceneNode(feature, matLine, geopackageProjection, transform){
  50029. let geometry = feature.geometry;
  50030. let color = new Color(1, 1, 1);
  50031. if(feature.geometry.type === "Point"){
  50032. let sg = new SphereGeometry(1, 18, 18);
  50033. let sm = new MeshNormalMaterial();
  50034. let s = new Mesh(sg, sm);
  50035. let [long, lat] = geometry.coordinates;
  50036. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50037. s.position.set(...pos, 20);
  50038. s.scale.set(10, 10, 10);
  50039. return s;
  50040. }else if(geometry.type === "LineString"){
  50041. let coordinates = [];
  50042. let min = new Vector3(Infinity, Infinity, Infinity);
  50043. for(let i = 0; i < geometry.coordinates.length; i++){
  50044. let [long, lat] = geometry.coordinates[i];
  50045. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50046. min.x = Math.min(min.x, pos[0]);
  50047. min.y = Math.min(min.y, pos[1]);
  50048. min.z = Math.min(min.z, 20);
  50049. coordinates.push(...pos, 20);
  50050. if(i > 0 && i < geometry.coordinates.length - 1){
  50051. coordinates.push(...pos, 20);
  50052. }
  50053. }
  50054. for(let i = 0; i < coordinates.length; i += 3){
  50055. coordinates[i+0] -= min.x;
  50056. coordinates[i+1] -= min.y;
  50057. coordinates[i+2] -= min.z;
  50058. }
  50059. const lineGeometry = new LineGeometry();
  50060. lineGeometry.setPositions( coordinates );
  50061. const line = new Line2( lineGeometry, matLine );
  50062. line.computeLineDistances();
  50063. line.scale.set( 1, 1, 1 );
  50064. line.position.copy(min);
  50065. return line;
  50066. }else if(geometry.type === "Polygon"){
  50067. for(let pc of geometry.coordinates){
  50068. let coordinates = [];
  50069. let min = new Vector3(Infinity, Infinity, Infinity);
  50070. for(let i = 0; i < pc.length; i++){
  50071. let [long, lat] = pc[i];
  50072. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50073. min.x = Math.min(min.x, pos[0]);
  50074. min.y = Math.min(min.y, pos[1]);
  50075. min.z = Math.min(min.z, 20);
  50076. coordinates.push(...pos, 20);
  50077. if(i > 0 && i < pc.length - 1){
  50078. coordinates.push(...pos, 20);
  50079. }
  50080. }
  50081. for(let i = 0; i < coordinates.length; i += 3){
  50082. coordinates[i+0] -= min.x;
  50083. coordinates[i+1] -= min.y;
  50084. coordinates[i+2] -= min.z;
  50085. }
  50086. const lineGeometry = new LineGeometry();
  50087. lineGeometry.setPositions( coordinates );
  50088. const line = new Line2( lineGeometry, matLine );
  50089. line.computeLineDistances();
  50090. line.scale.set( 1, 1, 1 );
  50091. line.position.copy(min);
  50092. return line;
  50093. }
  50094. }else {
  50095. console.log("unhandled feature: ", feature);
  50096. }
  50097. }
  50098. };
  50099. class ClipVolume extends Object3D{
  50100. constructor(args={}){
  50101. super();
  50102. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  50103. this.name = "clip_volume_" + this.constructor.counter;
  50104. let alpha = args.alpha || 0;
  50105. let beta = args.beta || 0;
  50106. let gamma = args.gamma || 0;
  50107. this.rotation.x = alpha;
  50108. this.rotation.y = beta;
  50109. this.rotation.z = gamma;
  50110. this.clipOffset = 0.001;
  50111. this.clipRotOffset = 1;
  50112. let boxGeometry = new BoxGeometry(1, 1, 1);
  50113. boxGeometry.computeBoundingBox();
  50114. let boxFrameGeometry = new Geometry();
  50115. {
  50116. // bottom
  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. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  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. // top
  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.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50130. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50131. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50132. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50133. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50134. // sides
  50135. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50136. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50137. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50138. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50139. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50140. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50141. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50142. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50143. boxFrameGeometry.colors.push(new Vector3(1, 1, 1));
  50144. }
  50145. let planeFrameGeometry = new Geometry();
  50146. {
  50147. // middle line
  50148. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  50149. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  50150. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  50151. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  50152. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  50153. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  50154. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  50155. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  50156. }
  50157. this.dimension = new Vector3(1, 1, 1);
  50158. this.material = new MeshBasicMaterial( {
  50159. color: 0x00ff00,
  50160. transparent: true,
  50161. opacity: 0.3,
  50162. depthTest: true,
  50163. depthWrite: false} );
  50164. this.box = new Mesh(boxGeometry, this.material);
  50165. this.box.geometry.computeBoundingBox();
  50166. this.boundingBox = this.box.geometry.boundingBox;
  50167. this.add(this.box);
  50168. this.frame = new LineSegments( boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  50169. this.add(this.frame);
  50170. this.planeFrame = new LineSegments( planeFrameGeometry, new LineBasicMaterial({color: 0xff0000}));
  50171. this.add(this.planeFrame);
  50172. // set default thickness
  50173. this.setScaleZ(0.1);
  50174. // create local coordinate system
  50175. let createArrow = (name, direction, color) => {
  50176. let material = new MeshBasicMaterial({
  50177. color: color,
  50178. depthTest: false,
  50179. depthWrite: false});
  50180. let shaftGeometry = new Geometry();
  50181. shaftGeometry.vertices.push(new Vector3(0, 0, 0));
  50182. shaftGeometry.vertices.push(new Vector3(0, 1, 0));
  50183. let shaftMaterial = new LineBasicMaterial({
  50184. color: color,
  50185. depthTest: false,
  50186. depthWrite: false,
  50187. transparent: true
  50188. });
  50189. let shaft = new Line(shaftGeometry, shaftMaterial);
  50190. shaft.name = name + "_shaft";
  50191. let headGeometry = new CylinderGeometry(0, 0.04, 0.1, 10, 1, false);
  50192. let headMaterial = material;
  50193. let head = new Mesh(headGeometry, headMaterial);
  50194. head.name = name + "_head";
  50195. head.position.y = 1;
  50196. let arrow = new Object3D();
  50197. arrow.name = name;
  50198. arrow.add(shaft);
  50199. arrow.add(head);
  50200. return arrow;
  50201. };
  50202. this.arrowX = createArrow("arrow_x", new Vector3(1, 0, 0), 0xFF0000);
  50203. this.arrowY = createArrow("arrow_y", new Vector3(0, 1, 0), 0x00FF00);
  50204. this.arrowZ = createArrow("arrow_z", new Vector3(0, 0, 1), 0x0000FF);
  50205. this.arrowX.rotation.z = -Math.PI / 2;
  50206. this.arrowZ.rotation.x = Math.PI / 2;
  50207. this.arrowX.visible = false;
  50208. this.arrowY.visible = false;
  50209. this.arrowZ.visible = false;
  50210. this.add(this.arrowX);
  50211. this.add(this.arrowY);
  50212. this.add(this.arrowZ);
  50213. { // event listeners
  50214. this.addEventListener("ui_select", e => {
  50215. this.arrowX.visible = true;
  50216. this.arrowY.visible = true;
  50217. this.arrowZ.visible = true;
  50218. });
  50219. this.addEventListener("ui_deselect", e => {
  50220. this.arrowX.visible = false;
  50221. this.arrowY.visible = false;
  50222. this.arrowZ.visible = false;
  50223. });
  50224. this.addEventListener("select", e => {
  50225. let scene_header = $("#" + this.name + " .scene_header");
  50226. if(!scene_header.next().is(":visible")) {
  50227. scene_header.click();
  50228. }
  50229. });
  50230. this.addEventListener("deselect", e => {
  50231. let scene_header = $("#" + this.name + " .scene_header");
  50232. if(scene_header.next().is(":visible")) {
  50233. scene_header.click();
  50234. }
  50235. });
  50236. }
  50237. this.update();
  50238. };
  50239. setClipOffset(offset) {
  50240. this.clipOffset = offset;
  50241. }
  50242. setClipRotOffset(offset) {
  50243. this.clipRotOffset = offset;
  50244. }
  50245. setScaleX(x) {
  50246. this.box.scale.x = x;
  50247. this.frame.scale.x = x;
  50248. this.planeFrame.scale.x = x;
  50249. }
  50250. setScaleY(y) {
  50251. this.box.scale.y = y;
  50252. this.frame.scale.y = y;
  50253. this.planeFrame.scale.y = y;
  50254. }
  50255. setScaleZ(z) {
  50256. this.box.scale.z = z;
  50257. this.frame.scale.z = z;
  50258. this.planeFrame.scale.z = z;
  50259. }
  50260. offset(args) {
  50261. let cs = args.cs || null;
  50262. let axis = args.axis || null;
  50263. let dir = args.dir || null;
  50264. if(!cs || !axis || !dir) return;
  50265. if(axis === "x") {
  50266. if(cs === "local") {
  50267. this.position.add(this.localX.clone().multiplyScalar(dir * this.clipOffset));
  50268. } else if(cs === "global") {
  50269. this.position.x = this.position.x + dir * this.clipOffset;
  50270. }
  50271. }else if(axis === "y") {
  50272. if(cs === "local") {
  50273. this.position.add(this.localY.clone().multiplyScalar(dir * this.clipOffset));
  50274. } else if(cs === "global") {
  50275. this.position.y = this.position.y + dir * this.clipOffset;
  50276. }
  50277. }else if(axis === "z") {
  50278. if(cs === "local") {
  50279. this.position.add(this.localZ.clone().multiplyScalar(dir * this.clipOffset));
  50280. } else if(cs === "global") {
  50281. this.position.z = this.position.z + dir * this.clipOffset;
  50282. }
  50283. }
  50284. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  50285. }
  50286. rotate(args) {
  50287. let cs = args.cs || null;
  50288. let axis = args.axis || null;
  50289. let dir = args.dir || null;
  50290. if(!cs || !axis || !dir) return;
  50291. if(cs === "local") {
  50292. if(axis === "x") {
  50293. this.rotateOnAxis(new Vector3(1, 0, 0), dir * this.clipRotOffset * Math.PI / 180);
  50294. } else if(axis === "y") {
  50295. this.rotateOnAxis(new Vector3(0, 1, 0), dir * this.clipRotOffset * Math.PI / 180);
  50296. } else if(axis === "z") {
  50297. this.rotateOnAxis(new Vector3(0, 0, 1), dir * this.clipRotOffset * Math.PI / 180);
  50298. }
  50299. } else if(cs === "global") {
  50300. let rotaxis = new Vector4(1, 0, 0, 0);
  50301. if(axis === "y") {
  50302. rotaxis = new Vector4(0, 1, 0, 0);
  50303. } else if(axis === "z") {
  50304. rotaxis = new Vector4(0, 0, 1, 0);
  50305. }
  50306. this.updateMatrixWorld();
  50307. let invM = newthis.matrixWorld.clone().invert();
  50308. rotaxis = rotaxis.applyMatrix4(invM).normalize();
  50309. rotaxis = new Vector3(rotaxis.x, rotaxis.y, rotaxis.z);
  50310. this.rotateOnAxis(rotaxis, dir * this.clipRotOffset * Math.PI / 180);
  50311. }
  50312. this.updateLocalSystem();
  50313. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  50314. }
  50315. update(){
  50316. this.boundingBox = this.box.geometry.boundingBox;
  50317. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  50318. this.box.visible = false;
  50319. this.updateLocalSystem();
  50320. };
  50321. updateLocalSystem() {
  50322. // extract local coordinate axes
  50323. let rotQuat = this.getWorldQuaternion();
  50324. this.localX = new Vector3(1, 0, 0).applyQuaternion(rotQuat).normalize();
  50325. this.localY = new Vector3(0, 1, 0).applyQuaternion(rotQuat).normalize();
  50326. this.localZ = new Vector3(0, 0, 1).applyQuaternion(rotQuat).normalize();
  50327. }
  50328. raycast(raycaster, intersects){
  50329. let is = [];
  50330. this.box.raycast(raycaster, is);
  50331. if(is.length > 0){
  50332. let I = is[0];
  50333. intersects.push({
  50334. distance: I.distance,
  50335. object: this,
  50336. point: I.point.clone()
  50337. });
  50338. }
  50339. };
  50340. };
  50341. class ClippingTool extends EventDispatcher{
  50342. constructor(viewer){
  50343. super();
  50344. this.viewer = viewer;
  50345. this.maxPolygonVertices = 8;
  50346. this.addEventListener("start_inserting_clipping_volume", e => {
  50347. this.viewer.dispatchEvent({
  50348. type: "cancel_insertions"
  50349. });
  50350. });
  50351. this.sceneMarker = new Scene();
  50352. this.sceneVolume = new Scene();
  50353. this.sceneVolume.name = "scene_clip_volume";
  50354. this.viewer.inputHandler.registerInteractiveScene(this.sceneVolume);
  50355. this.onRemove = e => {
  50356. this.sceneVolume.remove(e.volume);
  50357. };
  50358. this.onAdd = e => {
  50359. this.sceneVolume.add(e.volume);
  50360. };
  50361. this.viewer.inputHandler.addEventListener("delete", e => {
  50362. let volumes = e.selection.filter(e => (e instanceof ClipVolume));
  50363. volumes.forEach(e => this.viewer.scene.removeClipVolume(e));
  50364. let polyVolumes = e.selection.filter(e => (e instanceof PolygonClipVolume));
  50365. polyVolumes.forEach(e => this.viewer.scene.removePolygonClipVolume(e));
  50366. });
  50367. //----
  50368. /* var a = new ClipVolume()
  50369. viewer.scene.addVolume(a);
  50370. viewer.setObjectLayers(a, 'volume' ) */
  50371. }
  50372. setScene(scene){
  50373. if(this.scene === scene){
  50374. return;
  50375. }
  50376. if(this.scene){
  50377. this.scene.removeEventListeners("clip_volume_added", this.onAdd);
  50378. this.scene.removeEventListeners("clip_volume_removed", this.onRemove);
  50379. this.scene.removeEventListeners("polygon_clip_volume_added", this.onAdd);
  50380. this.scene.removeEventListeners("polygon_clip_volume_removed", this.onRemove);
  50381. }
  50382. this.scene = scene;
  50383. this.scene.addEventListener("clip_volume_added", this.onAdd);
  50384. this.scene.addEventListener("clip_volume_removed", this.onRemove);
  50385. this.scene.addEventListener("polygon_clip_volume_added", this.onAdd);
  50386. this.scene.addEventListener("polygon_clip_volume_removed", this.onRemove);
  50387. }
  50388. startInsertion(args = {}) {
  50389. let type = args.type || null;
  50390. if(!type) return null;
  50391. let domElement = this.viewer.renderer.domElement;
  50392. let canvasSize = this.viewer.renderer.getSize(new Vector2$1());
  50393. let svg = $(`
  50394. <svg height="${canvasSize.height}" width="${canvasSize.width}" style="position:absolute; pointer-events: none">
  50395. <defs>
  50396. <marker id="diamond" markerWidth="24" markerHeight="24" refX="12" refY="12"
  50397. markerUnits="userSpaceOnUse">
  50398. <circle cx="12" cy="12" r="6" fill="white" stroke="black" stroke-width="3"/>
  50399. </marker>
  50400. </defs>
  50401. <polyline fill="none" stroke="black"
  50402. style="stroke:rgb(0, 0, 0);
  50403. stroke-width:6;"
  50404. stroke-dasharray="9, 6"
  50405. stroke-dashoffset="2"
  50406. />
  50407. <polyline fill="none" stroke="black"
  50408. style="stroke:rgb(255, 255, 255);
  50409. stroke-width:2;"
  50410. stroke-dasharray="5, 10"
  50411. marker-start="url(#diamond)"
  50412. marker-mid="url(#diamond)"
  50413. marker-end="url(#diamond)"
  50414. />
  50415. </svg>`);
  50416. $(domElement.parentElement).append(svg);
  50417. let polyClipVol = new PolygonClipVolume(this.viewer.scene.getActiveCamera().clone());
  50418. this.dispatchEvent({"type": "start_inserting_clipping_volume"});
  50419. this.viewer.scene.addPolygonClipVolume(polyClipVol);
  50420. this.sceneMarker.add(polyClipVol);
  50421. let cancel = {
  50422. callback: null
  50423. };
  50424. let insertionCallback = (e) => {
  50425. if(e.button === MOUSE.LEFT){
  50426. polyClipVol.addMarker();
  50427. // SVC Screen Line
  50428. svg.find("polyline").each((index, target) => {
  50429. let newPoint = svg[0].createSVGPoint();
  50430. newPoint.x = e.offsetX;
  50431. newPoint.y = e.offsetY;
  50432. let polyline = target.points.appendItem(newPoint);
  50433. });
  50434. if(polyClipVol.markers.length > this.maxPolygonVertices){
  50435. cancel.callback();
  50436. }
  50437. this.viewer.inputHandler.startDragging(
  50438. polyClipVol.markers[polyClipVol.markers.length - 1]);
  50439. }else if(e.button === MOUSE.RIGHT){
  50440. cancel.callback(e);
  50441. }
  50442. };
  50443. cancel.callback = e => {
  50444. //let first = svg.find("polyline")[0].points[0];
  50445. //svg.find("polyline").each((index, target) => {
  50446. // let newPoint = svg[0].createSVGPoint();
  50447. // newPoint.x = first.x;
  50448. // newPoint.y = first.y;
  50449. // let polyline = target.points.appendItem(newPoint);
  50450. //});
  50451. svg.remove();
  50452. if(polyClipVol.markers.length > 3) {
  50453. polyClipVol.removeLastMarker();
  50454. polyClipVol.initialized = true;
  50455. } else {
  50456. this.viewer.scene.removePolygonClipVolume(polyClipVol);
  50457. }
  50458. this.viewer.renderer.domElement.removeEventListener("mouseup", insertionCallback, true);
  50459. this.viewer.removeEventListener("cancel_insertions", cancel.callback);
  50460. this.viewer.inputHandler.enabled = true;
  50461. };
  50462. this.viewer.addEventListener("cancel_insertions", cancel.callback);
  50463. this.viewer.renderer.domElement.addEventListener("mouseup", insertionCallback , true);
  50464. this.viewer.inputHandler.enabled = false;
  50465. polyClipVol.addMarker();
  50466. this.viewer.inputHandler.startDragging(
  50467. polyClipVol.markers[polyClipVol.markers.length - 1]);
  50468. return polyClipVol;
  50469. }
  50470. update() {
  50471. }
  50472. };
  50473. var GeoTIFF = (function (exports) {
  50474. 'use strict';
  50475. const Endianness = new Enum({
  50476. LITTLE: "II",
  50477. BIG: "MM",
  50478. });
  50479. const Type = new Enum({
  50480. BYTE: {value: 1, bytes: 1},
  50481. ASCII: {value: 2, bytes: 1},
  50482. SHORT: {value: 3, bytes: 2},
  50483. LONG: {value: 4, bytes: 4},
  50484. RATIONAL: {value: 5, bytes: 8},
  50485. SBYTE: {value: 6, bytes: 1},
  50486. UNDEFINED: {value: 7, bytes: 1},
  50487. SSHORT: {value: 8, bytes: 2},
  50488. SLONG: {value: 9, bytes: 4},
  50489. SRATIONAL: {value: 10, bytes: 8},
  50490. FLOAT: {value: 11, bytes: 4},
  50491. DOUBLE: {value: 12, bytes: 8},
  50492. });
  50493. const Tag = new Enum({
  50494. IMAGE_WIDTH: 256,
  50495. IMAGE_HEIGHT: 257,
  50496. BITS_PER_SAMPLE: 258,
  50497. COMPRESSION: 259,
  50498. PHOTOMETRIC_INTERPRETATION: 262,
  50499. STRIP_OFFSETS: 273,
  50500. ORIENTATION: 274,
  50501. SAMPLES_PER_PIXEL: 277,
  50502. ROWS_PER_STRIP: 278,
  50503. STRIP_BYTE_COUNTS: 279,
  50504. X_RESOLUTION: 282,
  50505. Y_RESOLUTION: 283,
  50506. PLANAR_CONFIGURATION: 284,
  50507. RESOLUTION_UNIT: 296,
  50508. SOFTWARE: 305,
  50509. COLOR_MAP: 320,
  50510. SAMPLE_FORMAT: 339,
  50511. MODEL_PIXEL_SCALE: 33550, // [GeoTIFF] TYPE: double N: 3
  50512. MODEL_TIEPOINT: 33922, // [GeoTIFF] TYPE: double N: 6 * NUM_TIEPOINTS
  50513. GEO_KEY_DIRECTORY: 34735, // [GeoTIFF] TYPE: short N: >= 4
  50514. GEO_DOUBLE_PARAMS: 34736, // [GeoTIFF] TYPE: short N: variable
  50515. GEO_ASCII_PARAMS: 34737, // [GeoTIFF] TYPE: ascii N: variable
  50516. });
  50517. const typeMapping = new Map([
  50518. [Type.BYTE, Uint8Array],
  50519. [Type.ASCII, Uint8Array],
  50520. [Type.SHORT, Uint16Array],
  50521. [Type.LONG, Uint32Array],
  50522. [Type.RATIONAL, Uint32Array],
  50523. [Type.SBYTE, Int8Array],
  50524. [Type.UNDEFINED, Uint8Array],
  50525. [Type.SSHORT, Int16Array],
  50526. [Type.SLONG, Int32Array],
  50527. [Type.SRATIONAL, Int32Array],
  50528. [Type.FLOAT, Float32Array],
  50529. [Type.DOUBLE, Float64Array],
  50530. ]);
  50531. class IFDEntry{
  50532. constructor(tag, type, count, offset, value){
  50533. this.tag = tag;
  50534. this.type = type;
  50535. this.count = count;
  50536. this.offset = offset;
  50537. this.value = value;
  50538. }
  50539. }
  50540. class Image{
  50541. constructor(){
  50542. this.width = 0;
  50543. this.height = 0;
  50544. this.buffer = null;
  50545. this.metadata = [];
  50546. }
  50547. }
  50548. class Reader{
  50549. constructor(){
  50550. }
  50551. static read(data){
  50552. let endiannessTag = String.fromCharCode(...Array.from(data.slice(0, 2)));
  50553. let endianness = Endianness.fromValue(endiannessTag);
  50554. let tiffCheckTag = data.readUInt8(2);
  50555. if(tiffCheckTag !== 42){
  50556. throw new Error("not a valid tiff file");
  50557. }
  50558. let offsetToFirstIFD = data.readUInt32LE(4);
  50559. console.log("offsetToFirstIFD", offsetToFirstIFD);
  50560. let ifds = [];
  50561. let IFDsRead = false;
  50562. let currentIFDOffset = offsetToFirstIFD;
  50563. let i = 0;
  50564. while(IFDsRead || i < 100){
  50565. console.log("currentIFDOffset", currentIFDOffset);
  50566. let numEntries = data.readUInt16LE(currentIFDOffset);
  50567. let nextIFDOffset = data.readUInt32LE(currentIFDOffset + 2 + numEntries * 12);
  50568. console.log("next offset: ", currentIFDOffset + 2 + numEntries * 12);
  50569. let entryBuffer = data.slice(currentIFDOffset + 2, currentIFDOffset + 2 + 12 * numEntries);
  50570. for(let i = 0; i < numEntries; i++){
  50571. let tag = Tag.fromValue(entryBuffer.readUInt16LE(i * 12));
  50572. let type = Type.fromValue(entryBuffer.readUInt16LE(i * 12 + 2));
  50573. let count = entryBuffer.readUInt32LE(i * 12 + 4);
  50574. let offsetOrValue = entryBuffer.readUInt32LE(i * 12 + 8);
  50575. let valueBytes = type.bytes * count;
  50576. let value;
  50577. if(valueBytes <= 4){
  50578. value = offsetOrValue;
  50579. }else {
  50580. let valueBuffer = new Uint8Array(valueBytes);
  50581. valueBuffer.set(data.slice(offsetOrValue, offsetOrValue + valueBytes));
  50582. let ArrayType = typeMapping.get(type);
  50583. value = new ArrayType(valueBuffer.buffer);
  50584. if(type === Type.ASCII){
  50585. value = String.fromCharCode(...value);
  50586. }
  50587. }
  50588. let ifd = new IFDEntry(tag, type, count, offsetOrValue, value);
  50589. ifds.push(ifd);
  50590. }
  50591. console.log("nextIFDOffset", nextIFDOffset);
  50592. if(nextIFDOffset === 0){
  50593. break;
  50594. }
  50595. currentIFDOffset = nextIFDOffset;
  50596. i++;
  50597. }
  50598. let ifdForTag = (tag) => {
  50599. for(let entry of ifds){
  50600. if(entry.tag === tag){
  50601. return entry;
  50602. }
  50603. }
  50604. return null;
  50605. };
  50606. let width = ifdForTag(Tag.IMAGE_WIDTH, ifds).value;
  50607. let height = ifdForTag(Tag.IMAGE_HEIGHT, ifds).value;
  50608. let compression = ifdForTag(Tag.COMPRESSION, ifds).value;
  50609. let rowsPerStrip = ifdForTag(Tag.ROWS_PER_STRIP, ifds).value;
  50610. let ifdStripOffsets = ifdForTag(Tag.STRIP_OFFSETS, ifds);
  50611. let ifdStripByteCounts = ifdForTag(Tag.STRIP_BYTE_COUNTS, ifds);
  50612. let numStrips = Math.ceil(height / rowsPerStrip);
  50613. let stripByteCounts = [];
  50614. for(let i = 0; i < ifdStripByteCounts.count; i++){
  50615. let type = ifdStripByteCounts.type;
  50616. let offset = ifdStripByteCounts.offset + i * type.bytes;
  50617. let value;
  50618. if(type === Type.SHORT){
  50619. value = data.readUInt16LE(offset);
  50620. }else if(type === Type.LONG){
  50621. value = data.readUInt32LE(offset);
  50622. }
  50623. stripByteCounts.push(value);
  50624. }
  50625. let stripOffsets = [];
  50626. for(let i = 0; i < ifdStripOffsets.count; i++){
  50627. let type = ifdStripOffsets.type;
  50628. let offset = ifdStripOffsets.offset + i * type.bytes;
  50629. let value;
  50630. if(type === Type.SHORT){
  50631. value = data.readUInt16LE(offset);
  50632. }else if(type === Type.LONG){
  50633. value = data.readUInt32LE(offset);
  50634. }
  50635. stripOffsets.push(value);
  50636. }
  50637. let imageBuffer = new Uint8Array(width * height * 3);
  50638. let linesProcessed = 0;
  50639. for(let i = 0; i < numStrips; i++){
  50640. let stripOffset = stripOffsets[i];
  50641. let stripBytes = stripByteCounts[i];
  50642. let stripData = data.slice(stripOffset, stripOffset + stripBytes);
  50643. let lineBytes = width * 3;
  50644. for(let y = 0; y < rowsPerStrip; y++){
  50645. let line = stripData.slice(y * lineBytes, y * lineBytes + lineBytes);
  50646. imageBuffer.set(line, linesProcessed * lineBytes);
  50647. if(line.length === lineBytes){
  50648. linesProcessed++;
  50649. }else {
  50650. break;
  50651. }
  50652. }
  50653. }
  50654. console.log(`width: ${width}`);
  50655. console.log(`height: ${height}`);
  50656. console.log(`numStrips: ${numStrips}`);
  50657. console.log("stripByteCounts", stripByteCounts.join(", "));
  50658. console.log("stripOffsets", stripOffsets.join(", "));
  50659. let image = new Image();
  50660. image.width = width;
  50661. image.height = height;
  50662. image.buffer = imageBuffer;
  50663. image.metadata = ifds;
  50664. return image;
  50665. }
  50666. }
  50667. class Exporter{
  50668. constructor(){
  50669. }
  50670. static toTiffBuffer(image, params = {}){
  50671. let offsetToFirstIFD = 8;
  50672. let headerBuffer = new Uint8Array([0x49, 0x49, 42, 0, offsetToFirstIFD, 0, 0, 0]);
  50673. let [width, height] = [image.width, image.height];
  50674. let ifds = [
  50675. new IFDEntry(Tag.IMAGE_WIDTH, Type.SHORT, 1, null, width),
  50676. new IFDEntry(Tag.IMAGE_HEIGHT, Type.SHORT, 1, null, height),
  50677. new IFDEntry(Tag.BITS_PER_SAMPLE, Type.SHORT, 4, null, new Uint16Array([8, 8, 8, 8])),
  50678. new IFDEntry(Tag.COMPRESSION, Type.SHORT, 1, null, 1),
  50679. new IFDEntry(Tag.PHOTOMETRIC_INTERPRETATION, Type.SHORT, 1, null, 2),
  50680. new IFDEntry(Tag.ORIENTATION, Type.SHORT, 1, null, 1),
  50681. new IFDEntry(Tag.SAMPLES_PER_PIXEL, Type.SHORT, 1, null, 4),
  50682. new IFDEntry(Tag.ROWS_PER_STRIP, Type.LONG, 1, null, height),
  50683. new IFDEntry(Tag.STRIP_BYTE_COUNTS, Type.LONG, 1, null, width * height * 3),
  50684. new IFDEntry(Tag.PLANAR_CONFIGURATION, Type.SHORT, 1, null, 1),
  50685. new IFDEntry(Tag.RESOLUTION_UNIT, Type.SHORT, 1, null, 1),
  50686. new IFDEntry(Tag.SOFTWARE, Type.ASCII, 6, null, "......"),
  50687. new IFDEntry(Tag.STRIP_OFFSETS, Type.LONG, 1, null, null),
  50688. new IFDEntry(Tag.X_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  50689. new IFDEntry(Tag.Y_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  50690. ];
  50691. if(params.ifdEntries){
  50692. ifds.push(...params.ifdEntries);
  50693. }
  50694. let valueOffset = offsetToFirstIFD + 2 + ifds.length * 12 + 4;
  50695. // create 12 byte buffer for each ifd and variable length buffers for ifd values
  50696. let ifdEntryBuffers = new Map();
  50697. let ifdValueBuffers = new Map();
  50698. for(let ifd of ifds){
  50699. let entryBuffer = new ArrayBuffer(12);
  50700. let entryView = new DataView(entryBuffer);
  50701. let valueBytes = ifd.type.bytes * ifd.count;
  50702. entryView.setUint16(0, ifd.tag.value, true);
  50703. entryView.setUint16(2, ifd.type.value, true);
  50704. entryView.setUint32(4, ifd.count, true);
  50705. if(ifd.count === 1 && ifd.type.bytes <= 4){
  50706. entryView.setUint32(8, ifd.value, true);
  50707. }else {
  50708. entryView.setUint32(8, valueOffset, true);
  50709. let valueBuffer = new Uint8Array(ifd.count * ifd.type.bytes);
  50710. if(ifd.type === Type.ASCII){
  50711. valueBuffer.set(new Uint8Array(ifd.value.split("").map(c => c.charCodeAt(0))));
  50712. }else {
  50713. valueBuffer.set(new Uint8Array(ifd.value.buffer));
  50714. }
  50715. ifdValueBuffers.set(ifd.tag, valueBuffer);
  50716. valueOffset = valueOffset + valueBuffer.byteLength;
  50717. }
  50718. ifdEntryBuffers.set(ifd.tag, entryBuffer);
  50719. }
  50720. let imageBufferOffset = valueOffset;
  50721. new DataView(ifdEntryBuffers.get(Tag.STRIP_OFFSETS)).setUint32(8, imageBufferOffset, true);
  50722. let concatBuffers = (buffers) => {
  50723. let totalLength = buffers.reduce( (sum, buffer) => (sum + buffer.byteLength), 0);
  50724. let merged = new Uint8Array(totalLength);
  50725. let offset = 0;
  50726. for(let buffer of buffers){
  50727. merged.set(new Uint8Array(buffer), offset);
  50728. offset += buffer.byteLength;
  50729. }
  50730. return merged;
  50731. };
  50732. let ifdBuffer = concatBuffers([
  50733. new Uint16Array([ifds.length]),
  50734. ...ifdEntryBuffers.values(),
  50735. new Uint32Array([0])]);
  50736. let ifdValueBuffer = concatBuffers([...ifdValueBuffers.values()]);
  50737. let tiffBuffer = concatBuffers([
  50738. headerBuffer,
  50739. ifdBuffer,
  50740. ifdValueBuffer,
  50741. image.buffer
  50742. ]);
  50743. return {width: width, height: height, buffer: tiffBuffer};
  50744. }
  50745. }
  50746. exports.Tag = Tag;
  50747. exports.Type = Type;
  50748. exports.IFDEntry = IFDEntry;
  50749. exports.Image = Image;
  50750. exports.Reader = Reader;
  50751. exports.Exporter = Exporter;
  50752. return exports;
  50753. }({}));
  50754. function updateAzimuth(viewer, measure){
  50755. if(!measure.showAzimuth)return
  50756. const azimuth = measure.azimuth;
  50757. const isOkay = measure.points.length === 2;
  50758. azimuth.node.visible = isOkay;
  50759. if(!azimuth.node.visible){
  50760. return;
  50761. }
  50762. const camera = viewer.scene.getActiveCamera();
  50763. const renderAreaSize = viewer.renderer.getSize(new Vector2$1());
  50764. const width = renderAreaSize.width;
  50765. const height = renderAreaSize.height;
  50766. const [p0, p1] = measure.points;
  50767. const r = p0.position.distanceTo(p1.position);
  50768. const northVec = Utils.getNorthVec(p0.position, r, viewer.getProjection());
  50769. const northPos = p0.position.clone().add(northVec);
  50770. azimuth.center.position.copy(p0.position);
  50771. azimuth.center.scale.set(2, 2, 2);
  50772. azimuth.center.visible = false;
  50773. // azimuth.target.visible = false;
  50774. { // north
  50775. azimuth.north.position.copy(northPos);
  50776. azimuth.north.scale.set(2, 2, 2);
  50777. let distance = azimuth.north.position.distanceTo(camera.position);
  50778. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50779. let scale = (5 / pr);
  50780. azimuth.north.scale.set(scale, scale, scale);
  50781. }
  50782. { // target
  50783. azimuth.target.position.copy(p1.position);
  50784. azimuth.target.position.z = azimuth.north.position.z;
  50785. let distance = azimuth.target.position.distanceTo(camera.position);
  50786. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50787. let scale = (5 / pr);
  50788. azimuth.target.scale.set(scale, scale, scale);
  50789. }
  50790. azimuth.circle.position.copy(p0.position);
  50791. azimuth.circle.scale.set(r, r, r);
  50792. azimuth.circle.material.resolution.set(width, height);
  50793. // to target
  50794. azimuth.centerToTarget.geometry.setPositions([
  50795. 0, 0, 0,
  50796. ...p1.position.clone().sub(p0.position).toArray(),
  50797. ]);
  50798. azimuth.centerToTarget.position.copy(p0.position);
  50799. azimuth.centerToTarget.geometry.verticesNeedUpdate = true;
  50800. azimuth.centerToTarget.geometry.computeBoundingSphere();
  50801. azimuth.centerToTarget.computeLineDistances();
  50802. azimuth.centerToTarget.material.resolution.set(width, height);
  50803. // to target ground
  50804. azimuth.centerToTargetground.geometry.setPositions([
  50805. 0, 0, 0,
  50806. p1.position.x - p0.position.x,
  50807. p1.position.y - p0.position.y,
  50808. 0,
  50809. ]);
  50810. azimuth.centerToTargetground.position.copy(p0.position);
  50811. azimuth.centerToTargetground.geometry.verticesNeedUpdate = true;
  50812. azimuth.centerToTargetground.geometry.computeBoundingSphere();
  50813. azimuth.centerToTargetground.computeLineDistances();
  50814. azimuth.centerToTargetground.material.resolution.set(width, height);
  50815. // to north
  50816. azimuth.centerToNorth.geometry.setPositions([
  50817. 0, 0, 0,
  50818. northPos.x - p0.position.x,
  50819. northPos.y - p0.position.y,
  50820. 0,
  50821. ]);
  50822. azimuth.centerToNorth.position.copy(p0.position);
  50823. azimuth.centerToNorth.geometry.verticesNeedUpdate = true;
  50824. azimuth.centerToNorth.geometry.computeBoundingSphere();
  50825. azimuth.centerToNorth.computeLineDistances();
  50826. azimuth.centerToNorth.material.resolution.set(width, height);
  50827. // label
  50828. const radians = Utils.computeAzimuth(p0.position, p1.position, viewer.getProjection());
  50829. let degrees = MathUtils.radToDeg(radians);
  50830. if(degrees < 0){
  50831. degrees = 360 + degrees;
  50832. }
  50833. const txtDegrees = `${degrees.toFixed(2)}°`;
  50834. const labelDir = northPos.clone().add(p1.position).multiplyScalar(0.5).sub(p0.position);
  50835. if(labelDir.length() > 0){
  50836. labelDir.z = 0;
  50837. labelDir.normalize();
  50838. const labelVec = labelDir.clone().multiplyScalar(r);
  50839. const labelPos = p0.position.clone().add(labelVec);
  50840. azimuth.label.position.copy(labelPos);
  50841. }
  50842. azimuth.label.setText(txtDegrees);
  50843. let distance = azimuth.label.position.distanceTo(camera.position);
  50844. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50845. let scale = (70 / pr);
  50846. azimuth.label.scale.set(scale, scale, scale);
  50847. }
  50848. class MeasuringTool extends EventDispatcher{
  50849. constructor (viewer) {
  50850. super();
  50851. this.viewer = viewer;
  50852. this.renderer = viewer.renderer;
  50853. this.viewer.addEventListener('start_inserting_measurement', e => {
  50854. this.viewer.dispatchEvent({
  50855. type: 'cancel_insertions'
  50856. });
  50857. });
  50858. this.showLabels = true;
  50859. this.scene = new Scene();
  50860. this.scene.name = 'scene_measurement';
  50861. //this.light = new THREE.PointLight(0xffffff, 1.0);
  50862. //this.scene.add(this.light);
  50863. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  50864. //this.scene = viewer.overlay//
  50865. this.onRemove = (e) => { e.measurement.dispose();/* this.scene.remove(e.measurement); */};
  50866. this.onAdd = e => {this.scene.add(e.measurement);};
  50867. for(let measurement of viewer.scene.measurements){
  50868. this.onAdd({measurement: measurement});
  50869. }
  50870. viewer.addEventListener('camera_changed',(e)=>{
  50871. if(e.viewport == viewer.mainViewport ) this.update();
  50872. });
  50873. //viewer.addEventListener("update", this.update.bind(this));
  50874. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  50875. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  50876. viewer.scene.addEventListener('measurement_added', this.onAdd);
  50877. viewer.scene.addEventListener('measurement_removed', this.onRemove);
  50878. viewer.addEventListener('resize',this.setSize.bind(this));
  50879. }
  50880. onSceneChange(e){
  50881. if(e.oldScene){
  50882. e.oldScene.removeEventListener('measurement_added', this.onAdd);
  50883. e.oldScene.removeEventListener('measurement_removed', this.onRemove);
  50884. }
  50885. e.scene.addEventListener('measurement_added', this.onAdd);
  50886. e.scene.addEventListener('measurement_removed', this.onRemove);
  50887. }
  50888. createMeasureFromData(data){//add
  50889. const measure = new Measure(data);
  50890. if(measure.failBuilded){
  50891. return
  50892. }
  50893. viewer.scene.addMeasurement(measure);
  50894. if(measure.guideLine)measure.guideLine.visible = false;
  50895. return measure
  50896. }
  50897. update(){
  50898. return;
  50899. let camera = this.viewer.scene.getActiveCamera();
  50900. let domElement = this.renderer.domElement;
  50901. let measurements = this.viewer.scene.measurements;
  50902. // make size independant of distance
  50903. let mainLabels = [], subLabels = [];
  50904. for (let measure of measurements) {
  50905. measure.lengthUnit = this.viewer.lengthUnit;
  50906. measure.lengthUnitDisplay = this.viewer.lengthUnitDisplay;
  50907. //measure.update();
  50908. updateAzimuth(this.viewer, measure);
  50909. /* [...measure.markers, ...measure.edgeLabels, measure.areaLabel].forEach(e=>{
  50910. e && e.update()
  50911. }); */
  50912. // labels
  50913. /* let labels = measure.edgeLabels.concat(measure.angleLabels);
  50914. for(let label of labels){
  50915. label.update()
  50916. if(label.elem.hasClass('sub')){
  50917. subLabels.push(label)
  50918. }else{
  50919. mainLabels.push(label)
  50920. }
  50921. }
  50922. // coordinate labels
  50923. for (let j = 0; j < measure.coordinateLabels.length; j++) {
  50924. let label = measure.coordinateLabels[j];
  50925. label.update()
  50926. mainLabels.push(label)
  50927. }
  50928. if(measure.showArea){ // area label
  50929. let label = measure.areaLabel;
  50930. label.update()
  50931. mainLabels.push(label)
  50932. } */
  50933. /* if(measure.showCircle){ // radius label
  50934. let label = measure.circleRadiusLabel;
  50935. let distance = label.position.distanceTo(camera.position);
  50936. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  50937. let scale = (70 / pr);
  50938. label.scale.set(scale, scale, scale);
  50939. } */
  50940. if(!this.showLabels){
  50941. const labels = [
  50942. ...measure.sphereLabels,
  50943. ...measure.angleLabels,
  50944. measure.circleRadiusLabel,
  50945. ];
  50946. for(const label of labels){
  50947. label.visible = false;
  50948. }
  50949. }
  50950. }
  50951. //this.updateLabelZIndex([{labels:subLabels},{labels:mainLabels}])
  50952. }
  50953. setSize(e){ //e.resolution
  50954. /* if(Measure.lineMats){
  50955. for(var m in Measure.lineMats){
  50956. Measure.lineMats[m].resolution.set(e.canvasWidth, e.canvasHeight);
  50957. }
  50958. }
  50959. if(Measure.sphereMats){
  50960. for(var s in Measure.sphereMats){
  50961. Measure.sphereMats[s].uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  50962. }
  50963. }
  50964. for (let measure of this.viewer.scene.measurements) {
  50965. measure.edgeLabels.concat(measure.areaLabel).forEach(label=>{
  50966. label.sprite.material.uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  50967. })
  50968. } */
  50969. }
  50970. updateLabelZIndex(group){//[{labels:[]},{}] 顺序按照z-index低到高
  50971. group.forEach((e,i)=>{
  50972. e.base = group[i-1] ? group[i-1].base + group[i-1].labels.length : 0;
  50973. var labels = e.labels.sort((a,b)=>{
  50974. return b.pos2d.z - a.pos2d.z
  50975. });
  50976. labels.forEach((label,index)=>{
  50977. $(label.elem).css('z-index', e.base+index);
  50978. });
  50979. });
  50980. }
  50981. editStateChange(e){
  50982. //console.log("editStateChange" , e.state)
  50983. let state = e.state;
  50984. if(!state){
  50985. state = viewer.scene.measurements.some(e=>e.isEditing);
  50986. }
  50987. if(state){
  50988. viewer.dispatchEvent({type:"measureMovePoint"});
  50989. }else {
  50990. viewer.dispatchEvent({type:"endMeasureMove"});
  50991. }
  50992. //this.editing =
  50993. }
  50994. startInsertion (args = {}, callback, cancelFun) {
  50995. let domElement = this.viewer.renderer.domElement;
  50996. const pick = (defaul, alternative) => {
  50997. if(defaul != null){
  50998. return defaul;
  50999. }else {
  51000. return alternative;
  51001. }
  51002. };
  51003. args.showDistances = (args.showDistances === null) ? true : args.showDistances;
  51004. args.showArea = pick(args.showArea, false);
  51005. args.showAngles = pick(args.showAngles, false);
  51006. args.showCoordinates = pick(args.showCoordinates, false);
  51007. args.showHeight = pick(args.showHeight, false);
  51008. args.showCircle = pick(args.showCircle, false);
  51009. args.showAzimuth = pick(args.showAzimuth, false);
  51010. args.showEdges = pick(args.showEdges, true);
  51011. args.closed = pick(args.closed, false);
  51012. args.maxMarkers = pick(args.maxMarkers, Infinity);
  51013. args.direction = args.direction;//add
  51014. args.type = args.type; /* || 'Measurement'; */
  51015. args.showGuideLine = pick(args.showGuideLine, false);
  51016. args.isRect = pick(args.isRect, false);
  51017. let measure = new Measure(args);
  51018. this.scene.add(measure);
  51019. measure.isNew = true;
  51020. this.viewer.dispatchEvent({
  51021. type: 'start_inserting_measurement',
  51022. measure: measure
  51023. });
  51024. measure.addEventListener('editStateChange', this.editStateChange.bind(this));
  51025. measure.editStateChange(true);
  51026. let timer;
  51027. let endDragFun = (e) => {
  51028. let length = measure.points.length;
  51029. if (e.button == MOUSE.LEFT || e.isTouch) {
  51030. if (length >= measure.maxMarkers) {
  51031. end({finish:true});
  51032. }else {
  51033. var marker = measure.addMarker({point:measure.points[length - 1].clone()});
  51034. if(args.isRect && measure.markers.length == 3){//marker全可见
  51035. measure.addMarker({point:measure.points[0].clone()});
  51036. }else {
  51037. measure.markers[length].visible = false;
  51038. measure.edges[length].visible = false;
  51039. }
  51040. measure.edges[length-1].visible = true;
  51041. measure.markers[length-1].visible = true;
  51042. measure.editStateChange(true); //重新激活reticule状态
  51043. marker.isDragging = true;
  51044. measure.continueDrag(marker, e);
  51045. }
  51046. } else if (e.button === MOUSE.RIGHT ) { //触屏怎么取消?
  51047. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  51048. else measure.continueDrag(null, e);
  51049. }
  51050. };
  51051. let end = (e={}) => {//确定、结束
  51052. if(!measure.isNew)return
  51053. if(args.minMarkers != void 0){
  51054. if(!e.finish && measure.markers.length<=args.minMarkers){//右键 当个数不够时取消
  51055. //this.viewer.scene.removeMeasurement(measure)
  51056. //cancelFun && cancelFun()
  51057. //重新开始画
  51058. measure.markers[0].removeEventListener('mousedown',end);
  51059. measure.reDraw();
  51060. this.viewer.addEventListener('global_click', click, 10);
  51061. measure.editStateChange(true);
  51062. return
  51063. /* if(!Potree.settings.isOfficial) this.viewer.scene.removeMeasurement(measure)
  51064. else if(e.drag){ //正式版本不允许右键退出, 继续
  51065. continueDrag(e.drag.object)
  51066. measure.editStateChange(true)
  51067. return
  51068. } */
  51069. }
  51070. }
  51071. if (/* !e.finish && */measure.markers.length > 3) {
  51072. measure.removeMarker(measure.points.length - 1);
  51073. measure.markers[0].removeEventListener('mouseover', mouseover);
  51074. measure.markers[0].removeEventListener('mouseleave', mouseleave);
  51075. measure.markers[0].removeEventListener('click'/* 'mousedown' */,Exit);
  51076. if(e.byClickMarker && measure.markers.length > 3){//通过点击第一个marker而结束的话,会多一个marker
  51077. measure.removeMarker(measure.points.length - 1);
  51078. }
  51079. }
  51080. measure.isNew = false;
  51081. let length = measure.points.length;
  51082. if(length){
  51083. measure.markers[length-1].visible = true;
  51084. measure.edges[length-1].visible = true;
  51085. measure.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  51086. measure.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  51087. }
  51088. clearTimeout(timer);
  51089. this.viewer.removeEventListener('cancel_insertions', Exit);
  51090. //pressExit && this.viewer.inputHandler.removeEventListener('keydown', pressExit);
  51091. this.viewer.removeEventListener('global_click', click);
  51092. this.viewer.removeEventListener('global_mousemove', ifAtWrongPlace);
  51093. viewer.dispatchEvent({
  51094. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  51095. });
  51096. viewer.inputHandler.dispatchEvent({type:'isMeasuring', v:false, cause:'stopInsertion'} );
  51097. e.remove || callback && callback();
  51098. /* this.viewer.dispatchEvent({
  51099. type: 'finish_inserting_measurement',
  51100. measure: measure
  51101. }); */
  51102. };
  51103. let Exit = (e)=>{//强制退出
  51104. if(e.measure && e.measure != measure){
  51105. return;//若指定了退出的measure但和该measure不一致,就返回
  51106. }
  51107. console.log('Exit: ' + measure.id);
  51108. if(e.remove){
  51109. viewer.scene.removeMeasurement(measure);
  51110. }
  51111. measure.editStateChange(false);
  51112. measure.cannotConfirmNormal = false; //一些dropMarker中的句子
  51113. measure.guideLine &&(measure.guideLine.visible = false);
  51114. /*
  51115. if(this.viewer.inputHandler.drag && !e.remove ){//还未触发drop的话
  51116. this.viewer.inputHandler.drag.object.dispatchEvent({ //这句会导致又增一个marker
  51117. type: 'drop',
  51118. drag: this.viewer.inputHandler.drag,
  51119. viewer: this.viewer,
  51120. pressDistance:0,
  51121. button : THREE.MOUSE.RIGHT
  51122. });
  51123. } else {*///未结束时添加新的measure时会触发
  51124. end({finish:true, remove:e.remove, byClickMarker: e.type == 'click'});
  51125. //}
  51126. this.viewer.inputHandler.drag && (this.viewer.inputHandler.drag.object = null);
  51127. };
  51128. this.viewer.addEventListener('cancel_insertions', Exit);
  51129. /*let pressExit
  51130. if(!Potree.settings.isOfficial){
  51131. pressExit = (e)=>{
  51132. if(e.keyCode == 27){//Esc
  51133. //Exit()
  51134. //怎么模拟右键???//现由前端发出
  51135. }
  51136. }
  51137. this.viewer.inputHandler.addEventListener('keydown', pressExit)
  51138. } */
  51139. let mouseover = (e) => {
  51140. measure.setMarkerSelected(e.object, 'hover', 'single');
  51141. };
  51142. let mouseleave = (e) => {
  51143. measure.setMarkerSelected(e.object, 'unhover', 'single');
  51144. };
  51145. let click = (e)=>{//一旦点击就立刻增加两marker
  51146. if(ifAtWrongPlace(e))return
  51147. if(e.clickElement)return //如点击label时focusOnObject
  51148. if(e.button === MOUSE.RIGHT)return
  51149. //console.log('measure clicked33', !!e.intersectPoint)
  51150. //var I = e.intersectPoint && (e.intersectPoint.orthoIntersect || e.intersectPoint.location)
  51151. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  51152. if(!I){
  51153. return measure.dispatchEvent('intersectNoPointcloud')
  51154. }
  51155. var atMap = e.drag.dragViewport.name == 'mapViewport';
  51156. //在地图上测量的首个点按楼层高度(暂时先只按mainViewport相机高度吧,但navvis是按楼层,画在楼层的地面上,可能因为平面图显示的是楼层近地面),
  51157. if(atMap){
  51158. I = I.clone().setZ(viewer.mainViewport.camera.position.z );
  51159. }
  51160. var marker = measure.addMarker({point:I});
  51161. marker.isDragging = true;
  51162. this.viewer.inputHandler.startDragging(marker , {endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽
  51163. e.drag = this.viewer.inputHandler.drag;
  51164. e.drag.endDragFun = endDragFun;
  51165. e.drag.notPressMouse = true;
  51166. //if(!measure.dragMarker(e) || !measure.dropMarker(e))return
  51167. measure.dragMarker(e);
  51168. measure.dropMarker(e);
  51169. if(measure.maxMarkers > 1 ){
  51170. measure.markers[1].visible = false;
  51171. measure.edges[1].visible = false;
  51172. }
  51173. if(measure.maxMarkers>2 && !measure.isRect){
  51174. measure.markers[0].addEventListener('mouseover', mouseover);
  51175. measure.markers[0].addEventListener('mouseleave', mouseleave);
  51176. measure.markers[0].addEventListener('click'/* 'mousedown' */,Exit); //点击到第一个marker就结束
  51177. }
  51178. this.viewer.removeEventListener('global_click', click);///* global_drop */
  51179. //console.log('measure clicked')
  51180. e.consume && e.consume();
  51181. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  51182. };
  51183. //点击第n下拥有n+1个marker, n>0
  51184. viewer.inputHandler.dispatchEvent({type: 'isMeasuring', v: true, cause:'startInsertion'});
  51185. this.viewer.addEventListener('global_click', click, 10);//add importance:10
  51186. let ifAtWrongPlace = (e)=>{
  51187. if(measure.unableDragAtMap && e.hoverViewport.name == 'mapViewport' ){
  51188. if(e.isTouch){
  51189. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  51190. }else {
  51191. viewer.dispatchEvent({
  51192. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  51193. });
  51194. }
  51195. return true
  51196. }else {
  51197. if(e.isTouch){
  51198. viewer.dispatchEvent({type:'reticule_forbit',v:false});
  51199. }else {
  51200. viewer.dispatchEvent({
  51201. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  51202. });
  51203. }
  51204. }
  51205. };
  51206. if(measure.unableDragAtMap){
  51207. this.viewer.addEventListener('global_mousemove', ifAtWrongPlace);
  51208. }
  51209. this.viewer.scene.addMeasurement(measure);
  51210. return measure;
  51211. }
  51212. render(o={}){
  51213. if(this.scene.children.length == 0)return
  51214. viewer.setCameraLayers(o.camera, ['measure']);
  51215. if(o.screenshot && this.viewer.ssaaRenderPass.enabled){ //抗锯齿
  51216. this.viewer.ssaaRenderPass.sampleLevel = 4;
  51217. this.viewer.composer.render(this.scene, o.camera );
  51218. /* viewer.scene.measurements.forEach(e=>{ //隐藏除了label以外的
  51219. e.children.forEach((c)=>{
  51220. if(!(c instanceof TextSprite)){
  51221. c.visible = false
  51222. }
  51223. })
  51224. }) */
  51225. }else {
  51226. this.viewer.renderer.render(this.scene, o.camera );
  51227. }
  51228. }
  51229. };
  51230. class Message{
  51231. constructor(content){
  51232. this.content = content;
  51233. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  51234. this.element = $(`
  51235. <div class="potree_message">
  51236. <span name="content_container" style="flex-grow: 1; padding: 5px"></span>
  51237. <img name="close" src="${closeIcon}" class="button-icon" style="width: 16px; height: 16px;">
  51238. </div>`);
  51239. this.elClose = this.element.find("img[name=close]");
  51240. this.elContainer = this.element.find("span[name=content_container]");
  51241. if(typeof content === "string"){
  51242. this.elContainer.append($(`<span>${content}</span>`));
  51243. }else {
  51244. this.elContainer.append(content);
  51245. }
  51246. }
  51247. setMessage(content){
  51248. this.elContainer.empty();
  51249. if(typeof content === "string"){
  51250. this.elContainer.append($(`<span>${content}</span>`));
  51251. }else {
  51252. this.elContainer.append(content);
  51253. }
  51254. }
  51255. }
  51256. class PointCloudSM{//shadow material ?
  51257. constructor(potreeRenderer){
  51258. this.potreeRenderer = potreeRenderer;
  51259. this.threeRenderer = this.potreeRenderer.threeRenderer;
  51260. this.target = new WebGLRenderTarget(2 * 1024, 2 * 1024, {
  51261. minFilter: LinearFilter,
  51262. magFilter: LinearFilter,
  51263. format: RGBAFormat,
  51264. type: FloatType,
  51265. });
  51266. this.target.depthTexture = new DepthTexture();
  51267. this.target.depthTexture.type = UnsignedIntType;
  51268. //this.threeRenderer.setClearColor(0x000000, 1);
  51269. this.threeRenderer.setClearColor(0xff0000, 1);
  51270. //HACK? removed while moving to three.js 109
  51271. //this.threeRenderer.clearTarget(this.target, true, true, true);
  51272. {
  51273. const oldTarget = this.threeRenderer.getRenderTarget();
  51274. this.threeRenderer.setRenderTarget(this.target);
  51275. //this.threeRenderer.clear(true, true, true); //救命,为什么iphoneX ios13.6执行这一句clear会崩溃?即使把target的大小改为1*1.
  51276. this.threeRenderer.setRenderTarget(oldTarget);
  51277. }
  51278. }
  51279. setLight(light){
  51280. this.light = light;
  51281. let fov = (180 * light.angle) / Math.PI;
  51282. let aspect = light.shadow.mapSize.width / light.shadow.mapSize.height;
  51283. let near = 0.1;
  51284. let far = light.distance === 0 ? 10000 : light.distance;
  51285. this.camera = new PerspectiveCamera(fov, aspect, near, far);
  51286. this.camera.up.set(0, 0, 1);
  51287. this.camera.position.copy(light.position);
  51288. let target = new Vector3().subVectors(light.position, light.getWorldDirection(new Vector3()));
  51289. this.camera.lookAt(target);
  51290. this.camera.updateProjectionMatrix();
  51291. this.camera.updateMatrix();
  51292. this.camera.updateMatrixWorld();
  51293. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  51294. }
  51295. setSize(width, height){
  51296. if(this.target.width !== width || this.target.height !== height){
  51297. this.target.dispose();
  51298. }
  51299. this.target.setSize(width, height);
  51300. }
  51301. render(scene, camera){
  51302. this.threeRenderer.setClearColor(0x000000, 1);
  51303. const oldTarget = this.threeRenderer.getRenderTarget();
  51304. this.threeRenderer.setRenderTarget(this.target);
  51305. this.threeRenderer.clear(true, true, true);
  51306. this.potreeRenderer.render(scene, this.camera, this.target, {});
  51307. this.threeRenderer.setRenderTarget(oldTarget);
  51308. }
  51309. }
  51310. class ProfileTool extends EventDispatcher {
  51311. constructor (viewer) {
  51312. super();
  51313. this.viewer = viewer;
  51314. this.renderer = viewer.renderer;
  51315. this.addEventListener('start_inserting_profile', e => {
  51316. this.viewer.dispatchEvent({
  51317. type: 'cancel_insertions'
  51318. });
  51319. });
  51320. this.scene = new Scene();
  51321. this.scene.name = 'scene_profile';
  51322. this.light = new PointLight(0xffffff, 1.0);
  51323. this.scene.add(this.light);
  51324. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  51325. this.onRemove = e => this.scene.remove(e.profile);
  51326. this.onAdd = e => this.scene.add(e.profile);
  51327. for(let profile of viewer.scene.profiles){
  51328. this.onAdd({profile: profile});
  51329. }
  51330. viewer.addEventListener("update", this.update.bind(this));
  51331. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  51332. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  51333. viewer.scene.addEventListener('profile_added', this.onAdd);
  51334. viewer.scene.addEventListener('profile_removed', this.onRemove);
  51335. }
  51336. onSceneChange(e){
  51337. if(e.oldScene){
  51338. e.oldScene.removeEventListeners('profile_added', this.onAdd);
  51339. e.oldScene.removeEventListeners('profile_removed', this.onRemove);
  51340. }
  51341. e.scene.addEventListener('profile_added', this.onAdd);
  51342. e.scene.addEventListener('profile_removed', this.onRemove);
  51343. }
  51344. startInsertion (args = {}) {
  51345. let domElement = this.viewer.renderer.domElement;
  51346. let profile = new Profile();
  51347. profile.name = args.name || 'Profile';
  51348. this.dispatchEvent({
  51349. type: 'start_inserting_profile',
  51350. profile: profile
  51351. });
  51352. this.scene.add(profile);
  51353. let cancel = {
  51354. callback: null
  51355. };
  51356. let insertionCallback = (e) => {
  51357. if(e.button === MOUSE.LEFT){
  51358. if(profile.points.length <= 1){
  51359. let camera = this.viewer.scene.getActiveCamera();
  51360. let distance = camera.position.distanceTo(profile.points[0]);
  51361. let clientSize = this.viewer.renderer.getSize(new Vector2$1());
  51362. let pr = Utils.projectedRadius(1, camera, distance, clientSize.width, clientSize.height);
  51363. let width = (10 / pr);
  51364. profile.setWidth(width);
  51365. }
  51366. profile.addMarker(profile.points[profile.points.length - 1].clone());
  51367. this.viewer.inputHandler.startDragging(
  51368. profile.spheres[profile.spheres.length - 1]);
  51369. } else if (e.button === MOUSE.RIGHT) {
  51370. cancel.callback();
  51371. }
  51372. };
  51373. cancel.callback = e => {
  51374. profile.removeMarker(profile.points.length - 1);
  51375. domElement.removeEventListener('mouseup', insertionCallback, false);
  51376. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  51377. };
  51378. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  51379. domElement.addEventListener('mouseup', insertionCallback, false);
  51380. profile.addMarker(new Vector3(0, 0, 0));
  51381. this.viewer.inputHandler.startDragging(
  51382. profile.spheres[profile.spheres.length - 1]);
  51383. this.viewer.scene.addProfile(profile);
  51384. return profile;
  51385. }
  51386. update(){
  51387. let camera = this.viewer.scene.getActiveCamera();
  51388. let profiles = this.viewer.scene.profiles;
  51389. let renderAreaSize = this.viewer.renderer.getSize(new Vector2$1());
  51390. let clientWidth = renderAreaSize.width;
  51391. let clientHeight = renderAreaSize.height;
  51392. this.light.position.copy(camera.position);
  51393. // make size independant of distance
  51394. for(let profile of profiles){
  51395. for(let sphere of profile.spheres){
  51396. let distance = camera.position.distanceTo(sphere.getWorldPosition(new Vector3()));
  51397. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  51398. let scale = (15 / pr);
  51399. sphere.scale.set(scale, scale, scale);
  51400. }
  51401. }
  51402. }
  51403. render(){
  51404. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  51405. }
  51406. }
  51407. class ScreenBoxSelectTool extends EventDispatcher{
  51408. constructor(viewer){
  51409. super();
  51410. this.viewer = viewer;
  51411. this.scene = new Scene();
  51412. viewer.addEventListener("update", this.update.bind(this));
  51413. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  51414. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  51415. }
  51416. onSceneChange(scene){
  51417. console.log("scene changed");
  51418. }
  51419. startInsertion(){
  51420. let domElement = this.viewer.renderer.domElement;
  51421. let volume = new BoxVolume();
  51422. volume.position.set(12345, 12345, 12345);
  51423. volume.showVolumeLabel = false;
  51424. volume.visible = false;
  51425. volume.update();
  51426. this.viewer.scene.addVolume(volume);
  51427. this.importance = 10;
  51428. let selectionBox = $(`<div style="position: absolute; border: 2px solid white; pointer-events: none; border-style:dashed"></div>`);
  51429. $(domElement.parentElement).append(selectionBox);
  51430. selectionBox.css("right", "10px");
  51431. selectionBox.css("bottom", "10px");
  51432. let drag = e =>{
  51433. volume.visible = true;
  51434. let mStart = e.drag.start;
  51435. let mEnd = e.drag.end;
  51436. let box2D = new Box2();
  51437. box2D.expandByPoint(mStart);
  51438. box2D.expandByPoint(mEnd);
  51439. selectionBox.css("left", `${box2D.min.x}px`);
  51440. selectionBox.css("top", `${box2D.min.y}px`);
  51441. selectionBox.css("width", `${box2D.max.x - box2D.min.x}px`);
  51442. selectionBox.css("height", `${box2D.max.y - box2D.min.y}px`);
  51443. let camera = e.viewer.scene.getActiveCamera();
  51444. let size = e.viewer.renderer.getSize(new Vector2$1());
  51445. let frustumSize = new Vector2$1(
  51446. camera.right - camera.left,
  51447. camera.top - camera.bottom);
  51448. let screenCentroid = new Vector2$1().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  51449. let pointer = new Vector3(0, 0, 0.5);
  51450. Utils.convertScreenPositionToNDC(pointer, screenCentroid, size.width, size.height);
  51451. pointer.unproject(camera);
  51452. //let ray = Utils.mouseToRay( pointer, camera, size.width, size.height);
  51453. let diff = new Vector2$1().subVectors(e.drag.end, e.drag.start);
  51454. diff.divide(size).multiply(frustumSize);
  51455. volume.position.copy(pointer);
  51456. //volume.position.copy(ray.origin); //orthographicCamera不能用这种方式 而且也该是用end
  51457. volume.up.copy(camera.up);
  51458. volume.rotation.copy(camera.rotation);
  51459. volume.scale.set(diff.x, diff.y, 1000 * 100);
  51460. e.consume();
  51461. };
  51462. let drop = e => {
  51463. this.importance = 0;
  51464. $(selectionBox).remove();
  51465. this.viewer.inputHandler.deselectAll();
  51466. this.viewer.inputHandler.toggleSelection(volume);
  51467. let camera = e.viewer.scene.getActiveCamera();
  51468. let size = e.viewer.renderer.getSize(new Vector2$1());
  51469. let screenCentroid = new Vector2$1().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  51470. let pointer = new Vector3(0, 0, 0.5);
  51471. Utils.convertScreenPositionToNDC(pointer, screenCentroid, size.width, size.height);
  51472. let ray = Utils.mouseToRay(pointer/* screenCentroid */, camera, size.width, size.height);
  51473. //let line = new THREE.Line3(ray.origin, new THREE.Vector3().addVectors(ray.origin, ray.direction));
  51474. this.removeEventListener("drag", drag);
  51475. this.removeEventListener("drop", drop);
  51476. let allPointsNear = [];
  51477. let allPointsFar = [];
  51478. // TODO support more than one point cloud
  51479. for(let pointcloud of this.viewer.scene.pointclouds){
  51480. if(!pointcloud.visible){
  51481. continue;
  51482. }
  51483. let volCam = camera.clone();
  51484. volCam.left = -volume.scale.x / 2;
  51485. volCam.right = +volume.scale.x / 2;
  51486. volCam.top = +volume.scale.y / 2;
  51487. volCam.bottom = -volume.scale.y / 2;
  51488. volCam.near = -volume.scale.z / 2;
  51489. volCam.far = +volume.scale.z / 2;
  51490. volCam.rotation.copy(volume.rotation);
  51491. volCam.position.copy(volume.position);
  51492. volCam.updateMatrix();
  51493. volCam.updateMatrixWorld();
  51494. volCam.updateProjectionMatrix();
  51495. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  51496. let ray = new Ray(volCam.getWorldPosition(new Vector3()), volCam.getWorldDirection(new Vector3()));
  51497. let rayInverse = new Ray(
  51498. ray.origin.clone().add(ray.direction.clone().multiplyScalar(volume.scale.z)),
  51499. ray.direction.clone().multiplyScalar(-1));
  51500. let diff = new Vector2$1().subVectors(e.drag.end, e.drag.start);
  51501. let pickerSettings = {
  51502. width: 16, //renderTarget大小,数值越大识别精度越高 原本的8太低了
  51503. height: 16,
  51504. pickWindowSize: 16, //??????
  51505. all: true,
  51506. pickClipped: true,
  51507. pointSizeType: PointSizeType.FIXED,
  51508. pointSize: 1
  51509. };
  51510. let pointsNear = pointcloud.pick(viewer, null, volCam, ray, pickerSettings);
  51511. volCam.rotateX(Math.PI);
  51512. volCam.updateMatrix();
  51513. volCam.updateMatrixWorld();
  51514. volCam.updateProjectionMatrix();
  51515. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  51516. let pointsFar = pointcloud.pick(viewer,null, volCam, rayInverse, pickerSettings);
  51517. pointsNear && allPointsNear.push(...pointsNear);
  51518. pointsFar && allPointsFar.push(...pointsFar);
  51519. }
  51520. /* if(allPointsNear.length > 0 && allPointsFar.length > 0){
  51521. let viewLine = new THREE.Line3(ray.origin, new THREE.Vector3().addVectors(ray.origin, ray.direction));
  51522. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new THREE.Vector3()));
  51523. let closest = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b))[0];
  51524. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new THREE.Vector3()));
  51525. let farthest = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a))[0];
  51526. let distance = closest.distanceTo(farthest);
  51527. let centroid = new THREE.Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  51528. volume.scale.z = distance * 1.1;
  51529. volume.position.copy(centroid);
  51530. } */
  51531. if(allPointsNear.length > 0 || allPointsFar.length > 0){
  51532. let viewLine = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  51533. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  51534. let closests = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b));//[0];
  51535. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  51536. let farthests = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a));//[0];
  51537. let closest, farthest;
  51538. if(closests.length == 0){
  51539. closest = farthests[farthests.length-1];
  51540. farthest = farthests[0];
  51541. }else if(farthests.length == 0){
  51542. closest = closests[closests.length-1];
  51543. farthest = closests[0];
  51544. }else {
  51545. closest = closests[0];
  51546. farthest = farthests[0];
  51547. }
  51548. let distance = closest.distanceTo(farthest);
  51549. let centroid = new Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  51550. volume.scale.z = distance * 1.1;
  51551. //volume.position.copy(centroid);
  51552. var pos2d = centroid.project(camera); //改变深度
  51553. pointer.setZ(pos2d.z);
  51554. pointer.unproject(camera);
  51555. volume.position.copy(pointer);
  51556. }
  51557. volume.clip = true;
  51558. };
  51559. this.addEventListener("drag", drag);
  51560. this.addEventListener("drop", drop);
  51561. viewer.inputHandler.addInputListener(this);
  51562. return volume;
  51563. }
  51564. update(e){
  51565. //console.log(e.delta)
  51566. }
  51567. render(){
  51568. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  51569. }
  51570. }
  51571. class SpotLightHelper$1 extends Object3D{
  51572. constructor(light, color){
  51573. super();
  51574. this.light = light;
  51575. this.color = color;
  51576. //this.up.set(0, 0, 1);
  51577. this.updateMatrix();
  51578. this.updateMatrixWorld();
  51579. { // SPHERE
  51580. let sg = new SphereGeometry(1, 32, 32);
  51581. let sm = new MeshNormalMaterial();
  51582. this.sphere = new Mesh(sg, sm);
  51583. this.sphere.scale.set(0.5, 0.5, 0.5);
  51584. this.add(this.sphere);
  51585. }
  51586. { // LINES
  51587. let positions = new Float32Array([
  51588. +0, +0, +0, +0, +0, -1,
  51589. +0, +0, +0, -1, -1, -1,
  51590. +0, +0, +0, +1, -1, -1,
  51591. +0, +0, +0, +1, +1, -1,
  51592. +0, +0, +0, -1, +1, -1,
  51593. -1, -1, -1, +1, -1, -1,
  51594. +1, -1, -1, +1, +1, -1,
  51595. +1, +1, -1, -1, +1, -1,
  51596. -1, +1, -1, -1, -1, -1,
  51597. ]);
  51598. let geometry = new BufferGeometry();
  51599. geometry.setAttribute("position", new BufferAttribute(positions, 3));
  51600. let material = new LineBasicMaterial();
  51601. this.frustum = new LineSegments(geometry, material);
  51602. this.add(this.frustum);
  51603. }
  51604. this.update();
  51605. }
  51606. update(){
  51607. this.light.updateMatrix();
  51608. this.light.updateMatrixWorld();
  51609. let position = this.light.position;
  51610. let target = new Vector3().addVectors(
  51611. this.light.position, this.light.getWorldDirection(new Vector3()).multiplyScalar(-1));
  51612. let quat = new Quaternion().setFromRotationMatrix(
  51613. new Matrix4().lookAt( position, target, new Vector3( 0, 0, 1 ) )
  51614. );
  51615. this.setRotationFromQuaternion(quat);
  51616. this.position.copy(position);
  51617. let coneLength = (this.light.distance > 0) ? this.light.distance : 1000;
  51618. let coneWidth = coneLength * Math.tan( this.light.angle * 0.5 );
  51619. this.frustum.scale.set(coneWidth, coneWidth, coneLength);
  51620. }
  51621. }
  51622. //add-------------------------------------
  51623. const OpaWhenNotSelect = 0.6;
  51624. const ScaleRatio = 8;
  51625. const OutlineColor = 0x666666;
  51626. //----------------------------------------
  51627. const hideFocusHandles = true;//add
  51628. class TransformationTool {
  51629. constructor(viewer) {
  51630. this.viewer = viewer;
  51631. this.scene = new Scene();
  51632. this.modesEnabled = {scale:true,translation:true,rotation:true};//add
  51633. this.selection = [];
  51634. this.pivot = new Vector3();
  51635. this.dragging = false;
  51636. this.showPickVolumes = false;
  51637. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  51638. this.viewer.inputHandler.addEventListener('selection_changed', (e) => {
  51639. for(let selected of this.selection){
  51640. this.viewer.inputHandler.blacklist.delete(selected);
  51641. }
  51642. this.selection = e.selection;
  51643. for(let selected of this.selection){
  51644. this.viewer.inputHandler.blacklist.add(selected);
  51645. }
  51646. });
  51647. this.viewer.addEventListener('global_touchstart',(e)=>{ //add
  51648. this.update();
  51649. });
  51650. let red = Potree.config.axis.x.color;
  51651. let green = Potree.config.axis.y.color;
  51652. let blue = Potree.config.axis.z.color;
  51653. this.activeHandle = null;
  51654. this.scaleHandles = {
  51655. "scale.x+": {name: "scale.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  51656. "scale.x-": {name: "scale.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  51657. "scale.y+": {name: "scale.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  51658. "scale.y-": {name: "scale.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  51659. "scale.z+": {name: "scale.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  51660. "scale.z-": {name: "scale.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  51661. };
  51662. this.focusHandles = {
  51663. "focus.x+": {name: "focus.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  51664. "focus.x-": {name: "focus.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  51665. "focus.y+": {name: "focus.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  51666. "focus.y-": {name: "focus.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  51667. "focus.z+": {name: "focus.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  51668. "focus.z-": {name: "focus.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  51669. };
  51670. this.translationHandles = {
  51671. "translation.x": {name: "translation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  51672. "translation.y": {name: "translation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  51673. "translation.z": {name: "translation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  51674. };
  51675. this.rotationHandles = {
  51676. "rotation.x": {name: "rotation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  51677. "rotation.y": {name: "rotation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  51678. "rotation.z": {name: "rotation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  51679. };
  51680. this.handles = Object.assign({}, this.scaleHandles, hideFocusHandles?{}:this.focusHandles, this.translationHandles, this.rotationHandles);
  51681. this.pickVolumes = [];
  51682. this.initializeScaleHandles();
  51683. this.initializeFocusHandles();
  51684. this.initializeTranslationHandles();
  51685. this.initializeRotationHandles();
  51686. let boxFrameGeometry = new Geometry();
  51687. {
  51688. // bottom
  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. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  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. // top
  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. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51702. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51703. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51704. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51705. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51706. // sides
  51707. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51708. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51709. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51710. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51711. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51712. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51713. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51714. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51715. }
  51716. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0xffff00}));
  51717. this.scene.add(this.frame);
  51718. viewer.setObjectLayers(this.scene, 'transformationTool' );
  51719. this.scene.traverse(e=>{
  51720. e.pickDontCheckDis = true; //pick时不需要识别是否在点云之上
  51721. });
  51722. }
  51723. setModeEnable(mode,enable){//xzw add
  51724. let handels = this[mode + 'Handles'];
  51725. if(!handels)return
  51726. for(let o in handels){
  51727. handels[o].node.visible = !!enable;
  51728. }
  51729. this.modesEnabled[mode] = !!enable;
  51730. }
  51731. initializeScaleHandles(){
  51732. let sgSphere = new SphereGeometry(1, 32, 32);
  51733. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  51734. for(let handleName of Object.keys(this.scaleHandles)){
  51735. let handle = this.scaleHandles[handleName];
  51736. let node = handle.node;
  51737. this.scene.add(node);
  51738. node.position.set(...handle.alignment).multiplyScalar(0.5);
  51739. let material = new MeshBasicMaterial({
  51740. color: handle.color,
  51741. opacity: OpaWhenNotSelect,
  51742. transparent: true
  51743. });
  51744. let outlineMaterial = new MeshBasicMaterial({
  51745. color: OutlineColor,
  51746. side: BackSide,
  51747. opacity: OpaWhenNotSelect,
  51748. transparent: true});
  51749. let pickMaterial = new MeshNormalMaterial({
  51750. opacity: 0.2,
  51751. transparent: true,
  51752. visible: this.showPickVolumes});
  51753. let sphere = new Mesh(sgSphere, material);
  51754. sphere.scale.set(2, 2, 2 );
  51755. sphere.name = `${handleName}.handle`;
  51756. node.add(sphere);
  51757. let outline = new Mesh(sgSphere, outlineMaterial);
  51758. outline.scale.set(1.1, 1.1, 1.1);
  51759. outline.name = `${handleName}.outline`;
  51760. sphere.add(outline);
  51761. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  51762. pickSphere.name = `${handleName}.pick_volume`;
  51763. pickSphere.scale.set(2, 2, 2);
  51764. sphere.add(pickSphere);
  51765. pickSphere.handle = handleName;
  51766. this.pickVolumes.push(pickSphere);
  51767. node.setOpacity = (target) => {
  51768. let opacity = {x: material.opacity};
  51769. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51770. t.onUpdate(() => {
  51771. sphere.visible = opacity.x > 0;
  51772. pickSphere.visible = opacity.x > 0;
  51773. material.opacity = opacity.x;
  51774. outlineMaterial.opacity = opacity.x;
  51775. pickSphere.material.opacity = opacity.x * 0.5;
  51776. });
  51777. t.start();
  51778. };
  51779. pickSphere.addEventListener("drag", (e) => this.dragScaleHandle(e));
  51780. pickSphere.addEventListener("drop", (e) => this.dropScaleHandle(e));
  51781. pickSphere.addEventListener("mouseover", e => {
  51782. //node.setOpacity(1);
  51783. });
  51784. pickSphere.addEventListener("click", e => {
  51785. //e.consume();
  51786. });
  51787. pickSphere.addEventListener("mouseleave", e => {
  51788. //node.setOpacity(OpaWhenNotSelect);
  51789. });
  51790. }
  51791. }
  51792. initializeFocusHandles(){
  51793. if(hideFocusHandles)return//add
  51794. //let sgBox = new THREE.BoxGeometry(1, 1, 1);
  51795. let sgPlane = new PlaneGeometry(4, 4, 1, 1);
  51796. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  51797. let texture = new TextureLoader().load(`${exports.resourcePath}/icons/eye_2.png`);
  51798. for(let handleName of Object.keys(this.focusHandles)){
  51799. let handle = this.focusHandles[handleName];
  51800. let node = handle.node;
  51801. this.scene.add(node);
  51802. let align = handle.alignment;
  51803. //node.lookAt(new THREE.Vector3().addVectors(node.position, new THREE.Vector3(...align)));
  51804. node.lookAt(new Vector3(...align));
  51805. let off = 0.8;
  51806. if(align[0] === 1){
  51807. node.position.set(1, off, -off).multiplyScalar(0.5);
  51808. node.rotation.z = Math.PI / 2;
  51809. }else if(align[0] === -1){
  51810. node.position.set(-1, -off, -off).multiplyScalar(0.5);
  51811. node.rotation.z = Math.PI / 2;
  51812. }else if(align[1] === 1){
  51813. node.position.set(-off, 1, -off).multiplyScalar(0.5);
  51814. node.rotation.set(Math.PI / 2, Math.PI, 0.0);
  51815. }else if(align[1] === -1){
  51816. node.position.set(off, -1, -off).multiplyScalar(0.5);
  51817. node.rotation.set(Math.PI / 2, 0.0, 0.0);
  51818. }else if(align[2] === 1){
  51819. node.position.set(off, off, 1).multiplyScalar(0.5);
  51820. }else if(align[2] === -1){
  51821. node.position.set(-off, off, -1).multiplyScalar(0.5);
  51822. }
  51823. let material = new MeshBasicMaterial({
  51824. color: handle.color,
  51825. opacity: 0,
  51826. transparent: true,
  51827. map: texture
  51828. });
  51829. //let outlineMaterial = new THREE.MeshBasicMaterial({
  51830. // color: 0x000000,
  51831. // side: THREE.BackSide,
  51832. // opacity: 0,
  51833. // transparent: true});
  51834. let pickMaterial = new MeshNormalMaterial({
  51835. //opacity: 0,
  51836. transparent: true,
  51837. visible: this.showPickVolumes});
  51838. let box = new Mesh(sgPlane, material);
  51839. box.name = `${handleName}.handle`;
  51840. box.scale.set(1.5, 1.5, 1.5);
  51841. box.position.set(0, 0, 0);
  51842. box.visible = false;
  51843. node.add(box);
  51844. //handle.focusNode = box;
  51845. //let outline = new THREE.Mesh(sgPlane, outlineMaterial);
  51846. //outline.scale.set(1.4, 1.4, 1.4);
  51847. //outline.name = `${handleName}.outline`;
  51848. //box.add(outline);
  51849. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  51850. pickSphere.name = `${handleName}.pick_volume`;
  51851. pickSphere.scale.set(2, 2, 2);
  51852. box.add(pickSphere);
  51853. pickSphere.handle = handleName;
  51854. this.pickVolumes.push(pickSphere);
  51855. node.setOpacity = (target) => {
  51856. let opacity = {x: material.opacity};
  51857. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51858. t.onUpdate(() => {
  51859. pickSphere.visible = opacity.x > 0;
  51860. box.visible = opacity.x > 0;
  51861. material.opacity = opacity.x;
  51862. //outlineMaterial.opacity = opacity.x;
  51863. pickSphere.material.opacity = opacity.x * 0.5;
  51864. });
  51865. t.start();
  51866. };
  51867. //pickSphere.addEventListener("drag", e => {});
  51868. pickSphere.addEventListener("mouseup", e => {
  51869. //e.consume();
  51870. });
  51871. pickSphere.addEventListener("mousedown", e => {
  51872. //e.consume();
  51873. });
  51874. pickSphere.addEventListener("click", e => {
  51875. //e.consume();
  51876. let selected = this.selection[0];
  51877. let maxScale = Math.max(...selected.scale.toArray());
  51878. let minScale = Math.min(...selected.scale.toArray());
  51879. let handleLength = Math.abs(selected.scale.dot(new Vector3(...handle.alignment)));
  51880. let alignment = new Vector3(...handle.alignment).multiplyScalar(2 * maxScale / handleLength);
  51881. alignment.applyMatrix4(selected.matrixWorld);
  51882. let newCamPos = alignment;
  51883. let newCamTarget = selected.getWorldPosition(new Vector3());
  51884. Utils.moveTo(this.viewer.scene, newCamPos, newCamTarget);
  51885. });
  51886. pickSphere.addEventListener("mouseover", e => {
  51887. //box.setOpacity(1);
  51888. });
  51889. pickSphere.addEventListener("mouseleave", e => {
  51890. //box.setOpacity(OpaWhenNotSelect);
  51891. });
  51892. }
  51893. }
  51894. initializeTranslationHandles(){
  51895. let boxGeometry = new BoxGeometry(1, 1, 1);
  51896. for(let handleName of Object.keys(this.translationHandles)){
  51897. let handle = this.handles[handleName];
  51898. let node = handle.node;
  51899. this.scene.add(node);
  51900. let material = new MeshBasicMaterial({
  51901. color: handle.color,
  51902. opacity: OpaWhenNotSelect,
  51903. transparent: true});
  51904. let outlineMaterial = new MeshBasicMaterial({
  51905. color: OutlineColor,
  51906. side: BackSide,
  51907. opacity: OpaWhenNotSelect,
  51908. transparent: true});
  51909. let pickMaterial = new MeshNormalMaterial({
  51910. opacity: 0.2,
  51911. transparent: true,
  51912. visible: this.showPickVolumes
  51913. });
  51914. let box = new Mesh(boxGeometry, material);
  51915. box.name = `${handleName}.handle`;
  51916. box.scale.set(1, 1, 72);
  51917. box.lookAt(new Vector3(...handle.alignment));
  51918. box.renderOrder = 10;
  51919. node.add(box);
  51920. handle.translateNode = box;
  51921. let outline = new Mesh(boxGeometry, outlineMaterial);
  51922. outline.name = `${handleName}.outline`;
  51923. outline.scale.set(1.3, 1.3, 1.01);
  51924. outline.renderOrder = 0;
  51925. box.add(outline);
  51926. let pickVolume = new Mesh(boxGeometry, pickMaterial);
  51927. pickVolume.name = `${handleName}.pick_volume`;
  51928. pickVolume.scale.set(4, 4, 1.1);
  51929. pickVolume.handle = handleName;
  51930. box.add(pickVolume);
  51931. this.pickVolumes.push(pickVolume);
  51932. node.setOpacity = (target) => {
  51933. let opacity = {x: material.opacity};
  51934. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51935. t.onUpdate(() => {
  51936. box.visible = opacity.x > 0;
  51937. pickVolume.visible = opacity.x > 0;
  51938. material.opacity = opacity.x;
  51939. outlineMaterial.opacity = opacity.x;
  51940. pickMaterial.opacity = opacity.x * 0.5;
  51941. });
  51942. t.start();
  51943. };
  51944. pickVolume.addEventListener("drag", (e) => {this.dragTranslationHandle(e);});
  51945. pickVolume.addEventListener("drop", (e) => {this.dropTranslationHandle(e);});
  51946. }
  51947. }
  51948. initializeRotationHandles(){
  51949. let adjust = 1.5;
  51950. let torusGeometry = new TorusGeometry(1, adjust * 0.015, 8, 64, Math.PI / 2);
  51951. let outlineGeometry = new TorusGeometry(1, adjust * 0.018, 8, 64, Math.PI / 2);
  51952. let pickGeometry = new TorusGeometry(1, adjust * 0.04, 6, 4, Math.PI / 2);
  51953. for(let handleName of Object.keys(this.rotationHandles)){
  51954. let handle = this.handles[handleName];
  51955. let node = handle.node;
  51956. this.scene.add(node);
  51957. let material = new MeshBasicMaterial({
  51958. color: handle.color,
  51959. opacity: OpaWhenNotSelect,
  51960. transparent: true
  51961. });
  51962. let outlineMaterial = new MeshBasicMaterial({
  51963. color: OutlineColor,
  51964. side: BackSide,
  51965. opacity: OpaWhenNotSelect,
  51966. transparent: true
  51967. });
  51968. let pickMaterial = new MeshNormalMaterial({
  51969. opacity: 0.2,
  51970. transparent: true,
  51971. visible: this.showPickVolumes
  51972. });
  51973. let box = new Mesh(torusGeometry, material);
  51974. box.name = `${handleName}.handle`;
  51975. box.scale.set(30, 30, 30);
  51976. box.lookAt(new Vector3(...handle.alignment));
  51977. node.add(box);
  51978. handle.translateNode = box;
  51979. let outline = new Mesh(outlineGeometry, outlineMaterial);
  51980. outline.name = `${handleName}.outline`;
  51981. outline.scale.set(1, 1, 1);
  51982. outline.renderOrder = 0;
  51983. box.add(outline);
  51984. let pickVolume = new Mesh(pickGeometry, pickMaterial);
  51985. pickVolume.name = `${handleName}.pick_volume`;
  51986. pickVolume.scale.set(1, 1, 1);
  51987. pickVolume.handle = handleName;
  51988. box.add(pickVolume);
  51989. this.pickVolumes.push(pickVolume);
  51990. node.setOpacity = (target) => {
  51991. let opacity = {x: material.opacity};
  51992. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51993. t.onUpdate(() => {
  51994. box.visible = opacity.x > 0;
  51995. pickVolume.visible = opacity.x > 0;
  51996. material.opacity = opacity.x;
  51997. outlineMaterial.opacity = opacity.x;
  51998. pickMaterial.opacity = opacity.x * 0.5;
  51999. });
  52000. t.start();
  52001. };
  52002. //pickVolume.addEventListener("mouseover", (e) => {
  52003. // //let a = this.viewer.scene.getActiveCamera().getWorldDirection(new THREE.Vector3()).dot(pickVolume.getWorldDirection(new THREE.Vector3()));
  52004. // console.log(pickVolume.getWorldDirection(new THREE.Vector3()));
  52005. //});
  52006. pickVolume.addEventListener("drag", (e) => {this.dragRotationHandle(e);});
  52007. pickVolume.addEventListener("drop", (e) => {this.dropRotationHandle(e);});
  52008. }
  52009. }
  52010. dragRotationHandle(e){
  52011. let drag = e.drag;
  52012. let handle = this.activeHandle;
  52013. let camera = this.viewer.scene.getActiveCamera();
  52014. if(!handle){
  52015. return
  52016. };
  52017. let localNormal = new Vector3(...handle.alignment);
  52018. let n = new Vector3();
  52019. n.copy(new Vector4(...localNormal.toArray(), 0).applyMatrix4(handle.node.matrixWorld));
  52020. n.normalize();
  52021. if (!drag.intersectionStart){
  52022. //this.viewer.scene.scene.remove(this.debug);
  52023. //this.debug = new THREE.Object3D();
  52024. //this.viewer.scene.scene.add(this.debug);
  52025. //Utils.debugSphere(this.debug, drag.location, 3, 0xaaaaaa);
  52026. //let debugEnd = drag.location.clone().add(n.clone().multiplyScalar(20));
  52027. //Utils.debugLine(this.debug, drag.location, debugEnd, 0xff0000);
  52028. drag.intersectionStart = drag.location;
  52029. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52030. drag.handle = handle;
  52031. let plane = new Plane().setFromNormalAndCoplanarPoint(n, drag.intersectionStart);
  52032. drag.dragPlane = plane;
  52033. drag.pivot = drag.intersectionStart;
  52034. }else {
  52035. handle = drag.handle;
  52036. }
  52037. this.dragging = true;
  52038. let pointer = this.viewer.inputHandler.pointer;
  52039. let domElement = this.viewer.renderer.domElement;
  52040. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52041. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52042. if (I) {
  52043. let center = this.scene.getWorldPosition(new Vector3());
  52044. let from = drag.pivot;
  52045. let to = I;
  52046. let v1 = from.clone().sub(center).normalize();
  52047. let v2 = to.clone().sub(center).normalize();
  52048. let angle = Math.acos(v1.dot(v2));
  52049. let sign = Math.sign(v1.cross(v2).dot(n));
  52050. angle = angle * sign;
  52051. if (Number.isNaN(angle)) {
  52052. return;
  52053. }
  52054. let normal = new Vector3(...handle.alignment);
  52055. for (let selection of this.selection) {
  52056. selection.rotateOnAxis(normal, angle);
  52057. selection.dispatchEvent({
  52058. type: "orientation_changed",
  52059. object: selection
  52060. });
  52061. }
  52062. drag.pivot = I;
  52063. }
  52064. }
  52065. dropRotationHandle(e){
  52066. this.dragging = false;
  52067. this.setActiveHandle(null);
  52068. }
  52069. dragTranslationHandle(e){
  52070. let drag = e.drag;
  52071. let handle = this.activeHandle;
  52072. let camera = this.viewer.scene.getActiveCamera();
  52073. if(!drag.intersectionStart && handle){
  52074. drag.intersectionStart = drag.location;
  52075. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52076. let start = drag.intersectionStart;
  52077. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  52078. let end = new Vector3().addVectors(start, dir);
  52079. let line = new Line3(start.clone(), end.clone());
  52080. drag.line = line;
  52081. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  52082. let normal = new Vector3().subVectors(camera.position, camOnLine);
  52083. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart);
  52084. drag.dragPlane = plane;
  52085. drag.pivot = drag.intersectionStart;
  52086. }else {
  52087. handle = drag.handle;
  52088. }
  52089. this.dragging = true;
  52090. {
  52091. let pointer = this.viewer.inputHandler.pointer;
  52092. let domElement = this.viewer.renderer.domElement;
  52093. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52094. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52095. if (I) {
  52096. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  52097. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  52098. for (let selection of this.selection) {
  52099. selection.position.add(diff);
  52100. selection.dispatchEvent({
  52101. type: "position_changed",
  52102. object: selection
  52103. });
  52104. }
  52105. drag.pivot = drag.pivot.add(diff);
  52106. }
  52107. }
  52108. }
  52109. dropTranslationHandle(e){
  52110. this.dragging = false;
  52111. this.setActiveHandle(null);
  52112. }
  52113. dropScaleHandle(e){
  52114. this.dragging = false;
  52115. this.setActiveHandle(null);
  52116. }
  52117. dragScaleHandle(e){
  52118. let drag = e.drag;
  52119. let handle = this.activeHandle;
  52120. let camera = this.viewer.scene.getActiveCamera();
  52121. if(!drag.intersectionStart){
  52122. drag.intersectionStart = drag.location;
  52123. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52124. drag.handle = handle;
  52125. let start = drag.intersectionStart;
  52126. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  52127. let end = new Vector3().addVectors(start, dir);
  52128. let line = new Line3(start.clone(), end.clone());
  52129. drag.line = line;
  52130. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  52131. let normal = new Vector3().subVectors(camera.position, camOnLine);
  52132. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart);
  52133. drag.dragPlane = plane;
  52134. drag.pivot = drag.intersectionStart;
  52135. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  52136. }else {
  52137. handle = drag.handle;
  52138. }
  52139. this.dragging = true;
  52140. {
  52141. let pointer = this.viewer.inputHandler.pointer;
  52142. let domElement = this.viewer.renderer.domElement;
  52143. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52144. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52145. if (I) {
  52146. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  52147. let direction = handle.alignment.reduce( (a, v) => a + v, 0);
  52148. let toObjectSpace = this.selection[0].matrixWorld.clone().invert();
  52149. let iOnLineOS = iOnLine.clone().applyMatrix4(toObjectSpace);
  52150. let pivotOS = drag.pivot.clone().applyMatrix4(toObjectSpace);
  52151. let diffOS = new Vector3().subVectors(iOnLineOS, pivotOS);
  52152. let dragDirectionOS = diffOS.clone().normalize();
  52153. if(iOnLine.distanceTo(drag.pivot) === 0){
  52154. dragDirectionOS.set(0, 0, 0);
  52155. }
  52156. let dragDirection = dragDirectionOS.dot(new Vector3(...handle.alignment));
  52157. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  52158. let diffScale = new Vector3(...handle.alignment).multiplyScalar(diff.length() * direction * dragDirection);
  52159. let diffPosition = diff.clone().multiplyScalar(0.5);
  52160. for (let selection of this.selection) {
  52161. //xzw 改:否则不跟手
  52162. let diffScale_ = diffScale.clone().divide(selection.boundingBox.getSize(new Vector3));
  52163. selection.scale.add(diffScale_);
  52164. //selection.scale.add(diffScale);
  52165. selection.scale.x = Math.max(0.1, selection.scale.x);
  52166. selection.scale.y = Math.max(0.1, selection.scale.y);
  52167. selection.scale.z = Math.max(0.1, selection.scale.z);
  52168. selection.position.add(diffPosition);
  52169. selection.dispatchEvent({
  52170. type: "position_changed",
  52171. object: selection
  52172. });
  52173. selection.dispatchEvent({
  52174. type: "scale_changed",
  52175. object: selection
  52176. });
  52177. }
  52178. drag.pivot.copy(iOnLine);
  52179. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  52180. }
  52181. }
  52182. }
  52183. setActiveHandle(handle){
  52184. if(this.dragging){
  52185. return;
  52186. }
  52187. if(this.activeHandle === handle){
  52188. return;
  52189. }
  52190. this.activeHandle = handle;
  52191. if(handle === null){
  52192. for(let handleName of Object.keys(this.handles)){
  52193. let handle = this.handles[handleName];
  52194. handle.node.setOpacity(0);
  52195. }
  52196. }
  52197. if(!hideFocusHandles){
  52198. for(let handleName of Object.keys(this.focusHandles)){
  52199. let handle = this.focusHandles[handleName];
  52200. if(this.activeHandle === handle){
  52201. handle.node.setOpacity(1.0);
  52202. }else {
  52203. handle.node.setOpacity(OpaWhenNotSelect);
  52204. }
  52205. }
  52206. }
  52207. for(let handleName of Object.keys(this.translationHandles)){
  52208. let handle = this.translationHandles[handleName];
  52209. if(this.activeHandle === handle){
  52210. handle.node.setOpacity(1.0);
  52211. }else {
  52212. handle.node.setOpacity(OpaWhenNotSelect);
  52213. }
  52214. }
  52215. for(let handleName of Object.keys(this.rotationHandles)){
  52216. let handle = this.rotationHandles[handleName];
  52217. //if(this.activeHandle === handle){
  52218. // handle.node.setOpacity(1.0);
  52219. //}else{
  52220. // handle.node.setOpacity(OpaWhenNotSelect)
  52221. //}
  52222. handle.node.setOpacity(OpaWhenNotSelect);
  52223. }
  52224. for(let handleName of Object.keys(this.scaleHandles)){
  52225. let handle = this.scaleHandles[handleName];
  52226. if(this.activeHandle === handle){
  52227. handle.node.setOpacity(1.0);
  52228. if(!hideFocusHandles){
  52229. let relatedFocusHandle = this.focusHandles[handle.name.replace("scale", "focus")];
  52230. let relatedFocusNode = relatedFocusHandle.node;
  52231. relatedFocusNode.setOpacity(OpaWhenNotSelect);
  52232. }
  52233. for(let translationHandleName of Object.keys(this.translationHandles)){
  52234. let translationHandle = this.translationHandles[translationHandleName];
  52235. translationHandle.node.setOpacity(OpaWhenNotSelect);
  52236. }
  52237. //let relatedTranslationHandle = this.translationHandles[
  52238. // handle.name.replace("scale", "translation").replace(/[+-]/g, "")];
  52239. //let relatedTranslationNode = relatedTranslationHandle.node;
  52240. //relatedTranslationNode.setOpacity(OpaWhenNotSelect);
  52241. }else {
  52242. handle.node.setOpacity(OpaWhenNotSelect);
  52243. }
  52244. }
  52245. if(handle){
  52246. handle.node.setOpacity(1.0);
  52247. }
  52248. }
  52249. update () {
  52250. if(this.selection.length === 1){
  52251. this.scene.visible = true;
  52252. this.scene.updateMatrix();
  52253. this.scene.updateMatrixWorld();
  52254. let selected = this.selection[0];
  52255. let world = selected.matrixWorld;
  52256. let camera = this.viewer.scene.getActiveCamera();
  52257. let domElement = this.viewer.renderer.domElement;
  52258. let pointer = this.viewer.inputHandler.pointer;
  52259. let center = selected.boundingBox.getCenter(new Vector3()).clone().applyMatrix4(selected.matrixWorld);
  52260. this.scene.scale.copy(selected.boundingBox.getSize(new Vector3()).multiply(selected.scale));
  52261. this.scene.position.copy(center);
  52262. this.scene.rotation.copy(selected.rotation);
  52263. this.scene.updateMatrixWorld();
  52264. {
  52265. // adjust rotation handles
  52266. if(!this.dragging){
  52267. let tWorld = this.scene.matrixWorld;
  52268. let tObject = tWorld.clone().invert();
  52269. let camObjectPos = camera.getWorldPosition(new Vector3()).applyMatrix4(tObject);
  52270. let x = this.rotationHandles["rotation.x"].node.rotation;
  52271. let y = this.rotationHandles["rotation.y"].node.rotation;
  52272. let z = this.rotationHandles["rotation.z"].node.rotation;
  52273. x.order = "ZYX";
  52274. y.order = "ZYX";
  52275. let above = camObjectPos.z > 0;
  52276. let below = !above;
  52277. let PI_HALF = Math.PI / 2;
  52278. if(above){
  52279. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  52280. x.x = 1 * PI_HALF;
  52281. y.y = 3 * PI_HALF;
  52282. z.z = 0 * PI_HALF;
  52283. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  52284. x.x = 1 * PI_HALF;
  52285. y.y = 2 * PI_HALF;
  52286. z.z = 1 * PI_HALF;
  52287. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  52288. x.x = 2 * PI_HALF;
  52289. y.y = 2 * PI_HALF;
  52290. z.z = 2 * PI_HALF;
  52291. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  52292. x.x = 2 * PI_HALF;
  52293. y.y = 3 * PI_HALF;
  52294. z.z = 3 * PI_HALF;
  52295. }
  52296. }else if(below){
  52297. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  52298. x.x = 0 * PI_HALF;
  52299. y.y = 0 * PI_HALF;
  52300. z.z = 0 * PI_HALF;
  52301. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  52302. x.x = 0 * PI_HALF;
  52303. y.y = 1 * PI_HALF;
  52304. z.z = 1 * PI_HALF;
  52305. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  52306. x.x = 3 * PI_HALF;
  52307. y.y = 1 * PI_HALF;
  52308. z.z = 2 * PI_HALF;
  52309. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  52310. x.x = 3 * PI_HALF;
  52311. y.y = 0 * PI_HALF;
  52312. z.z = 3 * PI_HALF;
  52313. }
  52314. }
  52315. }
  52316. // adjust scale of components
  52317. for(let handleName of Object.keys(this.handles)){
  52318. let handle = this.handles[handleName];
  52319. let node = handle.node;
  52320. let handlePos = node.getWorldPosition(new Vector3());
  52321. let distance = handlePos.distanceTo(camera.position);
  52322. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  52323. let ws = node.parent.getWorldScale(new Vector3());
  52324. let s = (ScaleRatio / pr);
  52325. let scale = new Vector3(s, s, s).divide(ws);
  52326. let rot = new Matrix4().makeRotationFromEuler(node.rotation); //需要使用到旋转,所以我把设置scale的移到旋转后了,否则在视图上下旋转的分界线处rotateHandel会被拉长从而闪烁。
  52327. let rotInv = rot.clone().invert();
  52328. scale.applyMatrix4(rotInv);
  52329. scale.x = Math.abs(scale.x);
  52330. scale.y = Math.abs(scale.y);
  52331. scale.z = Math.abs(scale.z);
  52332. node.scale.copy(scale);
  52333. }
  52334. {
  52335. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52336. let raycaster = new Raycaster(ray.origin, ray.direction);
  52337. raycaster.layers.enableAll();//add
  52338. let pickVolumes = this.pickVolumes.filter(v=>{
  52339. let mode = v.handle.split('.')[0];
  52340. return this.modesEnabled[mode]
  52341. });
  52342. let intersects = raycaster.intersectObjects(pickVolumes, true);
  52343. if(intersects.length > 0){
  52344. let I = intersects[0];
  52345. let handleName = I.object.handle;
  52346. console.log(handleName);
  52347. this.setActiveHandle(this.handles[handleName]);
  52348. }else {
  52349. this.setActiveHandle(null);
  52350. }
  52351. }
  52352. //
  52353. for(let handleName of Object.keys(this.scaleHandles)){
  52354. let handle = this.handles[handleName];
  52355. let node = handle.node;
  52356. let alignment = handle.alignment;
  52357. }
  52358. }
  52359. }else {
  52360. this.scene.visible = false;
  52361. }
  52362. }
  52363. };
  52364. /*
  52365. note:
  52366. transformationTool.scene会跟随选中物体,其scale就是boundingbox的大小。因此transformationTool.frame这个框也会跟着缩放
  52367. */
  52368. class VolumeTool extends EventDispatcher{
  52369. constructor (viewer) {
  52370. super();
  52371. this.viewer = viewer;
  52372. this.renderer = viewer.renderer;
  52373. this.addEventListener('start_inserting_volume', e => {
  52374. this.viewer.dispatchEvent({
  52375. type: 'cancel_insertions'
  52376. });
  52377. });
  52378. this.scene = new Scene();
  52379. this.scene.name = 'scene_volume';
  52380. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  52381. this.onRemove = e => {
  52382. this.scene.remove(e.volume);
  52383. };
  52384. this.onAdd = e => {
  52385. this.scene.add(e.volume);
  52386. };
  52387. for(let volume of viewer.scene.volumes){
  52388. this.onAdd({volume: volume});
  52389. }
  52390. this.viewer.inputHandler.addEventListener('delete', e => {
  52391. let volumes = e.selection.filter(e => (e instanceof Volume));
  52392. volumes.forEach(e => this.viewer.scene.removeVolume(e));
  52393. });
  52394. viewer.addEventListener("update", this.update.bind(this));
  52395. viewer.addEventListener("render.pass.scene", e => this.render(e));
  52396. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  52397. viewer.scene.addEventListener('volume_added', this.onAdd);
  52398. viewer.scene.addEventListener('volume_removed', this.onRemove);
  52399. }
  52400. onSceneChange(e){
  52401. if(e.oldScene){
  52402. e.oldScene.removeEventListeners('volume_added', this.onAdd);
  52403. e.oldScene.removeEventListeners('volume_removed', this.onRemove);
  52404. }
  52405. e.scene.addEventListener('volume_added', this.onAdd);
  52406. e.scene.addEventListener('volume_removed', this.onRemove);
  52407. }
  52408. startInsertion (args = {}) {
  52409. let volume;
  52410. if(args.type){
  52411. volume = new args.type();
  52412. }else {
  52413. volume = new BoxVolume();
  52414. }
  52415. volume.clip = args.clip || false;
  52416. volume.name = args.name || 'Volume';
  52417. this.dispatchEvent({
  52418. type: 'start_inserting_volume',
  52419. volume: volume
  52420. });
  52421. this.viewer.scene.addVolume(volume);
  52422. //this.scene.add(volume);
  52423. let cancel = {
  52424. callback: null
  52425. };
  52426. let drag = e => {
  52427. let camera = this.viewer.scene.getActiveCamera();
  52428. var I = e.intersect;
  52429. if (I) {
  52430. volume.position.copy(I.location);
  52431. let wp = volume.getWorldPosition(new Vector3()).applyMatrix4(camera.matrixWorldInverse);
  52432. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  52433. let w = Math.abs((wp.z / 5));
  52434. volume.scale.set(w, w, w);
  52435. }
  52436. };
  52437. let drop = e => {
  52438. volume.removeEventListener('drag', drag);
  52439. volume.removeEventListener('drop', drop);
  52440. cancel.callback();
  52441. };
  52442. cancel.callback = e => {
  52443. volume.removeEventListener('drag', drag);
  52444. volume.removeEventListener('drop', drop);
  52445. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  52446. };
  52447. volume.addEventListener('drag', drag);
  52448. volume.addEventListener('drop', drop);
  52449. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  52450. this.viewer.inputHandler.startDragging(volume);
  52451. return volume;
  52452. }
  52453. update(){
  52454. if (!this.viewer.scene) {
  52455. return;
  52456. }
  52457. let camera = this.viewer.scene.getActiveCamera();
  52458. let renderAreaSize = this.viewer.renderer.getSize(new Vector2$1());
  52459. let clientWidth = renderAreaSize.width;
  52460. let clientHeight = renderAreaSize.height;
  52461. let volumes = this.viewer.scene.volumes;
  52462. for (let volume of volumes) {
  52463. }
  52464. }
  52465. render(params){
  52466. const renderer = this.viewer.renderer;
  52467. const oldTarget = renderer.getRenderTarget();
  52468. if(params.renderTarget){
  52469. renderer.setRenderTarget(params.renderTarget);
  52470. }
  52471. renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  52472. renderer.setRenderTarget(oldTarget);
  52473. }
  52474. }
  52475. const initDir = new Vector3(0,1,0);//指南针模型的北方向 向屏幕里
  52476. class Compass extends EventDispatcher{
  52477. constructor(dom, viewport){
  52478. super();
  52479. this.angle = 0;
  52480. this.show = false;
  52481. if(dom){
  52482. this.dom = $(dom);
  52483. }
  52484. this.viewport = viewport;
  52485. this.init();
  52486. }
  52487. init(){
  52488. var width = 100, height = 100;
  52489. if(!this.dom){
  52490. this.dom = $('<div name="compass"></div>');
  52491. $(viewer.renderArea).append(this.dom);
  52492. }
  52493. this.dom.css({ display:"none", position:"absolute",right:"1%",top: "60px",width:width+"px",height:height+"px", "z-index":100,"pointer-events":"none" });
  52494. let child = $("<div class='dirText north'><span>"+/* (config.lang=='zh'? */'北'/* :'N') */+"</span></div><div class='center'></div>");
  52495. this.dom.append(child);
  52496. this.dom.find(".dirText").css({textAlign:"center","font-size":"10px","position":"absolute",
  52497. width: "100%",
  52498. height: "25px",
  52499. "line-height": "25px"});
  52500. this.dom.find(".north").css({"color":"#02a0e9","top":"0"});
  52501. this.dom.find(".south").css({"color":"#ff1414","bottom":"0"});
  52502. this.dom.find(".center").css({
  52503. //"background":`url(${config.getStaticResource('img')}/dire.png)`,
  52504. width: width/2+"px",
  52505. height: height/2+"px",
  52506. "background-size": "contain",
  52507. "background-position": "center",
  52508. left: "50%",
  52509. top: "50%",
  52510. transform: "translate(-50%,-50%)",
  52511. position: "absolute"
  52512. });
  52513. this.dom.find(".dirText").css({
  52514. "text-align": "center",
  52515. "font-size": "10px",
  52516. "color": "rgb(255, 255, 255)",
  52517. "position": "absolute",
  52518. "top": "50%",
  52519. "left": "50%",
  52520. "width": "45%",
  52521. "height": "0px",
  52522. "transform-origin": "left center",
  52523. });
  52524. this.dom.find(".dirText span").css({
  52525. display: "block",
  52526. position: "absolute",
  52527. right: "5px",
  52528. top: "0",
  52529. width: "20px",
  52530. height: "20px",
  52531. "line-height": "20px",
  52532. // "font-size": ".75rem ",
  52533. "margin-top": "-10px",
  52534. });
  52535. try {
  52536. this.renderer = new WebGLRenderer({ antialias: true, alpha:true });//许钟文 添加个抗锯齿,否则添加的线条锯齿严重,
  52537. this.renderer.autoClear = !0;
  52538. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
  52539. this.renderer.domElement.setAttribute('name','compass');
  52540. this.renderer.setClearAlpha(0.0);
  52541. this.renderer.setSize(width/2, height/2, false, window.devicePixelRatio ? window.devicePixelRatio : 1);
  52542. //this.emit(SceneRendererEvents.ContextCreated)
  52543. } catch (e) {
  52544. viewer.dispatchEvent('webglError', {msg:e});
  52545. }
  52546. this.dom.find(".center")[0].appendChild(this.renderer.domElement);
  52547. this.renderer.domElement.style.width = this.renderer.domElement.style.height = '100%';
  52548. this.camera = new PerspectiveCamera;
  52549. this.camera.fov = 50;
  52550. this.camera.updateProjectionMatrix();
  52551. this.scene = new Scene,
  52552. this.scene.add(this.camera);
  52553. this.createCompass();
  52554. viewer.addEventListener('camera_changed', e => {
  52555. if (e.viewport == this.viewport && (e.changeInfo.positionChanged || e.changeInfo.quaternionChanged)) {
  52556. this.update();
  52557. }
  52558. });
  52559. this.setDomPos();
  52560. if(this.viewport)this.setDisplay(true);
  52561. }
  52562. createCompass(){
  52563. //ConeBufferGeometry(radius : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)
  52564. const height = 2;
  52565. const geometry1 = new ConeBufferGeometry( 0.7, height, 4, true );
  52566. const geometry2 = new ConeBufferGeometry( 0.7, height, 4, true );
  52567. const material = new MeshBasicMaterial({
  52568. vertexColors :true
  52569. });
  52570. //指南针由两个四棱锥拼成,为了渐变颜色,采用指定vertexColor的方式。
  52571. var setColor = function(geometry, color1,color2){
  52572. const colors = [];
  52573. for ( let i = 0, n = geometry.attributes.position.count; i < n; ++ i ) {
  52574. colors.push( 1, 1, 1 );
  52575. }
  52576. var set = function(index, color){//设置第index个点的颜色
  52577. colors[index*3+0] = color[0];
  52578. colors[index*3+1] = color[1];
  52579. colors[index*3+2] = color[2];
  52580. };
  52581. var mid = [(color1[0]+color2[0])/2, (color1[1]+color2[1])/2, (color1[2]+color2[2])/2 ];
  52582. set(1,color1); set(5,color1);set(6,color1);
  52583. set(2,mid); set(3,mid);set(7,mid);
  52584. set(4,color2); set(8,color2);set(9,color2);
  52585. geometry.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
  52586. };
  52587. var blue1 = [1/255,238/255,245/255]; //逐渐变深
  52588. var blue2 = [20/255,146/255,170/255];
  52589. var blue3 = [40/255,60/255,103/255];
  52590. setColor(geometry1, blue1,blue2);
  52591. setColor(geometry2, blue2,blue3);
  52592. /* 朝箭头方向看点构成如下 虽然geometry.attributes.position.count = 19 只有1-9设置的颜色是有效的 另外为什么7决定了上下两边的颜色呢…… 5、9可将其分成上下两个颜色
  52593. 6
  52594. /|\
  52595. / | \
  52596. 7 /_2|1_\ 5
  52597. \ 3|4 / 9
  52598. \ | /
  52599. \|/
  52600. 8
  52601. */
  52602. const cone = new Mesh( geometry1, material );
  52603. cone.position.setY(height/2);
  52604. geometry1.computeVertexNormals();//computeFaceNormals
  52605. geometry2.computeVertexNormals();
  52606. const cones = new Object3D();
  52607. cones.add(cone);
  52608. let cone2 = new Mesh( geometry2, material );
  52609. cone2.rotation.x = Math.PI;
  52610. cone2.position.setY(-height/2);
  52611. cones.add(cone2);
  52612. //cones.rotation.x = Math.PI / 2;//转向initDir的方向
  52613. //cones.rotation.z = Math.PI / 2;
  52614. cones.rotation.z = Math.PI ;//转向initDir的方向
  52615. cones.scale.set(0.7,0.7,0.7);
  52616. this.scene.add(cones);
  52617. this.cones = cones;
  52618. }
  52619. setNorth(){ //设置北方向,这决定了指南针自身的朝向。
  52620. const floors = store.getters['scene/houstFloor'].floors;
  52621. if(!floors || !floors.length){
  52622. return
  52623. }
  52624. const floor = floors[0];
  52625. const metadata = app.store.getters['scene/metadata'] || {};
  52626. this.angle = (floor && floor.dire || 0) + MathUtils.radToDeg(parseFloat(metadata.floorPlanAngle || 0)); //基础朝向
  52627. this.cones.rotation.y = Math.PI / 2 - MathUtils.degToRad(this.angle);
  52628. //console.log("dir:"+floor.dire+", floorPlanAngle:"+metadata.floorPlanAngle)
  52629. this.update();
  52630. }
  52631. update(quaternion){
  52632. if(!this.show)return;
  52633. if(!quaternion) quaternion = this.viewport.camera.quaternion.clone();
  52634. this.updateCamera(quaternion);
  52635. this.updateLabel(quaternion);
  52636. this.render();
  52637. }
  52638. /*updateLabel(quaternion){//更新北标签
  52639. var dir = viewer.mainViewport.view.direction;
  52640. var oriDir = initDir.clone() //指南针最初始时的北方向
  52641. var extraQua
  52642. if(objects.player.mode == "transitioning"){//当transitioning时,相机的quaternion不是用control的lookAt算出来,而是直接由一个quaternion过渡到另一个,这样相机将会是歪的,投影面也就不会是原先的水平面。
  52643. var tempCamera = new THREE.Camera(); //借用camera的lookAt算出如果正视同样的target, quaternion会是什么值。 将它乘以当前相机quaternion,得到的就是相机歪的旋转值。
  52644. tempCamera.position.copy(this.camera.position);
  52645. tempCamera.lookAt(tempCamera.position.clone().add(dir))
  52646. var q = tempCamera.quaternion.inverse()
  52647. extraQua = q.premultiply(quaternion) //歪掉的额外旋转值
  52648. }
  52649. //北标签的方向为指南针轮盘方向,也就是要将camera的方向投影到水平面上。 但是如果相机歪了,看到的世界都会歪一定角度,投影面也要歪一定角度。
  52650. var up = new THREE.Vector3(0,0,1) //投影水平面的法线,也是相机的摆正的up方向
  52651. extraQua && up.applyQuaternion(extraQua)
  52652. dir.projectOnPlane(up) //将方向投影到水平面上; 如果相机不是正视(extraQua不为0001),就要将水平面也转动
  52653. oriDir.projectOnPlane(up)//为什么initDir投影了和没有投影angle结果一样
  52654. var angle = dir.angleTo(oriDir)
  52655. if(dir.cross(oriDir).y > 0)angle = -angle
  52656. var deg = this.angle - 90 + THREE.Math.radToDeg(angle) //因为css写的样式初始是指向右方,和initDir差了90°,所以减去。
  52657. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" )
  52658. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)")
  52659. } */
  52660. updateLabel(quaternion){//更新北标签
  52661. let deg = MathUtils.radToDeg(this.viewport.view.yaw) - 90;
  52662. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" );
  52663. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)");
  52664. }
  52665. updateCamera(quaternion){ //更新canvas中的指南针表现,也就是更新相机,和场景中的相机朝向一致。
  52666. const radius = 5; //相机距离
  52667. this.camera.quaternion.copy(quaternion);
  52668. var dir = this.viewport.view.direction; //相机朝向
  52669. this.camera.position.copy(dir.multiplyScalar(radius).negate()); //相机绕着指南针中心(000)转动
  52670. }
  52671. changeViewport(viewport){
  52672. this.viewport = viewport;
  52673. this.update(); //因相机更新了
  52674. }
  52675. render(){
  52676. this.renderer.render(this.scene, this.camera);
  52677. }
  52678. setDisplay(state){
  52679. this.show = !!state;
  52680. if(this.show){
  52681. this.update();
  52682. this.dom.fadeIn(100);
  52683. }else {
  52684. this.dom.fadeOut(100);
  52685. }
  52686. }
  52687. autoJudgeDisplay(){
  52688. }
  52689. setDomPos(){
  52690. if(!this.viewport)return
  52691. let right = this.viewport.left + this.viewport.width;
  52692. this.dom.css({'right':((1-right)*100 + 1) + '%'});
  52693. }
  52694. }
  52695. class PotreeRenderer {
  52696. constructor (viewer) {
  52697. this.viewer = viewer;
  52698. this.renderer = viewer.renderer;
  52699. {
  52700. let dummyScene = new Scene();
  52701. let geometry = new SphereGeometry(0.001, 2, 2);
  52702. let mesh = new Mesh(geometry, new MeshBasicMaterial());
  52703. mesh.position.set(36453, 35163, 764712);
  52704. dummyScene.add(mesh);
  52705. this.dummyMesh = mesh;
  52706. this.dummyScene = dummyScene;
  52707. }
  52708. }
  52709. clearTargets(params){//add
  52710. const viewer = this.viewer;
  52711. const {renderer} = viewer;
  52712. const oldTarget = renderer.getRenderTarget();
  52713. if(params.target){//add
  52714. renderer.setRenderTarget( params.target);
  52715. renderer.clear();
  52716. }
  52717. if(params.rtEDL){
  52718. renderer.setRenderTarget( params.rtEDL);
  52719. renderer.clear();
  52720. }else {
  52721. renderer.setRenderTarget( this.rtEDL );
  52722. renderer.clear( true, true, true );
  52723. }
  52724. /* renderer.setRenderTarget( this.rtRegular );
  52725. renderer.clear( true, true, false ); */
  52726. renderer.setRenderTarget(oldTarget);
  52727. }
  52728. clear(params={}){
  52729. let {viewer, renderer} = this;
  52730. // render skybox
  52731. if(viewer.background === "skybox"){
  52732. renderer.setClearColor(0xff0000, 1);
  52733. }else if(viewer.background === "gradient"){
  52734. renderer.setClearColor(0x00ff00, 1);
  52735. }else if(viewer.background === "black"){
  52736. renderer.setClearColor(0x000000, 1);
  52737. }else if(viewer.background === "white"){
  52738. renderer.setClearColor(0xFFFFFF, 1);
  52739. }else {
  52740. renderer.setClearColor(0x000000, 0);
  52741. }
  52742. params.target || renderer.clear();
  52743. renderer.clear();
  52744. this.clearTargets(params);
  52745. }
  52746. render(params={}){
  52747. let {viewer, renderer} = this;
  52748. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52749. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52750. const renderAreaSize = renderer.getSize(new Vector2$1());
  52751. const width = params.width ? params.width : params.viewport ? params.viewport[2] : renderAreaSize.x;
  52752. const height = params.height ? params.height : params.viewport ? params.viewport[3] : renderAreaSize.y;
  52753. // render skybox
  52754. if(viewer.background === "skybox"){
  52755. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  52756. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  52757. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  52758. viewer.skybox.parent.rotation.x = 0;
  52759. viewer.skybox.parent.updateMatrixWorld();
  52760. viewer.skybox.camera.updateProjectionMatrix();
  52761. renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  52762. }else if(viewer.background === "gradient"){
  52763. if(params.target){//add
  52764. renderer.setRenderTarget(params.target);
  52765. renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  52766. renderer.setRenderTarget(null);
  52767. }else {
  52768. renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  52769. }
  52770. }
  52771. for(let pointcloud of this.viewer.scene.pointclouds){
  52772. const {material} = pointcloud;
  52773. material.useEDL = false;
  52774. }
  52775. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.target || null, {
  52776. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof Potree.SphereVolume)),
  52777. });
  52778. // render scene
  52779. viewer.dispatchEvent({type: "render.pass.scene",viewer: viewer});
  52780. renderer.setRenderTarget(params.target ? params.target : null);//add
  52781. renderer.render(viewer.scene.scene, camera);
  52782. renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  52783. renderer.clearDepth();
  52784. viewer.transformationTool.update();
  52785. if(!params.target){
  52786. //测量线
  52787. viewer.dispatchEvent({type: "render.pass.perspective_overlay", viewer: viewer, camera});
  52788. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  52789. }
  52790. viewer.clippingTool.update();
  52791. renderer.render(viewer.clippingTool.sceneMarker, viewer.scene.cameraScreenSpace); //viewer.scene.cameraScreenSpace);
  52792. renderer.render(viewer.clippingTool.sceneVolume, camera);
  52793. renderer.render(viewer.controls.sceneControls, camera);
  52794. viewer.renderer.render(viewer.transformationTool.scene, camera);
  52795. //viewer.renderer.render(viewer.transformationTool.scene, camera);
  52796. // renderer.render(viewer.controls.sceneControls, camera);
  52797. // renderer.render(viewer.clippingTool.sceneVolume, camera);
  52798. // renderer.render(viewer.transformationTool.scene, camera);
  52799. // renderer.setViewport(width - viewer.navigationCube.width,
  52800. // height - viewer.navigationCube.width,
  52801. // viewer.navigationCube.width, viewer.navigationCube.width);
  52802. // renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  52803. // renderer.setViewport(0, 0, width, height);
  52804. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  52805. }
  52806. }
  52807. const copyShader = {
  52808. uniforms: {
  52809. tDiffuse: {
  52810. type: "t",
  52811. value: null
  52812. },
  52813. opacity: {
  52814. type: "f",
  52815. value: 1
  52816. }
  52817. },
  52818. vertexShader: `
  52819. varying vec2 vUv;
  52820. void main() {
  52821. vUv = uv;
  52822. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  52823. }
  52824. `,
  52825. fragmentShader: `
  52826. uniform float opacity;
  52827. uniform sampler2D tDiffuse;
  52828. varying vec2 vUv;
  52829. void main() {
  52830. vec4 texel = texture2D( tDiffuse, vUv );
  52831. gl_FragColor = opacity * texel;
  52832. }
  52833. `
  52834. };
  52835. class EDLRenderer{//Eye-Dome Lighting 眼罩照明
  52836. constructor(viewer){
  52837. this.viewer = viewer;
  52838. this.edlMaterial = null;
  52839. //this.rtRegular;
  52840. this.rtEDLs = new Map;
  52841. this.gl = viewer.renderer.getContext();
  52842. //反正也没用到,注释了:
  52843. //this.shadowMap = new PointCloudSM(this.viewer.pRenderer);
  52844. viewer.addEventListener('resize',this.resize.bind(this));
  52845. this.initEDL(viewer);
  52846. }
  52847. initEDL(viewer){
  52848. if (this.edlMaterial != null) {
  52849. return;
  52850. }
  52851. this.edlMaterial = new EyeDomeLightingMaterial();
  52852. this.edlMaterial.depthTest = true;
  52853. this.edlMaterial.depthWrite = true;
  52854. this.edlMaterial.transparent = true;
  52855. /* this.rtRegular = new THREE.WebGLRenderTarget(viewer.mainViewport.resolution2.x, viewer.mainViewport.resolution2.y, {
  52856. minFilter: THREE.NearestFilter,
  52857. magFilter: THREE.NearestFilter,
  52858. format: THREE.RGBAFormat,
  52859. depthTexture: new THREE.DepthTexture(undefined, undefined, THREE.UnsignedIntType)
  52860. });
  52861. */
  52862. /* let copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
  52863. this.copyMaterial = new THREE.ShaderMaterial( {
  52864. uniforms: copyUniforms,
  52865. vertexShader: copyShader.vertexShader,
  52866. fragmentShader: copyShader.fragmentShader,
  52867. //premultipliedAlpha: true,
  52868. transparent: true,
  52869. //blending: THREE.AdditiveBlending,
  52870. depthTest: false,
  52871. depthWrite: false
  52872. }); */
  52873. };
  52874. resize(e ){
  52875. if(Features.EXT_DEPTH.isSupported()){
  52876. let viewport = e.viewport;
  52877. this.getRtEDL(viewport).setSize(viewport.resolution2.x, viewport.resolution2.y);
  52878. }
  52879. }
  52880. clearTargets(params={}){
  52881. const viewer = this.viewer;
  52882. const {renderer} = viewer;
  52883. const oldTarget = renderer.getRenderTarget();
  52884. if(params.target){//add
  52885. renderer.setRenderTarget( params.target);
  52886. renderer.clear();
  52887. }
  52888. if(Features.EXT_DEPTH.isSupported()){
  52889. if(params.rtEDL){
  52890. renderer.setRenderTarget( params.rtEDL);
  52891. renderer.clear();
  52892. }else {
  52893. var rtEDL = this.getRtEDL(params.viewport);
  52894. if(rtEDL){
  52895. renderer.setRenderTarget( rtEDL );
  52896. renderer.clear( true, true, true );
  52897. }
  52898. }
  52899. }
  52900. //renderer.setRenderTarget( this.rtRegular );
  52901. //renderer.clear( true, true, false );
  52902. renderer.setRenderTarget(oldTarget);
  52903. }
  52904. getRtEDL(viewport){//根据不同viewport返回rtEDL的texture
  52905. if(!viewport){
  52906. console.warn('getRtEDL没传viewport!!!! !!!!!!!!!!');
  52907. viewport = viewer.mainViewport;
  52908. }
  52909. var rtEDL = this.rtEDLs.get(viewport);
  52910. if(!rtEDL){
  52911. if(Features.EXT_DEPTH.isSupported()){
  52912. rtEDL = new WebGLRenderTarget(viewport.resolution2.x, viewport.resolution2.y, {
  52913. minFilter: NearestFilter,
  52914. magFilter: NearestFilter,
  52915. format: RGBAFormat,
  52916. type: FloatType,
  52917. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  52918. });
  52919. //注: 部分手机在resize时会崩溃,经检验去掉rtEDL的resize可以解决,所以更应该注释掉这个
  52920. this.rtEDLs.set(viewport, rtEDL);
  52921. }
  52922. }
  52923. return rtEDL
  52924. }
  52925. renderShadowMap(visiblePointClouds, camera, lights){
  52926. const {viewer} = this;
  52927. const doShadows = lights.length > 0 && !(lights[0].disableShadowUpdates);
  52928. if(doShadows){
  52929. let light = lights[0];
  52930. this.shadowMap.setLight(light);
  52931. let originalAttributes = new Map();
  52932. for(let pointcloud of viewer.scene.pointclouds){
  52933. // TODO IMPORTANT !!! check
  52934. originalAttributes.set(pointcloud, pointcloud.material.activeAttributeName);
  52935. pointcloud.material.disableEvents();
  52936. pointcloud.material.activeAttributeName = "depth";
  52937. //pointcloud.material.pointColorType = PointColorType.DEPTH;
  52938. }
  52939. this.shadowMap.render(viewer.scene.scenePointCloud, camera);
  52940. for(let pointcloud of visiblePointClouds){
  52941. let originalAttribute = originalAttributes.get(pointcloud);
  52942. // TODO IMPORTANT !!! check
  52943. pointcloud.material.activeAttributeName = originalAttribute;
  52944. pointcloud.material.enableEvents();
  52945. }
  52946. viewer.shadowTestCam.updateMatrixWorld();
  52947. viewer.shadowTestCam.matrixWorldInverse.copy(viewer.shadowTestCam.matrixWorld).invert();
  52948. viewer.shadowTestCam.updateProjectionMatrix();
  52949. }
  52950. }
  52951. render(params={}){
  52952. /*
  52953. 渲染顺序:
  52954. 底层:背景 -> skybox(也可中间)
  52955. 中间层(含有深度信息):1 点云、marker等mesh,
  52956. 2 测量线(现在被做成借用depthTex
  52957. 顶层:maginifier
  52958. magnifier的贴图渲染不需要顶层、中间层只需要点云。
  52959. */
  52960. const viewer = this.viewer;
  52961. let camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52962. const resolution = params.viewport ? params.viewport.resolution2 : this.viewer.renderer.getSize(new Vector2$1());
  52963. //viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52964. let lights = [];
  52965. /* viewer.scene.scene.traverse(node => {
  52966. if(node.type === "SpotLight"){
  52967. lights.push(node);
  52968. }
  52969. }); */
  52970. viewer.renderer.setRenderTarget(params.target || null);
  52971. let background = params.background || viewer.background;
  52972. let backgroundOpacity = params.backgroundOpacity == void 0 ? viewer.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  52973. if(backgroundOpacity != 0){//绘制背景
  52974. if(background === "skybox"){
  52975. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  52976. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  52977. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  52978. viewer.skybox.parent.rotation.x = 0;
  52979. viewer.skybox.parent.updateMatrixWorld();
  52980. viewer.skybox.camera.updateProjectionMatrix();
  52981. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  52982. }else if(background === 'gradient'){
  52983. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  52984. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  52985. }else if(background === 'overlayColor'){//在不clear的前提下加一层背景色
  52986. viewer.scene.bg2.material.color.copy(params.backgroundColor);
  52987. viewer.scene.bg2.material.opacity = params.backgroundOpacity;
  52988. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg2);
  52989. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  52990. }
  52991. }
  52992. //skybox 全景图
  52993. if(!params.magnifier){
  52994. viewer.setCameraLayers(camera, ['skybox']);
  52995. let useDepthTex;
  52996. if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && Features.EXT_DEPTH.isSupported()){//渲染深度图
  52997. useDepthTex = true;
  52998. viewer.renderer.setRenderTarget(params.rtEDL || this.getRtEDL(params.viewport)); //将带有深度图的skybox画在rtEDL一下,这样就不需要绘制后边的点云了
  52999. viewer.renderer.render(viewer.scene.scene, camera);
  53000. viewer.renderer.setRenderTarget(params.target || null);
  53001. }
  53002. viewer.renderer.render(viewer.scene.scene, camera);
  53003. if(useDepthTex)return
  53004. }
  53005. const visiblePointClouds2 = viewer.scene.pointclouds.filter(pc => viewer.getObjVisiByReason(pc,'datasetSelection') ); //需要绘制到rtEDL的
  53006. const showPointClouds = params.magnifier ? visiblePointClouds2.length>0 : viewer.scene.pointclouds.some(e=>e.visible); //是否有需要绘制到屏幕的
  53007. visiblePointClouds2.forEach(e=>{//为了绘制到depthTexture,先显示(展示全景图时隐藏了点云,所以需要显示下。且放大镜需要绘制点云)
  53008. e.oldVisi = e.visible;
  53009. e.visible = true;
  53010. });
  53011. viewer.setCameraLayers(camera, ['pointcloud']);
  53012. camera.layers.set(Potree.config.renderLayers.pointcloud);
  53013. //TODO adapt to multiple lights
  53014. //this.renderShadowMap(visiblePointClouds2, camera, lights); //???????
  53015. {
  53016. for (let pointcloud of visiblePointClouds2) {
  53017. let material = pointcloud.material;
  53018. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  53019. material.fov = MathUtils.degToRad(camera.fov);
  53020. /* material.screenWidth = width;
  53021. material.screenHeight = height; */
  53022. material.resolution = resolution;
  53023. material.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  53024. material.near = camera.near;
  53025. material.far = camera.far;
  53026. material.uniforms.octreeSize.value = octreeSize;
  53027. if(viewer.useEDL && Potree.settings.displayMode != 'showPanos'){
  53028. /* material.weighted = false;
  53029. material.useLogarithmicDepthBuffer = false; */
  53030. material.useEDL = true;
  53031. //material.fakeEDL = false; //add
  53032. }else {
  53033. material.useEDL = false;
  53034. //material.fakeEDL = true; //add 使也输出深度
  53035. }
  53036. }
  53037. if(Features.EXT_DEPTH.isSupported() && !params.dontRenderRtEDL){
  53038. //借用rtEDL存储深度信息
  53039. viewer.renderer.setRenderTarget(params.rtEDL || this.getRtEDL(params.viewport)/* this.rtEDL */);
  53040. if(visiblePointClouds2.length>0){
  53041. //渲染scenePointCloud到rtEDL
  53042. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.rtEDL || this.getRtEDL(params.viewport), {
  53043. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  53044. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53045. transparent: false,
  53046. });
  53047. }
  53048. if(Potree.settings.intersectOnObjs){// model也要渲染到rtEDL
  53049. camera.layers.set(Potree.config.renderLayers.model);
  53050. viewer.objs.traverse(e=>{if(e.material)e._OlddepthWrite = e.material.depthWrite, e.material.depthWrite = true;}); //否则半透明的mesh无法遮住测量线
  53051. viewer.renderer.render(viewer.scene.scene, camera);
  53052. viewer.objs.traverse(e=>{if(e.material)e.material.depthWrite = e._OlddepthWrite;});
  53053. //缺点:半透明的model 就算完全透明, 也会遮住测量线
  53054. }
  53055. //test
  53056. /* {
  53057. viewer.objs.traverse((obj)=>{
  53058. if(obj.material){
  53059. obj.material = obj.depthMat
  53060. }
  53061. })
  53062. viewer.setCameraLayers(camera, ['sceneObjects'])
  53063. viewer.renderer.render(viewer.scene.scene, camera)
  53064. viewer.objs.traverse((obj)=>{
  53065. if(obj.material){
  53066. obj.material = obj.standardMat
  53067. }
  53068. })
  53069. } */
  53070. }
  53071. }
  53072. //渲染到rtEDL完毕
  53073. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer/* , renderTarget: this.rtRegular */});
  53074. viewer.renderer.setRenderTarget(params.target || null);
  53075. if(!params.magnifier)visiblePointClouds2.forEach(e=>{//放大镜显示点云
  53076. e.visible = e.oldVisi;
  53077. });
  53078. if(showPointClouds){ //绘制点云到画布
  53079. if(viewer.useEDL) { //设置edlMaterial
  53080. //Features.EXT_DEPTH不支持的话不会到这一块
  53081. const uniforms = this.edlMaterial.uniforms;
  53082. //if(viewer.useEDL){
  53083. /* uniforms.screenWidth.value = width;
  53084. uniforms.screenHeight.value = height; */
  53085. uniforms.resolution.value.copy(resolution);
  53086. uniforms.edlStrength.value = viewer.edlStrength;
  53087. uniforms.radius.value = viewer.edlRadius;
  53088. uniforms.useEDL.value = 1;//add
  53089. /* }else{
  53090. uniforms.useEDL.value = 0;//add
  53091. } */
  53092. let proj = camera.projectionMatrix;
  53093. let projArray = new Float32Array(16);
  53094. projArray.set(proj.elements);
  53095. uniforms.uProj.value = projArray;
  53096. uniforms.uEDLColor.value = (params.rtEDL || this.getRtEDL(params.viewport)).texture;
  53097. //uniforms.uEDLDepth.value = (params.rtEDL || this.getRtEDL(params.viewport)).depthTexture; //其实没用到
  53098. uniforms.opacity.value = viewer.edlOpacity; // HACK
  53099. Utils.screenPass.render(viewer.renderer, this.edlMaterial, params.target);
  53100. }else {
  53101. //渲染点云 (直接用rtEDL上的会失去抗锯齿)
  53102. let prop = {
  53103. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  53104. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)) ,
  53105. notAdditiveBlending: Potree.settings.notAdditiveBlending//add 否则透明的点云会挡住后面的模型。 加上这句后竟然透明不会叠加了!
  53106. };
  53107. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, null , prop);
  53108. }
  53109. }
  53110. //viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  53111. visiblePointClouds2.forEach(e=>{
  53112. e.visible = e.oldVisi;
  53113. });
  53114. }
  53115. }
  53116. class HQSplatRenderer{
  53117. //rtAttribute 估计需要给magnifer复制一份
  53118. constructor(viewer){
  53119. this.viewer = viewer;
  53120. this.depthMaterials = new Map();
  53121. this.attributeMaterials = new Map();
  53122. this.normalizationMaterial = null;
  53123. this.rtDepth = null;
  53124. this.rtAttribute = null;
  53125. this.gl = viewer.renderer.getContext();
  53126. this.initialized = false;
  53127. viewer.addEventListener('resize',this.resize.bind(this));
  53128. }
  53129. init(){
  53130. if (this.initialized) {
  53131. return;
  53132. }
  53133. this.normalizationMaterial = new NormalizationMaterial();
  53134. this.normalizationMaterial.depthTest = true;
  53135. this.normalizationMaterial.depthWrite = true;
  53136. this.normalizationMaterial.transparent = true;
  53137. this.normalizationEDLMaterial = new NormalizationEDLMaterial();
  53138. this.normalizationEDLMaterial.depthTest = true;
  53139. this.normalizationEDLMaterial.depthWrite = true;
  53140. this.normalizationEDLMaterial.transparent = true;
  53141. this.rtDepth = new WebGLRenderTarget(1024, 1024, {
  53142. minFilter: NearestFilter,
  53143. magFilter: NearestFilter,
  53144. format: RGBAFormat,
  53145. type: FloatType,
  53146. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  53147. });
  53148. this.rtAttribute = new WebGLRenderTarget(1024, 1024, {
  53149. minFilter: NearestFilter,
  53150. magFilter: NearestFilter,
  53151. format: RGBAFormat,
  53152. type: FloatType,
  53153. depthTexture: this.rtDepth.depthTexture,
  53154. });
  53155. this.initialized = true;
  53156. };
  53157. resize(e/* width, height */){
  53158. this.rtDepth.setSize(e.canvasWidth, e.canvasHeight);
  53159. this.rtAttribute.setSize(e.canvasWidth, e.canvasHeight);
  53160. }
  53161. clearTargets(params){
  53162. const viewer = this.viewer;
  53163. const {renderer} = viewer;
  53164. const oldTarget = renderer.getRenderTarget();
  53165. if(params.target){//add
  53166. renderer.setRenderTarget( params.target);
  53167. renderer.clear();
  53168. }
  53169. renderer.setClearColor(0x000000, 0);
  53170. renderer.setRenderTarget( this.rtDepth );
  53171. renderer.clear( true, true, true );
  53172. renderer.setRenderTarget( this.rtAttribute );
  53173. renderer.clear( true, true, true );
  53174. renderer.setRenderTarget(oldTarget);
  53175. }
  53176. clear(params={}){
  53177. this.init();
  53178. const {renderer, background} = this.viewer;
  53179. if(background === "skybox"){
  53180. renderer.setClearColor(0x000000, 0);
  53181. } else if (background === 'gradient') {
  53182. renderer.setClearColor(0x000000, 0);
  53183. } else if (background === 'black') {
  53184. renderer.setClearColor(0x000000, 1);
  53185. } else if (background === 'white') {
  53186. renderer.setClearColor(0xFFFFFF, 1);
  53187. } else {
  53188. renderer.setClearColor(0x000000, 0);
  53189. }
  53190. params.target || renderer.clear();
  53191. this.clearTargets(params);
  53192. }
  53193. render(params={}) {
  53194. this.init();
  53195. const viewer = this.viewer;
  53196. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  53197. const {width, height} = params.width ? params : this.viewer.renderer.getSize(new Vector2$1());
  53198. viewer.renderer.setRenderTarget(params.target||null);
  53199. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  53200. //params.target || this.resize(width, height);
  53201. const visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  53202. const originalMaterials = new Map();
  53203. for(let pointcloud of visiblePointClouds){
  53204. originalMaterials.set(pointcloud, pointcloud.material);
  53205. if(!this.attributeMaterials.has(pointcloud)){
  53206. let attributeMaterial = new PointCloudMaterial$1();
  53207. this.attributeMaterials.set(pointcloud, attributeMaterial);
  53208. }
  53209. if(!this.depthMaterials.has(pointcloud)){
  53210. let depthMaterial = new PointCloudMaterial$1();
  53211. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  53212. depthMaterial.setDefine("use_edl", "#define use_edl");
  53213. this.depthMaterials.set(pointcloud, depthMaterial);
  53214. }
  53215. }
  53216. { // DEPTH PASS
  53217. for (let pointcloud of visiblePointClouds) {
  53218. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  53219. let material = originalMaterials.get(pointcloud);
  53220. let depthMaterial = this.depthMaterials.get(pointcloud);
  53221. depthMaterial.size = material.size;
  53222. depthMaterial.minSize = material.minSize;
  53223. depthMaterial.maxSize = material.maxSize;
  53224. depthMaterial.pointSizeType = material.pointSizeType;
  53225. depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  53226. depthMaterial.weighted = false;
  53227. depthMaterial.screenWidth = width;
  53228. depthMaterial.shape = PointShape.CIRCLE;
  53229. depthMaterial.screenHeight = height;
  53230. depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  53231. depthMaterial.uniforms.octreeSize.value = octreeSize;
  53232. depthMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  53233. depthMaterial.classification = material.classification;
  53234. depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  53235. depthMaterial.classificationTexture.needsUpdate = true;
  53236. depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  53237. depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  53238. depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  53239. depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  53240. depthMaterial.clipTask = material.clipTask;
  53241. depthMaterial.clipMethod = material.clipMethod;
  53242. depthMaterial.setClipBoxes(material.clipBoxes);
  53243. depthMaterial.setClipPolygons(material.clipPolygons);
  53244. pointcloud.material = depthMaterial;
  53245. }
  53246. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, (params.rtEDL || this.rtDepth), {
  53247. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53248. });
  53249. }
  53250. { // ATTRIBUTE PASS
  53251. for (let pointcloud of visiblePointClouds) {
  53252. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  53253. let material = originalMaterials.get(pointcloud);
  53254. let attributeMaterial = this.attributeMaterials.get(pointcloud);
  53255. attributeMaterial.size = material.size;
  53256. attributeMaterial.minSize = material.minSize;
  53257. attributeMaterial.maxSize = material.maxSize;
  53258. attributeMaterial.pointSizeType = material.pointSizeType;
  53259. attributeMaterial.activeAttributeName = material.activeAttributeName;
  53260. attributeMaterial.visibleNodesTexture = material.visibleNodesTexture;
  53261. attributeMaterial.weighted = true;
  53262. attributeMaterial.screenWidth = width;
  53263. attributeMaterial.screenHeight = height;
  53264. attributeMaterial.shape = PointShape.CIRCLE;
  53265. attributeMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  53266. attributeMaterial.uniforms.octreeSize.value = octreeSize;
  53267. attributeMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  53268. attributeMaterial.classification = material.classification;
  53269. attributeMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  53270. attributeMaterial.classificationTexture.needsUpdate = true;
  53271. attributeMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  53272. attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  53273. attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  53274. attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  53275. attributeMaterial.elevationGradientRepeat = material.elevationGradientRepeat;
  53276. attributeMaterial.elevationRange = material.elevationRange;
  53277. attributeMaterial.gradient = material.gradient;
  53278. attributeMaterial.matcap = material.matcap;
  53279. attributeMaterial.intensityRange = material.intensityRange;
  53280. attributeMaterial.intensityGamma = material.intensityGamma;
  53281. attributeMaterial.intensityContrast = material.intensityContrast;
  53282. attributeMaterial.intensityBrightness = material.intensityBrightness;
  53283. attributeMaterial.rgbGamma = material.rgbGamma;
  53284. attributeMaterial.rgbContrast = material.rgbContrast;
  53285. attributeMaterial.rgbBrightness = material.rgbBrightness;
  53286. attributeMaterial.weightRGB = material.weightRGB;
  53287. attributeMaterial.weightIntensity = material.weightIntensity;
  53288. attributeMaterial.weightElevation = material.weightElevation;
  53289. attributeMaterial.weightRGB = material.weightRGB;
  53290. attributeMaterial.weightClassification = material.weightClassification;
  53291. attributeMaterial.weightReturnNumber = material.weightReturnNumber;
  53292. attributeMaterial.weightSourceID = material.weightSourceID;
  53293. attributeMaterial.color = material.color;
  53294. attributeMaterial.clipTask = material.clipTask;
  53295. attributeMaterial.clipMethod = material.clipMethod;
  53296. attributeMaterial.setClipBoxes(material.clipBoxes);
  53297. attributeMaterial.setClipPolygons(material.clipPolygons);
  53298. pointcloud.material = attributeMaterial;
  53299. }
  53300. let gl = this.gl;
  53301. //viewer.renderer.setRenderTarget(null);
  53302. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  53303. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53304. //material: this.attributeMaterial,
  53305. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  53306. //depthTest: false,
  53307. depthWrite: false
  53308. });
  53309. }
  53310. for(let [pointcloud, material] of originalMaterials){
  53311. pointcloud.material = material;
  53312. }
  53313. if(viewer.background === "skybox"){
  53314. viewer.renderer.setClearColor(0x000000, 0);
  53315. viewer.renderer.clear();
  53316. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  53317. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  53318. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  53319. viewer.skybox.parent.rotation.x = 0;
  53320. viewer.skybox.parent.updateMatrixWorld();
  53321. viewer.skybox.camera.updateProjectionMatrix();
  53322. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  53323. } else if (viewer.background === 'gradient') {
  53324. viewer.renderer.setClearColor(0x000000, 0);
  53325. viewer.renderer.clear();
  53326. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  53327. } else if (viewer.background === 'black') {
  53328. viewer.renderer.setClearColor(0x000000, 1);
  53329. viewer.renderer.clear();
  53330. } else if (viewer.background === 'white') {
  53331. viewer.renderer.setClearColor(0xFFFFFF, 1);
  53332. viewer.renderer.clear();
  53333. } else {
  53334. viewer.renderer.setClearColor(0x000000, 0);
  53335. viewer.renderer.clear();
  53336. }
  53337. { // NORMALIZATION PASS
  53338. let normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  53339. if(this.useEDL){
  53340. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  53341. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  53342. normalizationMaterial.uniforms.screenWidth.value = width;
  53343. normalizationMaterial.uniforms.screenHeight.value = height;
  53344. normalizationMaterial.uniforms.uEDLMap.value = (params.rtEDL || this.rtDepth).texture;
  53345. }
  53346. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  53347. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  53348. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  53349. }
  53350. viewer.renderer.render(viewer.scene.scene, camera);
  53351. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  53352. viewer.renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  53353. viewer.renderer.clearDepth();
  53354. viewer.transformationTool.update();
  53355. if(!params.target){
  53356. //测量线
  53357. viewer.dispatchEvent({type: "render.pass.perspective_overlay",viewer: viewer, camera});
  53358. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  53359. }
  53360. viewer.renderer.render(viewer.controls.sceneControls, camera);
  53361. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  53362. viewer.renderer.render(viewer.transformationTool.scene, camera);
  53363. viewer.renderer.setViewport(width - viewer.navigationCube.width,
  53364. height - viewer.navigationCube.width,
  53365. viewer.navigationCube.width, viewer.navigationCube.width);
  53366. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  53367. viewer.renderer.setViewport(0, 0, width, height);
  53368. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  53369. viewer.renderer.setRenderTarget(null);
  53370. }
  53371. }
  53372. let sid = 0;
  53373. class View extends EventDispatcher{
  53374. constructor () {
  53375. super();
  53376. this.position = new Vector3(0, 0, 0);
  53377. this.yaw = 0;//Math.PI / 4; // = 4dkk lon + 90
  53378. this._pitch = 0;//-Math.PI / 4; //上下旋转 = 4dkk lat
  53379. this.radius = 1;
  53380. this.maxPitch = Math.PI / 2;
  53381. this.minPitch = -Math.PI / 2;
  53382. this.sid = sid++;
  53383. this.LookTransition = 'LookTransition'+this.sid;
  53384. }
  53385. //add------
  53386. applyToCamera(camera){
  53387. camera.position.copy(this.position);
  53388. camera.rotation.copy(this.rotation);
  53389. camera.updateMatrix();
  53390. camera.updateMatrixWorld();
  53391. //camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  53392. }
  53393. get rotation(){
  53394. var rotation = new Euler;
  53395. rotation.order = "ZXY";
  53396. rotation.x = Math.PI / 2 + this.pitch;
  53397. rotation.z = this.yaw;
  53398. return rotation
  53399. }
  53400. set rotation(rotation){
  53401. //因为 rotation的y不一定是0 , 所以不能直接逆着写。
  53402. this.direction = new Vector3(0,0,-1).applyEuler(rotation);
  53403. }
  53404. copy(a){
  53405. Common.CopyClassObject(this, a);
  53406. }
  53407. clone () {
  53408. /* let c = new View();
  53409. c.yaw = this.yaw;
  53410. c._pitch = this.pitch;
  53411. c.radius = this.radius;
  53412. c.maxPitch = this.maxPitch;
  53413. c.minPitch = this.minPitch;
  53414. return c; */
  53415. return Common.CloneClassObject(this)
  53416. }
  53417. //----------
  53418. get pitch () {
  53419. return this._pitch;
  53420. }
  53421. set pitch (angle) {
  53422. this._pitch = Math.max(Math.min(angle, this.maxPitch), this.minPitch);
  53423. }
  53424. get direction () {
  53425. let dir = new Vector3(0, 1, 0);
  53426. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  53427. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  53428. return dir;
  53429. }
  53430. set direction (dir) {
  53431. //if(dir.x === dir.y){
  53432. if(dir.x === 0 && dir.y === 0){
  53433. this.pitch = Math.PI / 2 * Math.sign(dir.z);
  53434. }else {
  53435. let yaw = Math.atan2(dir.y, dir.x) - Math.PI / 2;
  53436. let pitch = Math.atan2(dir.z, Math.sqrt(dir.x * dir.x + dir.y * dir.y));
  53437. this.yaw = yaw;
  53438. this.pitch = pitch;
  53439. }
  53440. }
  53441. lookAt(t){//setPivot
  53442. let V;
  53443. if(arguments.length === 1){
  53444. V = new Vector3().subVectors(t, this.position);
  53445. }else if(arguments.length === 3){
  53446. V = new Vector3().subVectors(new Vector3(...arguments), this.position);
  53447. }
  53448. let radius = V.length();
  53449. let dir = V.normalize();
  53450. this.radius = radius;
  53451. this.direction = dir;
  53452. }
  53453. getPivot () {
  53454. return new Vector3().addVectors(this.position, this.direction.multiplyScalar(this.radius));
  53455. }
  53456. getSide () {
  53457. let side = new Vector3(1, 0, 0);
  53458. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  53459. return side;
  53460. }
  53461. /* pan (x, y) {
  53462. let dir = new THREE.Vector3(0, 1, 0);
  53463. dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), this.pitch);
  53464. dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  53465. // let side = new THREE.Vector3(1, 0, 0);
  53466. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  53467. let side = this.getSide();
  53468. let up = side.clone().cross(dir);
  53469. let pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  53470. this.position = this.position.add(pan);
  53471. // this.target = this.target.add(pan);
  53472. } */
  53473. pan (x, y) { //发现pan其实就是translate
  53474. this.translate(x, 0, y);
  53475. }
  53476. translate (x, y, z, forceHorizon ) {
  53477. //相机方向
  53478. let dir = new Vector3(0, 1, 0);
  53479. dir.applyAxisAngle(new Vector3(1, 0, 0), forceHorizon ? 0 : this.pitch); //上下角度
  53480. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);//水平角度
  53481. let side = new Vector3(1, 0, 0);
  53482. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //垂直于相机当前水平朝向的 左右方向
  53483. let up = side.clone().cross(dir); //垂直于相机当前水平朝向的 向上方向
  53484. let t = side.multiplyScalar(x) //x影响 左右分量
  53485. .add(dir.multiplyScalar(y)) //y影响 前后分量
  53486. .add(up.multiplyScalar(z)); //z影响 上下分量
  53487. this.position = this.position.add(t);
  53488. this.restrictPos();
  53489. }
  53490. translateWorld (x, y, z) {
  53491. this.position.x += x;
  53492. this.position.y += y;
  53493. this.position.z += z;
  53494. this.restrictPos();
  53495. }
  53496. restrictPos(){//add
  53497. if(this.limitBound){
  53498. this.position.clamp(this.limitBound.min, this.limitBound.max);
  53499. }
  53500. }
  53501. setCubeView(dir) {
  53502. switch(dir) {
  53503. case "front":
  53504. this.yaw = 0;
  53505. this.pitch = 0;
  53506. break;
  53507. case "back":
  53508. this.yaw = Math.PI;
  53509. this.pitch = 0;
  53510. break;
  53511. case "left":
  53512. this.yaw = -Math.PI / 2;
  53513. this.pitch = 0;
  53514. break;
  53515. case "right":
  53516. this.yaw = Math.PI / 2;
  53517. this.pitch = 0;
  53518. break;
  53519. case "top":
  53520. this.yaw = 0;
  53521. this.pitch = -Math.PI / 2;
  53522. break;
  53523. case "bottom":
  53524. this.yaw = -Math.PI;
  53525. this.pitch = Math.PI / 2;
  53526. break;
  53527. }
  53528. }
  53529. isFlying(){
  53530. return transitions.getById(this.LookTransition).length > 0
  53531. }
  53532. cancelFlying(){//外界只能通过这个来cancel
  53533. transitions.cancelById(this.LookTransition, true );
  53534. }
  53535. setView( info = {}){
  53536. // position, target, duration = 0, callback = null, onUpdate = null, Easing='', cancelFun
  53537. this.cancelFlying();
  53538. let done = ()=>{
  53539. if(endTarget){
  53540. this.lookAt(endTarget); //compute radius for orbitcontrol
  53541. }else if(endQuaternion){
  53542. this.rotation = new Euler().setFromQuaternion(endQuaternion);
  53543. }
  53544. let f = ()=>{
  53545. info.callback && info.callback();
  53546. this.dispatchEvent('flyingDone');
  53547. };
  53548. if(info.duration){
  53549. setTimeout(f,1);//延迟是为了使isFlying先为false
  53550. }else {
  53551. f(); //有的需要迅速执行回调
  53552. }
  53553. };
  53554. let endPosition = new Vector3().copy(info.position);
  53555. let startPosition = this.position.clone();
  53556. let startQuaternion, endQuaternion, endTarget = null ;
  53557. if(info.target ){
  53558. endTarget = new Vector3().copy(info.target);
  53559. endQuaternion = math.getQuaFromPosAim(endPosition,endTarget);
  53560. }else if(info.quaternion){
  53561. endQuaternion = info.quaternion.clone();
  53562. }
  53563. if(endQuaternion){
  53564. startQuaternion = new Quaternion().setFromEuler(this.rotation);
  53565. /* const startTarget = this.getPivot();
  53566. let startQuaternion = math.getQuaFromPosAim(startPosition,startTarget) */
  53567. }
  53568. if(!info.duration){
  53569. this.position.copy(endPosition);
  53570. this.restrictPos();
  53571. info.onUpdate && info.onUpdate(1);
  53572. done();
  53573. }else {
  53574. transitions.start(lerp.vector(this.position, endPosition, (pos, progress)=>{
  53575. let t = progress;
  53576. if(endQuaternion){
  53577. let quaternion = (new Quaternion()).copy(startQuaternion);
  53578. lerp.quaternion(quaternion, endQuaternion)(progress),
  53579. this.rotation = new Euler().setFromQuaternion(quaternion);
  53580. }
  53581. this.restrictPos();
  53582. info.onUpdate && info.onUpdate(t);//add
  53583. }), info.duration, done, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine /*easeInOutQuad */,null, this.LookTransition, info.cancelFun);
  53584. }
  53585. }
  53586. //平移Ortho相机
  53587. moveOrthoCamera(viewport, info, duration, easeName){//boundSize优先于endZoom。
  53588. let camera = viewport.camera;
  53589. let startZoom = camera.zoom;
  53590. let endPosition = info.endPosition;
  53591. let boundSize = info.boundSize;
  53592. let endZoom = info.endZoom;
  53593. let margin = info.margin || {x:0,y:0};/* 200 */ //像素
  53594. if(info.bound){//需要修改boundSize以适应相机的旋转,当相机不在xy水平面上朝向z时
  53595. endPosition = endPosition || info.bound.getCenter(new Vector3());
  53596. let matrixRot = new Matrix4().makeRotationFromEuler(this.rotation).invert();
  53597. let boundingBox = info.bound.clone().applyMatrix4(matrixRot);
  53598. boundSize = boundingBox.getSize(new Vector3());
  53599. }
  53600. if(boundSize && boundSize.x == 0 && boundSize.y == 0){
  53601. boundSize.set(1,1); //避免infinity
  53602. }
  53603. this.setView({ position:endPosition, duration,
  53604. callback:()=>{//done
  53605. },
  53606. onUpdate:(progress)=>{
  53607. if(boundSize || endZoom){
  53608. if(boundSize){
  53609. let aspect = boundSize.x / boundSize.y;
  53610. let w, h;
  53611. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  53612. h = boundSize.y;
  53613. endZoom = (viewport.resolution.y - margin.y) / h; //注意,要在resolution不为0时执行
  53614. }else {
  53615. w = boundSize.x;
  53616. endZoom = (viewport.resolution.x - margin.x) / w;
  53617. }
  53618. //onUpdate时更新endzoom是因为画布大小可能更改
  53619. }
  53620. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  53621. camera.updateProjectionMatrix();
  53622. }
  53623. },
  53624. Easing:easeName
  53625. });
  53626. }
  53627. zoomOrthoCamera(camera, endZoom, pointer, duration, onProgress){//定点缩放
  53628. let startZoom = camera.zoom;
  53629. let pointerPos = new Vector3(pointer.x, pointer.y,0.5);
  53630. transitions.start(( progress)=>{
  53631. let oldPos = pointerPos.clone().unproject(camera);
  53632. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  53633. camera.updateProjectionMatrix();
  53634. let newPos = pointerPos.clone().unproject(camera);
  53635. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  53636. let moveVec = new Vector3().subVectors(newPos, oldPos);
  53637. camera.position.sub(moveVec);
  53638. this.position.copy(camera.position);
  53639. onProgress && onProgress();
  53640. } , duration, null/* done */, 0, easing.easeInOutSine, null, "zoomInView"/* , info.cancelFun */);
  53641. }
  53642. };
  53643. /*
  53644. z
  53645. |
  53646. |
  53647. |
  53648. |
  53649. x <-------| 中心为点云position加boudingbox中心
  53650. /
  53651. /
  53652. y
  53653. */
  53654. var lineLen$1 = 2, stemLen = 4, arrowLen = 2, lineDisToStem = 5;
  53655. var opacity = 0.5;
  53656. class Axis extends Object3D {// 坐标轴
  53657. constructor (position) {
  53658. super();
  53659. this.getArrow();
  53660. this.createArrows();
  53661. //this.position.copy(position) 点云的中心点就是在(0,0,0)
  53662. //this.scale.set(2,2,2)
  53663. }
  53664. getArrow(){
  53665. var arrowGroup = new Object3D();
  53666. var line = LineDraw.createLine([new Vector3, new Vector3(0,0,lineLen$1)]);
  53667. var stem = new Mesh(new BoxGeometry(0.3, 0.3, stemLen));
  53668. stem.position.set(0,0,lineLen$1+lineDisToStem+stemLen/2);
  53669. 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
  53670. arrow.position.set(0,0,lineLen$1+lineDisToStem+stemLen + arrowLen/2);
  53671. arrow.rotation.set(Math.PI/2,0,0);
  53672. arrowGroup.add(stem);
  53673. arrowGroup.add(line);
  53674. arrowGroup.add(arrow);
  53675. this.arrowGroup = arrowGroup;
  53676. }
  53677. createArrows(){
  53678. var material = new MeshBasicMaterial({color:"#00d7df",side:2,transparent:true,opacity:0.8, depthWrite:false});
  53679. let axis = Object.keys(Potree.config.axis);
  53680. axis.forEach((axisText)=>{
  53681. let color = Potree.config.axis[axisText].color;
  53682. var group = this.arrowGroup.clone();
  53683. group.children.forEach(e=>{
  53684. e.material = e.material.clone();
  53685. /* e.material.opacity = opacity
  53686. e.material.transparent = true */
  53687. e.material.color.set(color);
  53688. });
  53689. var label = this.createLabel(axisText, color);
  53690. label.position.set(0, 0, lineLen$1 + stemLen + arrowLen + lineDisToStem + 3);
  53691. group.add(label);
  53692. if(axisText == 'y'){
  53693. group.rotation.x = -Math.PI / 2;
  53694. }else if(axisText == 'x'){
  53695. group.rotation.y = Math.PI / 2;
  53696. }
  53697. this.add(group);
  53698. });
  53699. }
  53700. createLabel(text,color){
  53701. var canvas = document.createElement("canvas");
  53702. var context = canvas.getContext("2d");
  53703. canvas.width = 256,
  53704. canvas.height = 256;
  53705. var fontSize = 120;
  53706. context.fillStyle = color; //"#00ffee";
  53707. context.font = "normal " + fontSize + "px 微软雅黑";
  53708. var textWidth = context.measureText(text).width;
  53709. context.clearRect(0,0,canvas.width,canvas.height);
  53710. context.fillText(text, (canvas.width - textWidth) / 2 , (canvas.height + fontSize) / 2);
  53711. var tex = new Texture(canvas);
  53712. tex.needsUpdate = true;
  53713. tex.minFilter = NearestFilter;//防止边缘发黑
  53714. tex.magFilter = NearestFilter;//防止边缘发黑
  53715. var sprite = new Sprite(new SpriteMaterial({
  53716. map: tex , // depthWrite:false,
  53717. }));
  53718. sprite.renderOrder = 1;//防止在透明后还是出现白矩形挡住其他mesh
  53719. sprite.scale.set(3,3,3);
  53720. return sprite
  53721. }
  53722. }
  53723. class Scene$1 extends EventDispatcher{
  53724. constructor(){
  53725. super();
  53726. this.annotations = new Annotation();
  53727. this.scene = new Scene();
  53728. //this.sceneBG = new THREE.Scene(); //用来放skybox
  53729. //this.sceneOverlay = new THREE.Scene();
  53730. this.scenePointCloud = new Scene();
  53731. this.cameraP = new PerspectiveCamera(this.fov, 1, Potree.config.view.near, Potree.config.view.near);
  53732. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  53733. this.cameraP.limitFar = true;//add
  53734. this.cameraVR = new PerspectiveCamera();
  53735. this.cameraBG = new Camera();
  53736. this.cameraScreenSpace = new OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
  53737. this.cameraMode = CameraMode.PERSPECTIVE;
  53738. this.overrideCamera = null;
  53739. this.pointclouds = [];
  53740. this.measurements = [];
  53741. this.profiles = [];
  53742. this.volumes = [];
  53743. this.polygonClipVolumes = [];
  53744. this.cameraAnimations = [];
  53745. this.orientedImages = [];
  53746. this.images360 = [];
  53747. this.geopackages = [];
  53748. this.fpControls = null;
  53749. this.orbitControls = null;
  53750. this.earthControls = null;
  53751. this.geoControls = null;
  53752. this.deviceControls = null;
  53753. this.inputHandler = null;
  53754. this.view = new View();
  53755. this.directionalLight = null;
  53756. this.initialize();
  53757. //-------------
  53758. this.axisArrow = new Axis();
  53759. this.scene.add(this.axisArrow);
  53760. if(!Potree.settings.isDebug)this.axisArrow.visible = false;
  53761. viewer.setObjectLayers(this.axisArrow, 'bothMapAndScene' );
  53762. this.tags = new Object3D;
  53763. this.scene.add(this.tags);
  53764. }
  53765. estimateHeightAt (position) {
  53766. let height = null;
  53767. let fromSpacing = Infinity;
  53768. for (let pointcloud of this.pointclouds) {
  53769. if (pointcloud.root.geometryNode === undefined) {
  53770. continue;
  53771. }
  53772. let pHeight = null;
  53773. let pFromSpacing = Infinity;
  53774. let lpos = position.clone().sub(pointcloud.position);
  53775. lpos.z = 0;
  53776. let ray = new Ray(lpos, new Vector3(0, 0, 1));
  53777. let stack = [pointcloud.root];
  53778. while (stack.length > 0) {
  53779. let node = stack.pop();
  53780. let box = node.getBoundingBox();
  53781. let inside = ray.intersectBox(box);
  53782. if (!inside) {
  53783. continue;
  53784. }
  53785. let h = node.geometryNode.mean.z +
  53786. pointcloud.position.z +
  53787. node.geometryNode.boundingBox.min.z;
  53788. if (node.geometryNode.spacing <= pFromSpacing) {
  53789. pHeight = h;
  53790. pFromSpacing = node.geometryNode.spacing;
  53791. }
  53792. for (let index of Object.keys(node.children)) {
  53793. let child = node.children[index];
  53794. if (child.geometryNode) {
  53795. stack.push(node.children[index]);
  53796. }
  53797. }
  53798. }
  53799. if (height === null || pFromSpacing < fromSpacing) {
  53800. height = pHeight;
  53801. fromSpacing = pFromSpacing;
  53802. }
  53803. }
  53804. return height;
  53805. }
  53806. getBoundingBox(pointclouds = this.pointclouds){
  53807. let box = new Box3();
  53808. this.scenePointCloud.updateMatrixWorld(true);
  53809. this.referenceFrame.updateMatrixWorld(true);
  53810. for (let pointcloud of pointclouds) {
  53811. pointcloud.updateMatrixWorld(true);
  53812. let pointcloudBox = pointcloud.pcoGeometry.tightBoundingBox ? pointcloud.pcoGeometry.tightBoundingBox : pointcloud.boundingBox;
  53813. let boxWorld = Utils.computeTransformedBoundingBox(pointcloudBox, pointcloud.matrixWorld);
  53814. box.union(boxWorld);
  53815. }
  53816. return box;
  53817. }
  53818. addPointCloud (pointcloud) {
  53819. this.pointclouds.push(pointcloud);
  53820. this.scenePointCloud.add(pointcloud);
  53821. this.dispatchEvent({
  53822. type: 'pointcloud_added',
  53823. pointcloud: pointcloud
  53824. });
  53825. }
  53826. //add:
  53827. removePointCloud (pointcloud) {
  53828. let index = this.pointclouds.indexOf(pointcloud);
  53829. if(index == -1)return
  53830. this.pointclouds.splice(index, 1);
  53831. this.scenePointCloud.remove(pointcloud);
  53832. pointcloud.panos.forEach(pano=>{
  53833. pano.dispose();
  53834. });
  53835. }
  53836. addVolume (volume) {
  53837. this.volumes.push(volume);
  53838. this.dispatchEvent({
  53839. 'type': 'volume_added',
  53840. 'scene': this,
  53841. 'volume': volume
  53842. });
  53843. }
  53844. addOrientedImages(images){
  53845. this.orientedImages.push(images);
  53846. this.scene.add(images.node);
  53847. this.dispatchEvent({
  53848. 'type': 'oriented_images_added',
  53849. 'scene': this,
  53850. 'images': images
  53851. });
  53852. };
  53853. removeOrientedImages(images){
  53854. let index = this.orientedImages.indexOf(images);
  53855. if (index > -1) {
  53856. this.orientedImages.splice(index, 1);
  53857. this.dispatchEvent({
  53858. 'type': 'oriented_images_removed',
  53859. 'scene': this,
  53860. 'images': images
  53861. });
  53862. }
  53863. };
  53864. add360Images(images){
  53865. this.images360.push(images);
  53866. this.scene.add(images.node);
  53867. //this.sceneOverlay.add(images.node);//add
  53868. this.dispatchEvent({
  53869. 'type': '360_images_added',
  53870. 'scene': this,
  53871. 'images': images
  53872. });
  53873. }
  53874. remove360Images(images){
  53875. let index = this.images360.indexOf(images);
  53876. if (index > -1) {
  53877. this.images360.splice(index, 1);
  53878. this.dispatchEvent({
  53879. 'type': '360_images_removed',
  53880. 'scene': this,
  53881. 'images': images
  53882. });
  53883. }
  53884. }
  53885. addGeopackage(geopackage){
  53886. this.geopackages.push(geopackage);
  53887. this.scene.add(geopackage.node);
  53888. this.dispatchEvent({
  53889. 'type': 'geopackage_added',
  53890. 'scene': this,
  53891. 'geopackage': geopackage
  53892. });
  53893. };
  53894. removeGeopackage(geopackage){
  53895. let index = this.geopackages.indexOf(geopackage);
  53896. if (index > -1) {
  53897. this.geopackages.splice(index, 1);
  53898. this.dispatchEvent({
  53899. 'type': 'geopackage_removed',
  53900. 'scene': this,
  53901. 'geopackage': geopackage
  53902. });
  53903. }
  53904. };
  53905. removeVolume (volume) {
  53906. let index = this.volumes.indexOf(volume);
  53907. if (index > -1) {
  53908. this.volumes.splice(index, 1);
  53909. this.dispatchEvent({
  53910. 'type': 'volume_removed',
  53911. 'scene': this,
  53912. 'volume': volume
  53913. });
  53914. }
  53915. };
  53916. addCameraAnimation(animation) {
  53917. this.cameraAnimations.push(animation);
  53918. this.dispatchEvent({
  53919. 'type': 'camera_animation_added',
  53920. 'scene': this,
  53921. 'animation': animation
  53922. });
  53923. };
  53924. removeCameraAnimation(animation){
  53925. let index = this.cameraAnimations.indexOf(animation);
  53926. if (index > -1) {
  53927. this.cameraAnimations.splice(index, 1);
  53928. this.dispatchEvent({
  53929. 'type': 'camera_animation_removed',
  53930. 'scene': this,
  53931. 'animation': animation
  53932. });
  53933. }
  53934. };
  53935. addPolygonClipVolume(volume){
  53936. this.polygonClipVolumes.push(volume);
  53937. this.dispatchEvent({
  53938. "type": "polygon_clip_volume_added",
  53939. "scene": this,
  53940. "volume": volume
  53941. });
  53942. };
  53943. removePolygonClipVolume(volume){
  53944. let index = this.polygonClipVolumes.indexOf(volume);
  53945. if (index > -1) {
  53946. this.polygonClipVolumes.splice(index, 1);
  53947. this.dispatchEvent({
  53948. "type": "polygon_clip_volume_removed",
  53949. "scene": this,
  53950. "volume": volume
  53951. });
  53952. }
  53953. };
  53954. addMeasurement(measurement){
  53955. measurement.lengthUnit = this.lengthUnit;
  53956. measurement.lengthUnitDisplay = this.lengthUnitDisplay;
  53957. this.measurements.push(measurement);
  53958. this.dispatchEvent({
  53959. 'type': 'measurement_added',
  53960. 'scene': this,
  53961. 'measurement': measurement
  53962. });
  53963. };
  53964. removeMeasurement (measurement) {
  53965. let index = this.measurements.indexOf(measurement);
  53966. if (index > -1) {
  53967. this.measurements.splice(index, 1);
  53968. this.dispatchEvent({
  53969. 'type': 'measurement_removed',
  53970. 'scene': this,
  53971. 'measurement': measurement
  53972. });
  53973. }
  53974. }
  53975. addProfile (profile) {
  53976. this.profiles.push(profile);
  53977. this.dispatchEvent({
  53978. 'type': 'profile_added',
  53979. 'scene': this,
  53980. 'profile': profile
  53981. });
  53982. }
  53983. removeProfile (profile) {
  53984. let index = this.profiles.indexOf(profile);
  53985. if (index > -1) {
  53986. this.profiles.splice(index, 1);
  53987. this.dispatchEvent({
  53988. 'type': 'profile_removed',
  53989. 'scene': this,
  53990. 'profile': profile
  53991. });
  53992. }
  53993. }
  53994. removeAllMeasurements () {
  53995. while (this.measurements.length > 0) {
  53996. this.removeMeasurement(this.measurements[0]);
  53997. }
  53998. while (this.profiles.length > 0) {
  53999. this.removeProfile(this.profiles[0]);
  54000. }
  54001. while (this.volumes.length > 0) {
  54002. this.removeVolume(this.volumes[0]);
  54003. }
  54004. }
  54005. removeAllClipVolumes(){
  54006. let clipVolumes = this.volumes.filter(volume => volume.clip === true);
  54007. for(let clipVolume of clipVolumes){
  54008. this.removeVolume(clipVolume);
  54009. }
  54010. while(this.polygonClipVolumes.length > 0){
  54011. this.removePolygonClipVolume(this.polygonClipVolumes[0]);
  54012. }
  54013. }
  54014. getActiveCamera() {
  54015. return viewer.mainViewport.camera
  54016. if(this.overrideCamera){
  54017. return this.overrideCamera;
  54018. }
  54019. if(this.cameraMode === CameraMode.PERSPECTIVE){
  54020. return this.cameraP;
  54021. }else if(this.cameraMode === CameraMode.ORTHOGRAPHIC){
  54022. return this.cameraO;
  54023. }else if(this.cameraMode === CameraMode.VR){
  54024. return this.cameraVR;
  54025. }
  54026. return null;
  54027. }
  54028. initialize(){
  54029. this.referenceFrame = new Object3D();
  54030. this.referenceFrame.matrixAutoUpdate = false;
  54031. this.scenePointCloud.add(this.referenceFrame);
  54032. if(window.axisYup){
  54033. }else {
  54034. this.cameraP.up.set(0, 0, 1);
  54035. this.cameraO.up.set(0, 0, 1);
  54036. }
  54037. this.cameraP.position.set(1000, 1000, 1000);
  54038. this.cameraO.position.set(1000, 1000, 1000);
  54039. //this.camera.rotation.y = -Math.PI / 4;
  54040. //this.camera.rotation.x = -Math.PI / 6;
  54041. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  54042. this.directionalLight = new DirectionalLight( 0xffffff, 0.5 );
  54043. this.directionalLight.position.set( 10, 10, 10 );
  54044. this.directionalLight.lookAt( new Vector3(0, 0, 0));
  54045. this.scenePointCloud.add( this.directionalLight );
  54046. let light = new AmbientLight( 0x555555 ); // soft white light
  54047. this.scenePointCloud.add( light );
  54048. //add:------给空间模型的box 或其他obj------
  54049. let light2 = new AmbientLight( 16777215, 1 );
  54050. viewer.setObjectLayers(light2, 'bothMapAndScene');
  54051. this.scene.add(light2);
  54052. let light3 = new DirectionalLight( 16777215, 1);
  54053. light3.position.set( 10, 10, 10 );
  54054. light3.lookAt( new Vector3(0, 0, 0));
  54055. viewer.setObjectLayers(light3, 'bothMapAndScene');
  54056. this.scene.add(light3);
  54057. //--------------------------------------------
  54058. { // background
  54059. let texture = Utils.createBackgroundTexture(512, 512);
  54060. texture.minFilter = texture.magFilter = NearestFilter;
  54061. texture.minFilter = texture.magFilter = LinearFilter;
  54062. let bg = new Mesh(
  54063. new PlaneBufferGeometry(2, 2, 1),
  54064. new MeshBasicMaterial({
  54065. map: texture
  54066. })
  54067. );
  54068. bg.material.depthTest = false;
  54069. bg.material.depthWrite = false;
  54070. bg.name = 'bg';
  54071. //this.sceneBG.add(bg);
  54072. this.scene.add(bg);
  54073. bg.layers.set(Potree.config.renderLayers.bg);
  54074. }
  54075. { // background color
  54076. let bg2 = new Mesh(
  54077. new PlaneBufferGeometry(2, 2, 1),
  54078. new MeshBasicMaterial({
  54079. transparent : true
  54080. })
  54081. );
  54082. bg2.material.depthTest = false;
  54083. bg2.material.depthWrite = false;
  54084. bg2.name = 'bg2';
  54085. this.scene.add(bg2);
  54086. bg2.layers.set(Potree.config.renderLayers.bg2);
  54087. this.bg2 = bg2;
  54088. }
  54089. // { // lights
  54090. // {
  54091. // let light = new THREE.DirectionalLight(0xffffff);
  54092. // light.position.set(10, 10, 1);
  54093. // light.target.position.set(0, 0, 0);
  54094. // this.scene.add(light);
  54095. // }
  54096. // {
  54097. // let light = new THREE.DirectionalLight(0xffffff);
  54098. // light.position.set(-10, 10, 1);
  54099. // light.target.position.set(0, 0, 0);
  54100. // this.scene.add(light);
  54101. // }
  54102. // {
  54103. // let light = new THREE.DirectionalLight(0xffffff);
  54104. // light.position.set(0, -10, 20);
  54105. // light.target.position.set(0, 0, 0);
  54106. // this.scene.add(light);
  54107. // }
  54108. // }
  54109. }
  54110. /* switchBg(type){//add
  54111. let bg,;
  54112. if(type == 'gradient'){
  54113. bg
  54114. }else if(type == 'overlayColor'){
  54115. }
  54116. } */
  54117. addAnnotation(position, args = {}){
  54118. if(position instanceof Array){
  54119. args.position = new Vector3().fromArray(position);
  54120. } else if (position.x != null) {
  54121. args.position = position;
  54122. }
  54123. let annotation = new Annotation(args);
  54124. this.annotations.add(annotation);
  54125. return annotation;
  54126. }
  54127. getAnnotations () {
  54128. return this.annotations;
  54129. };
  54130. removeAnnotation(annotationToRemove) {
  54131. this.annotations.remove(annotationToRemove);
  54132. }
  54133. };
  54134. // http://epsg.io/
  54135. //see http://openlayers.org/
  54136. proj4.defs([
  54137. ['UTM10N', '+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'],
  54138. ['EPSG:6339', '+proj=utm +zone=10 +ellps=GRS80 +units=m +no_defs'],
  54139. ['EPSG:6340', '+proj=utm +zone=11 +ellps=GRS80 +units=m +no_defs'],
  54140. ['EPSG:6341', '+proj=utm +zone=12 +ellps=GRS80 +units=m +no_defs'],
  54141. ['EPSG:6342', '+proj=utm +zone=13 +ellps=GRS80 +units=m +no_defs'],
  54142. ['EPSG:6343', '+proj=utm +zone=14 +ellps=GRS80 +units=m +no_defs'],
  54143. ['EPSG:6344', '+proj=utm +zone=15 +ellps=GRS80 +units=m +no_defs'],
  54144. ['EPSG:6345', '+proj=utm +zone=16 +ellps=GRS80 +units=m +no_defs'],
  54145. ['EPSG:6346', '+proj=utm +zone=17 +ellps=GRS80 +units=m +no_defs'],
  54146. ['EPSG:6347', '+proj=utm +zone=18 +ellps=GRS80 +units=m +no_defs'],
  54147. ['EPSG:6348', '+proj=utm +zone=19 +ellps=GRS80 +units=m +no_defs'],
  54148. ['EPSG:26910', '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54149. ['EPSG:26911', '+proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54150. ['EPSG:26912', '+proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54151. ['EPSG:26913', '+proj=utm +zone=13 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54152. ['EPSG:26914', '+proj=utm +zone=14 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54153. ['EPSG:26915', '+proj=utm +zone=15 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54154. ['EPSG:26916', '+proj=utm +zone=16 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54155. ['EPSG:26917', '+proj=utm +zone=17 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54156. ['EPSG:26918', '+proj=utm +zone=18 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54157. ['EPSG:26919', '+proj=utm +zone=19 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  54158. ]);
  54159. class MapView{
  54160. constructor (viewer) {
  54161. this.viewer = viewer;
  54162. this.webMapService = 'WMTS';
  54163. this.mapProjectionName = 'EPSG:3857'; //navvis也是这个
  54164. this.mapProjection = proj4.defs(this.mapProjectionName);
  54165. this.sceneProjection = null;
  54166. this.extentsLayer = null;
  54167. this.cameraLayer = null;
  54168. this.toolLayer = null;
  54169. this.sourcesLayer = null;
  54170. this.sourcesLabelLayer = null;
  54171. this.images360Layer = null;
  54172. this.enabled = false;
  54173. this.createAnnotationStyle = (text) => {
  54174. return [
  54175. new ol.style.Style({
  54176. image: new ol.style.Circle({
  54177. radius: 10,
  54178. stroke: new ol.style.Stroke({
  54179. color: [255, 255, 255, 0.5],
  54180. width: 2
  54181. }),
  54182. fill: new ol.style.Fill({
  54183. color: [0, 0, 0, 0.5]
  54184. })
  54185. })
  54186. })
  54187. ];
  54188. };
  54189. this.createLabelStyle = (text) => {
  54190. let style = new ol.style.Style({
  54191. image: new ol.style.Circle({
  54192. radius: 6,
  54193. stroke: new ol.style.Stroke({
  54194. color: 'white',
  54195. width: 2
  54196. }),
  54197. fill: new ol.style.Fill({
  54198. color: 'green'
  54199. })
  54200. }),
  54201. text: new ol.style.Text({
  54202. font: '12px helvetica,sans-serif',
  54203. text: text,
  54204. fill: new ol.style.Fill({
  54205. color: '#000'
  54206. }),
  54207. stroke: new ol.style.Stroke({
  54208. color: '#fff',
  54209. width: 2
  54210. })
  54211. })
  54212. });
  54213. return style;
  54214. };
  54215. }
  54216. showSources (show) {
  54217. this.sourcesLayer.setVisible(show);
  54218. this.sourcesLabelLayer.setVisible(show);
  54219. }
  54220. init () {
  54221. if(typeof ol === "undefined"){
  54222. return;
  54223. }
  54224. this.elMap = $('#potree_map');
  54225. this.elMap.draggable({ handle: $('#potree_map_header') });
  54226. this.elMap.resizable();
  54227. this.elTooltip = $(`<div style="position: relative; z-index: 100"></div>`);
  54228. this.elMap.append(this.elTooltip);
  54229. let extentsLayer = this.getExtentsLayer();
  54230. let cameraLayer = this.getCameraLayer();
  54231. this.getToolLayer();
  54232. let sourcesLayer = this.getSourcesLayer();
  54233. this.images360Layer = this.getImages360Layer();
  54234. this.getSourcesLabelLayer();
  54235. this.getAnnotationsLayer();
  54236. let mousePositionControl = new ol.control.MousePosition({
  54237. coordinateFormat: ol.coordinate.createStringXY(5),
  54238. projection: 'EPSG:4326',
  54239. undefinedHTML: '&nbsp;'
  54240. });
  54241. let _this = this;
  54242. let DownloadSelectionControl = function (optOptions) {
  54243. let options = optOptions || {};
  54244. // TOGGLE TILES
  54245. let btToggleTiles = document.createElement('button');
  54246. btToggleTiles.innerHTML = 'T';
  54247. btToggleTiles.addEventListener('click', () => {
  54248. let visible = sourcesLayer.getVisible();
  54249. _this.showSources(!visible);
  54250. }, false);
  54251. btToggleTiles.style.float = 'left';
  54252. btToggleTiles.title = 'show / hide tiles';
  54253. // DOWNLOAD SELECTED TILES
  54254. let link = document.createElement('a');
  54255. link.href = '#';
  54256. link.download = 'list.txt';
  54257. link.style.float = 'left';
  54258. let button = document.createElement('button');
  54259. button.innerHTML = 'D';
  54260. link.appendChild(button);
  54261. let handleDownload = (e) => {
  54262. let features = selectedFeatures.getArray();
  54263. let url = [document.location.protocol, '//', document.location.host, document.location.pathname].join('');
  54264. if (features.length === 0) {
  54265. alert('No tiles were selected. Select area with ctrl + left mouse button!');
  54266. e.preventDefault();
  54267. e.stopImmediatePropagation();
  54268. return false;
  54269. } else if (features.length === 1) {
  54270. let feature = features[0];
  54271. if (feature.source) {
  54272. let cloudjsurl = feature.pointcloud.pcoGeometry.url;
  54273. let sourceurl = new URL(url + '/../' + cloudjsurl + '/../source/' + feature.source.name);
  54274. link.href = sourceurl.href;
  54275. link.download = feature.source.name;
  54276. }
  54277. } else {
  54278. let content = '';
  54279. for (let i = 0; i < features.length; i++) {
  54280. let feature = features[i];
  54281. if (feature.source) {
  54282. let cloudjsurl = feature.pointcloud.pcoGeometry.url;
  54283. let sourceurl = new URL(url + '/../' + cloudjsurl + '/../source/' + feature.source.name);
  54284. content += sourceurl.href + '\n';
  54285. }
  54286. }
  54287. let uri = 'data:application/octet-stream;base64,' + btoa(content);
  54288. link.href = uri;
  54289. link.download = 'list_of_files.txt';
  54290. }
  54291. };
  54292. button.addEventListener('click', handleDownload, false);
  54293. // assemble container
  54294. let element = document.createElement('div');
  54295. element.className = 'ol-unselectable ol-control';
  54296. element.appendChild(link);
  54297. element.appendChild(btToggleTiles);
  54298. element.style.bottom = '0.5em';
  54299. element.style.left = '0.5em';
  54300. element.title = 'Download file or list of selected tiles. Select tile with left mouse button or area using ctrl + left mouse.';
  54301. ol.control.Control.call(this, {
  54302. element: element,
  54303. target: options.target
  54304. });
  54305. };
  54306. ol.inherits(DownloadSelectionControl, ol.control.Control);
  54307. this.map = new ol.Map({
  54308. controls: ol.control.defaults({
  54309. attributionOptions: ({
  54310. collapsible: false
  54311. })
  54312. }).extend([
  54313. // this.controls.zoomToExtent,
  54314. new DownloadSelectionControl(),
  54315. mousePositionControl
  54316. ]),
  54317. layers: [
  54318. new ol.layer.Tile({source: new ol.source.OSM()}),
  54319. this.toolLayer,
  54320. this.annotationsLayer,
  54321. this.sourcesLayer,
  54322. this.sourcesLabelLayer,
  54323. this.images360Layer,
  54324. extentsLayer,
  54325. cameraLayer
  54326. ],
  54327. target: 'potree_map_content',
  54328. view: new ol.View({
  54329. center: this.olCenter,
  54330. zoom: 9
  54331. })
  54332. });
  54333. // DRAGBOX / SELECTION
  54334. this.dragBoxLayer = new ol.layer.Vector({
  54335. source: new ol.source.Vector({}),
  54336. style: new ol.style.Style({
  54337. stroke: new ol.style.Stroke({
  54338. color: 'rgba(0, 0, 255, 1)',
  54339. width: 2
  54340. })
  54341. })
  54342. });
  54343. this.map.addLayer(this.dragBoxLayer);
  54344. let select = new ol.interaction.Select();
  54345. this.map.addInteraction(select);
  54346. let selectedFeatures = select.getFeatures();
  54347. let dragBox = new ol.interaction.DragBox({
  54348. condition: ol.events.condition.platformModifierKeyOnly
  54349. });
  54350. this.map.addInteraction(dragBox);
  54351. // this.map.on('pointermove', evt => {
  54352. // let pixel = evt.pixel;
  54353. // let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
  54354. // return feature;
  54355. // });
  54356. // // console.log(feature);
  54357. // // this.elTooltip.css("display", feature ? '' : 'none');
  54358. // this.elTooltip.css('display', 'none');
  54359. // if (feature && feature.onHover) {
  54360. // feature.onHover(evt);
  54361. // // overlay.setPosition(evt.coordinate);
  54362. // // tooltip.innerHTML = feature.get('name');
  54363. // }
  54364. // });
  54365. this.map.on('click', evt => {
  54366. let pixel = evt.pixel;
  54367. let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
  54368. return feature;
  54369. });
  54370. if (feature && feature.onClick) {
  54371. feature.onClick(evt);
  54372. }
  54373. });
  54374. dragBox.on('boxend', (e) => {
  54375. // features that intersect the box are added to the collection of
  54376. // selected features, and their names are displayed in the "info"
  54377. // div
  54378. let extent = dragBox.getGeometry().getExtent();
  54379. this.getSourcesLayer().getSource().forEachFeatureIntersectingExtent(extent, (feature) => {
  54380. selectedFeatures.push(feature);
  54381. });
  54382. });
  54383. // clear selection when drawing a new box and when clicking on the map
  54384. dragBox.on('boxstart', (e) => {
  54385. selectedFeatures.clear();
  54386. });
  54387. this.map.on('click', () => {
  54388. selectedFeatures.clear();
  54389. });
  54390. this.viewer.addEventListener('scene_changed', e => {
  54391. this.setScene(e.scene);
  54392. });
  54393. this.onPointcloudAdded = e => {
  54394. this.load(e.pointcloud);
  54395. };
  54396. this.on360ImagesAdded = e => {
  54397. this.addImages360(e.images);
  54398. };
  54399. this.onAnnotationAdded = e => {
  54400. if (!this.sceneProjection) {
  54401. return;
  54402. }
  54403. let annotation = e.annotation;
  54404. let position = annotation.position;
  54405. let mapPos = this.toMap.forward([position.x, position.y]);
  54406. let feature = new ol.Feature({
  54407. geometry: new ol.geom.Point(mapPos),
  54408. name: annotation.title
  54409. });
  54410. feature.setStyle(this.createAnnotationStyle(annotation.title));
  54411. feature.onHover = evt => {
  54412. let coordinates = feature.getGeometry().getCoordinates();
  54413. let p = this.map.getPixelFromCoordinate(coordinates);
  54414. this.elTooltip.html(annotation.title);
  54415. this.elTooltip.css('display', '');
  54416. this.elTooltip.css('left', `${p[0]}px`);
  54417. this.elTooltip.css('top', `${p[1]}px`);
  54418. };
  54419. feature.onClick = evt => {
  54420. annotation.clickTitle();
  54421. };
  54422. this.getAnnotationsLayer().getSource().addFeature(feature);
  54423. };
  54424. this.setScene(this.viewer.scene);
  54425. }
  54426. setScene (scene) {
  54427. if (this.scene === scene) {
  54428. return;
  54429. };
  54430. if (this.scene) {
  54431. this.scene.removeEventListener('pointcloud_added', this.onPointcloudAdded);
  54432. this.scene.removeEventListener('360_images_added', this.on360ImagesAdded);
  54433. this.scene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  54434. }
  54435. this.scene = scene;
  54436. this.scene.addEventListener('pointcloud_added', this.onPointcloudAdded);
  54437. this.scene.addEventListener('360_images_added', this.on360ImagesAdded);
  54438. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  54439. for (let pointcloud of this.viewer.scene.pointclouds) {
  54440. this.load(pointcloud);
  54441. }
  54442. this.viewer.scene.annotations.traverseDescendants(annotation => {
  54443. this.onAnnotationAdded({annotation: annotation});
  54444. });
  54445. for(let images of this.viewer.scene.images360){
  54446. this.on360ImagesAdded({images: images});
  54447. }
  54448. }
  54449. getExtentsLayer () {
  54450. if (this.extentsLayer) {
  54451. return this.extentsLayer;
  54452. }
  54453. this.gExtent = new ol.geom.LineString([[0, 0], [0, 0]]);
  54454. let feature = new ol.Feature(this.gExtent);
  54455. let featureVector = new ol.source.Vector({
  54456. features: [feature]
  54457. });
  54458. this.extentsLayer = new ol.layer.Vector({
  54459. source: featureVector,
  54460. style: new ol.style.Style({
  54461. fill: new ol.style.Fill({
  54462. color: 'rgba(255, 255, 255, 0.2)'
  54463. }),
  54464. stroke: new ol.style.Stroke({
  54465. color: '#0000ff',
  54466. width: 2
  54467. }),
  54468. image: new ol.style.Circle({
  54469. radius: 3,
  54470. fill: new ol.style.Fill({
  54471. color: '#0000ff'
  54472. })
  54473. })
  54474. })
  54475. });
  54476. return this.extentsLayer;
  54477. }
  54478. getAnnotationsLayer () {
  54479. if (this.annotationsLayer) {
  54480. return this.annotationsLayer;
  54481. }
  54482. this.annotationsLayer = new ol.layer.Vector({
  54483. source: new ol.source.Vector({
  54484. }),
  54485. style: new ol.style.Style({
  54486. fill: new ol.style.Fill({
  54487. color: 'rgba(255, 0, 0, 1)'
  54488. }),
  54489. stroke: new ol.style.Stroke({
  54490. color: 'rgba(255, 0, 0, 1)',
  54491. width: 2
  54492. })
  54493. })
  54494. });
  54495. return this.annotationsLayer;
  54496. }
  54497. getCameraLayer () {
  54498. if (this.cameraLayer) {
  54499. return this.cameraLayer;
  54500. }
  54501. // CAMERA LAYER
  54502. this.gCamera = new ol.geom.LineString([[0, 0], [0, 0], [0, 0], [0, 0]]);
  54503. let feature = new ol.Feature(this.gCamera);
  54504. let featureVector = new ol.source.Vector({
  54505. features: [feature]
  54506. });
  54507. this.cameraLayer = new ol.layer.Vector({
  54508. source: featureVector,
  54509. style: new ol.style.Style({
  54510. stroke: new ol.style.Stroke({
  54511. color: '#0000ff',
  54512. width: 2
  54513. })
  54514. })
  54515. });
  54516. return this.cameraLayer;
  54517. }
  54518. getToolLayer () {
  54519. if (this.toolLayer) {
  54520. return this.toolLayer;
  54521. }
  54522. this.toolLayer = new ol.layer.Vector({
  54523. source: new ol.source.Vector({
  54524. }),
  54525. style: new ol.style.Style({
  54526. fill: new ol.style.Fill({
  54527. color: 'rgba(255, 0, 0, 1)'
  54528. }),
  54529. stroke: new ol.style.Stroke({
  54530. color: 'rgba(255, 0, 0, 1)',
  54531. width: 2
  54532. })
  54533. })
  54534. });
  54535. return this.toolLayer;
  54536. }
  54537. getImages360Layer(){
  54538. if(this.images360Layer){
  54539. return this.images360Layer;
  54540. }
  54541. let style = new ol.style.Style({
  54542. image: new ol.style.Circle({
  54543. radius: 4,
  54544. stroke: new ol.style.Stroke({
  54545. color: [255, 0, 0, 1],
  54546. width: 2
  54547. }),
  54548. fill: new ol.style.Fill({
  54549. color: [255, 100, 100, 1]
  54550. })
  54551. })
  54552. });
  54553. let layer = new ol.layer.Vector({
  54554. source: new ol.source.Vector({}),
  54555. style: style,
  54556. });
  54557. this.images360Layer = layer;
  54558. return this.images360Layer;
  54559. }
  54560. getSourcesLayer () {
  54561. if (this.sourcesLayer) {
  54562. return this.sourcesLayer;
  54563. }
  54564. this.sourcesLayer = new ol.layer.Vector({
  54565. source: new ol.source.Vector({}),
  54566. style: new ol.style.Style({
  54567. fill: new ol.style.Fill({
  54568. color: 'rgba(0, 0, 150, 0.1)'
  54569. }),
  54570. stroke: new ol.style.Stroke({
  54571. color: 'rgba(0, 0, 150, 1)',
  54572. width: 1
  54573. })
  54574. })
  54575. });
  54576. return this.sourcesLayer;
  54577. }
  54578. getSourcesLabelLayer () {
  54579. if (this.sourcesLabelLayer) {
  54580. return this.sourcesLabelLayer;
  54581. }
  54582. this.sourcesLabelLayer = new ol.layer.Vector({
  54583. source: new ol.source.Vector({
  54584. }),
  54585. style: new ol.style.Style({
  54586. fill: new ol.style.Fill({
  54587. color: 'rgba(255, 0, 0, 0.1)'
  54588. }),
  54589. stroke: new ol.style.Stroke({
  54590. color: 'rgba(255, 0, 0, 1)',
  54591. width: 2
  54592. })
  54593. }),
  54594. minResolution: 0.01,
  54595. maxResolution: 20
  54596. });
  54597. return this.sourcesLabelLayer;
  54598. }
  54599. setSceneProjection (sceneProjection) {
  54600. this.sceneProjection = sceneProjection;
  54601. this.toMap = proj4(this.sceneProjection, this.mapProjection);
  54602. this.toScene = proj4(this.mapProjection, this.sceneProjection);
  54603. };
  54604. getMapExtent () {
  54605. let bb = this.viewer.getBoundingBox();
  54606. let bottomLeft = this.toMap.forward([bb.min.x, bb.min.y]);
  54607. let bottomRight = this.toMap.forward([bb.max.x, bb.min.y]);
  54608. let topRight = this.toMap.forward([bb.max.x, bb.max.y]);
  54609. let topLeft = this.toMap.forward([bb.min.x, bb.max.y]);
  54610. let extent = {
  54611. bottomLeft: bottomLeft,
  54612. bottomRight: bottomRight,
  54613. topRight: topRight,
  54614. topLeft: topLeft
  54615. };
  54616. return extent;
  54617. };
  54618. getMapCenter () {
  54619. let mapExtent = this.getMapExtent();
  54620. let mapCenter = [
  54621. (mapExtent.bottomLeft[0] + mapExtent.topRight[0]) / 2,
  54622. (mapExtent.bottomLeft[1] + mapExtent.topRight[1]) / 2
  54623. ];
  54624. return mapCenter;
  54625. };
  54626. updateToolDrawings () {
  54627. this.toolLayer.getSource().clear();
  54628. let profiles = this.viewer.profileTool.profiles;
  54629. for (let i = 0; i < profiles.length; i++) {
  54630. let profile = profiles[i];
  54631. let coordinates = [];
  54632. for (let j = 0; j < profile.points.length; j++) {
  54633. let point = profile.points[j];
  54634. let pointMap = this.toMap.forward([point.x, point.y]);
  54635. coordinates.push(pointMap);
  54636. }
  54637. let line = new ol.geom.LineString(coordinates);
  54638. let feature = new ol.Feature(line);
  54639. this.toolLayer.getSource().addFeature(feature);
  54640. }
  54641. let measurements = this.viewer.measuringTool.measurements;
  54642. for (let i = 0; i < measurements.length; i++) {
  54643. let measurement = measurements[i];
  54644. let coordinates = [];
  54645. for (let j = 0; j < measurement.points.length; j++) {
  54646. let point = measurement.points[j].position;
  54647. let pointMap = this.toMap.forward([point.x, point.y]);
  54648. coordinates.push(pointMap);
  54649. }
  54650. if (measurement.closed && measurement.points.length > 0) {
  54651. coordinates.push(coordinates[0]);
  54652. }
  54653. let line = new ol.geom.LineString(coordinates);
  54654. let feature = new ol.Feature(line);
  54655. this.toolLayer.getSource().addFeature(feature);
  54656. }
  54657. }
  54658. addImages360(images){
  54659. let transform = this.toMap.forward;
  54660. let layer = this.getImages360Layer();
  54661. for(let pano of images.panos){
  54662. let p = transform([pano.position.x, pano.position.y]);
  54663. let feature = new ol.Feature({
  54664. 'geometry': new ol.geom.Point(p),
  54665. });
  54666. feature.onClick = () => {
  54667. //images.focus(pano);
  54668. images.flyToPano({
  54669. pano
  54670. });
  54671. };
  54672. layer.getSource().addFeature(feature);
  54673. }
  54674. }
  54675. async load (pointcloud) {
  54676. if (!pointcloud) {
  54677. return;
  54678. }
  54679. /* if (!pointcloud.projection) {
  54680. return;
  54681. }
  54682. */
  54683. if (!this.sceneProjection) {
  54684. try {
  54685. this.setSceneProjection(proj4.defs("NAVVIS:TMERC") || pointcloud.projection);
  54686. }catch (e) {
  54687. console.log('Failed projection:', e);
  54688. if (pointcloud.fallbackProjection) {
  54689. try {
  54690. console.log('Trying fallback projection...');
  54691. this.setSceneProjection(pointcloud.fallbackProjection);
  54692. console.log('Set projection from fallback');
  54693. }catch (e) {
  54694. console.log('Failed fallback projection:', e);
  54695. return;
  54696. }
  54697. }else {
  54698. return;
  54699. };
  54700. }
  54701. }
  54702. let mapExtent = this.getMapExtent();
  54703. let mapCenter = this.getMapCenter();
  54704. let view = this.map.getView();
  54705. view.setCenter(mapCenter);
  54706. this.gExtent.setCoordinates([
  54707. mapExtent.bottomLeft,
  54708. mapExtent.bottomRight,
  54709. mapExtent.topRight,
  54710. mapExtent.topLeft,
  54711. mapExtent.bottomLeft
  54712. ]);
  54713. view.fit(this.gExtent, [300, 300], {
  54714. constrainResolution: false
  54715. });
  54716. if (pointcloud.pcoGeometry.type == 'ept'){
  54717. return;
  54718. }
  54719. let url = `${pointcloud.pcoGeometry.url}/../sources.json`;
  54720. //let response = await fetch(url);
  54721. fetch(url).then(async (response) => {
  54722. let data = await response.json();
  54723. let sources = data.sources;
  54724. for (let i = 0; i < sources.length; i++) {
  54725. let source = sources[i];
  54726. let name = source.name;
  54727. let bounds = source.bounds;
  54728. let mapBounds = {
  54729. min: this.toMap.forward([bounds.min[0], bounds.min[1]]),
  54730. max: this.toMap.forward([bounds.max[0], bounds.max[1]])
  54731. };
  54732. let mapCenter = [
  54733. (mapBounds.min[0] + mapBounds.max[0]) / 2,
  54734. (mapBounds.min[1] + mapBounds.max[1]) / 2
  54735. ];
  54736. let p1 = this.toMap.forward([bounds.min[0], bounds.min[1]]);
  54737. let p2 = this.toMap.forward([bounds.max[0], bounds.min[1]]);
  54738. let p3 = this.toMap.forward([bounds.max[0], bounds.max[1]]);
  54739. let p4 = this.toMap.forward([bounds.min[0], bounds.max[1]]);
  54740. // let feature = new ol.Feature({
  54741. // 'geometry': new ol.geom.LineString([p1, p2, p3, p4, p1])
  54742. // });
  54743. let feature = new ol.Feature({
  54744. 'geometry': new ol.geom.Polygon([[p1, p2, p3, p4, p1]])
  54745. });
  54746. feature.source = source;
  54747. feature.pointcloud = pointcloud;
  54748. this.getSourcesLayer().getSource().addFeature(feature);
  54749. feature = new ol.Feature({
  54750. geometry: new ol.geom.Point(mapCenter),
  54751. name: name
  54752. });
  54753. feature.setStyle(this.createLabelStyle(name));
  54754. this.sourcesLabelLayer.getSource().addFeature(feature);
  54755. }
  54756. }).catch(() => {
  54757. });
  54758. }
  54759. toggle () {
  54760. if (this.elMap.is(':visible')) {
  54761. this.elMap.css('display', 'none');
  54762. this.enabled = false;
  54763. } else {
  54764. this.elMap.css('display', 'block');
  54765. this.enabled = true;
  54766. }
  54767. }
  54768. update (delta) {
  54769. if (!this.sceneProjection) {
  54770. return;
  54771. }
  54772. let pm = $('#potree_map');
  54773. if (!this.enabled) {
  54774. return;
  54775. }
  54776. // resize
  54777. let mapSize = this.map.getSize();
  54778. let resized = (pm.width() !== mapSize[0] || pm.height() !== mapSize[1]);
  54779. if (resized) {
  54780. this.map.updateSize();
  54781. }
  54782. //
  54783. let camera = this.viewer.scene.getActiveCamera();
  54784. let scale = this.map.getView().getResolution();
  54785. let campos = camera.position;
  54786. let camdir = camera.getWorldDirection(new Vector3());
  54787. let sceneLookAt = camdir.clone().multiplyScalar(30 * scale).add(campos);
  54788. let geoPos = camera.position;
  54789. let geoLookAt = sceneLookAt;
  54790. let mapPos = new Vector2$1().fromArray(this.toMap.forward([geoPos.x, geoPos.y]));
  54791. let mapLookAt = new Vector2$1().fromArray(this.toMap.forward([geoLookAt.x, geoLookAt.y]));
  54792. let mapDir = new Vector2$1().subVectors(mapLookAt, mapPos).normalize();
  54793. mapLookAt = mapPos.clone().add(mapDir.clone().multiplyScalar(30 * scale));
  54794. let mapLength = mapPos.distanceTo(mapLookAt);
  54795. let mapSide = new Vector2$1(-mapDir.y, mapDir.x);
  54796. let p1 = mapPos.toArray();
  54797. let p2 = mapLookAt.clone().sub(mapSide.clone().multiplyScalar(0.3 * mapLength)).toArray();
  54798. let p3 = mapLookAt.clone().add(mapSide.clone().multiplyScalar(0.3 * mapLength)).toArray();
  54799. this.gCamera.setCoordinates([p1, p2, p3, p1]);
  54800. }
  54801. get sourcesVisible () {
  54802. return this.getSourcesLayer().getVisible();
  54803. }
  54804. set sourcesVisible (value) {
  54805. this.getSourcesLayer().setVisible(value);
  54806. }
  54807. }
  54808. let texLoader$1 = new TextureLoader();
  54809. texLoader$1.crossOrigin = "anonymous";
  54810. let createErrorMaterial = function() {
  54811. var t = new MeshBasicMaterial({
  54812. transparent: !0,
  54813. depthWrite: !1,
  54814. depthTest: !0,
  54815. opacity: 1,
  54816. side: DoubleSide
  54817. });
  54818. return t.color = new Color(3355443),
  54819. t
  54820. };
  54821. let tempVector = new Vector3, //sharedata
  54822. face1 = new Face3(0,1,2),
  54823. face2 = new Face3(2,3,0),
  54824. errorMaterial = createErrorMaterial(),
  54825. uv00 = new Vector2$1(0,0),
  54826. uv01 = new Vector2$1(0,1),
  54827. uv10 = new Vector2$1(1,0),
  54828. uv11 = new Vector2$1(1,1),
  54829. face1UV = [uv00, uv10, uv11],
  54830. face2UV = [uv11, uv01, uv00];
  54831. const HALF_WORLD_SIZE = 21e6;
  54832. const MAX_VERTICAL_DIST = 2;
  54833. const MAX_VERTICAL_DIST_TO_BEST = 1;
  54834. //高德坐标拾取工具 : https://lbs.amap.com/tools/picker
  54835. class MapLayer extends EventDispatcher{ // 包括了 MapLayerBase SceneLayer
  54836. constructor(viewer_, viewport){
  54837. super();
  54838. this.sceneGroup = new Object3D;
  54839. this.sceneGroup.name = "MapLayer";
  54840. this.loadingInProgress = 0;
  54841. this.maps = [];
  54842. this.frustum = new Frustum;
  54843. this.frustumMatrix = new Matrix4;
  54844. this.tileColor = /* i && i.tileColor ? i.tileColor : */new Color(16777215);
  54845. this.viewport = viewport;
  54846. this.changeViewer(viewer_);
  54847. //添加地图
  54848. var map = new TiledMapOpenStreetMap(this, this.tileColor );
  54849. this.addMap(map);
  54850. //map.setEnable(false)
  54851. /* this.on('needUpdate',()=>{
  54852. this.mapLayer.update()
  54853. })
  54854. */
  54855. }
  54856. addMapEntity(data, datasetId){
  54857. if(!data || !data[0]){
  54858. Potree.Log('平面图无数据','red');
  54859. return
  54860. }
  54861. var floorplan = new TiledMapFromEntity(this, this.tileColor, data[0] );//[0]?
  54862. if(floorplan){
  54863. floorplan.name += "_"+ datasetId;
  54864. this.addMap(floorplan);
  54865. floorplan.updateProjection();
  54866. floorplan.updateObjectGroup();
  54867. let visible = false;
  54868. if(datasetId in Potree.settings.floorplanEnables){
  54869. visible = Potree.settings.floorplanEnables[datasetId];
  54870. }else {
  54871. visible = Potree.settings.floorplanEnable;
  54872. }
  54873. if(visible){
  54874. this.needUpdate = true;
  54875. }else {
  54876. floorplan.setEnable(false);
  54877. }
  54878. this.dispatchEvent({type:'floorplanLoaded', floorplan});
  54879. }
  54880. return floorplan
  54881. }
  54882. getFloorplan(datasetId){
  54883. return this.maps.find(e=>e.name == 'floorplan'+"_"+ datasetId )
  54884. }
  54885. addMap(t){
  54886. this.maps.push(t);
  54887. //this.view.invalidateScene()
  54888. this.needUpdate = true;
  54889. }
  54890. removeMap(t){
  54891. var e = this.maps.indexOf(t);
  54892. if(e >= 0){
  54893. t.removeFromSceneGroup(this.sceneGroup);
  54894. this.maps.splice(e, 1);
  54895. }
  54896. /* this.view.invalidateScene() */
  54897. this.needUpdate = true;
  54898. this.viewer.dispatchEvent({
  54899. type:'content_changed'
  54900. });
  54901. }
  54902. changeViewer(viewer_){//add
  54903. this.viewer = viewer_;
  54904. }
  54905. initProjection(){
  54906. this.maps.forEach(map=>{
  54907. map.updateProjection();
  54908. map.updateObjectGroup();
  54909. });
  54910. }
  54911. visibilityChanged(){
  54912. if (!this.visible)
  54913. for (var t = 0, e = this.maps; t < e.length; t++){
  54914. e[t].removeFromSceneGroup(this.sceneGroup);
  54915. }
  54916. }
  54917. onAfterRenderViewport(e){
  54918. var n = this;
  54919. /* this.isVisibleInViewport(e) && (this.updateTimer || this.loadingInProgress || (this.updateTimer = window.setTimeout((function(){
  54920. n.update(e).then((function (t){
  54921. t && n.loadComplete.emit(!0)
  54922. }
  54923. )).catch(u.handleWarning)
  54924. }
  54925. ), 100))) */
  54926. }
  54927. update(){
  54928. this.needUpdate = false;
  54929. if(this.disabled || !this.maps.find(e=>!e.disabled) || !this.maps.find(e=>e.objectGroup.visible) )return //add
  54930. var e, n, i, r, o;
  54931. this.updateTimer = void 0,
  54932. e = this.viewport.camera,
  54933. n = e.projectionMatrix.clone(),
  54934. n.elements[0] /= 1.5,
  54935. n.elements[5] /= 1.5,
  54936. this.frustumMatrix.multiplyMatrices(n, e.matrixWorldInverse),
  54937. this.frustum.setFromProjectionMatrix(this.frustumMatrix),
  54938. this.frustum.planes[4].setComponents(0, 0, 0, 0),
  54939. this.frustum.planes[5].setComponents(0, 0, 0, 0),
  54940. i = !0;
  54941. for (r = 0; r < this.maps.length; r++){
  54942. var map = this.maps[r];
  54943. i = map.update(this.frustum, this.sceneGroup) && i;
  54944. }
  54945. return [2, i]
  54946. }
  54947. getAttributions(){
  54948. for (var t = {}, e = 0, n = this.maps; e < n.length; e++){
  54949. n[e].fillAttributions(t);
  54950. }
  54951. return t
  54952. }
  54953. updateProjection(){
  54954. for (var t = 0, e = this.maps; t < e.length; t++){
  54955. var n = e[t];
  54956. n.clearProjection(),
  54957. n.updateObjectGroup();
  54958. }
  54959. }
  54960. }
  54961. class TiledMapBase extends EventDispatcher{
  54962. constructor(/* t, */name, mapLayer, tileColor, projection){
  54963. super();
  54964. this.name = name;
  54965. //this.TransformService = t,
  54966. this.mapLayer = mapLayer,
  54967. this.tileColor = tileColor,
  54968. this.bias = 0;
  54969. this.zIndex = -1;
  54970. this.objectGroup = new Object3D;
  54971. this.objectGroup.name = name;
  54972. this.objectGroupAdded = !1,
  54973. this.baseTile = new MapTile(this,/* this.mapLayer, */this.objectGroup,this.tileColor),
  54974. this.isTileVisibleBox = new Box3,
  54975. this.isTileVisibleVec = new Vector3;
  54976. this.projection = projection;
  54977. this._zoomLevel = 0;//1-20
  54978. }
  54979. get zoomLevel(){
  54980. return this._zoomLevel
  54981. }
  54982. set zoomLevel(zoomLevel){
  54983. if(this._zoomLevel != zoomLevel){
  54984. this._zoomLevel = zoomLevel;
  54985. //this.dispatchEvent('zoomLevelChange',zoomLevel)
  54986. //if(this.name == 'map')console.log(zoomLevel,viewer.mapViewer.camera.zoom)
  54987. }
  54988. }
  54989. updateObjectGroup(){
  54990. this.position && this.objectGroup.position.copy(this.position),
  54991. this.quaternion && this.objectGroup.quaternion.copy(this.quaternion),
  54992. this.objectGroup.updateMatrixWorld(!0);
  54993. }
  54994. updateProjection(){
  54995. //this.transformMapToLocal || (this.transformMapToLocal = this.TransformService.getTransform(this.projection, this.TransformService.crsLocal))
  54996. if(!this.transformMapToLocal){
  54997. if(proj4.defs("NAVVIS:TMERC")){
  54998. if(this.projection == "EPSG:4550"){
  54999. this.transformMapToLocal = {
  55000. forward:(e)=>{
  55001. var a = viewer.transform.lonlatTo4550.inverse(e);
  55002. return viewer.transform.lonlatToLocal.forward(a)
  55003. },
  55004. };
  55005. }else {
  55006. this.transformMapToLocal = proj4(this.projection, "NAVVIS:TMERC");
  55007. }
  55008. //this.transformMapToLocal = proj4(this.projection, "NAVVIS:TMERC")
  55009. }
  55010. }
  55011. }
  55012. setEnable(enable){//add
  55013. if(!this.disabled == enable)return
  55014. if(enable){
  55015. console.log('setEnable',true);
  55016. }
  55017. this.disabled = !enable;
  55018. viewer.updateVisible(this.objectGroup, 'setEnable', enable);
  55019. if(!enable){
  55020. this.baseTile.remove();
  55021. }else {
  55022. this.mapLayer.needUpdate = true;
  55023. }
  55024. this.mapLayer.viewer.dispatchEvent({
  55025. type:'content_changed'
  55026. });
  55027. }
  55028. /* clearProjection(){
  55029. this.transformMapToLocal = void 0,
  55030. this.projection.name !== this.TransformService.NAVVIS_LOCAL && this.baseTile.remove()
  55031. } */
  55032. update(e, n){
  55033. var unavailable = (this.disabled || !this.objectGroup.visible);//地图即使不显示也要获得zoomlevel
  55034. if(this.name != 'map' && unavailable)return
  55035. this.updateProjection();
  55036. if(!this.transformMapToLocal)return
  55037. if (!this.isTileVisible(new Vector3(0,0,0), this.mapSizeM, e))
  55038. return this.removeFromSceneGroup(n), !0;
  55039. let viewport = this.mapLayer.viewport;
  55040. var i = new Vector3(-.5 * this.mapSizeM,0,0);
  55041. i.applyMatrix4(this.objectGroup.matrixWorld),
  55042. i.project(viewport.camera);
  55043. var o = new Vector3(.5 * this.mapSizeM,0,0);
  55044. o.applyMatrix4(this.objectGroup.matrixWorld),
  55045. o.project(viewport.camera);
  55046. var a = viewport.resolution.x
  55047. , s = viewport.resolution.y;
  55048. if (a <= 0 || s <= 0 || isNaN(i.x) || isNaN(o.x)) return !1;
  55049. i.sub(o),
  55050. i.x *= a / 2,
  55051. i.y *= s / 2;
  55052. var c = this.tileSizePx / i.length()
  55053. , level = Math.ceil(-Math.log(c) / Math.log(2) - this.bias);
  55054. level = Math.max(level, 0);
  55055. level = Math.min(level, void 0 === this.maxDepth ? 1 / 0 : this.maxDepth);
  55056. this.zoomLevel = level;//add
  55057. //console.log(level)
  55058. if(!unavailable){
  55059. this.addToSceneGroup(n);
  55060. return this.baseTile.update(this, e, level, this.mapSizeM, 0, 0, "")
  55061. }
  55062. }
  55063. isTileVisible(e, n, i){
  55064. if (n > HALF_WORLD_SIZE) return !0;
  55065. var r = .5 * n;
  55066. this.transformMapToLocal.forward(e);
  55067. this.isTileVisibleBox.makeEmpty();
  55068. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55069. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55070. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55071. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55072. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55073. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55074. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  55075. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  55076. return i.intersectsBox(this.isTileVisibleBox)
  55077. }
  55078. addToSceneGroup(t){
  55079. this.objectGroupAdded || (t.add(this.objectGroup),
  55080. this.objectGroupAdded = !0);
  55081. }
  55082. removeFromSceneGroup(t){
  55083. this.baseTile.remove(),
  55084. this.objectGroupAdded && (t.remove(this.objectGroup),
  55085. this.objectGroupAdded = !1);
  55086. }
  55087. }
  55088. class MapTile{
  55089. constructor(map,/* t, */ e, n){
  55090. this.map = map;
  55091. //this.mapLayer = t,
  55092. this.objectGroup = e,
  55093. this.tileColor = n,
  55094. this.meshAdded = !1,
  55095. this.textureLoaded = !1,
  55096. this.children = [];
  55097. }
  55098. update(e, n, i, r, o, a, s){
  55099. return !!this.doesNotContainTilesToBeDisplayed(e) || (0 === i ? this.updateTile(e, r, o, a) : this.updateSubTiles(e, n, i, r, o, a, s))
  55100. }
  55101. doesNotContainTilesToBeDisplayed(t){
  55102. return t.tilePresenceMap && t.tilePresenceMap.empty
  55103. }
  55104. updateTile(t, e, n, i){
  55105. if(!this.mesh){
  55106. this.createTileObject(t, e, n, i);
  55107. }
  55108. if(!this.meshAdded){
  55109. this.objectGroup.add(this.mesh);
  55110. this.meshAdded = !0;
  55111. }
  55112. if(this.textureLoaded){
  55113. this.removeChildren();
  55114. }
  55115. return this.textureLoaded
  55116. }
  55117. updateSubTiles(entity, n, level, o, a, s, c){
  55118. 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){
  55119. var h = c + p.toString(10);
  55120. //一级(512):0 1 2 3分别为左上、右上、左下、右下。二级(1024)就是把一级的每一块分裂,如00 01 02 03分别是0的左上、右上、左下、右下……
  55121. /* if(entity.name == 'floorplan'){
  55122. console.log(1)
  55123. } */
  55124. if (!entity.tilePresenceMap || entity.tilePresenceMap[h]){
  55125. //去掉判断,直接显示
  55126. var f = a + u[p]
  55127. , m = s + d[p];
  55128. tempVector.set(f, m, 0);
  55129. if (entity.isTileVisible(tempVector, .5 * o, n)){
  55130. this.children[p] || (this.children[p] = new MapTile(this.map, this.objectGroup,this.tileColor));
  55131. l = this.children[p].update(entity, n, level - 1, .5 * o, f, m, h) && l;
  55132. } else {
  55133. if (this.children[p]){
  55134. this.children[p].remove();
  55135. delete this.children[p];
  55136. }
  55137. }
  55138. }
  55139. }
  55140. return l && this.removeObject3D(),
  55141. l
  55142. }
  55143. createTileObject(t, e, n, a){
  55144. var s = this;
  55145. this.mesh = this.createMesh(t.transformMapToLocal, e, n, a),
  55146. this.textureLoaded = !1;
  55147. var c = t.mapSizeM / e
  55148. , l = Math.log(c) / Math.log(2)
  55149. , u = n / e + .5 * (c - 1)
  55150. , d = -a / e + .5 * (c - 1)
  55151. , p = t.getTileUrl(Math.round(l), Math.round(u), Math.round(d));
  55152. viewer.setObjectLayers(this.mesh, 'map' );
  55153. this.mesh.renderOrder = -(1e6 - l - 100 * (t.zIndex || 0));
  55154. var h = this.mesh.material;
  55155. var loadDone = ()=>{
  55156. this.map.mapLayer.loadingInProgress--;
  55157. if(this.map.mapLayer.loadingInProgress == 0){
  55158. this.map.mapLayer.dispatchEvent('loadDone');
  55159. }
  55160. };
  55161. h.map = texLoader$1.load(p, (tex)=>{
  55162. if(this.mesh){//如果还要显示的话
  55163. this.textureLoaded = true;
  55164. this.mesh.material.opacity = 1;
  55165. //this.mapLayer.view.invalidateScene()
  55166. this.map.mapLayer.viewer.dispatchEvent({
  55167. type:'content_changed'
  55168. });
  55169. this.map.mapLayer.needUpdate = true; //表示还要继续update(以removeChildren)
  55170. }else {
  55171. tex.dispose();
  55172. }
  55173. loadDone();
  55174. } , void 0, (()=>{//error
  55175. this.textureLoaded = !0;
  55176. if(this.mesh){
  55177. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh)
  55178. this.mesh.material = errorMaterial;
  55179. //this.map.mapLayer.view.invalidateScene())
  55180. this.map.mapLayer.viewer.dispatchEvent({
  55181. type:'content_changed'
  55182. });
  55183. }
  55184. loadDone();
  55185. }));
  55186. h.map.anisotropy = 0,
  55187. h.map.generateMipmaps = !1,
  55188. h.map.minFilter = LinearFilter,
  55189. h.map.magFilter = LinearFilter,
  55190. this.map.mapLayer.loadingInProgress++;
  55191. }
  55192. createMesh(t, e, n, o){
  55193. var a = new Geometry;
  55194. return tempVector.set(n - e / 2, o - e / 2, 0),
  55195. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55196. tempVector.set(n + e / 2, o - e / 2, 0),
  55197. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55198. tempVector.set(n + e / 2, o + e / 2, 0),
  55199. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55200. tempVector.set(n - e / 2, o + e / 2, 0),
  55201. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  55202. a.faces.push(face1),
  55203. a.faces.push(face2),
  55204. a.faceVertexUvs[0].push(face1UV),
  55205. a.faceVertexUvs[0].push(face2UV),
  55206. new Mesh(a,this.createMaterial())
  55207. }
  55208. createMaterial(){
  55209. var t = new MeshBasicMaterial({
  55210. transparent: !0,
  55211. depthWrite: !1,
  55212. depthTest: !0,
  55213. opacity: 0,
  55214. side: DoubleSide
  55215. });
  55216. return t.color = this.tileColor ? this.tileColor : new Color(16777215),
  55217. t
  55218. }
  55219. remove(){
  55220. this.removeObject3D(),
  55221. this.removeChildren();
  55222. }
  55223. removeObject3D(){
  55224. if (this.mesh){
  55225. if (this.objectGroup.remove(this.mesh),
  55226. this.textureLoaded){
  55227. var t = this.mesh.material.map;
  55228. t && t.dispose();
  55229. }
  55230. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh),
  55231. this.mesh.geometry.dispose();
  55232. this.mesh = void 0;
  55233. }
  55234. this.meshAdded = !1,
  55235. this.textureLoaded = !1;
  55236. }
  55237. removeChildren(){
  55238. for (var t = 0, e = this.children; t < e.length; t++){
  55239. var n = e[t];
  55240. n && (n.removeObject3D(),
  55241. n.removeChildren());
  55242. }
  55243. this.children.length = 0;
  55244. }
  55245. }
  55246. 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");
  55247. //这里地图世界的中心是不是lon:0,lat:0
  55248. class TiledMapOpenStreetMap extends TiledMapBase{
  55249. constructor(mapLayer, tileColor){
  55250. super('map', mapLayer, tileColor, /* "EPSG:4550" */ "EPSG:3857" ); //EPSG projection
  55251. //this.baseUrl = "https://wprd03.is.autonavi.com/appmaptile?style=7&x=${x}&y=${y}&z=${z}",
  55252. //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
  55253. this.baseUrl = "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&style=7&x=${x}&y=${y}&z=${z}"; //最高只到19
  55254. this.attribution = "© PopSmart, © 高德地图",
  55255. this.tileSizePx = 256;
  55256. this.mapSizeM = 40075017;
  55257. this.maxDepth = 19;//20
  55258. this.bias = 0.5;
  55259. }
  55260. getTileUrl(t, e, n){
  55261. return this.baseUrl.replace(/\${z}/, t.toString(10)).replace(/\${x}/, e.toString(10)).replace(/\${y}/, n.toString(10))
  55262. }
  55263. fillAttributions(t){
  55264. t[this.attribution] = {
  55265. score: 50
  55266. };
  55267. }
  55268. }
  55269. class TiledMapFromEntity extends TiledMapBase{
  55270. constructor(mapLayer, tileColor, data){
  55271. super('floorplan', mapLayer, tileColor, "NAVVIS:TMERC" /* "EPSG:3857" *//* "WGS84" */); //直接就是本地坐标,没有projec
  55272. let entity = this.tiledMapEntity = this.fillFromData(data);
  55273. let time = entity.updateTime || entity.createTime;
  55274. this.tileSizePx = entity.tileSizePx,
  55275. this.mapSizeM = entity.mapSizeM,
  55276. this.maxDepth = entity.maxDepth;
  55277. this.postStamp = time ? time.replace(/[^0-9]/ig,'') : (new Date).getTime();
  55278. //this.projection = n.crsLocal,
  55279. this.zIndex = 0,
  55280. this.tilePresenceMap = this.decodeBitStream(this.tiledMapEntity.quadtree); //包含tile分裂信息,如果写错了会造成tile显示不全
  55281. }
  55282. fillFromData(e){
  55283. let data = {};
  55284. data.id = e.id;
  55285. data.globalLocation = Potree.Utils.VectorFactory.fromArray3(e.location),
  55286. data.orientation = Potree.Utils.QuaternionFactory.fromArray(e.orientation);
  55287. //if(Potree.fileServer){
  55288. data.filePath = `${Potree.settings.urls.prefix1}${e.file_path}`;
  55289. //}else{
  55290. // data.filePath = `${Potree.settings.urls.prefix}/data/${Potree.settings.number}/${e.file_path}`
  55291. //}
  55292. //if(!data.filePath.includes('building_1'))data.filePath = data.filePath.replace('building','building_1')//暂时
  55293. data.fileName = '$DEPTH/$X/$Y.png'; //e.file_name,
  55294. data.type = e.type,
  55295. data.mapSizeM = e.map_size_m,
  55296. data.tileSizePx = e.tile_size_px,
  55297. data.maxDepth = e.max_depth,
  55298. data.quadtree = e.quadtree,
  55299. data.floorId = e.floor_id,
  55300. data.bundleId = e.bundle_id;
  55301. //this.computeLocalCoordinates()
  55302. return data
  55303. }
  55304. computeLocalCoordinates(){
  55305. if(proj4.defs("NAVVIS:TMERC")){
  55306. this.tiledMapEntity.location = new Vector3().copy(viewer.transform.lonlatToLocal.forward(this.tiledMapEntity.globalLocation));
  55307. }
  55308. }
  55309. updateProjection() {
  55310. super.updateProjection();
  55311. if(!this.position){
  55312. this.computeLocalCoordinates();
  55313. }
  55314. /* this.projection = this.TransformService.crsLocal,
  55315. t.prototype.updateProjection.call(this) */
  55316. }
  55317. get position(){
  55318. return this.tiledMapEntity.location
  55319. /* enumerable: !0,
  55320. configurable: !0 */
  55321. }
  55322. get quaternion(){
  55323. return this.tiledMapEntity.orientation
  55324. /* enumerable: !0,
  55325. configurable: !0 */
  55326. }
  55327. getTileUrl(t, e, n) {
  55328. 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));
  55329. return i += "?t=" + this.postStamp
  55330. //this.RestService.addAuthorizationQueryParameter(i) //????
  55331. }
  55332. fillAttributions(t) {
  55333. t.NavVis = {
  55334. score: 100
  55335. };
  55336. }
  55337. decodeBitStream(t) {
  55338. if (!t)
  55339. return {
  55340. empty: !0
  55341. };
  55342. for (var e = {}, n = [e], i = 0; i < t.length; i++) {
  55343. var r = n.shift()
  55344. , o = parseInt(t.substr(i, 1), 16);
  55345. if (1 & o) {
  55346. var a = {};
  55347. r[0] = a,
  55348. n.push(a);
  55349. }
  55350. 2 & o && (a = {},
  55351. r[1] = a,
  55352. n.push(a)),
  55353. 4 & o && (a = {},
  55354. r[2] = a,
  55355. n.push(a)),
  55356. 8 & o && (a = {},
  55357. r[3] = a,
  55358. n.push(a));
  55359. }
  55360. var s = {
  55361. empty: !0
  55362. };
  55363. return this.computeHashes(s, e, ""),
  55364. s
  55365. }
  55366. computeHashes(t, e, n) {
  55367. for (var i = 0; i < 4; i++)
  55368. e[i] && (t[n + i.toString(10)] = !0,
  55369. t.empty = !1,
  55370. this.computeHashes(t, e[i], n + i.toString(10)));
  55371. }
  55372. }
  55373. /* {
  55374. "bundle_id": 1, //t-CwfhfqJ
  55375. "file_name": "$DEPTH/$X/$Y.png",
  55376. "file_path": "data/bundle_t-CwfhfqJ/building_1/map_tiles/11",
  55377. "floor_id": 11,
  55378. "id": 1,
  55379. "location": [
  55380. 113.5957510575092,
  55381. 22.366605927999239,
  55382. 0.0
  55383. ],
  55384. "map_size_m": 61.44,
  55385. "max_depth": 3,
  55386. "orientation": [
  55387. 0.7071067811865476,
  55388. 0.0,
  55389. 0.0,
  55390. 0.7071067811865475
  55391. ],
  55392. "quadtree": "fe5f7c7fcffff7f53",
  55393. "sceneCode": "t-CwfhfqJ",
  55394. "tile_size_px": 256,
  55395. "type": "TILED_PYRAMID"
  55396. }
  55397. */
  55398. var MathLight = {};
  55399. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  55400. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  55401. MathLight.Vector3 = function(e, t, i) {
  55402. this.x = e || 0,
  55403. this.y = t || 0,
  55404. this.z = i || 0;
  55405. };
  55406. MathLight.Matrix4 = function() {
  55407. this.elements = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
  55408. arguments.length > 0 && console.error("MathLight.Matrix4: the constructor no longer reads arguments. use .set() instead.");
  55409. };
  55410. MathLight.Matrix4.prototype = {
  55411. identity: function() {
  55412. return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
  55413. this
  55414. },
  55415. copy: function(e) {
  55416. return this.elements.set(e.elements),
  55417. this
  55418. },
  55419. applyToVector3: function(e) {
  55420. var t = e.x
  55421. , i = e.y
  55422. , n = e.z
  55423. , r = this.elements;
  55424. return e.x = r[0] * t + r[4] * i + r[8] * n + r[12],
  55425. e.y = r[1] * t + r[5] * i + r[9] * n + r[13],
  55426. e.z = r[2] * t + r[6] * i + r[10] * n + r[14],
  55427. this
  55428. },
  55429. getInverse: function(e, t) {
  55430. var i = this.elements
  55431. , n = e.elements
  55432. , r = n[0]
  55433. , o = n[1]
  55434. , a = n[2]
  55435. , s = n[3]
  55436. , l = n[4]
  55437. , c = n[5]
  55438. , h = n[6]
  55439. , u = n[7]
  55440. , d = n[8]
  55441. , p = n[9]
  55442. , f = n[10]
  55443. , g = n[11]
  55444. , m = n[12]
  55445. , v = n[13]
  55446. , A = n[14]
  55447. , y = n[15]
  55448. , C = p * A * u - v * f * u + v * h * g - c * A * g - p * h * y + c * f * y
  55449. , I = m * f * u - d * A * u - m * h * g + l * A * g + d * h * y - l * f * y
  55450. , E = d * v * u - m * p * u + m * c * g - l * v * g - d * c * y + l * p * y
  55451. , b = m * p * h - d * v * h - m * c * f + l * v * f + d * c * A - l * p * A
  55452. , w = r * C + o * I + a * E + s * b;
  55453. if (0 === w) {
  55454. var _ = "MathLight.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  55455. if (t)
  55456. throw new Error(_);
  55457. return console.warn(_),
  55458. this.identity()
  55459. }
  55460. var T = 1 / w;
  55461. return i[0] = C * T,
  55462. i[1] = (v * f * s - p * A * s - v * a * g + o * A * g + p * a * y - o * f * y) * T,
  55463. i[2] = (c * A * s - v * h * s + v * a * u - o * A * u - c * a * y + o * h * y) * T,
  55464. i[3] = (p * h * s - c * f * s - p * a * u + o * f * u + c * a * g - o * h * g) * T,
  55465. i[4] = I * T,
  55466. i[5] = (d * A * s - m * f * s + m * a * g - r * A * g - d * a * y + r * f * y) * T,
  55467. i[6] = (m * h * s - l * A * s - m * a * u + r * A * u + l * a * y - r * h * y) * T,
  55468. i[7] = (l * f * s - d * h * s + d * a * u - r * f * u - l * a * g + r * h * g) * T,
  55469. i[8] = E * T,
  55470. i[9] = (m * p * s - d * v * s - m * o * g + r * v * g + d * o * y - r * p * y) * T,
  55471. i[10] = (l * v * s - m * c * s + m * o * u - r * v * u - l * o * y + r * c * y) * T,
  55472. i[11] = (d * c * s - l * p * s - d * o * u + r * p * u + l * o * g - r * c * g) * T,
  55473. i[12] = b * T,
  55474. i[13] = (d * v * a - m * p * a + m * o * f - r * v * f - d * o * A + r * p * A) * T,
  55475. i[14] = (m * c * a - l * v * a - m * o * h + r * v * h + l * o * A - r * c * A) * T,
  55476. i[15] = (l * p * a - d * c * a + d * o * h - r * p * h - l * o * f + r * c * f) * T,
  55477. this
  55478. },
  55479. makeRotationFromQuaternion: function(e) {
  55480. var t = this.elements
  55481. , i = e.x
  55482. , n = e.y
  55483. , r = e.z
  55484. , o = e.w
  55485. , a = i + i
  55486. , s = n + n
  55487. , l = r + r
  55488. , c = i * a
  55489. , h = i * s
  55490. , u = i * l
  55491. , d = n * s
  55492. , p = n * l
  55493. , f = r * l
  55494. , g = o * a
  55495. , m = o * s
  55496. , v = o * l;
  55497. return t[0] = 1 - (d + f),
  55498. t[4] = h - v,
  55499. t[8] = u + m,
  55500. t[1] = h + v,
  55501. t[5] = 1 - (c + f),
  55502. t[9] = p - g,
  55503. t[2] = u - m,
  55504. t[6] = p + g,
  55505. t[10] = 1 - (c + d),
  55506. t[3] = 0,
  55507. t[7] = 0,
  55508. t[11] = 0,
  55509. t[12] = 0,
  55510. t[13] = 0,
  55511. t[14] = 0,
  55512. t[15] = 1,
  55513. this
  55514. }
  55515. };
  55516. MathLight.Quaternion = function(e, t, i, n) {
  55517. this._x = e || 0,
  55518. this._y = t || 0,
  55519. this._z = i || 0,
  55520. this._w = void 0 !== n ? n : 1;
  55521. };
  55522. MathLight.Quaternion.prototype = {
  55523. get x() {
  55524. return this._x
  55525. },
  55526. set x(e) {
  55527. this._x = e;
  55528. },
  55529. get y() {
  55530. return this._y
  55531. },
  55532. set y(e) {
  55533. this._y = e;
  55534. },
  55535. get z() {
  55536. return this._z
  55537. },
  55538. set z(e) {
  55539. this._z = e;
  55540. },
  55541. get w() {
  55542. return this._w
  55543. },
  55544. set w(e) {
  55545. this._w = e;
  55546. },
  55547. copy: function(e) {
  55548. this._x = e.x,
  55549. this._y = e.y,
  55550. this._z = e.z,
  55551. this._w = e.w;
  55552. },
  55553. inverse: function() {
  55554. return this.conjugate().normalize()
  55555. },
  55556. conjugate: function() {
  55557. return this._x *= -1,
  55558. this._y *= -1,
  55559. this._z *= -1,
  55560. this
  55561. },
  55562. length: function() {
  55563. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
  55564. },
  55565. normalize: function() {
  55566. var e = this.length();
  55567. return 0 === e ? (this._x = 0,
  55568. this._y = 0,
  55569. this._z = 0,
  55570. this._w = 1) : (e = 1 / e,
  55571. this._x = this._x * e,
  55572. this._y = this._y * e,
  55573. this._z = this._z * e,
  55574. this._w = this._w * e),
  55575. this
  55576. },
  55577. setFromAxisAngle: function(e, t) {
  55578. var i = t / 2
  55579. , n = Math.sin(i);
  55580. return this._x = e.x * n,
  55581. this._y = e.y * n,
  55582. this._z = e.z * n,
  55583. this._w = Math.cos(i),
  55584. this
  55585. },
  55586. setFromUnitVectors: function() {
  55587. var e, t, i = 1e-6;
  55588. return function(n, o) {
  55589. return void 0 === e && (e = new MathLight.Vector3),
  55590. t = MathLight.dot(n, o) + 1,
  55591. t < i ? (t = 0,
  55592. 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),
  55593. this._x = e.x,
  55594. this._y = e.y,
  55595. this._z = e.z,
  55596. this._w = t,
  55597. this.normalize()
  55598. }
  55599. }(),
  55600. multiply: function(e) {
  55601. return this.multiplyQuaternions(this, e)
  55602. },
  55603. premultiply: function(e) {
  55604. return this.multiplyQuaternions(e, this)
  55605. },
  55606. multiplyQuaternions: function(e, t) {
  55607. var i = e._x
  55608. , n = e._y
  55609. , r = e._z
  55610. , o = e._w
  55611. , a = t._x
  55612. , s = t._y
  55613. , l = t._z
  55614. , c = t._w;
  55615. return this._x = i * c + o * a + n * l - r * s,
  55616. this._y = n * c + o * s + r * a - i * l,
  55617. this._z = r * c + o * l + i * s - n * a,
  55618. this._w = o * c - i * a - n * s - r * l,
  55619. this
  55620. }
  55621. };
  55622. MathLight.convertWorkshopVector = function(e) {
  55623. return new MathLight.Vector3(-e.x,e.y,e.z)
  55624. };
  55625. MathLight.convertWorkshopQuaternion = function(e) {
  55626. 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))
  55627. };
  55628. MathLight.convertWorkshopOrthoZoom = function(e) {
  55629. //return e === -1 ? -1 : e / 16 * ($('#player').width() / $('#player').height()) / n.workshopApsect
  55630. return e === -1 ? -1 : e * ($("#player").width() / $("#player").height()) ;
  55631. };
  55632. MathLight.convertWorkshopPanoramaQuaternion = function(e) {
  55633. 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))
  55634. };
  55635. MathLight.normalize = function(e) {
  55636. var t = e.x * e.x + e.y * e.y + e.z * e.z
  55637. , i = Math.sqrt(t);
  55638. e.x /= i,
  55639. e.y /= i,
  55640. e.z /= i;
  55641. };
  55642. MathLight.dot = function(e, t) {
  55643. return e.x * t.x + e.y * t.y + e.z * t.z
  55644. };
  55645. MathLight.cross = function(e, t, i) {
  55646. var n = e.x
  55647. , r = e.y
  55648. , o = e.z;
  55649. i.x = r * t.z - o * t.y,
  55650. i.y = o * t.x - n * t.z,
  55651. i.z = n * t.y - r * t.x;
  55652. };
  55653. MathLight.setVector = function(e, t, i, n) {
  55654. e.x = t,
  55655. e.y = i,
  55656. e.z = n;
  55657. };
  55658. MathLight.copyVector = function(e, t) {
  55659. t.x = e.x,
  55660. t.y = e.y,
  55661. t.z = e.z;
  55662. };
  55663. MathLight.addVector = function(e, t) {
  55664. e.x += t.x,
  55665. e.y += t.y,
  55666. e.z += t.z;
  55667. };
  55668. MathLight.subVector = function(e, t) {
  55669. e.x -= t.x,
  55670. e.y -= t.y,
  55671. e.z -= t.z;
  55672. };
  55673. MathLight.applyQuaternionToVector = function(e, t) {
  55674. var i = t.x
  55675. , n = t.y
  55676. , r = t.z
  55677. , o = e.x
  55678. , a = e.y
  55679. , s = e.z
  55680. , l = e.w
  55681. , c = l * i + a * r - s * n
  55682. , h = l * n + s * i - o * r
  55683. , u = l * r + o * n - a * i
  55684. , d = -o * i - a * n - s * r;
  55685. t.x = c * l + d * -o + h * -s - u * -a,
  55686. t.y = h * l + d * -a + u * -o - c * -s,
  55687. t.z = u * l + d * -s + c * -a - h * -o;
  55688. };
  55689. MathLight.angleBetweenVectors = function(e, t) {
  55690. return Math.acos(MathLight.dot(e, t))
  55691. };
  55692. var cameraLight = {
  55693. clampVFOV: function(currentFov, maxHFov, width, height) {//限制currentFov, 使之造成的横向fov不大于指定值maxHFov
  55694. var r = cameraLight.getHFOVFromVFOV(currentFov, width, height);
  55695. return r > maxHFov ? cameraLight.getVFOVFromHFOV(maxHFov, width, height) : currentFov
  55696. },
  55697. getHFOVForCamera: function(camera, getRad) {
  55698. return cameraLight.getHFOVByScreenPrecent(camera.fov, camera.aspect, getRad)
  55699. },
  55700. //add
  55701. getHFOVByScreenPrecent: function(fov, percent, getRad) { //当fov为占比百分百时,percent代表在屏幕上从中心到边缘的占比
  55702. let rad = 2 * Math.atan(percent * Math.tan(fov * MathLight.RADIANS_PER_DEGREE / 2));
  55703. if(getRad)return rad
  55704. else return rad * MathLight.DEGREES_PER_RADIAN;
  55705. }
  55706. };
  55707. /**
  55708. * @author mschuetz / http://mschuetz.at
  55709. *
  55710. * adapted from THREE.OrbitControls by
  55711. *
  55712. * @author qiao / https://github.com/qiao
  55713. * @author mrdoob / http://mrdoob.com
  55714. * @author alteredq / http://alteredqualia.com/
  55715. * @author WestLangley / http://github.com/WestLangley
  55716. * @author erich666 / http://erichaines.com
  55717. *
  55718. *
  55719. *
  55720. */
  55721. class FirstPersonControls extends EventDispatcher {
  55722. constructor (viewer, viewport) {
  55723. super();
  55724. this.viewer = viewer;
  55725. this.renderer = viewer.renderer;
  55726. this.scene = viewer.scene;
  55727. this.rotationSpeed = 200;
  55728. this.moveSpeed = 10;
  55729. this.setCurrentViewport({hoverViewport:viewport, force:true}); //this.currentViewport = viewport
  55730. this.keys = {
  55731. FORWARD: ['W'.charCodeAt(0), 38],
  55732. BACKWARD: ['S'.charCodeAt(0), 40],
  55733. LEFT: ['A'.charCodeAt(0), 37],
  55734. RIGHT: ['D'.charCodeAt(0), 39],
  55735. UP: ['Q'.charCodeAt(0)],
  55736. DOWN: ['E'.charCodeAt(0)],
  55737. //SHIFT : [16],
  55738. ALT : [18],
  55739. Rotate_LEFT : ['L'.charCodeAt(0)],
  55740. Rotate_RIGHT : ['J'.charCodeAt(0)],
  55741. Rotate_UP : ['K'.charCodeAt(0)],
  55742. Rotate_DOWN : ['I'.charCodeAt(0)],
  55743. };
  55744. this.fadeFactor = 20;
  55745. this.yawDelta = 0;
  55746. this.pitchDelta = 0;
  55747. this.translationDelta = new Vector3(0, 0, 0);
  55748. this.translationWorldDelta = new Vector3(0, 0, 0);
  55749. this.tweens = [];
  55750. this.dollyStart = new Vector2$1;
  55751. this.dollyEnd = new Vector2$1;
  55752. //this.enableChangePos = true
  55753. this.viewer.addEventListener('camera_changed',(e)=>{
  55754. this.setFPCMoveSpeed(e.viewport);
  55755. });
  55756. let drag = (e) => {
  55757. if(!this.enabled)return
  55758. let viewport = e.dragViewport;
  55759. if(!viewport)return
  55760. let camera = viewport.camera;
  55761. let mode;
  55762. if(e.isTouch){
  55763. if(e.touches.length == 1){
  55764. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan';
  55765. }else if(e.touches.length == 2){
  55766. mode = 'scale';
  55767. }else {
  55768. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'pan' : 'scale';
  55769. }
  55770. }else {
  55771. //mode = e.buttons === Buttons.LEFT && (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan'
  55772. mode = e.buttons === Buttons.LEFT && camera.type != 'OrthographicCamera' ? 'rotate' : 'pan';
  55773. }
  55774. //console.log('mode ', mode )
  55775. let moveSpeed = this.currentViewport.getMoveSpeed();
  55776. if (e.drag.startHandled === undefined) {///???????
  55777. e.drag.startHandled = true;
  55778. this.dispatchEvent({type: 'start'});
  55779. }
  55780. if (mode.includes('rotate')) {//旋转
  55781. //来自panoramaControl updateRotation
  55782. if(!this.pointerDragStart){
  55783. return this.pointerDragStart = e.pointer.clone()
  55784. }
  55785. let view = this.scene.view;
  55786. if(Potree.settings.rotAroundPoint && this.intersectStart && this.canMovePos(viewport) && !viewer.images360.isAtPano() && !this.viewer.inputHandler.pressedKeys[17]){//定点旋转: 以当前intersect的点为target旋转,不改点在屏幕中的位置
  55787. let distance = camera.position.distanceTo(this.intersectStart.location); //不按下ctrl的话
  55788. //按照orbitControl的方式旋转:
  55789. let rotationSpeed = 2.5;
  55790. this.yawDelta -= e.drag.pointerDelta.x * rotationSpeed;
  55791. this.pitchDelta += e.drag.pointerDelta.y * rotationSpeed;
  55792. //先更新一下相机:
  55793. this.update();
  55794. view.applyToCamera(camera);
  55795. //然后得到新的相机角度下,原先点在屏幕中的位置所对应的3d点现在的坐标。只需要平移一下新旧坐标差值即可。
  55796. let newPointerDir = viewer.inputHandler.getMouseDirection(this.intersectStart.pointer).direction.clone().multiplyScalar(distance);
  55797. let pivot = new Vector3().addVectors(camera.position, newPointerDir); //新的3d点
  55798. let moveVec = new Vector3().subVectors(pivot, this.intersectStart.location);
  55799. this.translationWorldDelta.copy(moveVec.negate());
  55800. //立即更新下,防止因update和此drag频率不同而打滑。
  55801. this.update();
  55802. view.applyToCamera(camera);
  55803. }else {
  55804. let _matrixWorld = camera.matrixWorld;
  55805. camera.matrixWorld = new Matrix4;//unproject 前先把相机置于原点
  55806. var e1 = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y,-1).unproject(camera)
  55807. , t = new Vector3(e.pointer.x,e.pointer.y,-1).unproject(camera)
  55808. , i = Math.sqrt(e1.x * e1.x + e1.z * e1.z)
  55809. , n = Math.sqrt(t.x * t.x + t.z * t.z)
  55810. , o = Math.atan2(e1.y, i)
  55811. , a = Math.atan2(t.y, n);
  55812. this.pitchDelta += o - a; //上下旋转
  55813. e1.y = 0,
  55814. t.y = 0;
  55815. var s = Math.acos(e1.dot(t) / e1.length() / t.length());
  55816. if(!isNaN(s)){
  55817. var yawDelta = s; //左右旋转
  55818. this.pointerDragStart.x > e.pointer.x && (yawDelta *= -1);
  55819. this.yawDelta += yawDelta;
  55820. }
  55821. //console.log('rotate:', this.pitchDelta, e.pointer.toArray(), this.pointerDragStart.toArray())
  55822. this.pointerDragStart.copy(e.pointer);
  55823. camera.matrixWorld = _matrixWorld ;
  55824. }
  55825. }
  55826. if (mode.includes('pan')) {//平移
  55827. if(!this.canMovePos(viewport)){
  55828. return
  55829. }
  55830. if(camera.type == "OrthographicCamera"){
  55831. //console.log(e.drag.pointerDelta, e.pointer, e.drag.end)
  55832. let moveVec = Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, camera );//最近一次移动向量
  55833. let pointclouds;
  55834. let Alignment = window.viewer.modules.Alignment;
  55835. let MergeEditor = window.viewer.modules.MergeEditor;
  55836. let handleState = Alignment.handleState;
  55837. let a = e.buttons === Buttons.LEFT && viewport.alignment && handleState && viewport.alignment[handleState];
  55838. if(Potree.settings.editType == 'pano'){//右键平移视图、左键操作点云
  55839. let PanoEditor = window.viewer.modules.PanoEditor;
  55840. if(a && PanoEditor.selectedPano){
  55841. if(!PanoEditor.selectedGroup || !PanoEditor.checkIfAllLinked({group:PanoEditor.selectedGroup}) ){
  55842. if(handleState == 'translate' && ( e.drag.intersectStart.pointclouds && Common.getMixedSet(PanoEditor.selectedClouds, e.drag.intersectStart.pointclouds).length || PanoEditor.selectedPano.hovered)//拖拽到点云上 或 circle
  55843. || handleState == 'rotate' )
  55844. {
  55845. pointclouds = PanoEditor.selectedClouds;
  55846. }
  55847. }else {
  55848. PanoEditor.dispatchEvent('needToDisConnect');
  55849. console.warn('选中的漫游点连通了整个数据集,不允许移动');
  55850. }
  55851. }
  55852. if(!pointclouds && e.buttons === Buttons.LEFT && viewport.rotateSide){
  55853. return PanoEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  55854. }
  55855. }else if(Potree.settings.editType == 'merge'){
  55856. if(e.buttons === Buttons.LEFT && viewport.rotateSide){
  55857. return MergeEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  55858. }
  55859. }else {
  55860. /* if(Alignment.selectedClouds && Alignment.selectedClouds.length){
  55861. pointclouds = a && e.drag.intersectStart.pointclouds && Common.getMixedSet(Alignment.selectedClouds, e.drag.intersectStart.pointclouds).length && Alignment.selectedClouds
  55862. }else{ */
  55863. pointclouds = a && e.drag.intersectStart.pointcloud && [e.drag.intersectStart.pointcloud];
  55864. //}
  55865. }
  55866. if(pointclouds){
  55867. this.dispatchEvent({
  55868. type : "transformPointcloud",
  55869. intersect: e.intersect.orthoIntersect,
  55870. intersectStart: e.drag.intersectStart.orthoIntersect,
  55871. moveVec,
  55872. pointclouds,
  55873. camera
  55874. });
  55875. }else {
  55876. this.translationWorldDelta.add(moveVec.negate());
  55877. }
  55878. }else {
  55879. if(e.drag.intersectStart){//如果拖拽着点云
  55880. if(e.drag.z == void 0){//拖拽开始
  55881. let pointerStartPos2d = e.drag.intersectStart.location.clone().project(camera);//识别到的点云点的位置
  55882. e.drag.z = pointerStartPos2d.z; //记录z,保持拖拽物体到屏幕距离不变,所以z深度不变
  55883. e.drag.projectionMatrixInverse = camera.projectionMatrixInverse.clone();
  55884. //防止吸附到最近点上(因为鼠标所在位置并非识别到的点云点的位置,需要得到鼠标所在位置的3d坐标。)
  55885. let pointerStartPos2dReal = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y, e.drag.z);
  55886. e.drag.translateStartPos = pointerStartPos2dReal.clone().unproject(camera);
  55887. /* this.viewer.dispatchEvent({
  55888. type: 'dragPanBegin',
  55889. projectionMatrixInverse : e.drag.projectionMatrixInverse
  55890. }); */
  55891. //console.log('开始拖拽', e.pointer.clone())
  55892. }
  55893. //拖拽的过程中将projectionMatrixInverse替换成开始拖拽时的,因为near、far一直在变,会导致unproject计算出的3d坐标改变很大而闪烁。
  55894. var _projectionMatrixInverse = camera.projectionMatrixInverse;
  55895. camera.projectionMatrixInverse = e.drag.projectionMatrixInverse;
  55896. let newPos2d = new Vector3(e.pointer.x,e.pointer.y, e.drag.z );
  55897. let newPos3d = newPos2d.clone().unproject(camera);
  55898. let moveVec = newPos3d.clone().sub( e.drag.translateStartPos /* e.drag.intersectStart.location */ );//移动相机,保持鼠标下的位置永远不变,所以用鼠标下的新位置减去鼠标下的原始位置
  55899. camera.projectionMatrixInverse = _projectionMatrixInverse;
  55900. this.translationWorldDelta.copy(moveVec.negate()); //这里没法用add,原因未知,会跳动
  55901. //console.log('pan 1', this.translationWorldDelta.clone())
  55902. //四指松开剩三指时会偏移一下,暂不知道哪里的问题,或许跟开头防止点云吸附有关?
  55903. }else { //如果鼠标没有找到和点云的交点,就假设移动整个模型(也可以去扩大范围寻找最近点云)
  55904. /* let center = viewer.scene.pointclouds[0].position;
  55905. let radius = camera.position.distanceTo(center);
  55906. let ratio = radius * Math.tan(THREE.Math.degToRad(camera.fov)/2) / 1000 */
  55907. /* let speed = this.currentViewport.getMoveSpeed()
  55908. if(FirstPersonControls.boundPlane){
  55909. speed = FirstPersonControls.boundPlane.distanceToPoint(this.currentViewport.position)
  55910. speed = Math.max(1 , speed)
  55911. } */
  55912. let lastIntersect = viewport.lastIntersect ? (viewport.lastIntersect.location || viewport.lastIntersect) : viewer.bound.center; //该viewport的最近一次鼠标和点云的交点
  55913. let speed = camera.position.distanceTo(lastIntersect);
  55914. let fov = cameraLight.getHFOVForCamera(camera, true);
  55915. let ratio = speed * Math.tan(fov/2);
  55916. this.translationDelta.x -= e.drag.pointerDelta.x * ratio;
  55917. this.translationDelta.z -= e.drag.pointerDelta.y * ratio;
  55918. //console.log('pan2', e.drag.pointerDelta)
  55919. }
  55920. }
  55921. this.useAttenuation = false;
  55922. }
  55923. if(mode.includes('scale')){
  55924. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  55925. //if(!this.dollyStart)return
  55926. var scale = this.dollyEnd.length() / this.dollyStart.length();
  55927. //console.log('scale ',scale)
  55928. let pointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  55929. dolly({
  55930. pointer,
  55931. scale, camera
  55932. });
  55933. this.dollyStart.copy(this.dollyEnd);
  55934. }
  55935. //最好按ctrl可以变为dollhouse的那种旋转
  55936. };
  55937. let drop = e => {
  55938. if(!this.enabled)return
  55939. this.dispatchEvent({type: 'end'});
  55940. };
  55941. let dolly = (e={})=>{
  55942. if(Potree.settings.displayMode == 'showPanos' && this.currentViewport == viewer.mainViewport/* this.currentViewport.unableChangePos */){//全景时
  55943. this.dispatchEvent({type:'dollyStopCauseUnable',delta:e.delta, scale:e.scale});
  55944. return
  55945. }
  55946. let camera = e.camera;
  55947. if(camera.type == "OrthographicCamera"){
  55948. let ratio;
  55949. if(e.delta != void 0){//滚轮缩放
  55950. if(e.delta == 0){//mac
  55951. return
  55952. }else if (e.delta < 0) {
  55953. ratio = 0.9;
  55954. } else if (e.delta > 0) {
  55955. ratio = 1.1;
  55956. }
  55957. }else {
  55958. ratio = e.scale; //触屏缩放
  55959. }
  55960. let zoom = camera.zoom * ratio;
  55961. let limit = camera.zoomLimit;
  55962. if(limit) zoom = MathUtils.clamp(zoom, limit.min,limit.max );
  55963. let pointerPos = new Vector3(e.pointer.x, e.pointer.y,0.5);
  55964. let oldPos = pointerPos.clone().unproject(camera);
  55965. if(camera.zoom != zoom){
  55966. camera.zoom = zoom;
  55967. camera.updateProjectionMatrix();
  55968. }
  55969. let newPos = pointerPos.clone().unproject(camera);
  55970. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  55971. let moveVec = new Vector3().subVectors(newPos,oldPos);
  55972. this.translationWorldDelta.add(moveVec.negate());
  55973. this.useAttenuation = false;
  55974. }else {
  55975. let speed , direction;
  55976. if(e.delta != void 0){//滚轮缩放
  55977. speed = this.currentViewport.getMoveSpeed() * 15;
  55978. //var direction = this.currentViewport.view.direction.clone();
  55979. direction = this.viewer.inputHandler.getMouseDirection().direction; //定点缩放
  55980. if(e.delta == 0){//mac
  55981. return
  55982. }else if (e.delta < 0) {
  55983. speed *= -1;
  55984. }
  55985. }else {
  55986. const constantDis = this.currentViewport.getMoveSpeed() * 200; //constantDis = 10;//常量系数,当放大一倍时前进的距离。可以调整
  55987. speed = (e.scale-1)*constantDis; //触屏缩放
  55988. //pointer = new THREE.Vector2().addVectors().multiplyScalar(0.5);//两个指头的中心点
  55989. direction = this.viewer.inputHandler.getMouseDirection(e.pointer).direction; //定点缩放
  55990. }
  55991. this.useAttenuation = true;
  55992. var vec = direction.multiplyScalar(speed );
  55993. this.translationWorldDelta.copy(vec);
  55994. }
  55995. };
  55996. let scroll = (e) => {
  55997. if(!this.enabled || !e.hoverViewport)return
  55998. this.setCurrentViewport(e);
  55999. e.camera = e.hoverViewport.camera;
  56000. dolly(e);
  56001. };
  56002. let dblclick = (e) => {
  56003. if(!this.enabled)return
  56004. if(!Potree.settings.dblToFocusPoint)return;//调试时才可双击
  56005. if(Potree.settings.displayMode == 'showPointCloud'/* !viewer.images360.isAtPano() */) this.zoomToLocation(e.mouse);
  56006. };
  56007. this.viewer.addEventListener('global_drag', drag);
  56008. /* this.viewer.addEventListener('global_touchmove', (e)=>{
  56009. if(!this.enabled)return
  56010. if(e.touches.length>1){//单指的就触发上一句
  56011. //console.log('global_touchmove' )
  56012. drag(e)
  56013. }
  56014. }); */
  56015. this.viewer.addEventListener('global_drop', drop);
  56016. this.viewer.addEventListener('global_mousewheel', scroll);
  56017. this.viewer.addEventListener('global_dblclick', dblclick);
  56018. let prepareScale = (e)=>{//触屏的scale
  56019. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  56020. };
  56021. let prepareRotate = (e)=>{
  56022. this.pointerDragStart = e.pointer.clone();
  56023. this.intersectStart = e.intersect && e.intersect.location && {
  56024. location : e.intersect.location,
  56025. pointer : e.intersect.location.clone().project(e.dragViewport.camera) //intersect点在屏幕中的位置
  56026. };
  56027. //console.log('prepareRotate' )
  56028. };
  56029. let preparePan = (e)=>{//触屏的pan点云 还是会偏移
  56030. this.pointerDragStart = e.pointer.clone();
  56031. e.drag.z = void 0; //清空
  56032. drag(e); //触屏点击时更新的pointer直接用一次drag
  56033. //console.log('preparePan ' )
  56034. };
  56035. this.viewer.addEventListener('global_mousedown'/* 'startDragging' */, (e)=>{
  56036. if(!this.enabled)return
  56037. this.setCurrentViewport(e);
  56038. prepareRotate(e);
  56039. });
  56040. //注意,每次增减指头都会修改pointer,需要更新下状态
  56041. this.viewer.addEventListener('global_touchstart', (e)=>{
  56042. if(!this.enabled)return
  56043. if(e.touches.length==2){//只监听开头两个指头
  56044. prepareScale(e);
  56045. }else if(e.touches.length>=3){
  56046. preparePan(e);
  56047. }
  56048. });
  56049. this.viewer.addEventListener('global_touchend', (e)=>{
  56050. if(!this.enabled)return
  56051. if(e.touches.length==2){//停止平移,开始scale
  56052. prepareScale(e);
  56053. }else if(e.touches.length==1){//停止scale,开始rotate
  56054. prepareRotate(e);
  56055. }else if(e.touches.length>=3){//重新准备下平移(因为抬起的指头可能包含平移使用的数据),否则抬起时漂移
  56056. preparePan(e);
  56057. }
  56058. });
  56059. /* this.viewer.addEventListener('enableChangePos', (e)=>{
  56060. if(!this.enabled)return
  56061. this.enableChangePos = e.canLeavePano
  56062. }) */
  56063. }
  56064. canMovePos(viewport){
  56065. if(viewport == viewer.mainViewport && (Potree.settings.displayMode == 'showPanos'
  56066. || viewer.images360.bumping || viewer.images360.latestToPano))return false
  56067. else return true
  56068. }
  56069. setEnable(enabled){
  56070. this.enabled = enabled;
  56071. }
  56072. setFPCMoveSpeed(viewport){
  56073. if(viewport.camera.type == 'OrthographicCamera'){
  56074. let s = 1 / viewport.camera.zoom;
  56075. viewport.setMoveSpeed(s);
  56076. }else {
  56077. if(viewport == viewer.mainViewport && FirstPersonControls.boundPlane){
  56078. let s = FirstPersonControls.boundPlane.distanceToPoint(viewer.mainViewport.view.position);
  56079. s = Math.sqrt(s) / 10;
  56080. s = Math.max(FirstPersonControls.standardSpeed , s);
  56081. s *= Potree.config.moveSpeedAdujust;
  56082. viewer.setMoveSpeed(s);
  56083. }
  56084. }
  56085. }
  56086. setCurrentViewport(o={}){//add
  56087. if(!this.enabled && !o.force )return
  56088. if(o.hoverViewport && this.currentViewport != o.hoverViewport ){
  56089. this.currentViewport = o.hoverViewport;
  56090. //this.viewer.setMoveSpeed(this.currentViewport.radius/100);
  56091. this.setFPCMoveSpeed(this.currentViewport);
  56092. }
  56093. if(this.currentViewport.camera.type == 'OrthographicCamera'){
  56094. this.lockElevationOri = true;
  56095. this.lockRotation = true;
  56096. }else {
  56097. this.lockElevationOri = false;
  56098. this.lockRotation = false;
  56099. }
  56100. }
  56101. setScene (scene) {
  56102. this.scene = scene;
  56103. }
  56104. stop(){
  56105. this.yawDelta = 0;
  56106. this.pitchDelta = 0;
  56107. this.translationDelta.set(0, 0, 0);
  56108. }
  56109. zoomToLocation(mouse){
  56110. if(!this.enabled)return
  56111. let camera = this.scene.getActiveCamera();
  56112. /* let I = Utils.getMousePointCloudIntersection(
  56113. mouse,
  56114. camera,
  56115. this.viewer,
  56116. this.scene.pointclouds); */
  56117. var I = this.viewer.inputHandler.intersect;
  56118. if (!I) {
  56119. return;
  56120. }
  56121. let targetRadius = 0;
  56122. {
  56123. let minimumJumpDistance = 0.2;
  56124. let domElement = this.renderer.domElement;
  56125. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer, camera);
  56126. let {origin, direction} = this.viewer.inputHandler.getMouseDirection();
  56127. let raycaster = new Raycaster();
  56128. raycaster.ray.set(origin, direction);
  56129. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  56130. let nodes2 = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, raycaster.ray);
  56131. let lastNode = nodes[nodes.length - 1];
  56132. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  56133. targetRadius = Math.min(this.scene.view.radius, radius);
  56134. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  56135. }
  56136. let d = this.scene.view.direction.multiplyScalar(-1);
  56137. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  56138. // TODO Unused: let controlsTargetPosition = I.location;
  56139. let animationDuration = 600;
  56140. let easing = TWEEN.Easing.Quartic.Out;
  56141. { // animate
  56142. let value = {x: 0};
  56143. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  56144. tween.easing(easing);
  56145. this.tweens.push(tween);
  56146. let startPos = this.scene.view.position.clone();
  56147. let targetPos = cameraTargetPosition.clone();
  56148. let startRadius = this.scene.view.radius;
  56149. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  56150. tween.onUpdate(() => {
  56151. let t = value.x;
  56152. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  56153. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  56154. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  56155. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  56156. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  56157. });
  56158. tween.onComplete(() => {
  56159. this.tweens = this.tweens.filter(e => e !== tween);
  56160. });
  56161. tween.start();
  56162. }
  56163. }
  56164. update (delta=1) {
  56165. if(!this.enabled)return
  56166. //console.log('update')
  56167. let view = this.currentViewport.view;
  56168. { // cancel move animations on user input
  56169. let changes = [ this.yawDelta,
  56170. this.pitchDelta,
  56171. this.translationDelta.length(),
  56172. this.translationWorldDelta.length() ];
  56173. let changeHappens = changes.some(e => Math.abs(e) > 0.001);
  56174. if (changeHappens && this.tweens.length > 0) {
  56175. this.tweens.forEach(e => e.stop());
  56176. this.tweens = [];
  56177. }
  56178. }
  56179. { // accelerate while input is given
  56180. let ih = this.viewer.inputHandler;
  56181. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  56182. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  56183. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  56184. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  56185. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  56186. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  56187. let rotateLeft = this.keys.Rotate_LEFT.some(e => ih.pressedKeys[e]);
  56188. let rotateRight = this.keys.Rotate_RIGHT.some(e => ih.pressedKeys[e]);
  56189. let rotateUp = this.keys.Rotate_UP.some(e => ih.pressedKeys[e]);
  56190. let rotateDown = this.keys.Rotate_DOWN.some(e => ih.pressedKeys[e]);
  56191. this.lockElevation = this.lockElevationOri || this.keys.ALT.some(e => ih.pressedKeys[e]);
  56192. if(!this.lockRotation){
  56193. if(rotateLeft){
  56194. this.yawDelta -= 0.01;
  56195. }else if(rotateRight){
  56196. this.yawDelta += 0.01;
  56197. }
  56198. if(rotateUp){
  56199. this.pitchDelta -= 0.01;
  56200. }else if(rotateDown){
  56201. this.pitchDelta += 0.01;
  56202. }
  56203. }
  56204. if(this.canMovePos(this.currentViewport) && !this.lockKey){
  56205. if(this.lockElevation){
  56206. let dir = view.direction;
  56207. dir.z = 0;
  56208. dir.normalize();
  56209. if (moveForward && moveBackward) {
  56210. this.translationWorldDelta.set(0, 0, 0);
  56211. } else if (moveForward) {
  56212. this.translationWorldDelta.copy(dir.multiplyScalar(this.currentViewport.getMoveSpeed()));
  56213. } else if (moveBackward) {
  56214. this.translationWorldDelta.copy(dir.multiplyScalar(-this.currentViewport.getMoveSpeed()));
  56215. }
  56216. }else {
  56217. if (moveForward && moveBackward) {
  56218. this.translationDelta.y = 0;
  56219. } else if (moveForward) {
  56220. this.translationDelta.y = this.currentViewport.getMoveSpeed();
  56221. } else if (moveBackward) {
  56222. this.translationDelta.y = -this.currentViewport.getMoveSpeed();
  56223. }
  56224. }
  56225. if (moveLeft && moveRight) {
  56226. this.translationDelta.x = 0;
  56227. } else if (moveLeft) {
  56228. this.translationDelta.x = -this.currentViewport.getMoveSpeed();
  56229. } else if (moveRight) {
  56230. this.translationDelta.x = this.currentViewport.getMoveSpeed();
  56231. }
  56232. if (moveUp && moveDown) {
  56233. this.translationWorldDelta.z = 0;
  56234. } else if (moveUp) {
  56235. this.translationWorldDelta.z = this.currentViewport.getMoveSpeed();
  56236. } else if (moveDown) {
  56237. this.translationWorldDelta.z = -this.currentViewport.getMoveSpeed();
  56238. }
  56239. if(moveUp || moveDown || moveForward || moveBackward){
  56240. this.useAttenuation = false;
  56241. }
  56242. }
  56243. }
  56244. { // apply rotation
  56245. let yaw = view.yaw;
  56246. let pitch = view.pitch;
  56247. yaw += this.yawDelta; /* * delta; */
  56248. pitch += this.pitchDelta;/* * delta; */
  56249. view.yaw = yaw;
  56250. view.pitch = pitch;
  56251. this.yawDelta = 0;
  56252. this.pitchDelta = 0;
  56253. }
  56254. if(this.translationWorldDelta.length()>0) {
  56255. // console.log('translationDelta')
  56256. }
  56257. { // apply translation
  56258. view.translate(
  56259. this.translationDelta.x, /* * delta, */
  56260. this.translationDelta.y, /* * delta, */
  56261. this.translationDelta.z, /* * delta */
  56262. );
  56263. this.translationDelta.set(0,0,0);
  56264. //if(this.translationWorldDelta.length())console.log(translationWorldDelta)
  56265. view.translateWorld(
  56266. this.translationWorldDelta.x /* * delta */,
  56267. this.translationWorldDelta.y /* * delta */,
  56268. this.translationWorldDelta.z /* * delta */
  56269. );
  56270. //this.translationWorldDelta.set(0,0,0)
  56271. }
  56272. { // set view target according to speed
  56273. //view.radius = 1 * this.currentViewport.getMoveSpeed();
  56274. /* if(viewer.bound) view.radius = view.position.distanceTo(viewer.bound.center)
  56275. let speed = view.radius/100;
  56276. this.viewer.setMoveSpeed(speed); */
  56277. //this.setMoveSpeed()
  56278. }
  56279. if(this.useAttenuation){ //只有滚轮缩放时开启
  56280. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  56281. /*this.yawDelta *= attenuation;
  56282. this.pitchDelta *= attenuation;
  56283. this.translationDelta.multiplyScalar(attenuation);*/
  56284. this.translationWorldDelta.multiplyScalar(attenuation);
  56285. }else {
  56286. this.translationWorldDelta.set(0,0,0);
  56287. }
  56288. }
  56289. };
  56290. class Viewport{
  56291. constructor( view, camera, prop={}){//目前不支持换camera
  56292. this.left = prop.left;
  56293. this.bottom = prop.bottom;
  56294. this.width = prop.width;
  56295. this.height = prop.height;
  56296. this.name = prop.name;
  56297. this.view = view;
  56298. this.camera = camera;
  56299. this.active = true;
  56300. this.unableChangePos = false;
  56301. this.noPointcloud;
  56302. //this.keys = [...] firstPersonCtl....
  56303. this.resolution = new Vector2$1;
  56304. this.resolution2 = new Vector2$1;
  56305. this.offset = new Vector2$1; //viewportOffset 范围从0-整个画布的像素
  56306. this.extraEnableLayers = prop.extraEnableLayers || [];//额外可展示的层
  56307. this.cameraLayers = prop.cameraLayers;
  56308. this.pixelRatio = prop.pixelRatio; //如果规定pixelRatio的话要传,这样就覆盖devicePicelRatio, 如magnifier
  56309. }
  56310. clone(){
  56311. return Common.CloneClassObject(this)
  56312. }
  56313. getMoveSpeed(){
  56314. return this.moveSpeed
  56315. }
  56316. setMoveSpeed(e){
  56317. this.moveSpeed = e;
  56318. }
  56319. layersAdd(name){
  56320. this.extraEnableLayers.includes(name) || this.extraEnableLayers.push(name);
  56321. }
  56322. layersRemove(name){
  56323. let index = this.extraEnableLayers.indexOf(name);
  56324. if(index > -1){
  56325. this.extraEnableLayers.splice(index, 1);
  56326. }
  56327. }
  56328. cameraChanged() {
  56329. var copy = ()=>{
  56330. this.previousState = {
  56331. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在this.control时归零了所以不用了吧,用position和qua也一样
  56332. position: this.camera.position.clone(),
  56333. quaternion: this.camera.quaternion.clone()
  56334. };
  56335. };
  56336. let projectionChanged = true;
  56337. let positionChanged = true;
  56338. let quaternionChanged = true;
  56339. let getChanged = ()=>{
  56340. return {
  56341. projectionChanged,positionChanged,quaternionChanged,
  56342. changed:projectionChanged || positionChanged || quaternionChanged
  56343. }
  56344. };
  56345. if (this.previousState){
  56346. projectionChanged = !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix);
  56347. positionChanged = !this.camera.position.equals(this.previousState.position);
  56348. quaternionChanged = !this.camera.quaternion.equals(this.previousState.quaternion);
  56349. }
  56350. copy();
  56351. return getChanged()
  56352. }
  56353. setResolution(w,h, wholeW=0, wholeH=0){
  56354. this.resolution.set(w,h);//是client的width height
  56355. this.resolution2.copy(this.resolution).multiplyScalar(this.pixelRatio || window.devicePixelRatio);
  56356. this.offset.set(wholeW,wholeH).multiply(new Vector2$1(this.left,this.bottom)).multiplyScalar(window.devicePixelRatio);
  56357. }
  56358. }
  56359. /**
  56360. * @author mschuetz / http://mschuetz.at
  56361. *
  56362. *
  56363. */
  56364. class InputHandler extends EventDispatcher {
  56365. constructor (viewer,scene) {
  56366. super();
  56367. this.viewer = viewer;
  56368. this.renderer = viewer.renderer;
  56369. this.domElement = this.renderer.domElement;
  56370. this.enabled = true;
  56371. this.scene = scene;
  56372. this.interactiveScenes = [];
  56373. this.interactiveObjects = new Set();
  56374. this.inputListeners = [];
  56375. this.blacklist = new Set();
  56376. this.drag = null;
  56377. this.mouse = new Vector2$1(0, 0);
  56378. //add:
  56379. this.pointer = new Vector2$1(0, 0); //交互点的屏幕坐标,有别于DOM坐标,在此存放NDC坐标。(NDC,三维常用坐标系,二维坐标,整个屏幕映射范围(-1,1),屏幕中心为原点,+Y朝上,+X朝右)
  56380. this.mouseDownMouse = new Vector2$1(0, 0);
  56381. this.selection = [];
  56382. this.hoveredElements = [];
  56383. this.pressedKeys = {};
  56384. this.wheelDelta = 0;
  56385. this.speed = 1;
  56386. this.logMessages = false;
  56387. if (this.domElement.tabIndex === -1) {
  56388. this.domElement.tabIndex = 2222;
  56389. }
  56390. this.lastPointerUpTime = 0;
  56391. this.touches = [];
  56392. this.hoverViewport = viewer.viewports[0];
  56393. this.domElement.addEventListener('contextmenu', (event) => { event.preventDefault(); }, false);
  56394. this.domElement.addEventListener('click', this.onMouseClick.bind(this), false);
  56395. this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false);
  56396. window.addEventListener('mouseup', this.onMouseUp.bind(this), false);
  56397. this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this), false);
  56398. //add
  56399. /* this.domElement.addEventListener("pointerout", this.onMouseUp.bind(this)),
  56400. this.domElement.addEventListener("pointercancel", this.onMouseUp.bind(this)),
  56401. */
  56402. this.domElement.addEventListener('mousewheel', this.onMouseWheel.bind(this), false);
  56403. this.domElement.addEventListener('DOMMouseScroll', this.onMouseWheel.bind(this), false); // Firefox
  56404. //this.domElement.addEventListener('dblclick', this.onDoubleClick.bind(this)); //因为双击时间间隔是跟随系统的所以不好判断
  56405. this.domElement.addEventListener('keydown', this.onKeyDown.bind(this));
  56406. window.addEventListener('keyup', this.onKeyUp.bind(this));
  56407. //window.addEventListener('focus',()=>{
  56408. window.addEventListener('blur',this.onKeyUp.bind(this)); //add
  56409. this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this));
  56410. this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this));
  56411. this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this));
  56412. {
  56413. this.addEventListener('isMeasuring',(e)=>{
  56414. //console.log('isMeasuring',e.v,e.cause)
  56415. this.isMeasuring = e.v;
  56416. });
  56417. }
  56418. }
  56419. /* addInputListener (listener) {
  56420. this.inputListeners.push(listener);
  56421. }
  56422. removeInputListener (listener) {
  56423. this.inputListeners = this.inputListeners.filter(e => e !== listener);
  56424. }
  56425. getSortedListeners(){
  56426. return this.inputListeners.sort( (a, b) => {
  56427. let ia = (a.importance !== undefined) ? a.importance : 0;
  56428. let ib = (b.importance !== undefined) ? b.importance : 0;
  56429. return ib - ia;
  56430. });
  56431. } */
  56432. //统一跟第一个触碰的viewport相同
  56433. updateTouchesInfo(e){
  56434. var viewport, pointer, camera;
  56435. let oldTouches = this.touches;
  56436. let changedTouches = Array.from(e.changedTouches);
  56437. let touches = Array.from(e.touches);
  56438. this.touches = touches.map(touch=>{
  56439. let touch_ = oldTouches.find(a=>a.touch.identifier == touch.identifier);
  56440. let pointer = touch_ && touch_.pointer; //复制原先的值
  56441. return {
  56442. touch, pointer,
  56443. }
  56444. });
  56445. if(e.touches.length > 0){
  56446. let newTouches = touches.filter(e=>!
  56447. oldTouches.some(a=>a.touch.identifier == e.identifier) && !changedTouches.some(a=>a.identifier == e.identifier)
  56448. ); //从按钮处划过时e.touches中会出现this.touches和changedTouches中都没有的identifier
  56449. if(newTouches.length>0){
  56450. console.warn('has new',newTouches.map(e=>e.identifier));
  56451. }
  56452. newTouches.concat(changedTouches).forEach(touch=>{ //修改changedTouches的
  56453. let touch_ = this.touches.find(a=>a.touch.identifier == touch.identifier);
  56454. if(touch_){
  56455. let a = this.getPointerInViewport(touch.pageX, touch.pageY, this.dragViewport||viewport, new Vector2$1);
  56456. touch_.pointer = a.pointer.clone();
  56457. viewport = a.viewport; camera = a.camera;
  56458. }
  56459. });
  56460. //使用当前touches的平均
  56461. if(e.touches.length > 1){
  56462. let pageX = Common.average(e.touches, "pageX");
  56463. let pageY = Common.average(e.touches, "pageY");
  56464. let a = this.getPointerInViewport(pageX, pageY, viewport, new Vector2$1);
  56465. this.pointer.copy(a.pointer);
  56466. //console.log('updateTouchesInfo', this.pointer.clone())
  56467. }else {
  56468. this.pointer = this.touches[0].pointer.clone(); //更新,使用当前touches中的第一个
  56469. }
  56470. /* if(this.touches.find(e=>!e.pointer)){
  56471. console.error(' touches has no pointer', oldTouches.map(e=>e.touch.identifier),
  56472. Array.from(e.touches).map(e=>e.identifier), Array.from(e.changedTouches).map(e=>e.identifier) )
  56473. } */
  56474. //console.log(this.touches)
  56475. //console.log('更新pointer1',this.pointer.toArray())
  56476. return {viewport, camera/* , pointer:this.pointer */}
  56477. }
  56478. }
  56479. onTouchStart (e) {
  56480. if (this.logMessages) console.log(this.constructor.name + ': onTouchStart');
  56481. e.preventDefault();
  56482. /* if (e.touches.length === 1 || !this.drag) { //!this.drag代表一次性下了两个指头
  56483. let rect = this.domElement.getBoundingClientRect();
  56484. let x = e.touches[0].pageX
  56485. let y = e.touches[0].pageY
  56486. this.dealPointerDown(x,y,e,true)
  56487. }else{
  56488. this.updateTouchesInfo(e)
  56489. this.drag.end.copy(this.pointer)
  56490. } */
  56491. this.dealPointerDown(e,true);
  56492. this.viewer.dispatchEvent($.extend(
  56493. this.getEventDesc(e,true),
  56494. {
  56495. type: 'global_' + e.type,
  56496. changedTouches: e.changedTouches
  56497. }
  56498. ));
  56499. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  56500. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  56501. ) */
  56502. //console.log('')
  56503. }
  56504. onTouchMove (e) {
  56505. if (this.logMessages) console.log(this.constructor.name + ': onTouchMove');
  56506. e.preventDefault();
  56507. /* if (e.touches.length === 1) {
  56508. let rect = this.domElement.getBoundingClientRect();
  56509. let x = e.touches[0].pageX;
  56510. let y = e.touches[0].pageY;
  56511. }else{
  56512. this.updateTouchesInfo(e)
  56513. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end)
  56514. this.drag.end.copy(this.pointer)
  56515. }
  56516. */
  56517. this.dealPointerMove(e, true);
  56518. this.viewer.dispatchEvent($.extend(
  56519. this.getEventDesc(e,true),
  56520. {
  56521. type: 'global_' + e.type,
  56522. changedTouches: e.changedTouches
  56523. }
  56524. ));
  56525. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  56526. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  56527. ) */
  56528. }
  56529. onTouchEnd (e) {
  56530. if (this.logMessages) console.log(this.constructor.name + ': onTouchEnd');
  56531. e.preventDefault();
  56532. //console.log('onTouchEnd')
  56533. this.updateTouchesInfo(e);
  56534. /* if (e.touches.length === 0) {
  56535. let rect = this.domElement.getBoundingClientRect();
  56536. let x = e.changedTouches[0].pageX //万一一次松开两个指头的怎么办
  56537. let y = e.changedTouches[0].pageY
  56538. this.dealPointerUp(x,y,e,true)
  56539. }else {
  56540. this.drag.end.copy(this.pointer)
  56541. } */
  56542. this.dealPointerUp(e,true);
  56543. this.viewer.dispatchEvent($.extend(
  56544. this.getEventDesc(e,true),
  56545. {
  56546. type: 'global_' + e.type,
  56547. }
  56548. ));
  56549. //console.log('touchend length '+e.touches.length, this.touches.length)
  56550. }
  56551. onKeyDown (e) {
  56552. if (this.logMessages) console.log(this.constructor.name + ': onKeyDown');
  56553. // DELETE
  56554. if (e.keyCode === KeyCodes.DELETE && this.selection.length > 0) {
  56555. this.dispatchEvent({
  56556. type: 'delete',
  56557. selection: this.selection
  56558. });
  56559. this.deselectAll();
  56560. }
  56561. this.dispatchEvent({
  56562. type: 'keydown',
  56563. keyCode: e.keyCode,
  56564. event: e
  56565. });
  56566. // for(let l of this.getSortedListeners()){
  56567. // l.dispatchEvent({
  56568. // type: "keydown",
  56569. // keyCode: e.keyCode,
  56570. // event: e
  56571. // });
  56572. // }
  56573. this.pressedKeys[e.keyCode] = true;
  56574. // e.preventDefault();
  56575. }
  56576. onKeyUp (e) {
  56577. if (this.logMessages) console.log(this.constructor.name + ': onKeyUp');
  56578. if(e.keyCode != void 0){
  56579. delete this.pressedKeys[e.keyCode];
  56580. }else {
  56581. this.pressedKeys = {};
  56582. }
  56583. e.preventDefault();
  56584. }
  56585. onDoubleClick (e) {
  56586. if (this.logMessages) console.log(this.constructor.name + ': onDoubleClick');
  56587. let consumed = false;
  56588. for (let hovered of this.hoveredElements) {
  56589. if (hovered._listeners && hovered._listeners['dblclick']) {
  56590. hovered.object.dispatchEvent({
  56591. type: 'dblclick',
  56592. mouse: this.mouse,
  56593. object: hovered.object
  56594. });
  56595. consumed = true;
  56596. break;
  56597. }
  56598. }
  56599. if (!consumed) {
  56600. /* for (let inputListener of this.getSortedListeners()) {
  56601. inputListener. */this.viewer.dispatchEvent({
  56602. type: 'global_dblclick',
  56603. mouse: this.mouse,
  56604. object: null
  56605. });
  56606. //}
  56607. }
  56608. this.needSingleClick = false;//add
  56609. e.preventDefault();
  56610. }
  56611. onMouseClick (e) {
  56612. if (this.logMessages) console.log(this.constructor.name + ': onMouseClick');
  56613. e.preventDefault();
  56614. }
  56615. dealPointerDown(e,isTouch){
  56616. e.preventDefault();
  56617. //重新获取一下pointer, 因点击了浏览器的按钮展开列表时 move回来不会触发onmousemove,所以pointer是旧的
  56618. if(isTouch){
  56619. var { camera, viewport } = this.updateTouchesInfo(e);
  56620. if(this.drag){
  56621. //因为触屏在按下前缺少pointermove所以要更新下
  56622. this.drag.end = this.pointer.clone();
  56623. }
  56624. }else {
  56625. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  56626. }
  56627. this.dragViewport = this.hoverViewport = viewport;
  56628. if(isTouch || !Potree.settings.intersectWhenHover ){
  56629. this.hoveredElements = this.getHoveredElements();
  56630. this.intersect = this.getIntersect(viewport);
  56631. //this.intersect = this.getWholeIntersect()
  56632. }
  56633. if(!viewport)return
  56634. if(!isTouch || e.touches.length == 1){
  56635. let consumed = false;
  56636. let consume = () => { return consumed = true; };
  56637. //if (this.hoveredElements.length === 0) {
  56638. this.viewer.dispatchEvent($.extend(
  56639. this.getEventDesc(e,isTouch),
  56640. {
  56641. type: 'global_mousedown'
  56642. }
  56643. ));
  56644. for(let hovered of this.hoveredElements){
  56645. let object = hovered.object;
  56646. object.dispatchEvent({
  56647. type: 'mousedown',
  56648. viewer: this.viewer,
  56649. consume: consume
  56650. });
  56651. if(consumed){
  56652. break;
  56653. }
  56654. }
  56655. }
  56656. if (!this.drag) {
  56657. let target = (isTouch||e.button == MOUSE.LEFT) && this.hoveredElements.find(el => (//只有左键能拖拽
  56658. el.object._listeners &&
  56659. el.object._listeners['drag'] &&
  56660. el.object._listeners['drag'].length > 0));
  56661. if (target) {
  56662. this.startDragging(target.object, {location: target.point});
  56663. } else {
  56664. this.startDragging(null);
  56665. }
  56666. }
  56667. this.drag.intersectStart = this.intersect;
  56668. this.mouseDownMouse = this.mouse.clone();
  56669. this.pointerDownTime = Date.now();
  56670. }
  56671. onMouseDown (e) {
  56672. if (this.logMessages) console.log(this.constructor.name + ': onMouseDown');
  56673. this.dealPointerDown(e);
  56674. }
  56675. /* getWholeIntersect(hoveredElements, intersectPoint){//add
  56676. hoveredElements = hoveredElements || this.hoveredElements
  56677. intersectPoint = intersectPoint || this.intersectPoint
  56678. if(Potree.settings.intersectOnObjs && hoveredElements[0] && hoveredElements[0].object.isModel){
  56679. return {//模拟点云的intersectPoint的结构写法
  56680. hoveredElement : hoveredElements[0] ,
  56681. location: hoveredElements[0].point,
  56682. point: {normal: hoveredElements[0].face.normal },
  56683. distance: hoveredElements[0].distance,
  56684. object: hoveredElements[0].object
  56685. }
  56686. }else return intersectPoint
  56687. } */
  56688. getEventDesc(e,isTouch){//搜集dispatchEvent要给的一般数据
  56689. let o = {
  56690. viewer: this.viewer,
  56691. mouse: this.mouse,
  56692. pointer:this.pointer,
  56693. drag :this.drag,
  56694. isTouch,
  56695. dragViewport : this.dragViewport,
  56696. hoverViewport: this.hoverViewport,
  56697. // button: isTouch ? 0 : e.button,
  56698. //intersectPoint:this.intersectPoint,
  56699. hoveredElement: this.hoveredElements[0],
  56700. intersect: this.intersect//this.getWholeIntersect() , //可能包含mesh上的,针对融合页面
  56701. };
  56702. if(e){
  56703. o.isAtDomElement = e.target == this.domElement;
  56704. }
  56705. if(isTouch){
  56706. o.touches = this.touches;
  56707. }else if(e){
  56708. o.button = e.button;
  56709. o.buttons = e.buttons;
  56710. }
  56711. return o;
  56712. }
  56713. dealPointerUp(e,isTouch){
  56714. if(!this.drag){// 在canvas外mousedown
  56715. return
  56716. }
  56717. this.drag.end.copy(this.pointer);
  56718. if(isTouch && e.touches.length >= 1){
  56719. return
  56720. }
  56721. let now = Date.now();
  56722. if (this.logMessages) console.log(this.constructor.name + ': onMouseUp');
  56723. e.preventDefault();
  56724. let pressDistance = this.mouseDownMouse.distanceTo(this.mouse);
  56725. let pressTime = now - this.pointerDownTime;
  56726. let noMovement = this.drag.pointerDelta.length() == 0;//this.getNormalizedDrag().length() === 0;
  56727. let consumed = false;
  56728. let consume = () => { return consumed = true; };
  56729. //if (this.hoveredElements.length === 0) {
  56730. /* for (let inputListener of this.getSortedListeners()) {
  56731. inputListener */this.viewer.dispatchEvent($.extend(
  56732. this.getEventDesc(e,isTouch),
  56733. {
  56734. type: 'global_mouseup',
  56735. pressDistance,
  56736. consume,
  56737. }
  56738. ));
  56739. /* if(consumed){//??
  56740. break;
  56741. } */
  56742. //}
  56743. //}
  56744. if (this.hoveredElements.length > 0) {
  56745. let hovered = this.hoveredElements
  56746. .map(e => e.object)
  56747. .find(e => (e._listeners && e._listeners['mouseup']));
  56748. if(hovered){
  56749. hovered.dispatchEvent({
  56750. type: 'mouseup',
  56751. viewer: this.viewer,
  56752. consume: consume
  56753. });
  56754. }
  56755. }
  56756. if (this.drag) {
  56757. //拖拽结束
  56758. if (this.drag.object/* && e.button == THREE.MOUSE.LEFT */) {//add LEFT
  56759. if (this.logMessages) console.log(`${this.constructor.name}: drop ${this.drag.object.name}`);
  56760. this.drag.object.dispatchEvent($.extend(
  56761. this.getEventDesc(e,isTouch),
  56762. {
  56763. type: 'drop',
  56764. pressDistance,
  56765. }
  56766. ));
  56767. } else {
  56768. this.viewer.dispatchEvent($.extend(
  56769. this.getEventDesc(e,isTouch),
  56770. {
  56771. type: 'global_drop',
  56772. pressDistance
  56773. }
  56774. ));
  56775. }
  56776. // check for a click
  56777. if(pressDistance < Potree.config.clickMaxDragDis && pressTime<Potree.config.clickMaxPressTime && !e.unableClick){
  56778. let clickElement;
  56779. if(this.hoveredElements){
  56780. clickElement = this.hoveredElements.find(e=>e.object._listeners['click']);
  56781. if(clickElement){
  56782. //console.log('clickElement',clickElement)
  56783. if (this.logMessages) console.log(`${this.constructor.name}: click ${clickElement.name}`);
  56784. clickElement.object.dispatchEvent($.extend(
  56785. this.getEventDesc(e,isTouch),
  56786. {
  56787. type: 'click',
  56788. pressDistance
  56789. }
  56790. ));
  56791. }
  56792. }
  56793. let consumed = false;
  56794. let consume = () => { return consumed = true; };
  56795. let desc = this.getEventDesc(e,isTouch);
  56796. //if(!clickElement){
  56797. this.viewer.dispatchEvent($.extend(
  56798. desc,
  56799. {
  56800. type: 'global_click',
  56801. pressDistance,
  56802. clickElement,
  56803. consume
  56804. }
  56805. ));
  56806. //}
  56807. //增加 单击:
  56808. this.needSingleClick = true;
  56809. consumed || setTimeout(()=>{
  56810. if(this.needSingleClick){
  56811. this.viewer.dispatchEvent($.extend(
  56812. desc,
  56813. {
  56814. type: 'global_single_click',
  56815. pressDistance,
  56816. clickElement
  56817. }
  56818. ));
  56819. }
  56820. }, Potree.config.doubleClickTime+1);
  56821. //自行执行双击:
  56822. if(now - this.lastClickTime < Potree.config.doubleClickTime){
  56823. this.onDoubleClick(e);
  56824. }
  56825. this.lastClickTime = now;
  56826. }
  56827. this.drag = null;
  56828. }
  56829. this.dragViewport = null;
  56830. if(!consumed && !this.fixSelection){
  56831. if (e.button === MOUSE.LEFT) {
  56832. if (noMovement) {
  56833. let selectable = this.hoveredElements
  56834. .find(el => el.object._listeners && el.object._listeners['select']);
  56835. if (selectable) {
  56836. selectable = selectable.object;
  56837. if (this.isSelected(selectable)) {
  56838. this.selection
  56839. .filter(e => e !== selectable)
  56840. .forEach(e => this.toggleSelection(e));
  56841. } else {
  56842. this.deselectAll();
  56843. this.toggleSelection(selectable);
  56844. }
  56845. } else {
  56846. this.deselectAll();
  56847. }
  56848. }
  56849. } else if ((e.button === MOUSE.RIGHT) && noMovement) {
  56850. this.deselectAll();
  56851. }
  56852. }
  56853. }
  56854. onMouseUp (e) {
  56855. this.dealPointerUp( e );
  56856. }
  56857. getPointerInViewport(clientX, clientY, viewForceAt, pointer ){
  56858. let rect = this.domElement.getBoundingClientRect();
  56859. let x = clientX - rect.left;
  56860. let y = clientY - rect.top;
  56861. let camera;
  56862. let viewport;
  56863. pointer = pointer ||this.pointer;
  56864. //if(this.viewer.viewports || viewForceAt){
  56865. var getDimension = (view)=>{
  56866. var left = Math.ceil(this.domElement.clientWidth * view.left)
  56867. , bottom = Math.ceil(this.domElement.clientHeight * view.bottom)
  56868. , width = Math.ceil(this.domElement.clientWidth * view.width)
  56869. , height = Math.ceil(this.domElement.clientHeight * view.height)
  56870. , top = this.domElement.clientHeight - bottom - height;
  56871. return {left, bottom, width, height, top}
  56872. };
  56873. var getView = (view, left, bottom, width, height, top)=>{
  56874. this.mouse.set(x-left, y - top );
  56875. Utils.convertScreenPositionToNDC(pointer, this.mouse, width, height);
  56876. //console.log('更新pointer2',this.pointer.toArray())
  56877. camera = view.camera;
  56878. viewport = view;
  56879. };
  56880. if(viewForceAt){
  56881. let {left, bottom, width, height, top} = getDimension(viewForceAt);
  56882. getView(viewForceAt, left, bottom, width, height, top);
  56883. }else {
  56884. var length = this.viewer.viewports.length;
  56885. //var getif = false
  56886. for(var i=0;i<length;i++){
  56887. var view = this.viewer.viewports[i];
  56888. if(!view.active)continue
  56889. var {left, bottom, width, height, top} = getDimension(view);
  56890. if(x >= left && x <= left + width && y >= top && y <= top + height){
  56891. getView(view, left, bottom, width, height, top);
  56892. //getif = true
  56893. break;
  56894. }
  56895. }
  56896. }
  56897. return {
  56898. camera, viewport, pointer
  56899. }
  56900. }
  56901. ifBlockedByIntersect(point, margin=0, usePointcloud, cameraPos, pickWindowSize, pano){//某点是否被遮挡(不允许camera修改位置, 因为depthTex不好置换)
  56902. if(cameraPos){
  56903. usePointcloud = true; //只有使用点云才允许换位置
  56904. }
  56905. let intersect = this.getIntersect(this.hoverViewport, true, pickWindowSize, null, usePointcloud, {point, cameraPos, pano});
  56906. let cameraPos_ = (!usePointcloud && pano) ? pano.position : (cameraPos||this.hoverViewport.view.position);
  56907. if(intersect && intersect.distance+margin <= point.distanceTo(cameraPos_)){
  56908. return intersect //被遮挡
  56909. }
  56910. //点云模式,对没加载出的点云不准确。 尤其是需要修改相机位置时,因临时修改并不能使点云加载。
  56911. }
  56912. getIntersect(viewport, onlyGetIntersect, pickWindowSize, dontIntersect, usePointcloud, prop={}){// usePointcloud:必须使用点云
  56913. let intersectPoint;
  56914. let camera = viewport.camera;
  56915. let raycaster;
  56916. let getByDepthTex = ()=>{
  56917. /* if(prop.point){
  56918. raycaster = new THREE.Raycaster()
  56919. var dir = new THREE.Vector3().subVectors(prop.point, camera.position).normalize()
  56920. raycaster.set(camera.position, dir) //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  56921. } */
  56922. let intersect;
  56923. if(prop.point){
  56924. let cameraPos = prop.pano ? prop.pano.position : camera.position;
  56925. let dir = new Vector3().subVectors(prop.point, cameraPos).normalize();
  56926. intersect = {dir};
  56927. }else {
  56928. intersect = Utils.getIntersect(camera, [viewer.images360.cube], this.pointer, raycaster);
  56929. }
  56930. intersectPoint = viewer.images360.depthSampler.sample(intersect, prop.pano, !!prop.point); //可能不准确, 因pano可能未加载depthTex
  56931. };
  56932. let getByCloud = ()=>{
  56933. if(prop.point){
  56934. prop.cameraPos && camera.position.copy(prop.cameraPos);
  56935. camera.lookAt(prop.point);
  56936. camera.updateMatrixWorld();
  56937. prop.pointer = this.pointer.clone();
  56938. prop.mouse = this.mouse.clone();
  56939. this.pointer.set(0,0); //画布中心
  56940. this.mouse.set(Math.round(viewport.resolution.x/2), Math.round(viewport.resolution.y/2));
  56941. }
  56942. intersectPoint = (viewport.noPointcloud || dontIntersect)? null : Utils.getMousePointCloudIntersection(
  56943. viewport,
  56944. this.mouse,
  56945. this.pointer,
  56946. camera,
  56947. this.viewer,
  56948. this.viewer.scene.pointclouds,
  56949. {pickClipped: true, isMeasuring: this.isMeasuring, pickWindowSize, cameraChanged: !!prop.point }
  56950. );
  56951. //恢复
  56952. if(prop.point){
  56953. viewport.view.applyToCamera(camera);
  56954. this.pointer.copy(prop.pointer);
  56955. this.mouse.copy(prop.mouse);
  56956. }
  56957. };
  56958. let canUseDepthTex = Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && viewport == viewer.mainViewport && !usePointcloud;
  56959. if(canUseDepthTex && !this.isMeasuring){
  56960. getByDepthTex();
  56961. }else {
  56962. getByCloud();
  56963. if(!intersectPoint && canUseDepthTex ){//得不到的话再使用 getByDepthTex 得一次
  56964. getByDepthTex();
  56965. }
  56966. }
  56967. //console.log(viewport.name , intersectPoint && intersectPoint.location )
  56968. let intersect;
  56969. let intersectOnModel, allElements;
  56970. if(Potree.settings.intersectOnObjs && !dontIntersect){
  56971. if(prop.point){
  56972. raycaster = new Raycaster();
  56973. var dir = new Vector3().subVectors(prop.point, camera.position).normalize();
  56974. raycaster.set(camera.position, dir); //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  56975. }
  56976. allElements = this.getHoveredElements(viewer.objs.children, true, raycaster);
  56977. if(allElements[0]){
  56978. intersectOnModel = {//模拟点云的intersectPoint的结构写法
  56979. hoveredElement : allElements[0] ,
  56980. location: allElements[0].point,
  56981. //point: {normal: allElements[0].face.normal },
  56982. normal: allElements[0].face.normal,
  56983. distance: allElements[0].distance,
  56984. object: allElements[0].object
  56985. };
  56986. }
  56987. }
  56988. if(intersectPoint && intersectOnModel){
  56989. if(intersectPoint.distance < intersectOnModel.distance){
  56990. intersect = intersectPoint;
  56991. }else {
  56992. intersect = intersectOnModel;
  56993. }
  56994. }else {
  56995. intersect = intersectOnModel || intersectPoint;
  56996. }
  56997. if(viewport.camera.type == 'OrthographicCamera'/* == 'mapViewport' */){
  56998. let pos3d = new Vector3(this.pointer.x,this.pointer.y,-1).unproject(viewport.camera); //z:-1朝外
  56999. if(!intersect){
  57000. intersect = {};
  57001. }
  57002. intersect.orthoIntersect = pos3d.clone();
  57003. }
  57004. //记录全部hover到的:
  57005. if(intersect){
  57006. intersect.allElements = allElements;
  57007. intersect.pointclouds = intersectPoint ? intersectPoint.pointclouds : [];
  57008. }
  57009. if(onlyGetIntersect){
  57010. return intersect
  57011. }
  57012. if (intersect) {
  57013. if(viewer.showCoordType){ //显示坐标位置时
  57014. let pos = intersect.point.position.toArray();
  57015. if(viewer.showCoordType == "local"){
  57016. }else if(viewer.showCoordType == "lonlat"){
  57017. pos = viewer.transform.lonlatToLocal.inverse(pos);
  57018. }else {
  57019. pos = viewer.transform.lonlatToLocal.inverse(pos);
  57020. pos = viewer.transform.lonlatTo4550.forward(pos);
  57021. }
  57022. viewer.dispatchEvent({
  57023. type : "coordinateChange", pos
  57024. });
  57025. }
  57026. }
  57027. //console.log('getIntersect', !!intersectPoint)
  57028. this.intersect = intersect;
  57029. intersect && (this.hoverViewport.lastIntersect = intersect);
  57030. return intersect
  57031. }
  57032. onMouseMove (e) {
  57033. return this.dealPointerMove( e )
  57034. }
  57035. dealPointerMove(e, isTouch){
  57036. if(isTouch){
  57037. var { camera, viewport } = this.updateTouchesInfo(e);
  57038. }else {
  57039. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY, this.dragViewport);
  57040. }
  57041. this.hoverViewport = viewport;
  57042. if(!viewport)return//刚变化viewport时会找不到
  57043. let isFlying = this.viewer.viewports.some(e=>e.view.isFlying()) || viewer.scene.cameraAnimations.some(c=>c.onUpdate);
  57044. let intersect;
  57045. if(e.onlyGetIntersect || Potree.settings.intersectWhenHover && (!this.drag || this.drag.object || viewport.alignment ) ){ //没有拖拽物体,但按下鼠标了的话,不intersect
  57046. let dontIntersect = this.drag && viewport.alignment/* && Potree.settings.editType == 'pano' */|| isFlying;/* viewer.images360.flying */ // flying 时可能卡顿
  57047. //console.log('dontIntersectPointcloud',dontIntersectPointcloud)
  57048. intersect = this.getIntersect(viewport, e.onlyGetIntersect, e.pickWindowSize, !!dontIntersect, e.whichPointcloud); //数据集多的时候卡顿
  57049. //console.log('intersectPoint', intersectPoint)
  57050. }
  57051. if(e.onlyGetIntersect){
  57052. /* if(Potree.settings.intersectOnObjs){
  57053. let hoveredElements = this.getHoveredElements() //应该不用发送mouseover事件吧
  57054. let intersect = this.getWholeIntersect(hoveredElements, intersectPoint)
  57055. return intersect
  57056. }
  57057. return intersectPoint */
  57058. return intersect
  57059. }
  57060. e.preventDefault();
  57061. /* if(intersectPoint && intersectPoint.pointcloud){
  57062. console.log(intersectPoint.pointcloud.name)
  57063. } */
  57064. if (this.drag) {//有拖拽(不一定拖拽了物体, 也不一定按下了鼠标)
  57065. this.drag.mouse = isTouch ? 1 : e.buttons;
  57066. //add:
  57067. //this.drag.pointer = this.pointer.clone();
  57068. //this.drag.hoverViewport = this.hoverViewport
  57069. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end);
  57070. this.drag.end.copy(this.pointer);
  57071. if (this.drag.object && (e.buttons == Buttons.NONE || !this.drag.notPressMouse )){//如果是本不需要按鼠标的拖拽,但按下了鼠标,就不执行这段(改为拖拽场景,如添加测量时突然拖拽画面)
  57072. if (this.logMessages) console.log(this.constructor.name + ': drag: ' + this.drag.object.name);
  57073. this.drag.object.dispatchEvent($.extend(
  57074. this.getEventDesc(e,isTouch),
  57075. {
  57076. type: 'drag', //拖拽物体
  57077. }
  57078. ));
  57079. } else {
  57080. if (this.logMessages) console.log(this.constructor.name + ': drag: ');
  57081. let dragConsumed = false;
  57082. this.viewer.dispatchEvent($.extend(
  57083. this.getEventDesc(e,isTouch),
  57084. {
  57085. type: 'global_drag', //拖拽画面
  57086. consume: () => {dragConsumed = true;}
  57087. }
  57088. ));
  57089. }
  57090. }
  57091. if(!isTouch || e.touches.length == 1){
  57092. if((!this.drag || this.drag.notPressMouse || Potree.settings.intersectOnObjs && this.drag.object) && !isFlying){
  57093. /* let blacklist = this.drag && this.drag */
  57094. let hoveredElements = this.getHoveredElements( );
  57095. if(hoveredElements.length > 0){
  57096. let names = hoveredElements.map(h => h.object.name).join(", ");
  57097. if (this.logMessages) console.log(`${this.constructor.name}: onMouseMove; hovered: '${names}'`);
  57098. }
  57099. let curr = hoveredElements.map(a => a.object).find(a => true);//只取第一个
  57100. let prev = this.lastMouseoverElement; //this.hoveredElements.map(a => a.object).find(a => true);
  57101. if(curr !== prev){
  57102. if(curr){
  57103. if (this.logMessages) console.log(`${this.constructor.name}: mouseover: ${curr.name}`);
  57104. curr.dispatchEvent({
  57105. type: 'mouseover',
  57106. object: curr,
  57107. });
  57108. }
  57109. if(prev){
  57110. if (this.logMessages) console.log(`${this.constructor.name}: mouseleave: ${prev.name}`);
  57111. prev.dispatchEvent({
  57112. type: 'mouseleave',
  57113. object: prev,
  57114. });
  57115. }
  57116. this.lastMouseoverElement = curr;
  57117. }
  57118. if(hoveredElements.length > 0){
  57119. let object = hoveredElements
  57120. .map(e => e.object)
  57121. .find(e => (e._listeners && e._listeners['mousemove']));
  57122. if(object){
  57123. object.dispatchEvent({
  57124. type: 'mousemove',
  57125. object: object
  57126. });
  57127. }
  57128. }
  57129. this.hoveredElements = hoveredElements;
  57130. }
  57131. //this.intersect = this.getWholeIntersect()
  57132. this.viewer.dispatchEvent($.extend(
  57133. this.getEventDesc(e,isTouch),
  57134. {
  57135. type: 'global_mousemove',
  57136. }
  57137. ));
  57138. }
  57139. }
  57140. onMouseWheel(e){
  57141. if(!this.enabled) return;
  57142. if(this.logMessages) console.log(this.constructor.name + ": onMouseWheel");
  57143. e.preventDefault();
  57144. let delta = 0;
  57145. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  57146. delta = e.wheelDelta;
  57147. } else if (e.detail !== undefined) { // Firefox
  57148. delta = -e.detail;
  57149. }
  57150. let ndelta = Math.sign(delta);
  57151. // this.wheelDelta += Math.sign(delta);
  57152. if(!this.hoverViewport){//调试手机版时会无
  57153. var { viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  57154. this.hoverViewport = viewport;
  57155. }
  57156. if (this.hoveredElement) {
  57157. this.hoveredElement.object.dispatchEvent($.extend(
  57158. this.getEventDesc(e,isTouch),
  57159. {
  57160. type: 'mousewheel',
  57161. delta: ndelta,
  57162. object: this.hoveredElement.object
  57163. }
  57164. ));
  57165. } else {
  57166. this.viewer.dispatchEvent($.extend(
  57167. this.getEventDesc(e),
  57168. {
  57169. type: 'global_mousewheel',
  57170. delta: ndelta,
  57171. }
  57172. ));
  57173. }
  57174. }
  57175. startDragging (object, args = null) {
  57176. let name = object ? object.name : "no name";
  57177. if (this.logMessages) console.log(`${this.constructor.name}: startDragging: '${name}'`);
  57178. this.drag = {
  57179. start: this.pointer.clone(),
  57180. end: this.pointer.clone(),
  57181. pointerDelta: new Vector2$1(0, 0),
  57182. object: object,
  57183. hoverViewport: this.hoverViewport, //会变化
  57184. dragViewport: this.hoverViewport, //不变
  57185. };
  57186. if (args) {
  57187. for (let key of Object.keys(args)) {
  57188. this.drag[key] = args[key];
  57189. }
  57190. }
  57191. if(object){
  57192. object.dispatchEvent($.extend(
  57193. this.getEventDesc(),
  57194. {
  57195. type: 'startDragging'
  57196. }
  57197. ));
  57198. }
  57199. }
  57200. /* getMousePointCloudIntersection (mouse) {
  57201. return Utils.getMousePointCloudIntersection(
  57202. this.mouse,
  57203. this.scene.getActiveCamera(),
  57204. this.viewer,
  57205. this.scene.pointclouds);
  57206. } */
  57207. toggleSelection (object) {
  57208. let oldSelection = this.selection;
  57209. let index = this.selection.indexOf(object);
  57210. if (index === -1) {
  57211. this.selection.push(object);
  57212. object.dispatchEvent({
  57213. type: 'select'
  57214. });
  57215. } else {
  57216. this.selection.splice(index, 1);
  57217. object.dispatchEvent({
  57218. type: 'deselect'
  57219. });
  57220. }
  57221. this.dispatchEvent({
  57222. type: 'selection_changed',
  57223. oldSelection: oldSelection,
  57224. selection: this.selection
  57225. });
  57226. }
  57227. deselect(object){
  57228. let oldSelection = this.selection;
  57229. let index = this.selection.indexOf(object);
  57230. if(index >= 0){
  57231. this.selection.splice(index, 1);
  57232. object.dispatchEvent({
  57233. type: 'deselect'
  57234. });
  57235. this.dispatchEvent({
  57236. type: 'selection_changed',
  57237. oldSelection: oldSelection,
  57238. selection: this.selection
  57239. });
  57240. }
  57241. }
  57242. deselectAll () {
  57243. for (let object of this.selection) {
  57244. object.dispatchEvent({
  57245. type: 'deselect'
  57246. });
  57247. }
  57248. let oldSelection = this.selection;
  57249. if (this.selection.length > 0) {
  57250. this.selection = [];
  57251. this.dispatchEvent({
  57252. type: 'selection_changed',
  57253. oldSelection: oldSelection,
  57254. selection: this.selection
  57255. });
  57256. }
  57257. }
  57258. isSelected (object) {
  57259. let index = this.selection.indexOf(object);
  57260. return index !== -1;
  57261. }
  57262. registerInteractiveObject(object){
  57263. this.interactiveObjects.add(object);
  57264. }
  57265. removeInteractiveObject(object){
  57266. this.interactiveObjects.delete(object);
  57267. }
  57268. registerInteractiveScene (scene) {
  57269. let index = this.interactiveScenes.indexOf(scene);
  57270. if (index === -1) {
  57271. this.interactiveScenes.push(scene);
  57272. }
  57273. }
  57274. unregisterInteractiveScene (scene) {
  57275. let index = this.interactiveScenes.indexOf(scene);
  57276. if (index > -1) {
  57277. this.interactiveScenes.splice(index, 1);
  57278. }
  57279. }
  57280. getHoveredElement () {
  57281. let hoveredElements = this.getHoveredElements();
  57282. if (hoveredElements.length > 0) {
  57283. return hoveredElements[0];
  57284. } else {
  57285. return null;
  57286. }
  57287. }
  57288. getHoveredElements (interactables, dontCheckDis, raycaster) {
  57289. if(!interactables){
  57290. let scenes = this.hoverViewport.interactiveScenes || this.interactiveScenes.concat(this.scene);
  57291. let interactableListeners = ['mouseup', 'mousemove', 'mouseover', 'mouseleave', 'drag', 'drop', 'click', 'select', 'deselect'];
  57292. interactables = [];
  57293. for (let scene of scenes) {
  57294. scene.traverseVisible(node => {//检测加了侦听的object
  57295. if (node._listeners && node.visible && !this.blacklist.has(node) ) {
  57296. let hasInteractableListener = interactableListeners.filter((e) => {
  57297. return node._listeners[e] !== undefined;
  57298. }).length > 0;
  57299. if (hasInteractableListener) {
  57300. interactables.push(node);
  57301. }
  57302. }
  57303. });
  57304. }
  57305. }
  57306. let camera = this.hoverViewport.camera;
  57307. if(!raycaster){
  57308. let ray = Utils.mouseToRay(this.pointer, camera );
  57309. raycaster = new Raycaster();
  57310. raycaster.ray.set(ray.origin, ray.direction);
  57311. raycaster.camera = camera; //add
  57312. }
  57313. if(camera.type == "OrthographicCamera"){//使无论多远,threshold区域都是一样宽的
  57314. raycaster.params.Line.threshold = 20/camera.zoom;
  57315. }else {
  57316. raycaster.params.Line.threshold = 0.2;
  57317. }
  57318. raycaster.params.Line2 = {threshold :20 }; //拓宽的lineWidth
  57319. //raycaster.layers.enableAll()//add
  57320. viewer.setCameraLayers(raycaster, //设置能识别到的layers(如空间模型里只有mapViewer能识别到marker)
  57321. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  57322. this.hoverViewport && this.hoverViewport.extraEnableLayers
  57323. );
  57324. //this.hoverViewport.beforeRender && this.hoverViewport.beforeRender()
  57325. viewer.dispatchEvent( {type:'raycaster', viewport: this.hoverViewport});//add
  57326. let intersections = raycaster.intersectObjects(interactables.filter(o => o.visible), true); //原本是false 检测不到children
  57327. let intersectionsCopy = intersections.slice();
  57328. if(this.intersect && this.intersect.distance != void 0 && !dontCheckDis){//add
  57329. intersections = intersections.filter(e=>{
  57330. let material = e.object.material;
  57331. return (e.object.pickDontCheckDis || material.depthTest == false || material.depthWrite == false) && !material.useDepth //!material.depthTestWhenPick
  57332. || ( material.useDepth ? e.distance < this.intersect.distance + material.uniforms.occlusionDistance.value : e.distance < this.intersect.distance )
  57333. });
  57334. }
  57335. intersections = intersections.map(e=>{//add 转化为interactables
  57336. var object = e.object;
  57337. do{
  57338. if(interactables.includes(object)) {
  57339. e.oriObject = e.object;
  57340. e.object = object;
  57341. break
  57342. }
  57343. object = object.parent;
  57344. }while(object)
  57345. return e
  57346. });
  57347. //add for测量线,在检测到sphere时优先选中sphere而非线
  57348. //intersections = intersections.sort(function(a,b){return b.object.renderOrder-a.object.renderOrder}) // 降序
  57349. intersections = intersections.sort(function(a,b){
  57350. let order2 = b.object.pickOrder || 0;
  57351. let order1 = a.object.pickOrder || 0;
  57352. return order2-order1
  57353. }); // 降序
  57354. //console.log('getHoveredElement ', intersections)
  57355. return intersections;
  57356. }
  57357. /* setScene (scene) {
  57358. this.deselectAll();
  57359. this.scene = scene;
  57360. } */
  57361. update (delta) {
  57362. }
  57363. /*getNormalizedDrag () {
  57364. if (!this.drag) {
  57365. return new THREE.Vector2(0, 0);
  57366. }
  57367. let diff = new THREE.Vector2().subVectors(this.drag.end, this.drag.start);
  57368. diff.x = diff.x / this.domElement.clientWidth;
  57369. diff.y = diff.y / this.domElement.clientHeight;
  57370. return diff;
  57371. }
  57372. getNormalizedLastDrag () {
  57373. if (!this.drag) {
  57374. return new THREE.Vector2(0, 0);
  57375. }
  57376. let mouseDelta = this.drag.mouseDelta.clone();
  57377. mouseDelta.x = mouseDelta.x / this.domElement.clientWidth;
  57378. mouseDelta.y = mouseDelta.y / this.domElement.clientHeight;
  57379. return mouseDelta;
  57380. } */
  57381. getMouseDirection(pointer) {//add
  57382. pointer = pointer || this.pointer;
  57383. let camera = this.hoverViewport.camera;
  57384. var t = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  57385. i = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  57386. return {origin: t, direction:i.clone().sub(t).normalize() }
  57387. }
  57388. }
  57389. class ViewerBase extends EventDispatcher{
  57390. constructor(domElement, args = {}){
  57391. super();
  57392. this.name = args.name;
  57393. this.renderArea = domElement;
  57394. this.oldResolution = new Vector2$1();
  57395. this.screenSizeInfo = {
  57396. W:0, H:0, pixelRatio:1 , windowWidth:0, windowHeight:0
  57397. };
  57398. this.initContext(args);
  57399. this.addEventListener('content_changed', ()=>{//画面改变,需要渲染
  57400. this.needRender = true;
  57401. });
  57402. }
  57403. initContext(args){
  57404. //console.log(`initializing three.js ${THREE.REVISION}`);
  57405. let width = this.renderArea.clientWidth;
  57406. let height = this.renderArea.clientHeight;
  57407. let contextAttributes = {
  57408. alpha: true,
  57409. depth: true,
  57410. stencil: false,
  57411. antialias: true,
  57412. preserveDrawingBuffer: true,
  57413. powerPreference: "high-performance",
  57414. };
  57415. let canvas = document.createElement("canvas");
  57416. let context = canvas.getContext('webgl', contextAttributes );
  57417. this.renderer = new WebGLRenderer({
  57418. alpha: true, //支持透明
  57419. premultipliedAlpha: false,
  57420. canvas: canvas,
  57421. context: context,
  57422. });
  57423. this.renderer.sortObjects = true; //原先false 打开了renderOrder才奏效
  57424. //this.renderer.setSize(width, height);
  57425. this.renderer.autoClear = args.autoClear || false;
  57426. //args.clearColor = args.clearColor || '#aa0033'
  57427. args.clearColor && this.renderer.setClearColor(args.clearColor);
  57428. this.renderArea.appendChild(this.renderer.domElement);
  57429. this.renderer.domElement.tabIndex = '2222';
  57430. this.renderer.domElement.style.position = 'absolute';
  57431. this.renderer.domElement.addEventListener('mousedown', () => {
  57432. this.renderer.domElement.focus();
  57433. });
  57434. //this.renderer.domElement.focus();
  57435. // NOTE: If extension errors occur, pass the string into this.renderer.extensions.get(x) before enabling
  57436. // enable frag_depth extension for the interpolation shader, if available
  57437. let gl = this.renderer.getContext();
  57438. gl.getExtension('EXT_frag_depth');
  57439. gl.getExtension('WEBGL_depth_texture');
  57440. gl.getExtension('WEBGL_color_buffer_float'); // Enable explicitly for more portability, EXT_color_buffer_float is the proper name in WebGL 2
  57441. if(gl.createVertexArray == null){
  57442. let extVAO = gl.getExtension('OES_vertex_array_object');
  57443. if(!extVAO){
  57444. throw new Error("OES_vertex_array_object extension not supported");
  57445. }
  57446. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  57447. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  57448. }
  57449. /* let oldClear = gl.clear;
  57450. gl.clear = (bits)=>{
  57451. console.error('clear')
  57452. }
  57453. */
  57454. }
  57455. updateScreenSize(o={}) { //有可能需要让viewport来判断,当窗口大小不变但viewport大小变时
  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. if(w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || o.forceUpdateSize || this.screenSizeInfo.pixelRatio != window.devicePixelRatio){
  57467. this.screenSizeInfo.W = w;
  57468. this.screenSizeInfo.H = h;
  57469. render = true;
  57470. this.screenSizeInfo.pixelRatio = window.devicePixelRatio; //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  57471. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  57472. ratio = window.devicePixelRatio;
  57473. }
  57474. }
  57475. if (render) {
  57476. this.setSize(w, h, ratio);
  57477. }
  57478. }
  57479. /* updateScreenSize(o={}) { //容易出错。。
  57480. var render = false, ratio, w, h;
  57481. //记录应当render的大小
  57482. if (o.width != void 0 && o.height != void 0) {
  57483. w = o.width
  57484. h = o.height
  57485. render = true
  57486. ratio = 1
  57487. }else {
  57488. w = this.renderArea.clientWidth;
  57489. h = this.renderArea.clientHeight
  57490. let refreshWin = ()=>{
  57491. this.screenSizeInfo.windowWidth = window.innerWidth
  57492. this.screenSizeInfo.windowHeight = window.innerHeight
  57493. }
  57494. let prepareToRender = ()=>{
  57495. w = this.renderArea.clientWidth;
  57496. h = this.renderArea.clientHeight
  57497. this.screenSizeInfo.W = w
  57498. this.screenSizeInfo.H = h
  57499. refreshWin() //render后才refreshWin
  57500. render = true
  57501. this.screenSizeInfo.pixelRatio = window.devicePixelRatio //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  57502. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  57503. ratio = window.devicePixelRatio
  57504. //console.log('setSize11', w)
  57505. o.forceUpdateSize = false ;//防止再次render
  57506. }
  57507. let ifNeedUpdate = ()=>{
  57508. w = this.renderArea.clientWidth;
  57509. h = this.renderArea.clientHeight
  57510. return o.forceUpdateSize || w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || this.screenSizeInfo.pixelRatio != window.devicePixelRatio
  57511. }
  57512. if(ifNeedUpdate()){
  57513. //当只有一个有效viewport时,且因为改变整个窗口大小而触发的话,延时
  57514. let canInterval = !o.forceUpdateSize && this.viewports.filter(e=>e.active).length==1 && (this.screenSizeInfo.windowWidth != window.innerWidth || this.screenSizeInfo.windowHeight != window.innerHeight )
  57515. if(canInterval){
  57516. Common.intervalTool.isWaiting('updateScreenSize', ()=>{ //延时update,防止崩溃 , 未到时间就拦截(第一次直接执行)
  57517. if(ifNeedUpdate()){
  57518. prepareToRender()
  57519. return true
  57520. }
  57521. }, 500)
  57522. }else{
  57523. //console.log('soon', window.innerWidth, this.screenSizeInfo.windowWidth)
  57524. prepareToRender()
  57525. }
  57526. }
  57527. }
  57528. if (render) {
  57529. this.setSize(w, h, ratio);
  57530. }
  57531. } */
  57532. setSize(width, height, devicePixelRatio, onlyForTarget){
  57533. //console.log('setSize', width)
  57534. if(!onlyForTarget){//onlyForTarget表示不更改当前renderer,只是为了rendertarget才要改变viewport
  57535. this.renderer.setSize(width, height, null, devicePixelRatio); // resize之后会自动clear(似乎因为setScissor ),所以一定要立刻绘制,所以setSize要在cameraChanged、update之前
  57536. }
  57537. this.composer && this.composer.setSize(width, height);
  57538. if(this.viewports){
  57539. this.viewports.forEach((view,i)=>{
  57540. if(!view.active)return
  57541. var width_ = width * view.width;
  57542. var height_ = height * view.height;
  57543. if(height_ == 0)return //avoid NAN
  57544. view.setResolution(Math.ceil(width_), Math.ceil(height_), width, height ); //本来应该是floor,但是这样奇数时会少一个像素,导致向左移一个像素且宽度少1。现在则多绘制1个像素,超出的1个像素应该不会绘制出来(但不知道其他地方是否有偏差,比如pick时)
  57545. let aspect = width_ / height_; //camera的参数精确些,不用视口的归整的resolution像素值,否则hasChange无法为true, 导致canvasResize了但map没update从而闪烁
  57546. view.camera.aspect = aspect;
  57547. if(view.camera.type == "OrthographicCamera"){
  57548. /* //不改宽度 同4dkk
  57549. var heightHalf = view.camera.right / aspect
  57550. view.camera.top = heightHalf
  57551. view.camera.bottom = -heightHalf */
  57552. //高宽都改 使大小不随视口大小改变 navvis (直接和视口大小一致即可,通过zoom来定大小)
  57553. view.camera.left = -width_/2;
  57554. view.camera.right = width_/2;
  57555. view.camera.bottom = -height_/2;
  57556. view.camera.top = height_/2;
  57557. }else {
  57558. }
  57559. view.camera.updateProjectionMatrix();
  57560. });
  57561. }
  57562. if(!onlyForTarget){//因为onlyForTarget不传递devicePixelRatio所以不发送了
  57563. this.emitResizeMsg({viewport:this.viewports[0], deviceRatio:devicePixelRatio});
  57564. }
  57565. }
  57566. emitResizeMsg(e){//切换viewport渲染时就发送一次, 通知一些材质更新resolution。
  57567. if(!e.viewport.resolution.equals(this.oldResolution)){
  57568. this.dispatchEvent($.extend(e, {type:'resize'}));
  57569. this.oldResolution.copy(e.viewport.resolution);
  57570. }
  57571. }
  57572. cameraChanged() {//判断相机是否改变
  57573. var changed = false;
  57574. /* if(this.needRender){
  57575. this.needRender = false
  57576. return true
  57577. } */
  57578. for(let i=0,j=this.viewports.length;i<j;i++){
  57579. let changeInfo = this.viewports[i].cameraChanged();
  57580. if(changeInfo.changed){
  57581. changed = true;
  57582. //if(!this.changeTime ||this.changeTime<100){
  57583. this.dispatchEvent({
  57584. type: "camera_changed",
  57585. camera: this.viewports[i].camera,
  57586. viewport : this.viewports[i],
  57587. changeInfo
  57588. });
  57589. //this.changeTime = (this.changeTime || 0) +1
  57590. //}
  57591. }
  57592. }
  57593. return changed
  57594. }
  57595. makeScreenshot( size, viewports, compressRatio){//暂时不要指定viewports渲染,但也可以
  57596. let {width, height} = size;
  57597. /* let oldBudget = Potree.pointBudget;
  57598. Potree.pointBudget = Math.max(10 * 1000 * 1000, 2 * oldBudget);
  57599. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, size );
  57600. Potree.pointBudget = oldBudget;
  57601. this.dispatchEvent({ //resize everything such as lines targets
  57602. type: 'resize',
  57603. resolution: new THREE.Vector2(width,height),
  57604. });*/
  57605. let target = new WebGLRenderTarget(width, height, {
  57606. format: RGBAFormat,
  57607. });
  57608. this.setSize(width, height,1,true);
  57609. this.render({
  57610. target ,
  57611. //camera ,
  57612. viewports: viewports || this.viewports,
  57613. screenshot : true,
  57614. width ,
  57615. height,
  57616. resize :true //需要resize
  57617. });
  57618. let dataUrl = Potree.Utils.renderTargetToDataUrl(target, width, height, this.renderer, compressRatio);
  57619. /* let pixelCount = width * height;
  57620. let buffer = new Uint8Array(4 * pixelCount);
  57621. this.renderer.readRenderTargetPixels(target, 0, 0, width, height, buffer);
  57622. let dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio) */
  57623. target.dispose();
  57624. //resize back
  57625. //this.updateScreenSize({forceUpdateSize:true})
  57626. return {
  57627. width,
  57628. height,
  57629. dataUrl
  57630. };
  57631. }
  57632. }
  57633. 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";
  57634. const prefixFragment ="precision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n";
  57635. let shader = {
  57636. uniforms: {
  57637. opacity: {
  57638. type: "f",
  57639. value: 1
  57640. },
  57641. progress: {
  57642. type: "f",
  57643. value: 0
  57644. },
  57645. pano0Map: {
  57646. type: "t",
  57647. value: null
  57648. },
  57649. pano1Map: {
  57650. type: "t",
  57651. value: null
  57652. },
  57653. depthMap0: {
  57654. type: "t",
  57655. value: null
  57656. },
  57657. depthMap1: {
  57658. type: "t",
  57659. value: null
  57660. },
  57661. pano0Position: {
  57662. type: "v3",
  57663. value: new Vector3
  57664. },
  57665. pano0Matrix: {
  57666. type: "m4",
  57667. value: new Matrix4
  57668. },
  57669. pano1Position: {
  57670. type: "v3",
  57671. value: new Vector3
  57672. },
  57673. pano1Matrix: {
  57674. type: "m4",
  57675. value: new Matrix4
  57676. },
  57677. /* pano1Matrix2: {
  57678. type: "m4",
  57679. value: new THREE.Matrix4
  57680. },
  57681. */
  57682. inverseProjectionMatrix: {
  57683. value: new Matrix4
  57684. },
  57685. /* projectionMatrix:{//需要再写一遍吗
  57686. value: new THREE.Matrix4
  57687. }, */
  57688. viewport: {
  57689. value: new Vector4
  57690. },
  57691. //如 {x: 0, y: 0, z: 428, w: 969} xy应该是offset, zw是宽高
  57692. cameraHeight0: {
  57693. type: "f",
  57694. value: 1
  57695. },
  57696. cameraHeight1: {
  57697. type: "f",
  57698. value: 1
  57699. },
  57700. },
  57701. vertexShader: prefixVertex + `
  57702. uniform vec3 pano0Position;
  57703. uniform mat4 pano0Matrix;
  57704. uniform vec3 pano1Position;
  57705. uniform mat4 pano1Matrix;
  57706. //uniform mat4 pano1Matrix2;
  57707. varying vec2 vUv;
  57708. varying vec3 vWorldPosition0;
  57709. varying vec3 vWorldPosition1;
  57710. varying vec3 vWorldPosition12;
  57711. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  57712. {
  57713. float y = direction.y;
  57714. direction.y = direction.z;
  57715. direction.z = -y;
  57716. return direction;
  57717. }
  57718. void main() {
  57719. vUv = uv;
  57720. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  57721. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  57722. vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  57723. vWorldPosition0.x *= -1.0;
  57724. vWorldPosition0 = transformAxis(vWorldPosition0);
  57725. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  57726. vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  57727. vWorldPosition1.x *= -1.0;
  57728. vWorldPosition1 = transformAxis(vWorldPosition1);
  57729. /*
  57730. vec3 positionLocalToPanoCenter12 = worldPosition.xyz - pano1Position;
  57731. vWorldPosition12 = (vec4(positionLocalToPanoCenter12, 1.0) * pano1Matrix2).xyz;
  57732. vWorldPosition12.x *= -1.0;
  57733. vWorldPosition12 = transformAxis(vWorldPosition12);
  57734. */
  57735. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  57736. }
  57737. `,
  57738. fragmentShader: prefixFragment + `
  57739. #define PI 3.141592653
  57740. uniform float modelAlpha;
  57741. uniform float opacity;
  57742. uniform float progress;
  57743. uniform int blackout;
  57744. uniform vec3 pano0Position;
  57745. uniform vec3 pano1Position;
  57746. uniform float maxDistance;
  57747. uniform float minDistance;
  57748. uniform float minOpa;
  57749. uniform float cameraHeight0;
  57750. uniform float cameraHeight1;
  57751. /* uniform sampler2D pano0Map;
  57752. uniform sampler2D pano1Map; */
  57753. uniform samplerCube pano0Map;
  57754. uniform samplerCube pano1Map;
  57755. varying vec2 vUv;
  57756. varying vec3 vWorldPosition0;
  57757. varying vec3 vWorldPosition1;
  57758. //varying vec3 vWorldPosition12;
  57759. /* vec2 getSamplerCoord( vec3 direction )
  57760. {
  57761. direction = normalize(direction);
  57762. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  57763. float ty=acos(direction.z)/PI;
  57764. return vec2(tx,ty);
  57765. } */
  57766. vec2 getSamplerCoord2( vec3 direction )
  57767. {
  57768. direction = normalize(direction);
  57769. float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;
  57770. float ty=acos(direction.y)/PI;
  57771. return vec2(tx,ty);
  57772. }
  57773. #extension GL_EXT_frag_depth : enable
  57774. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  57775. uniform sampler2D depthMap0;
  57776. uniform sampler2D depthMap1;
  57777. uniform mat4 inverseProjectionMatrix;
  57778. uniform mat4 projectionMatrix;
  57779. uniform vec4 viewport;
  57780. vec2 getDepth(vec3 dir, sampler2D depthMap, float height, vec4 eyePos){
  57781. vec2 depthValue = vec2(0.0, 0.0);
  57782. vec2 uv2 = getSamplerCoord2(/* vWorldPosition12 */dir.xyz); //暂时只用基于目标漫游点的方向
  57783. uv2.x -= 0.25; //全景图和Cube的水平采样起始坐标相差90度,这里矫正 0.25 个采样偏移
  57784. vec4 depth = texture2D(depthMap, uv2);
  57785. //float distance = depth.r + 256. * (depth.g + 256. * depth.b);
  57786. //distance *= 255. * .001; // distance is now in meters
  57787. //更改
  57788. float distance = (depth.g + depth.r / 256.) * 255.; //为什么要乘以255
  57789. if(distance == 0.0){//漫游点底部识别不到的区域,给一个地板高度
  57790. if(uv2.y > 0.75)distance = height / dir.y;
  57791. else distance = 100000.0;//给个超级远的值
  57792. }
  57793. depthValue.x = distance;
  57794. // return r[1] + r[0] / 256
  57795. distance += .1; // add a safety margin
  57796. vec4 eyePos2 = vec4(normalize(eyePos.xyz) * distance, 1.);
  57797. vec4 clipPos2 = projectionMatrix * eyePos2;
  57798. vec4 ndcPos2 = clipPos2 * 1. / clipPos2.w;
  57799. depthValue.y = 0.5 * ((gl_DepthRange.far - gl_DepthRange.near) * ndcPos2.z
  57800. + gl_DepthRange.near + gl_DepthRange.far);
  57801. return depthValue;
  57802. }
  57803. //注:未加载好的话,depth为0,导致第一次漫游过去的时候许多mesh会立刻被遮挡,所以要确保加载完
  57804. #endif
  57805. void main()
  57806. {
  57807. /* vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  57808. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  57809. vec4 colorFromPano0=texture2D(pano0Map,samplerCoord0);
  57810. vec4 colorFromPano1=texture2D(pano1Map,samplerCoord1); */
  57811. vec4 colorFromPano0 = vec4(0.0,0.0,0.0,0.0);
  57812. if(progress < 1.0){//通常是1
  57813. colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  57814. }
  57815. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  57816. gl_FragColor=mix(colorFromPano0,colorFromPano1,progress);
  57817. //深度图修改深度
  57818. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  57819. vec4 ndcPos;
  57820. ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.;
  57821. ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
  57822. (gl_DepthRange.far - gl_DepthRange.near);
  57823. ndcPos.w = 1.0;
  57824. vec4 clipPos = ndcPos / gl_FragCoord.w;
  57825. vec4 eyePos = inverseProjectionMatrix * clipPos;
  57826. vec2 depth0 = vec2(0.0,0.0);
  57827. if(progress < 1.0){
  57828. depth0 = getDepth(vWorldPosition0, depthMap0, cameraHeight0, eyePos);
  57829. }
  57830. vec2 depth1 = getDepth(vWorldPosition1, depthMap1, cameraHeight1, eyePos);
  57831. /* if(progress < 1.0 && depth1.x == 0.0 && depth0.x > 0.0){
  57832. gl_FragDepthEXT = depth0.y;
  57833. }else{ */
  57834. gl_FragDepthEXT = mix(depth0.y,depth1.y,progress);
  57835. //}
  57836. #endif
  57837. }
  57838. `
  57839. };
  57840. class ModelTextureMaterial extends RawShaderMaterial {
  57841. constructor( ){
  57842. let defines = {};
  57843. super({
  57844. fragmentShader: shader.fragmentShader,
  57845. vertexShader: shader.vertexShader,
  57846. uniforms: UniformsUtils.clone(shader.uniforms),
  57847. side:DoubleSide,
  57848. name: "ModelTextureMaterial",
  57849. defines
  57850. });
  57851. let setSize = (e)=>{
  57852. let viewport = e.viewport;
  57853. let viewportOffset = viewport.offset || new Vector2();
  57854. let resolution = viewport.resolution2;
  57855. this.uniforms.viewport.value.set(viewportOffset.x, viewportOffset.y, resolution.x, resolution.y);
  57856. };
  57857. let viewport = viewer.mainViewport;
  57858. setSize({viewport});
  57859. viewer.addEventListener('resize',(e)=>{
  57860. setSize(e);
  57861. });
  57862. //var supportExtDepth = !!Features.EXT_DEPTH.isSupported()
  57863. {
  57864. //add
  57865. viewer.addEventListener('camera_changed', (e)=>{
  57866. //this.uniforms.projectionMatrix.value.copy(e.camera.projectionMatrix)
  57867. this.uniforms.inverseProjectionMatrix.value.copy(e.camera.projectionMatrixInverse);
  57868. });
  57869. }
  57870. //-------------------------------------
  57871. }
  57872. /**
  57873. *
  57874. * @param {Panorama} pano0
  57875. * @param {Panorama} pano1
  57876. * @param {boolean} flag
  57877. 更新全景图的材质uniforms
  57878. */
  57879. setProjectedPanos(pano0, pano1, progressValue ){
  57880. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  57881. //pano0.ensureSkyboxReadyForRender();
  57882. if(pano0){
  57883. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();//pano0.texture
  57884. this.uniforms.pano0Position.value.copy(pano0.position);
  57885. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix/* pano0.mesh.matrixWorld */ );
  57886. this.uniforms.cameraHeight0.value = pano0.floorPosition.distanceTo(pano0.position);
  57887. //pano1.ensureSkyboxReadyForRender();
  57888. }
  57889. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();//pano1.texture;
  57890. this.uniforms.pano1Position.value.copy(pano1.position);
  57891. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix /* pano1.mesh.matrixWorld */ );
  57892. this.uniforms.cameraHeight1.value = pano1.floorPosition.distanceTo(pano1.position);
  57893. this.pano0 = pano0;
  57894. this.pano1 = pano1;
  57895. this.updateDepthTex(pano0);
  57896. this.updateDepthTex(pano1);
  57897. //console.log('setProjectedPanos', pano0&&pano0.id, pano1&&pano1.id)
  57898. this.needsUpdate = true;
  57899. }
  57900. updateDepthTex(pano){
  57901. if( !Potree.settings.useDepthTex || !pano || !pano.depthTex || pano!=this.pano0 && pano!=this.pano1)return
  57902. //console.log('updateDepthTex', pano.id, this.pano0 && this.pano0.id, this.pano1 && this.pano1.id)
  57903. this.uniforms.depthMap0.value = this.pano0 && this.pano0.depthTex;
  57904. this.uniforms.depthMap1.value = this.pano1 && this.pano1.depthTex;
  57905. this.updateDepthTexEnable();
  57906. }
  57907. updateDepthTexEnable(){
  57908. let hasDepthTex = this.pano0 && this.pano1 && this.pano0.pointcloud.hasDepthTex && this.pano1.pointcloud.hasDepthTex; //暂时不知道一个有图一个没图怎么写所以
  57909. Common.addOrRemoveDefine(this, 'hasDepthTex', hasDepthTex?'add':'remove' );
  57910. }
  57911. /* EnableDepthTex(){//开启DepthTex
  57912. if(this.defines['hasDepthTex']){
  57913. return
  57914. }
  57915. this.defines['hasDepthTex'] = ''
  57916. this.needsUpdate = true;
  57917. } */
  57918. }
  57919. var TileUtils = {};
  57920. TileUtils.TILE_SIZE = 512,
  57921. TileUtils.FACES_PER_PANO = 6,
  57922. TileUtils.LocationOnTile = {
  57923. Center: 0,
  57924. UpperLeft: 1,
  57925. UpperRight: 2,
  57926. LowerRight: 3,
  57927. LowerLeft: 4
  57928. },
  57929. /*
  57930. * 获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的指定位置)。spherical通过先求uv,再直接得到dir
  57931. * @param {*} size 面分辨率
  57932. * @param {*} cubeFace 所在面
  57933. * @param {*} Center 在tile上的目标位置,默认为中心,其他位置就是四个顶点
  57934. * @param {*} c 似乎是在tile的缩进百分比,根据所在面的不同,分别向不同方向缩进,但都是向tile的中心
  57935. * @param {*} dir 所求方向
  57936. */
  57937. TileUtils.getTileVector = function() {//获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的中心)
  57938. return function(size, tileSize, cubeFace, tileX, tileY, Center, c, dir) {//c似乎是缩进百分比
  57939. Center = Center || TileUtils.LocationOnTile.Center;
  57940. //假设该cube边长为2:
  57941. var u = size / tileSize
  57942. , d = tileX / u;
  57943. tileY = -tileY + (u - 1);
  57944. var p = tileY / u
  57945. , f = tileSize / size
  57946. , g = 2 * f //一个tile的宽度 (乘以2是因为cube边长是2)
  57947. , m = g / 2
  57948. , v = 2 * d - 1 + m
  57949. , A = 2 * p - 1 + m;
  57950. switch (Center) {//计算在tile中指定位置带来的偏移
  57951. case TileUtils.LocationOnTile.UpperLeft: //1
  57952. v -= m,
  57953. A += m,
  57954. v += c * g; //似乎是向内缩进
  57955. break;
  57956. case TileUtils.LocationOnTile.UpperRight:
  57957. v += m,
  57958. A += m,
  57959. A -= c * g;
  57960. break;
  57961. case TileUtils.LocationOnTile.LowerRight:
  57962. v += m,
  57963. A -= m,
  57964. v -= c * g;
  57965. break;
  57966. case TileUtils.LocationOnTile.LowerLeft:
  57967. v -= m,
  57968. A -= m,
  57969. A += c * g;
  57970. break;
  57971. case TileUtils.LocationOnTile.Center: //0
  57972. }
  57973. switch (cubeFace) {
  57974. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  57975. MathLight.setVector(dir, -1, A, -v);
  57976. break;
  57977. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  57978. MathLight.setVector(dir, 1, A, v);
  57979. break;
  57980. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: //顶面
  57981. MathLight.setVector(dir, -v, 1, -A);
  57982. break;
  57983. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  57984. MathLight.setVector(dir, -v, -1, A);
  57985. break;
  57986. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  57987. MathLight.setVector(dir, -v, A, 1);
  57988. break;
  57989. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  57990. MathLight.setVector(dir, v, A, -1);
  57991. }
  57992. MathLight.normalize(dir);
  57993. }
  57994. }(),
  57995. /*
  57996. * 获取该tile在第几个面(简易装载法)
  57997. */
  57998. TileUtils.getFaceForTile = function(size, index) {//获取该tile在第几个面
  57999. var tileSize = TileUtils.TILE_SIZE;
  58000. size < TileUtils.TILE_SIZE && (tileSize = size);
  58001. var n = Math.floor(size / tileSize)
  58002. , sum = n * n; //得每个面tile总数
  58003. return Math.floor(index / sum)
  58004. }
  58005. ,
  58006. TileUtils.getTileLocation = function(size, t, result) {
  58007. var tileSize = TileUtils.TILE_SIZE;
  58008. size < TileUtils.TILE_SIZE && (tileSize = size);
  58009. var r = TileUtils.getFaceForTile(size, t)
  58010. , a = Math.floor(size / tileSize)
  58011. , s = a * a
  58012. , l = t - r * s;
  58013. result.tileX = l % a;
  58014. result.tileY = Math.floor(l / a);
  58015. result.face = r;
  58016. result.faceTileIndex = l;
  58017. return result
  58018. }
  58019. ,
  58020. /*
  58021. * 求size分辨率需要多少张tile
  58022. */
  58023. TileUtils.getTileCountForSize = function(e) {
  58024. if (e <= TileUtils.TILE_SIZE)
  58025. return TileUtils.FACES_PER_PANO;
  58026. var t = Math.floor(e / TileUtils.TILE_SIZE)
  58027. , i = t * t
  58028. , n = i * TileUtils.FACES_PER_PANO;
  58029. return n
  58030. }
  58031. ,
  58032. TileUtils.getRelativeDirection = function() {
  58033. var e = new MathLight.Matrix4
  58034. , t = new MathLight.Quaternion;
  58035. return function(i, n) {//i是pano.quaternion, n是camera的direction
  58036. t.copy(i),
  58037. t.inverse(),
  58038. e.makeRotationFromQuaternion(t),
  58039. e.applyToVector3(n),
  58040. MathLight.normalize(n);
  58041. }
  58042. }(),
  58043. /*
  58044. * 根据方向寻找合适的tile加载
  58045. */
  58046. TileUtils.matchingTilesInDirection = function() {
  58047. var e = new MathLight.Vector3
  58048. , t = new MathLight.Vector3(0,0,-1)
  58049. , i = new MathLight.Quaternion
  58050. , n = function(e, t) {
  58051. e.push({
  58052. face: t.face,
  58053. faceTileIndex: t.faceTileIndex,
  58054. tileX: t.tileX,
  58055. tileY: t.tileY
  58056. });
  58057. }
  58058. , a = function() {
  58059. var e = {
  58060. face: -1,
  58061. faceTileIndex: -1,
  58062. tileX: -1,
  58063. tileY: -1
  58064. };
  58065. return function(size, i, r) {
  58066. for (var a = TileUtils.getTileCountForSize(size), s = 0, l = 0; l < a; l++)
  58067. TileUtils.getTileLocation(size, l, e),
  58068. i && !i(e) || (s++,
  58069. r && n(r, e));
  58070. return s
  58071. }
  58072. }();
  58073. return function(pano, size, dir, hFov, vFov, result) {
  58074. var d = size < TileUtils.TILE_SIZE ? size : TileUtils.TILE_SIZE;
  58075. //TileUtils.getTileCountForSize(size);
  58076. if (!hFov && !vFov)
  58077. return a(size, null, result);
  58078. var p = !!vFov;
  58079. vFov = vFov || hFov,
  58080. vFov = Math.max(0, Math.min(vFov, 360)),
  58081. hFov = Math.max(0, Math.min(hFov, 360)),
  58082. MathLight.copyVector(dir, e),
  58083. TileUtils.getRelativeDirection(pano.quaternion4dkk, e);
  58084. if(p){//如果有vFov hFov
  58085. i.setFromUnitVectors(e, t);
  58086. var f = function(e) {
  58087. return TileUtils.isTileWithinFrustum(size, d, e.face, e.tileX, e.tileY, i, hFov, vFov)//在视野中的
  58088. };
  58089. return a(size, f, result)
  58090. }
  58091. var g = function(t) {//如果仅有hFov
  58092. return TileUtils.isTileWithinFOV(size, d, t.face, t.tileX, t.tileY, e, hFov)
  58093. };
  58094. return a(size, g, result)
  58095. }
  58096. }(),
  58097. /*
  58098. * 是否在屏幕范围内
  58099. */
  58100. TileUtils.isTileWithinFrustum = function() {
  58101. var e = new MathLight.Vector3
  58102. , t = 1e-5;
  58103. return function(i, n, a, s, l, c, h, u) {
  58104. 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++){
  58105. TileUtils.getTileVector(i, n, m, s, l, b, 0, e),//get e // size, tileSize, cubeFace, tileX, tileY, Center, c, dir
  58106. MathLight.applyQuaternionToVector(c, e);
  58107. if (e.z >= -t)//似乎是在相机背面
  58108. I++;
  58109. else {
  58110. var w = -1 / e.z
  58111. , _ = e.x * w
  58112. , T = e.y * w;
  58113. T > d ? v++ : T < p && A++, //这四种似乎代表在这个画框之外,如在左、在上、在下、在右
  58114. _ > f ? y++ : _ < g && C++,
  58115. E++;
  58116. }
  58117. }
  58118. return A !== E && v !== E && y !== E && C !== E //如果有一项和E相等代表要么是在相机背面要么是tile的四个顶点都画在画布的同一边,所以肯定不在画布上
  58119. }
  58120. }(),
  58121. /*
  58122. * 是否在FOV范围内
  58123. */
  58124. TileUtils.isTileWithinFOV = function() {
  58125. var e = new MathLight.Vector3
  58126. , t = new MathLight.Vector3(0,1,0)
  58127. , i = new MathLight.Vector3(1,0,0);
  58128. return function(panoSize, tileSize, face, tileX, tileY, direction, fov) {//direction是作用了pano.quaternion的camera.direction
  58129. var d = TileUtils.mapFaceToCubemapFace(face);
  58130. MathLight.cross(direction, t, i); //get i 好像没用到
  58131. TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, TileUtils.LocationOnTile.Center, 0, e);
  58132. if (TileUtils.isWithinFOV(e, direction, fov, null))//先判断tile中心在不在FOV内
  58133. return !0;
  58134. for (var p = fov / 360, f = Math.floor(1 / p), g = 0, m = 0; m < f; m++) {
  58135. for (var v = TileUtils.LocationOnTile.UpperLeft; v <= TileUtils.LocationOnTile.LowerLeft; v++)
  58136. if (TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, v, g, e),
  58137. TileUtils.isWithinFOV(e, direction, fov, null))
  58138. return !0;
  58139. g += p; //可能是考虑到有可能tile比fov覆盖了fov(虽然一般不可能,除非fov特别小),所以将tile分成若干段,取tile中的点再检测下
  58140. }
  58141. return !1
  58142. }
  58143. }(),
  58144. TileUtils.isWithinFOV = function() {
  58145. var e = new MathLight.Vector3
  58146. , t = new MathLight.Vector3;
  58147. return function(dir, cameraDir, fov, a) {
  58148. if (MathLight.copyVector(dir, t),
  58149. a) {
  58150. MathLight.copyVector(a, e),
  58151. MathLight.normalize(e);
  58152. var s = MathLight.dot(e, dir);
  58153. e.x *= s,
  58154. e.y *= s,
  58155. e.z *= s,
  58156. MathLight.subVector(t, e);
  58157. }
  58158. var l = fov / 2 * MathLight.RADIANS_PER_DEGREE
  58159. , c = Math.cos(l)
  58160. , h = MathLight.dot(t, cameraDir);
  58161. return h >= c
  58162. }
  58163. }(),
  58164. TileUtils.mapFaceToCubemapFace = function() {
  58165. var e = {
  58166. 0: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  58167. 1: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  58168. 2: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  58169. 3: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  58170. 4: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  58171. 5: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
  58172. };
  58173. return function(t) {
  58174. return e[t]
  58175. }
  58176. }();
  58177. var texLoader$2 = new TextureLoader();
  58178. const labelProp = {
  58179. sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  58180. backgroundColor:{r: 255, g: 255, b: 255, a: 0.4 },
  58181. textColor:{r: 0, g: 0, b: 0, a: 1 },
  58182. borderRadius: 15,
  58183. renderOrder:10
  58184. };
  58185. let standardMarkerMat;
  58186. let markerTex;
  58187. let getMarerMat = function(){
  58188. if(!markerTex) {
  58189. markerTex = {
  58190. default:texLoader$2.load( Potree.resourcePath+'/textures/marker.png' ),
  58191. ring:texLoader$2.load( Potree.resourcePath+'/textures/marker2.png' )
  58192. };
  58193. markerTex.default.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  58194. markerTex.ring.anisotropy = 4;
  58195. //有可能被点云遮住吗。
  58196. }
  58197. return new DepthBasicMaterial({opacity:0.7, side: DoubleSide , map:markerTex.default ,transparent:true,
  58198. clipDistance: 2, occlusionDistance:1, //不能设置太短,因为过渡时深度不准确
  58199. //depthTest: !!Potree.settings.useDepthTex,
  58200. useDepth: !!Potree.settings.useDepthTex
  58201. //改为DepthBasicMaterial是因为原Basic的材质过渡时会先隐藏后出现
  58202. })
  58203. };
  58204. //显示全景图时marker没有被遮挡,如果需要,要换成depthBasicMaterial 或者直接把skybox的深度修改(拿到深度贴图后更如此)
  58205. let planeGeo$1 = new PlaneBufferGeometry(0.2,0.2);
  58206. let sg = new SphereGeometry(0.1, 8, 8);
  58207. let smHovered = new MeshBasicMaterial({/* side: THREE.BackSide, */color: 0xff0000});
  58208. let sm = new MeshBasicMaterial({/* side: THREE.BackSide */});
  58209. var rot90 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  58210. //var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI/2 ); //4dkk->navvis
  58211. //var rot901 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/2 ); //整张球幕图要旋转下
  58212. //rot90 = new THREE.Quaternion().multiplyQuaternions( rot901, rot90)
  58213. var old = null;
  58214. /*
  58215. 转成四维看看的axis:
  58216. var a = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), THREE.Math.degToRad(-90)) 因为四维的要绕y转90
  58217. 这里的quaternion.multiply(a);
  58218. 先乘再换顺序 w : q.w, x:q.x , y:-q.z, z:q.y
  58219. */
  58220. //暂时直接用4dkkconsole输出的数据
  58221. class Panorama extends EventDispatcher{
  58222. constructor(o, images360){//file, time, longitude, latitude, altitude, course, pitch, roll
  58223. super();
  58224. this.id = o.id; //唯一标识
  58225. this.images360 = images360;
  58226. this.visible = true; //for viewer updateVisible
  58227. this.enabled = true;//是否可以走
  58228. this.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  58229. //console.log('pano isVisible', this.id, e.visible)
  58230. viewer.updateVisible(this.marker, 'panoVisi', e.visible);
  58231. Potree.settings.showPanoMesh && (this.mesh.visible = e.visible);
  58232. if(e.reason == 'screenshot' || e.visible){
  58233. this.label && (this.label.visible = e.visible);//截图时隐藏下
  58234. }
  58235. viewer.updateVisible(this.label2, 'panoVisi', e.visible);
  58236. });
  58237. /*
  58238. 漫游点可见性:旧
  58239. level reason 类型
  58240. 2(最高)buildingChange(不在此楼层) unvisible
  58241. 1 modeIsShowPanos(漫游模式) visible //不记得为什么加这个了,所以重写
  58242. 0 pointcloudVisi(隐藏了数据集) unvisible
  58243. */
  58244. /*
  58245. 漫游点可见性:新
  58246. level reason 类型
  58247. 2(最高)buildingChange(不在此楼层) unvisible
  58248. 1 ifShowMarker(marker显示开关) unvisible
  58249. 0 pointcloudVisi(隐藏了数据集) unvisible
  58250. */
  58251. if(Potree.settings.editType == 'pano'){//漫游点拼合编辑
  58252. this.uuid = o.uuid; //因为有多个数据集 所以会重复
  58253. this.index = o.index; //下标, 用于visibles
  58254. this.pointcloud = viewer.scene.pointclouds.find(e=>e.panoUuid == o.uuid);
  58255. this.pointcloud.panos.push(this);
  58256. this.sid = this.pointcloud.dataset_id + '|' + this.uuid; //不会更改的标记 用于entity.panos里的标记
  58257. this.panosData = o;
  58258. //数据中原本的位置朝向
  58259. this.dataPosition = new Vector3().copy(o.pose.translation);
  58260. this.dataQuaternion = new Quaternion().copy(o.pose.rotation);
  58261. this.dataRotation = new Euler().setFromQuaternion(this.dataQuaternion);
  58262. //因为位置朝向随着点云位置改变,所以直接运用到点云上,这里清零
  58263. this.originPosition = new Vector3(); //{x: 0, y: 0, z: 0}
  58264. this.quaternion = new Quaternion(); //{w: 0, x: 0, y: 0, z: 1}
  58265. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  58266. this.visibles = o.visibles;
  58267. const height = 1.4; //相机高度
  58268. this.originFloorPosition = this.originPosition.clone();
  58269. this.originFloorPosition.z -= height;
  58270. /* this.originPosition = new THREE.Vector3().copy(o.pose.translation) //{x: 0, y: 0, z: 0}
  58271. this.quaternion = new THREE.Quaternion().copy(o.pose.rotation) //{w: 0, x: 0, y: 0, z: 1}
  58272. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  58273. this.visibles = o.visibles
  58274. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.uuid)
  58275. this.pointcloud.panos.push(this)
  58276. const height = 1.5; //相机高度
  58277. this.originFloorPosition = this.originPosition.clone()
  58278. this.originFloorPosition.z -= height
  58279. */
  58280. }else {
  58281. this.originPosition = new Vector3().fromArray(o.dataset_location);
  58282. this.originFloorPosition = new Vector3().fromArray(o.dataset_floor_location);
  58283. this.originID = parseInt(o.file_id);//"file_id":"00022"对应是原本的4dkk的id --来自vision.txt
  58284. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.dataset_id) || viewer.scene.pointclouds[0];
  58285. this.pointcloud.panos.push(this);
  58286. //this.sid = this.pointcloud.sceneCode + '|' + this.originID //不会更改的标记
  58287. this.sid = this.pointcloud.dataset_id + '|' + this.originID; //不会更改的标记
  58288. //全景图和Cube的水平采样起始坐标相差90度
  58289. /* if(from4dkk){
  58290. var qua = o.dataset_orientation
  58291. var quaternion = new THREE.Quaternion().fromArray(qua)
  58292. quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion, rot901);//整张球幕图要旋转下 因为在4dkk里转过,还原。如果是tiles的不用
  58293. this.quaternion = new THREE.Quaternion(quaternion.x, -quaternion.z, quaternion.y, quaternion.w) //转化坐标
  58294. }else{ */
  58295. var qua = o.dataset_orientation;
  58296. qua = [qua[1], qua[2], qua[3], qua[0]];
  58297. this.quaternion = new Quaternion().fromArray(qua);
  58298. this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion);//4dkk内使用的quaternion
  58299. this.quaternion2 = this.quaternion.clone();
  58300. this.quaternion = new Quaternion().multiplyQuaternions(this.quaternion, rot90);//全景图和Cube的水平采样起始坐标相差90度,cubeTex转90度
  58301. this.rotation4dkk = new Euler().setFromQuaternion(this.quaternion4dkk);
  58302. //}
  58303. //this.quaternion1 = Potree.Utils.QuaternionFactory.fromArray(o.dataset_orientation)
  58304. //同quaternion
  58305. //let xy = this.transform.forward([this.longitude, this.latitude]);
  58306. this.file = `https://4dkk.4dage.com/images/images${Potree.settings.number}/pan/high/${this.id}.jpg`;
  58307. }
  58308. this.rotation = new Euler().setFromQuaternion(this.quaternion);
  58309. this.build();
  58310. this.transformByPointcloud(); //初始化位移
  58311. {//tile
  58312. this.minimumTiledPanoLoaded = !1;
  58313. this.highestPartialTileRenderOpCompleted = 0;
  58314. this.highestFullTileRenderOpCompleted = 0;
  58315. this.shouldRedrawOnBaseLoaded = !1;
  58316. this.resolutionPromise = {};
  58317. this.tiledPanoRenderTarget = null;
  58318. this.zoomed = !1;
  58319. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderSuccess, this.onTileRendered.bind(this));
  58320. images360.panoRenderer.addEventListener(PanoRendererEvents.PanoRenderComplete, this.onPanoRendered.bind(this));
  58321. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderFailure, this.onTileRenderFail.bind(this));
  58322. images360.panoRenderer.addEventListener(PanoRendererEvents.UploadAttemptedForAllTiles, this.onUploadAttemptedForAllTiles.bind(this));
  58323. }
  58324. this.addEventListener('hoverOn', (e)=>{//from Map
  58325. if(!e.byMainView){
  58326. this.hoverOn(e);
  58327. }
  58328. });
  58329. this.addEventListener('hoverOff', (e)=>{
  58330. if(!e.byMainView){
  58331. this.hoverOff(e);
  58332. }
  58333. });
  58334. }
  58335. setEnable(enable){//是否可以走
  58336. viewer.updateVisible(this, 'isEnabled', enable); //令所有marker不可见
  58337. this.enabled = enable;
  58338. //如果当前在全景模式且在这个点,需要切换显示吗? 目前用不到
  58339. }
  58340. loadDepthImg(){
  58341. if(!this.pointcloud.hasDepthTex || this.depthTex || this.depthTexLoading)return
  58342. this.depthTexLoading = true;
  58343. let src = Potree.settings.number == 'SS-t-7DUfWAUZ3V' ? `${Potree.scriptPath}/data/${Potree.settings.number}/depthMap/${this.originID}.png`
  58344. : `https://laser-oss.4dkankan.com/${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png`;
  58345. let texture = texLoader$2.load( src, ()=>{
  58346. this.depthTex = texture;
  58347. this.images360.dispatchEvent({type:'loadedDepthImg', pano:this, loaded:true});
  58348. this.depthTexLoading = false;
  58349. },(e)=>{//error
  58350. console.error('loadDepthImg失败, 数据集sceneCode'+ this.pointcloud.sceneCode, this.id );
  58351. this.pointcloud.hasDepthTex = false;
  58352. this.images360.dispatchEvent({type:'loadedDepthImg', pano:this, });
  58353. });
  58354. texture.wrapS = RepeatWrapping;
  58355. texture.flipY = false;
  58356. texture.magFilter = LinearFilter;
  58357. texture.minFilter = LinearFilter;
  58358. }
  58359. build(){
  58360. /* let mesh = new THREE.Mesh(sg, sm);
  58361. mesh.scale.set(1, 1, 1);
  58362. mesh.material.transparent = true;
  58363. mesh.material.opacity = 0.75;
  58364. mesh.pano = this;
  58365. mesh.name = 'panoSphere'
  58366. mesh.addEventListener('mouseover',(e)=>{
  58367. mesh.material = smHovered
  58368. })
  58369. mesh.addEventListener('mouseleave',(e)=>{
  58370. mesh.material = sm
  58371. })
  58372. mesh.addEventListener('click',(e)=>{
  58373. this.images360.focusPano(this)
  58374. })
  58375. this.mesh = mesh;
  58376. if(!Potree.settings.showPanoMesh) mesh.visible = false
  58377. this.images360.node.add(mesh)
  58378. */
  58379. { // orientation
  58380. //var {course, pitch, roll} = this;
  58381. //mesh.quaternion.copy(this.quaternion)
  58382. //add
  58383. //var quaternion = new THREE.Quaternion().multiplyQuaternions(this.quaternion, rot901);//改 为球目全
  58384. //quaternion.premultiply(rot90)
  58385. this.panoMatrix = new Matrix4().makeRotationFromQuaternion(this.quaternion);
  58386. this.oriPanoMatrix = this.panoMatrix.clone();
  58387. if(this.quaternion2)this.oriPanoMatrix2 = new Matrix4().makeRotationFromQuaternion(this.quaternion2);
  58388. //console.log(this.quaternion)
  58389. //this.quaternion = quaternion
  58390. }
  58391. let marker = new Mesh(planeGeo$1, getMarerMat() );
  58392. marker.name = 'marker_'+this.id;
  58393. marker.up.set(0,0,1);
  58394. marker.lookAt(marker.up);
  58395. marker.scale.set(2,2,2);
  58396. this.addEventListener('changeMarkerTex',(e)=>{
  58397. marker.material.map = markerTex[e.name];
  58398. });
  58399. this.marker = marker;
  58400. if(Potree.settings.editType == 'pano'){
  58401. viewer.updateVisible(marker, 'panoEdit', false, 4);
  58402. }
  58403. this.images360.node.add(marker);
  58404. Potree.settings.isTest && this.createTextLabel();
  58405. this.createTextLabel2();
  58406. /* let mouseover = (e)=>{
  58407. if(!e.byMap){
  58408. pano.mapMarker.material = panoMarkerMats.selected
  58409. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true})
  58410. this.needRender = true
  58411. }
  58412. }
  58413. let mouseleave = (e)=>{
  58414. if(!e.byMap){
  58415. pano.mapMarker.material = panoMarkerMats.default
  58416. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true})
  58417. this.needRender = true
  58418. }
  58419. } */
  58420. marker.addEventListener('mouseover', this.hoverOn.bind(this));
  58421. marker.addEventListener('mouseleave', this.hoverOff.bind(this));
  58422. }
  58423. transformByPointcloud(){
  58424. let position = this.originPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);//也可以用datasetPosTransform算
  58425. let floorPosition = this.originFloorPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);
  58426. this.setPosition(position, floorPosition);
  58427. this.panoMatrix = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix );
  58428. //this.panoMatrix2 = Potree.Utils.datasetRotTransform({fromDataset:true, pointcloud:this.pointcloud, matrix:this.oriPanoMatrix, getMatrix:true}) //和上一行结果一样
  58429. //quaternion也变下
  58430. if(this.oriPanoMatrix2){
  58431. this.panoMatrix2 = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix2 );//供DepthImageSampler使用
  58432. this.panoMatrix2Inverse = this.panoMatrix2.clone().invert();
  58433. }
  58434. this.dispatchEvent('rePos');
  58435. }
  58436. setPosition(position, floorPosition){
  58437. this.position = position;
  58438. this.floorPosition = floorPosition;
  58439. //this.mesh.position.copy(this.position)
  58440. this.marker.position.copy(this.floorPosition);
  58441. this.marker.position.z+=0.04;//会被点云遮住
  58442. if(this.label){
  58443. if(Potree.settings.editType == 'pano'){
  58444. this.label.position.copy(this.position);
  58445. }else {
  58446. this.label.position.copy(this.floorPosition);
  58447. }
  58448. this.label.position.z+=0.14;
  58449. this.label.update();
  58450. }
  58451. if(this.label2){
  58452. if(Potree.settings.editType == 'pano'){
  58453. this.label2.position.copy(this.position);
  58454. }else {
  58455. this.label2.position.copy(this.floorPosition);
  58456. }
  58457. this.label2.position.copy(this.marker.position);
  58458. this.label2.update();
  58459. }
  58460. }
  58461. hoverOn(e={}) {
  58462. //console.log("hoverOn " + this.id )
  58463. transitions.start(lerp.property(this.marker.material, "opacity", 1), 250);
  58464. if(!e.byMap) this.dispatchEvent({type:'hoverOn', byMainView:true});
  58465. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:true, pano:this});
  58466. }
  58467. hoverOff(e={}){
  58468. //console.log("hoverOff " + this.id )
  58469. transitions.start(lerp.property(this.marker.material, "opacity", 0.5), 250);
  58470. if(!e.byMap) this.dispatchEvent({type:'hoverOff', byMainView:true});
  58471. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:false, pano:this});
  58472. }
  58473. setZoomed(zoomed){
  58474. this.zoomed = zoomed;
  58475. Potree.settings.displayMode == 'showPanos' && this.updateSkyboxForZoomLevel(); //放大后换成zoomTarget贴图
  58476. viewer.dispatchEvent({type:'panoSetZoom', zoomed});
  58477. }
  58478. enter(){
  58479. this.setZoomed(!1),
  58480. viewer.dispatchEvent({type:PanoramaEvents.Enter, oldPano:old, newPano:this } );
  58481. old = this;
  58482. //console.log("enter pano "+ this.id)
  58483. }
  58484. exit(){
  58485. /* if(this.tiled)
  58486. { */
  58487. this.clearWaitDeferreds();
  58488. this.minimumTiledPanoLoaded = !1;
  58489. this.tiledPanoRenderTarget = null;
  58490. this.setZoomed(!1);
  58491. this.images360.panoRenderer.deactivateTiledPano(this);
  58492. this.highestPartialTileRenderOpCompleted = 0;
  58493. this.highestFullTileRenderOpCompleted = 0;
  58494. /*}
  58495. else
  58496. {
  58497. this.solidSkybox.dispose();
  58498. this.solidSkybox.loaded = !1;
  58499. this.solidSkybox.version = 0;
  58500. } */
  58501. //console.log("exit pano "+ this.id)
  58502. viewer.dispatchEvent({type:PanoramaEvents.Exit, pano:this});
  58503. }
  58504. updateSkyboxForZoomLevel(){
  58505. if(this.minimumTiledPanoLoaded){
  58506. this.images360.updateProjectedPanos();
  58507. }
  58508. }
  58509. getSkyboxTexture(){
  58510. if(this.minimumTiledPanoLoaded)
  58511. {
  58512. if(this.zoomed && this.images360.qualityManager.maxRenderTargetSize > this.images360.qualityManager.maxNavPanoSize)//change 如果放大后和不放大都是2k就不用这个
  58513. {
  58514. return this.images360.panoRenderer.zoomRenderTarget.texture;
  58515. }
  58516. else
  58517. {
  58518. this.tiledPanoRenderTarget.texture.mapping = UVMapping;//add
  58519. return this.tiledPanoRenderTarget.texture;
  58520. }
  58521. }
  58522. else
  58523. {
  58524. return null;
  58525. }
  58526. }
  58527. isLoaded(e){
  58528. if (e && "string" == typeof e)
  58529. console.error("Wrong panoSize given to Panorama.isLoaded(); a tiled pano uses PanoSizeClass");
  58530. return !!this.minimumTiledPanoLoaded && (!e || this.highestFullTileRenderOpCompleted >= e)//改:原本是:this.highestPartialTileRenderOpCompleted >= e, 希望这代表全部加载完
  58531. }
  58532. getWaitDeferred(size){//获取不同size的tile贴图的promiss
  58533. var t = this.resolutionPromise[this.id];
  58534. t || (t = {}, this.resolutionPromise[this.id] = t);
  58535. var i = t[size];
  58536. return i || (i = {
  58537. deferred: $.Deferred(),
  58538. active: !1
  58539. },
  58540. t[size] = i),
  58541. i
  58542. }
  58543. clearWaitDeferreds(){
  58544. var e = this.resolutionPromise[this.id];
  58545. e || (e = {},
  58546. this.resolutionPromise[this.id] = e);
  58547. for (var t in e)
  58548. if (e.hasOwnProperty(t)) {
  58549. var i = e[t];
  58550. i.active = !1,
  58551. i.deferred = $.Deferred();
  58552. }
  58553. }
  58554. resetWaitDeferred(e){
  58555. var t = this.getWaitDeferred(e);
  58556. t.active = !1;
  58557. t.deferred = $.Deferred();
  58558. }
  58559. onTileRendered(ev){
  58560. ev.id === this.id && this.dispatchEvent({
  58561. type:PanoramaEvents.TileLoaded,
  58562. size:ev.panoSize, index:ev.tileIndex, count:ev.totalTiles
  58563. });
  58564. }
  58565. onPanoRendered(ev) {
  58566. if(ev.id === this.id)
  58567. {
  58568. this.minimumTiledPanoLoaded = !0;
  58569. this.updateSkyboxForZoomLevel();//更新贴图 setProjected
  58570. ev.panoSize > this.highestPartialTileRenderOpCompleted && (this.highestPartialTileRenderOpCompleted = ev.panoSize);//应该是更新最高获取到的Partial size
  58571. ev.updateFullComplete && ev.panoSize > this.highestFullTileRenderOpCompleted && (this.highestFullTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Full size
  58572. //this.dispatchEvent("load", ev.panoSize);
  58573. viewer.ifAllLoaded( this);
  58574. this.dispatchEvent({type:PanoramaEvents.LoadComplete, size:ev.panoSize, count:ev.totalTiles});
  58575. }
  58576. }
  58577. onTileRenderFail(ev) {
  58578. ev.id === this.id && this.dispatchEvent({type:PanoramaEvents.LoadFailed });
  58579. }
  58580. onUploadAttemptedForAllTiles(ev) {
  58581. if (ev.id === this.id) {
  58582. var n = this.images360.qualityManager.getPanoSize(PanoSizeClass.BASE);
  58583. if(ev.panoSize === n && this.shouldRedrawOnBaseLoaded) //shouldRedrawOnBaseLoaded一直是false。在4dkk里只有初始点在quickstart后变为true。
  58584. {
  58585. this.shouldRedrawOnBaseLoaded = !1;
  58586. this.panoRenderer.resetRenderStatus(this.id, !0, !1);
  58587. this.panoRenderer.renderPanoTiles(this.id, null, !0, !0);
  58588. }
  58589. }
  58590. }
  58591. createTextLabel(){
  58592. this.removeTextLabel();
  58593. this.label = new TextSprite(Object.assign({},
  58594. labelProp, {text: this.id }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  58595. );
  58596. this.images360.node.add(this.label);
  58597. this.floorPosition && this.label.position.copy(this.floorPosition);
  58598. }
  58599. createTextLabel2(){
  58600. let labelProp2 = {
  58601. //sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  58602. backgroundColor:{r: 255, g: 255, b: 255, a: 0 },
  58603. textColor:{r:255 , g: 255, b: 255, a: 1 },
  58604. textBorderColor:{r:30 , g:30, b: 30, a: 1 },
  58605. textBorderThick:3,
  58606. dontFixOrient:true,
  58607. renderOrder:10,
  58608. fontsize:30,
  58609. };
  58610. this.label2 = new TextSprite(Object.assign({},
  58611. labelProp2, {text: /* this.originID */ parseInt(this.id)+1 }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  58612. );
  58613. this.images360.node.add(this.label2);
  58614. this.floorPosition && this.label2.position.copy(this.floorPosition);
  58615. let s = 0.4;
  58616. this.label2.scale.set(s,s,s);
  58617. viewer.updateVisible(this.label2, 'notDisplay', false);
  58618. }
  58619. removeTextLabel(){
  58620. if(this.label){
  58621. this.label.parent.remove(this.label);
  58622. }
  58623. }
  58624. dispose(){
  58625. let i = viewer.images360.panos.indexOf(this);
  58626. if(i==-1)return
  58627. this.marker.parent.remove(this.marker);
  58628. this.removeTextLabel();
  58629. if(this.depthTex) this.depthTex.dispose();
  58630. viewer.images360.panos.splice(i,1);
  58631. this.dispatchEvent('dispose');
  58632. //删除tile贴图、depthTex等以后再写
  58633. }
  58634. };
  58635. Panorama.prototype.loadTiledPano = function() {
  58636. //var downloads = [] , t = [];
  58637. var downloaded = {} , eventAdded = {}, latestPartialRequest = {}; //每个pano对应一组这些
  58638. return function(size, dirs, fov, o, a, download) {
  58639. var dir = dirs.datasetsLocal.find(e=>e.datasetId == this.pointcloud.dataset_id).direction;
  58640. //var dir = dirs
  58641. null !== o && void 0 !== o || (o = !0),
  58642. null !== a && void 0 !== a || (a = !0);
  58643. var l = this.getWaitDeferred(size)
  58644. , c = l.deferred
  58645. , h = null
  58646. , u = null;
  58647. fov && ("number" == typeof fov ? h = fov : (h = fov.hFov, u = fov.vFov));
  58648. if (!this.isLoaded(size)) {
  58649. //console.log('loadTiledPano', this.id, size, fov)
  58650. if (!l.active) {
  58651. l.active = !0;
  58652. let name = this.id + ":" + size;
  58653. downloaded[name] = downloaded[name] || [];
  58654. /*
  58655. this.downloaded = downloaded
  58656. this.latestPartialRequest = latestPartialRequest
  58657. */
  58658. latestPartialRequest[name] = null;
  58659. if (fov) {
  58660. let tileArr = [];//add
  58661. var d = TileUtils.matchingTilesInDirection(this, size, dir, h, u, tileArr);
  58662. latestPartialRequest[name] = tileArr;
  58663. downloaded[name].forEach((e)=>{
  58664. let item = latestPartialRequest[name].find(a=>e.faceTileIndex == a.faceTileIndex && e.face == a.face);
  58665. if(item){
  58666. item.loaded = true;
  58667. }
  58668. });
  58669. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的全部加载成功
  58670. //let total = TileUtils.getTileCountForSize(size)
  58671. //this.onPanoRendered(this.id, size, total, !0);
  58672. c.resolve(size/* , total */);
  58673. this.resetWaitDeferred(size);
  58674. //console.log('该部分早已经加载好了'+size, this.id)
  58675. latestPartialRequest[name] = null;
  58676. }
  58677. //console.log("Loading partial pano: " + this.id + " with " + d + " tiles")
  58678. }
  58679. if(!eventAdded[this.id]) {
  58680. eventAdded[this.id] = !0;
  58681. this.addEventListener(PanoramaEvents.LoadComplete, function(ev/* e, t */) {//本次任务全部加载完毕
  58682. //console.warn('点位(可能部分)下载完成 ', 'id:'+this.id, 'size:'+ev.size )
  58683. var i = this.getWaitDeferred(ev.size).deferred;//"pending"为还未完成
  58684. i && "pending" === i.state() && this.highestPartialTileRenderOpCompleted >= ev.size && (i.resolve(ev.size, ev.count),
  58685. this.resetWaitDeferred(ev.size));//恢复active为false
  58686. }.bind(this));
  58687. this.addEventListener(PanoramaEvents.LoadFailed, function(ev) {
  58688. var t = this.getWaitDeferred(e).deferred;
  58689. t && "pending" === t.state() && this.highestPartialTileRenderOpCompleted >= ev.t && (t.reject(ev.t),
  58690. this.resetWaitDeferred(ev.t));//恢复active为false
  58691. }.bind(this));
  58692. this.addEventListener(PanoramaEvents.TileLoaded, function(ev/* t, i, n */) {//每张加载完时
  58693. //console.log('tileLoaded', 'id:'+this.id, 'size:'+ev.size, 'tileIndex:'+ev.index )
  58694. let tileIndex = ev.index;
  58695. let total = ev.count;
  58696. let size = ev.size;
  58697. let name = this.id + ":" + size;
  58698. downloaded[name] = downloaded[name] || []; //不是所有的加载都是从loadTiledPano获取的所以会有未定义的情况
  58699. let {faceTileIndex,face} = TileUtils.getTileLocation(size, tileIndex, {});
  58700. downloaded[name].push({faceTileIndex,face});
  58701. var r = this.getWaitDeferred(size).deferred;
  58702. if (r && "pending" === r.state()) {
  58703. r.notify(size, tileIndex, total);
  58704. if(latestPartialRequest[name]){
  58705. let item = latestPartialRequest[name].find(e=>e.faceTileIndex == faceTileIndex && e.face == face);
  58706. item && (item.loaded = true );
  58707. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的局部tiles全部加载成功
  58708. this.onPanoRendered(this.id, size, total, !0); //onPanoRendered还会触发 PanoramaEvents.LoadComplete
  58709. r.resolve(size, total);
  58710. this.resetWaitDeferred(size);
  58711. //console.log('该部分加载好了'+size, this.id)
  58712. latestPartialRequest[name] = null;
  58713. }
  58714. }
  58715. }
  58716. /* var r = this.getWaitDeferred(ev.size).deferred;
  58717. if (r && "pending" === r.state()) {
  58718. r.notify(ev.size, ev.index, ev.count);
  58719. var o = downloads[this.id + ":" + ev.size];
  58720. if(o){//如果有规定下载哪些tile,只需要下载这些tile则LoadComplete
  58721. o.tileCount++
  58722. if(o.tileCount === o.targetTileCount){//达到下载目标数
  58723. this.onPanoRendered(this.id, ev.size, ev.count, !0);
  58724. r.resolve(ev.size, ev.count);
  58725. this.resetWaitDeferred(ev.size)
  58726. }
  58727. }
  58728. } */
  58729. }.bind(this));
  58730. }
  58731. }
  58732. this.images360.tileDownloader.clearForceQueue(),
  58733. this.images360.tileDownloader.forceQueueTilesForPano(this, size, dir, h, u, download);
  58734. this.tiledPanoRenderTarget = this.images360.panoRenderer.activateTiledPano(this, this.images360.qualityManager.getMaxNavPanoSize(), o);
  58735. this.images360.panoRenderer.renderPanoTiles(this.id, dirs, a);
  58736. }else {
  58737. //console.log('早已经全加载好了' +size, this.id)
  58738. c.resolve(size);
  58739. }
  58740. return c.promise()
  58741. }
  58742. }();
  58743. class QualityManager {
  58744. constructor(e, t, i) {
  58745. this.maxNavPanoSize = -1;
  58746. this.maxZoomPanoSize = -1;
  58747. this.devicePixelDensity = e;
  58748. this.deviceScreenSize = t;
  58749. this.clientBandwidth = i;
  58750. this.panoSizeClassMap = {};
  58751. this.useHighResolutionPanos = !0; //是否能够使用2k及以上图
  58752. this.useUltraHighResolutionPanos = !1;
  58753. this.modelHasUltraHighPanos = !1;
  58754. this.qualityManager = this;
  58755. this.maxRenderTargetSize = browser.isMobile() ? 2048 : 4096; //add
  58756. this.init();
  58757. }
  58758. init(e ) {
  58759. //var metadata = store.getters['scene/metadata'] ;//有时候请求不到
  58760. //if(metadata.sceneSource == 11 || metadata.sceneScheme == 12){
  58761. /* if(config.tileClass == '1k'){
  58762. this.useHighResolutionPanos = false //xzw add 只加载1k
  58763. } */
  58764. this.buildPanoSizeClassMap(this.devicePixelDensity, this.deviceScreenSize, this.clientBandwidth);
  58765. this.ultraHighSize = this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58766. this.highSize = this.getPanoSize(PanoSizeClass.HIGH);
  58767. this.standardSize = this.getPanoSize(PanoSizeClass.STANDARD);
  58768. this.baseSize = this.getPanoSize(PanoSizeClass.BASE);
  58769. config$1.tiling.maxZoomPanoQuality && this.ultraHighSize <= config$1.tiling.maxZoomPanoQuality && (config$1.tiling.allowUltraHighResolution = !0);
  58770. this.highQualityThreshold = browser.valueFromHash("threshold2k", config$1.windowHeightHighQualityThreshold);
  58771. this.updateMaximums();
  58772. //e.on(ModelManagerEvents.ActiveModelChanged, this.onModelChanged.bind(this));
  58773. }
  58774. updateFromModel(e) {
  58775. //this.updateHighResolutionSettings(e)
  58776. this.updateUltraHighResolutionSettings(e);
  58777. }
  58778. /* updateHighResolutionSettings(e) {
  58779. this.useHighResolutionPanos = !0
  58780. this.updateMaximums()
  58781. } */
  58782. updateUltraHighResolutionSettings(e) {
  58783. if (config$1.tiling.allowUltraHighResolution && this.modelHasUltraHighPanos) {
  58784. this.useUltraHighResolutionPanos = !0;
  58785. } else {
  58786. this.useUltraHighResolutionPanos = !1;
  58787. }
  58788. this.updateMaximums();
  58789. }
  58790. enableUltraHighQualityMode() {
  58791. this.modelHasUltraHighPanos = !0;
  58792. this.updateUltraHighResolutionSettings(null);
  58793. }
  58794. ultraHighQualityModeEnabled() {
  58795. return this.modelHasUltraHighPanos
  58796. }
  58797. onModelChanged(e) {
  58798. this.updateFromModel(e.model),
  58799. this.updateMaximums();
  58800. }
  58801. updateMaximums() {
  58802. this.maxNavPanoSize = config$1.tiling.maxNavPanoQuality || this.detectMaxNavPanoSize(),
  58803. this.maxZoomPanoSize = config$1.tiling.maxZoomPanoQuality || this.detectMaxZoomPanoSize(),
  58804. this.maxZoomPanoSize < this.maxNavPanoSize && (this.maxNavPanoSize = this.maxZoomPanoSize);
  58805. }
  58806. buildPanoSizeClassMap() {
  58807. this.panoSizeClassMap[PanoSizeClass.BASE] = 512,
  58808. this.panoSizeClassMap[PanoSizeClass.STANDARD] = 1024,
  58809. this.panoSizeClassMap[PanoSizeClass.HIGH] = 2048,
  58810. this.panoSizeClassMap[PanoSizeClass.ULTRAHIGH] = 4096;
  58811. }
  58812. getPanoSize(e) {
  58813. return this.panoSizeClassMap[e]
  58814. }
  58815. getMaxPossiblePanoSize() {
  58816. return this.getPanoSize(PanoSizeClass.ULTRAHIGH)
  58817. }
  58818. getMaxPanoSize() {
  58819. return this.maxZoomPanoSize
  58820. }
  58821. getMaxNavPanoSize() {
  58822. return this.maxNavPanoSize
  58823. }
  58824. getMaxZoomPanoSize() {
  58825. return this.maxZoomPanoSize
  58826. }
  58827. detectMaxNavPanoSizeClass() {
  58828. //return this.useHighResolutionPanos ? browser.isMobile() ? PanoSizeClass.STANDARD : window.innerHeight < this.highQualityThreshold ? PanoSizeClass.STANDARD : PanoSizeClass.HIGH : PanoSizeClass.STANDARD
  58829. /* if(config.name == 'decor'){
  58830. return PanoSizeClass.STANDARD
  58831. }
  58832. return PanoSizeClass.HIGH */
  58833. switch(Potree.settings.navTileClass){
  58834. case '1k':
  58835. return PanoSizeClass.STANDARD;
  58836. break;
  58837. case '2k':
  58838. default:
  58839. return PanoSizeClass.HIGH;
  58840. }
  58841. }
  58842. detectMaxNavPanoSize() {
  58843. var e = this.detectMaxNavPanoSizeClass();
  58844. return this.getPanoSize(e)
  58845. }
  58846. detectMaxZoomPanoSize() {
  58847. if(this.zoomLevelResolution){
  58848. if(this.zoomLevelResolution == '4k' && this.useUltraHighResolutionPanos){
  58849. return this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58850. }else if(this.zoomLevelResolution == '1k' || !this.useHighResolutionPanos){
  58851. return this.getPanoSize(PanoSizeClass.STANDARD);
  58852. }else {
  58853. return this.getPanoSize(PanoSizeClass.HIGH);
  58854. }
  58855. }else {
  58856. if (this.useHighResolutionPanos) {
  58857. /* if (browser.isMobile()) {//手机版如果要2k的将这里去掉
  58858. if (settings.tiling.mobileHighQualityOverride) {
  58859. return this.getPanoSize(PanoSizeClass.HIGH);
  58860. } else {
  58861. return this.getPanoSize(PanoSizeClass.STANDARD);
  58862. }
  58863. } else */if (this.useUltraHighResolutionPanos ) {
  58864. return this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58865. } else {
  58866. return this.getPanoSize(PanoSizeClass.HIGH);
  58867. }
  58868. } else {
  58869. return this.getPanoSize(PanoSizeClass.STANDARD);
  58870. }
  58871. }
  58872. }
  58873. }
  58874. var h = Object.freeze({
  58875. None: 0,
  58876. DirectionalFOV: 1
  58877. });
  58878. var u = function () {
  58879. var e = function e(t, i) {
  58880. var n = e._panoSpaceDir,
  58881. r = e._fovThreshold,
  58882. o = e._fovThresholdNarrow,
  58883. a = Math.max(Math.min(n.dot(t.direction), 1), -1),
  58884. s = Math.max(Math.min(n.dot(i.direction), 1), -1);
  58885. return t._dot = a,
  58886. i._dot = s,
  58887. 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)
  58888. };
  58889. return e._panoSpaceDir = new Vector3,
  58890. e._fovThreshold = -1,
  58891. e._fovThresholdNarrow = -1,
  58892. e
  58893. }();
  58894. class TilePrioritizer {//优先级处理序列
  58895. constructor(e,t, i, o, a) {
  58896. this.qualityManager = e;
  58897. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize();
  58898. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  58899. this.baseSize = t;
  58900. this.standardSize = i;
  58901. this.highSize = o;
  58902. this.ultraHighSize = a;
  58903. this.priorityCriteria = new TilePrioritizer.PriorityCriteria(null, new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 0, -1));
  58904. }
  58905. updateCriteria(e, t, i, n) {//由player更新
  58906. this.priorityCriteria.pano = e,
  58907. this.priorityCriteria.cameraPosition.copy(t),
  58908. //this.priorityCriteria.cameraDir.copy(i),
  58909. this.priorityCriteria.cameraDirs = i;
  58910. this.priorityCriteria.upcomingPanos = n,
  58911. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(),
  58912. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  58913. }
  58914. canDownloadSize(e) {
  58915. return this.maxNavQuality >= e || this.maxZoomQuality >= e && this.zoomingActive
  58916. }
  58917. /* populateNeighborPanos(e, t, i) {
  58918. i = i || [],
  58919. i.length = 0;
  58920. var n = t.getNeighbours(e);
  58921. for (var r in n)
  58922. if (n.hasOwnProperty(r)) {
  58923. var o = t.get(r);
  58924. if(!o){
  58925. console.log(1)
  58926. }
  58927. i.push(o)
  58928. }
  58929. return i
  58930. } */
  58931. populateScoredPanos(e, t, i, dirs, a) {
  58932. i = i || [],
  58933. i.length = 0;
  58934. var s = [Images360.filters.inPanoDirection(e.position, dirs, TilePrioritizer.DIRECTION_SCORE_STRICTNESS), Images360.filters.not(e)],
  58935. l = [Images360.scoreFunctions.distanceSquared(e), Images360.scoreFunctions.direction(e.position, dirs)],
  58936. c = Common.sortByScore(t, s, l);
  58937. if (c)
  58938. for (var h = 0; h < c.length && h < a; h++) {
  58939. var u = c[h].item;
  58940. i.push(u);
  58941. }
  58942. return i
  58943. }
  58944. queueTilesForPanos(e, t, i, n, r) {
  58945. for (var o = 0, a = 0; a < t.length; a++) {
  58946. var s = t[a],
  58947. l = this.queueTilesForPano(e, i, s, n);
  58948. if (o += l > 0 ? 1 : 0,
  58949. r && o >= r)
  58950. break
  58951. }
  58952. return o
  58953. }
  58954. /* queueTilesInDirectionForPanos(e, t, i, n, r, o, a, s) {//没用到
  58955. for (var l = 0, c = 0; c < i.length; c++) {
  58956. var h = i[c],
  58957. u = this.queueTilesInDirectionForPano(e, t, h, n, o, a);
  58958. if (l += u > 0 ? 1 : 0,
  58959. s && l >= s)
  58960. break
  58961. }
  58962. return l
  58963. }
  58964. */
  58965. canIncludeDescriptor(e) {
  58966. return e.status !== DownloadStatus.Downloading && e.status !== DownloadStatus.Downloaded
  58967. }
  58968. canIncludePano(e, t) {
  58969. return !e.isLoaded(t)
  58970. }
  58971. getFOVDotThreshold(e) {
  58972. return Math.cos(MathUtils.degToRad(e / 2))
  58973. }
  58974. setZoomingActive(e) {
  58975. e !== this.zoomingActive && (this.zoomingActive = e);
  58976. }
  58977. }
  58978. TilePrioritizer.PriorityCriteria = function (e, t, i, n, o) {
  58979. this.pano = e,
  58980. this.cameraPosition = (new Vector3).copy(t),
  58981. //this.cameraDir = (new THREE.Vector3).copy(i),
  58982. this.cameraDirs = [], //
  58983. this.panoSpaceDir = (new Vector3).copy(n),
  58984. this.upcomingPanos = o,
  58985. this.copy = function (e) {
  58986. this.pano = e.pano,
  58987. this.cameraPosition.copy(e.cameraPosition),
  58988. //this.cameraDir.copy(e.cameraDir),
  58989. this.cameraDirs = e.cameraDirs;
  58990. this.panoSpaceDir.copy(e.panoSpaceDir),
  58991. this.upcomingPanos = o;
  58992. },
  58993. this.zoomingActive = !1;
  58994. };
  58995. TilePrioritizer.DIRECTIONAL_FOV = 180;
  58996. TilePrioritizer.DIRECTIONAL_FOV_NARROW = 120;
  58997. TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER = 6;
  58998. TilePrioritizer.MAX_SCORED_PANOS_TOADD = 2;
  58999. TilePrioritizer.MAX_UPCOMING_PANOS_TOADD = 3;
  59000. TilePrioritizer.DIRECTION_SCORE_STRICTNESS = .75;
  59001. TilePrioritizer.appendQueue = function (e, t) {
  59002. if (e && t)
  59003. for (var i = 0; i < t.length; i++){
  59004. e.push(t[i]);
  59005. //console.log(t[i])
  59006. }
  59007. };
  59008. TilePrioritizer.sortPanoTiles = function (descriptors, pano, dir) {
  59009. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  59010. u._panoSpaceDir.copy(dir);
  59011. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir); //应该是将dir根据quaternion转化下
  59012. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59013. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  59014. descriptors.sort(u);
  59015. };
  59016. TilePrioritizer.insertSortedPanoTile = function (e, t, pano, dir) {
  59017. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  59018. u._panoSpaceDir.copy(dir),
  59019. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir),
  59020. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW),
  59021. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  59022. for (var o = -1, a = 0; a < e.length; a++) {
  59023. var s = u(t, e[a]);
  59024. if (s <= 0) {
  59025. o = a;
  59026. break
  59027. }
  59028. }
  59029. if (o === -1)
  59030. e[e.length] = t;
  59031. else {
  59032. for (var h = e.length; h > o; h--)
  59033. e[h] = e[h - 1];
  59034. e[o] = t;
  59035. }
  59036. };
  59037. TilePrioritizer.prototype.filterDepthTex = function (panos ) {//仅下载depthTex
  59038. if(!Potree.settings.useDepthTex || !this.priorityCriteria.pano)return
  59039. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  59040. let t = [];
  59041. //获得视野范围内的邻近点位序列t
  59042. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  59043. t.forEach(p=>p.loadDepthImg());
  59044. };
  59045. TilePrioritizer.prototype.filterAndPrioritize = function () {//挑选出优先加载的 pano和tile (有点复杂,没看很懂)
  59046. var e = [],
  59047. t = [],
  59048. i = [];
  59049. return function (queue, panos, tileDownloader) {
  59050. //this.populateNeighborPanos(this.priorityCriteria.pano, panos, e);
  59051. /* let cameraDirLocals = this.priorityCriteria.cameraDirs.map(e=>{ //add
  59052. var dataset = viewer.scene.pointclouds.find(u=>u.dataset_id == e.datasetId)
  59053. var matrix = new THREE.Matrix4().copy(dataset.rotateMatrix)
  59054. var direction = math.convertVector.YupToZup(e.direction)
  59055. return {
  59056. datasetId:e.datasetId,
  59057. direction: direction.clone().applyMatrix4(matrix)
  59058. }
  59059. }) */
  59060. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  59061. //获得视野范围内的邻近点位序列t
  59062. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  59063. t.forEach(p=>p.loadDepthImg()); //add
  59064. var s = this.baseSize //512
  59065. ,
  59066. l = this.standardSize //1024
  59067. ,
  59068. c = this.highSize //2048
  59069. ,
  59070. h = this.ultraHighSize; //4096
  59071. this.queueTilesForPano(queue, tileDownloader, this.priorityCriteria.pano, s); //把当前pano的512下载了
  59072. if (this.priorityCriteria.upcomingPanos) {// 添加即将走到的点(之前用于导览路线)512 tiles
  59073. this.queueTilesForPanos(queue, this.priorityCriteria.upcomingPanos, tileDownloader, s, TilePrioritizer.MAX_UPCOMING_PANOS_TOADD);
  59074. }
  59075. i.length = 0;
  59076. //把当前pano角度范围内的tile按照分辨率从低到高加入队列
  59077. if (this.canDownloadSize(l)) {//1024如果在限制范围内的话
  59078. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59079. }
  59080. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  59081. TilePrioritizer.appendQueue(queue, i);
  59082. //添加邻近点t 512的tiles
  59083. this.queueTilesForPanos(queue, t, tileDownloader, s, TilePrioritizer.MAX_SCORED_PANOS_TOADD);
  59084. i.length = 0;
  59085. //NARROW :
  59086. if (this.canDownloadSize(c)) {//2048
  59087. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59088. }
  59089. if (this.canDownloadSize(h)) {//4096
  59090. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  59091. }
  59092. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  59093. TilePrioritizer.appendQueue(queue, i);
  59094. i.length = 0;
  59095. if (this.canDownloadSize(l)) {//1024
  59096. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  59097. }
  59098. if (this.canDownloadSize(c)) {//2048
  59099. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  59100. }
  59101. if (this.canDownloadSize(h)) {//4096
  59102. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  59103. }
  59104. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  59105. TilePrioritizer.appendQueue(queue, i);
  59106. this.queueTilesForPanos(queue, e, tileDownloader, s); // 如果前面有populateNeighborPanos的话,这步就是加neibour
  59107. }
  59108. }();
  59109. TilePrioritizer.prototype.queueTilesInDirectionForPano = function () {
  59110. var e = {
  59111. filter: h.DirectionalFOV,
  59112. direction: new Vector3,
  59113. fov: 60
  59114. },
  59115. t = new Vector3;
  59116. return function (i, n, pano, o, a, dirs, c) {
  59117. var dir = dirs.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  59118. //var dir = dirs
  59119. t.copy(dir);
  59120. TileUtils.getRelativeDirection(pano.quaternion4dkk, t);
  59121. e.direction.copy(t);
  59122. e.fov = c;
  59123. return this.filterAndQueueTileDownloadDescriptors(i, n, pano, o, e)
  59124. }
  59125. }();
  59126. TilePrioritizer.prototype.filterAndQueueTileDownloadDescriptors = function () {
  59127. var e = [];
  59128. return function (t, i, n, r, o) {
  59129. var a = i.getTileDownloadDescriptors(n, r);
  59130. e.length = 0,
  59131. this.filterTileDownloadDescriptors(n, a, e, o);
  59132. for (var s = 0, l = 0; l < e.length; l++) {
  59133. var c = e[l];
  59134. if (c) {
  59135. t.push(c);
  59136. s++;
  59137. }
  59138. }
  59139. return s
  59140. }
  59141. }();
  59142. TilePrioritizer.prototype.filterTileDownloadDescriptors = function () {
  59143. new Vector3;
  59144. return function (e, t, i, n) {
  59145. var r, o;
  59146. switch (n.filter) {
  59147. case h.DirectionalFOV:
  59148. for (r = 0; r < t.length; r++)
  59149. o = t[r],
  59150. TileUtils.isTileWithinFOV(o.panoSize, o.tileSize, o.face, o.tileX, o.tileY, n.direction, n.fov) && i.push(o);
  59151. break;
  59152. default:
  59153. for (r = 0; r < t.length; r++)
  59154. o = t[r],
  59155. i.push(o);
  59156. }
  59157. for (r = 0; r < i.length; r++)
  59158. o = i[r],
  59159. this.canIncludeDescriptor(o) || (i[r] = null);
  59160. }
  59161. }();
  59162. TilePrioritizer.prototype.queueTilesForPano = function () {
  59163. var e = {
  59164. filter: h.None
  59165. };
  59166. return function (t, i, n, r) {
  59167. return this.filterAndQueueTileDownloadDescriptors(t, i, n, r, e)
  59168. }
  59169. }();
  59170. /* TilePrioritizer.prototype.queueTilesForPanosInDirection = function () { //没用到
  59171. var e = new THREE.Vector3;
  59172. return function (t, i, n, r, o, a, s, l) {
  59173. for (var h = 0, u = 0; u < n.length; u++) {
  59174. var d = n[u];
  59175. e.copy(d.position),
  59176. e.sub(o),
  59177. e.normalize();
  59178. var p = Math.max(Math.min(a.dot(e), 1), -1),
  59179. f = c.getFOVDotThreshold(s);
  59180. if (p >= f) {
  59181. var g = this.queueTilesInDirectionForPano(t, i, d, r, o, a, s);
  59182. if (h += g > 0 ? 1 : 0,
  59183. l && h >= l)
  59184. break
  59185. }
  59186. }
  59187. return h
  59188. }
  59189. }() */
  59190. //import { i18n } from "@/lang/index"
  59191. // 媒体名称
  59192. /* export const mediaTypes = {
  59193. image: i18n.t("common.photo"),
  59194. video: i18n.t("common.video"),
  59195. audio: i18n.t("common.voice"),
  59196. } */
  59197. // 媒体扩展类型
  59198. const mediaMimes = {
  59199. image: ["jpg", "png", "jpeg", "bmp", "gif"],
  59200. audio: ["mp3", "aac", "ogg", "wav" /* , "m4a" */],
  59201. video: ["mp4", "mov", "quicktime", "webm" /* "rmvb", "wmv" */], //ios:mov
  59202. };
  59203. // 媒体大小显示(MB)
  59204. const mediaMaxSize = {
  59205. image: 10,
  59206. video: 20,
  59207. audio: 5,
  59208. };
  59209. /**
  59210. * 获取媒体扩展类型
  59211. * @param {Stirng} filename 文件名称
  59212. */
  59213. const getMime = filename => {
  59214. if (!filename || filename.indexOf(".") === -1) {
  59215. return ""
  59216. }
  59217. return filename
  59218. .split(".")
  59219. .pop()
  59220. .toLowerCase()
  59221. };
  59222. /**
  59223. * 在路径中获取文件名
  59224. * @param {*} path
  59225. */
  59226. const getFilename = path => {
  59227. const segment = (path || "").split("/");
  59228. return segment[segment.length - 1]
  59229. };
  59230. /**
  59231. * 检测媒体文件是否超过预设限制
  59232. * @param {String} type 媒体类型
  59233. * @param {Number} size 文件大小
  59234. */
  59235. const checkSizeLimit = (type, size) => {
  59236. size = size / 1024 / 1024;
  59237. return size <= mediaMaxSize[type]
  59238. };
  59239. const checkSizeLimitFree = (size, limit) => {
  59240. size = size / 1024 / 1024;
  59241. return size <= limit
  59242. };
  59243. /**
  59244. * 检测媒体类型
  59245. * @param {String} type 媒体类型
  59246. * @param {String} filename 文件名称
  59247. */
  59248. const checkMediaMime = (type, filename) => {
  59249. const mime = getMime(filename);
  59250. const find = mediaMimes[type];
  59251. if (!find) {
  59252. return false
  59253. }
  59254. return find.indexOf(mime) !== -1
  59255. };
  59256. const checkMediaMimeByAccept = (accept, filename) => {
  59257. let mime = getMime(filename);
  59258. let type = accept;
  59259. if (type && type.indexOf("jpg") == -1 && type.indexOf("jpeg") != -1) {
  59260. type += ",image/jpg";
  59261. }
  59262. return (type || "").indexOf(mime) != -1
  59263. };
  59264. const base64ToBlob = base64 => {
  59265. let arr = base64.split(","),
  59266. mime = arr[0].match(/:(.*?);/)[1],
  59267. bstr = atob(arr[1]),
  59268. n = bstr.length,
  59269. u8arr = new Uint8Array(n);
  59270. while (n--) {
  59271. u8arr[n] = bstr.charCodeAt(n);
  59272. }
  59273. return new Blob([u8arr], { type: mime })
  59274. };
  59275. const base64ToDataURL = base64 => {
  59276. return window.URL.createObjectURL(base64ToBlob(base64))
  59277. };
  59278. const blobToBase64 = function(blob) {
  59279. return new Promise(resolve => {
  59280. var reader = new FileReader();
  59281. reader.onload = function() {
  59282. resolve(reader.result);
  59283. };
  59284. reader.readAsDataURL(blob);
  59285. })
  59286. };
  59287. /*
  59288. * @Author: Rindy
  59289. * @Date: 2019-08-06 16:25:08
  59290. * @LastEditors: Rindy
  59291. * @LastEditTime: 2021-08-27 12:33:49
  59292. * @Description: Request
  59293. */
  59294. //import { $alert, $confirm, $loginTips } from "@/components/shared/message"
  59295. //import { $waiting } from "@/components/shared/loading"
  59296. //import { checkLogin } from "@/api"
  59297. //import { LoginDetector } from "@/core/starter"
  59298. //import { i18n } from "@/lang"
  59299. //import { password } from "@/utils/string"
  59300. //import store from "../Store"
  59301. // 空函数
  59302. const noop = function() {};
  59303. // 请求回调队列
  59304. let postQueue = [];
  59305. /**
  59306. * @property {number} NEXT - 继续执行
  59307. * @property {number} SUCCESS - 成功
  59308. * @property {number} EXCEPTION - 异常错误
  59309. * @property {number} FAILURE_CODE_3001 - 缺少必要参数
  59310. * @property {number} FAILURE_CODE_3002 - 访问异常
  59311. * @property {number} FAILURE_CODE_3003 - 非法访问
  59312. * @property {number} FAILURE_CODE_3004 - 用户未登录
  59313. * @property {number} FAILURE_CODE_3005 - 验证码已过期
  59314. * @property {number} FAILURE_CODE_3006 - 验证码错误
  59315. * @property {number} FAILURE_CODE_3007 - 昵称已存在
  59316. * @property {number} FAILURE_CODE_3008 - 该手机已被注册
  59317. * @property {number} FAILURE_CODE_3009 - 两次输入的密码不一致
  59318. * @property {number} FAILURE_CODE_3010 - 昵称长度错误
  59319. * @property {number} FAILURE_CODE_3011 - 密码长度错误
  59320. * @property {number} FAILURE_CODE_3012 - 昵称包含敏感词
  59321. * @property {number} FAILURE_CODE_3013 - 手机号码格式错误
  59322. * @property {number} FAILURE_CODE_3014 - 账号或密码不正确
  59323. * @property {number} FAILURE_CODE_3015 - 用户不存在
  59324. * @property {number} FAILURE_CODE_3016 - 您没有权限,请联系管理员
  59325. * @property {number} FAILURE_CODE_3017 - 空文件
  59326. * @property {number} FAILURE_CODE_3018 - 需要上传或使用的文件不存在
  59327. * @property {number} FAILURE_CODE_5010 - 找不到该场景对应的相机
  59328. * @property {number} FAILURE_CODE_5012 - 数据不正常
  59329. * @property {number} FAILURE_CODE_5014 - 无权操作该场景
  59330. * @property {number} FAILURE_CODE_5005 - 场景不存在
  59331. */
  59332. const statusCode = {
  59333. NEXT: -999,
  59334. SUCCESS: 0,
  59335. EXCEPTION: -1,
  59336. FAILURE_CODE_3001: 3001,
  59337. FAILURE_CODE_3002: 3002,
  59338. FAILURE_CODE_3003: 3003,
  59339. FAILURE_CODE_3004: 3004,
  59340. FAILURE_CODE_3005: 3005,
  59341. FAILURE_CODE_3006: 3006,
  59342. FAILURE_CODE_3007: 3007,
  59343. FAILURE_CODE_3008: 3008,
  59344. FAILURE_CODE_3009: 3009,
  59345. FAILURE_CODE_3010: 3010,
  59346. FAILURE_CODE_3011: 3011,
  59347. FAILURE_CODE_3012: 3012,
  59348. FAILURE_CODE_3013: 3013,
  59349. FAILURE_CODE_3014: 3014,
  59350. FAILURE_CODE_3015: 3015,
  59351. FAILURE_CODE_3016: 3016,
  59352. FAILURE_CODE_3017: 3017,
  59353. FAILURE_CODE_3018: 3018,
  59354. FAILURE_CODE_5010: 5010,
  59355. FAILURE_CODE_5012: 5012,
  59356. FAILURE_CODE_5014: 5014,
  59357. FAILURE_CODE_5005: 5005,
  59358. };
  59359. /**
  59360. * 获取Token
  59361. * @function
  59362. */
  59363. function getToken() {
  59364. var urlToken = browser.urlHasValue("token", true);
  59365. if (urlToken) {
  59366. // 设置token共享给用户中心
  59367. localStorage.setItem("token", urlToken);
  59368. }
  59369. return urlToken || localStorage.getItem("token") || ""
  59370. }
  59371. /**
  59372. * 根据状态码的结果处理后续操作
  59373. * @function
  59374. * @param {number} code - 状态码
  59375. * @param {function} callback - 回调
  59376. */
  59377. function statusCodesHandler(code, callback) {
  59378. if (code == statusCode.EXCEPTION) {
  59379. return $alert({ content: i18n.t("tips.exception") })
  59380. }
  59381. if (
  59382. code == statusCode.FAILURE_CODE_3002 ||
  59383. code == statusCode.FAILURE_CODE_3003 ||
  59384. code == statusCode.FAILURE_CODE_3004
  59385. ) {
  59386. callback(code);
  59387. return showLoginTips()
  59388. }
  59389. if (code == statusCode.FAILURE_CODE_3001) {
  59390. callback(code);
  59391. return $alert({ content: i18n.t("tips.params_notfound") })
  59392. }
  59393. if (code == statusCode.FAILURE_CODE_3017) {
  59394. callback(code);
  59395. return $alert({ content: i18n.t("tips.file_notfound") })
  59396. }
  59397. if (code == statusCode.FAILURE_CODE_5005) {
  59398. /* if (!config.isEdit) {
  59399. return (location.href = config.pages.NotFound)
  59400. } */
  59401. callback(code);
  59402. return $alert({ content: i18n.t("tips.scene_notfound") })
  59403. }
  59404. if (code == statusCode.FAILURE_CODE_5010) {
  59405. callback(code);
  59406. return $alert({ content: i18n.t("tips.camera_notfound") })
  59407. }
  59408. if (code == statusCode.FAILURE_CODE_5012) {
  59409. callback(code);
  59410. return $alert({ content: i18n.t("tips.data_error") })
  59411. }
  59412. if (code == statusCode.FAILURE_CODE_5014) {
  59413. callback(code);
  59414. return $alert({ content: i18n.t("tips.auth_deny") })
  59415. }
  59416. return statusCode.NEXT
  59417. }
  59418. $.ajaxSetup({
  59419. headers: {},
  59420. beforeSend: function(xhr) {
  59421. const token = getToken();
  59422. if (token) {
  59423. xhr.setRequestHeader("token", token);
  59424. } else if (!token && this.url.indexOf("isLogin") != -1) {
  59425. showLoginTips();
  59426. }
  59427. /* if (config.oem == "localshow") {
  59428. // 本地版本兼容当前目录
  59429. if (this.url.indexOf("http") == -1 && this.url.indexOf("/") == 0) {
  59430. this.url = this.url.substr(1)
  59431. }
  59432. } */
  59433. // if(this.url.indexOf('http')==-1 && this.url.indexOf('/') !=0){
  59434. // this.url = '/'+this.url
  59435. // }
  59436. },
  59437. error: function(xhr, status, error) {
  59438. // 出错时默认的处理函数
  59439. if (this.url.indexOf("/scene.json") != -1 && xhr.status == 404) {
  59440. return $alert({ content: i18n.t("tips.scene_notfound") })
  59441. } else if (this.type === "POST") {
  59442. return $alert({ content: i18n.t("tips.network_error") })
  59443. }
  59444. },
  59445. success: function(result) {},
  59446. complete: function() {
  59447. // Post类型请求无论成功或失败都关闭等待提示
  59448. if (this.type === "POST") {
  59449. http.__loading && $waiting.hide();
  59450. }
  59451. http.__loading = true;
  59452. },
  59453. });
  59454. /**
  59455. * @namespace http
  59456. * @type {Object}
  59457. */
  59458. const http = {
  59459. statusCode,
  59460. __loading: true,
  59461. __request(xhr, method, url, data, done, fail) {
  59462. if (typeof done != "function") {
  59463. done = noop;
  59464. }
  59465. if (typeof fail != "function") {
  59466. fail = noop;
  59467. }
  59468. xhr.done(result => {
  59469. if (typeof result.code !== "undefined") {
  59470. const flag = statusCodesHandler(result.code, function(code) {
  59471. // 需要登录的状态
  59472. if (
  59473. code == statusCode.FAILURE_CODE_3001 ||
  59474. code == statusCode.FAILURE_CODE_3002 ||
  59475. code == statusCode.FAILURE_CODE_3003 ||
  59476. code == statusCode.FAILURE_CODE_3004
  59477. ) {
  59478. if (url.indexOf("isLogin") == -1 && url.indexOf("openSceneBykey") == -1) {
  59479. postQueue.push(function() {
  59480. http[method](url, data, done, fail);
  59481. });
  59482. }
  59483. }
  59484. fail();
  59485. });
  59486. if (flag === statusCode.NEXT) {
  59487. done(result, result.code == 0);
  59488. }
  59489. } else {
  59490. done(result);
  59491. }
  59492. });
  59493. xhr.fail(fail);
  59494. xhr.always(() => (xhr = null));
  59495. return xhr
  59496. },
  59497. /**
  59498. * Get请求
  59499. * @param {String} url 请求地址
  59500. * @param {Object?} data 请求参数
  59501. * @param {Function?} done 成功回调
  59502. * @param {Function?} fail 失败回调
  59503. */
  59504. get(url, data = {}, done, fail) {
  59505. if (/\.json/.test(url)) {
  59506. // json文件格式自动调用getJson方法
  59507. return this.getJson(url, data, done, fail)
  59508. }
  59509. return this.__request($.get(url, data), "get", url, data, done, fail)
  59510. },
  59511. /**
  59512. * Get Blob请求
  59513. * @param {String} url 请求地址
  59514. * @param {Object?} data 请求参数
  59515. * @param {Function?} done 成功回调
  59516. * @param {Function?} fail 失败回调
  59517. */
  59518. getText(url, data = {}, done, fail) {
  59519. return this.__request(
  59520. $.ajax({
  59521. url: url,
  59522. dataType: "text",
  59523. }),
  59524. "getText",
  59525. url,
  59526. data,
  59527. done,
  59528. fail
  59529. )
  59530. },
  59531. /**
  59532. * GetJson请求 读取json文件数据
  59533. * @param {String} url 请求地址
  59534. * @param {Object?} data 请求参数
  59535. * @param {Function?} done 成功回调
  59536. * @param {Function?} fail 失败回调
  59537. */
  59538. getJson(url, data = {}, done, fail) {
  59539. return this.__request($.getJSON(url, data), "get", url, data, done, fail)
  59540. },
  59541. /**
  59542. * Get Blob请求
  59543. * @param {String} url 请求地址
  59544. * @param {Object?} data 请求参数
  59545. * @param {Function?} done 成功回调
  59546. * @param {Function?} fail 失败回调
  59547. */
  59548. getBlob(url, data = {}, done, fail) {
  59549. return this.__request(
  59550. $.ajax({
  59551. url: url,
  59552. dataType: "blob",
  59553. }),
  59554. "getBlob",
  59555. url,
  59556. data,
  59557. done,
  59558. fail
  59559. )
  59560. },
  59561. /**
  59562. * Get Arraybuffer请求
  59563. * @param {String} url 请求地址
  59564. * @param {Object?} data 请求参数
  59565. * @param {Function?} done 成功回调
  59566. * @param {Function?} fail 失败回调
  59567. */
  59568. getArraybuffer(url, data = {}, done, fail) {
  59569. return this.__request(
  59570. $.ajax({
  59571. url: url,
  59572. dataType: "arraybuffer",
  59573. }),
  59574. "getArraybuffer",
  59575. url,
  59576. data,
  59577. done,
  59578. fail
  59579. )
  59580. },
  59581. /**
  59582. * Post 请求
  59583. * @param {String} url 请求地址
  59584. * @param {Object?} data 请求参数
  59585. * @param {Function?} done 成功回调
  59586. * @param {Function?} fail 失败回调
  59587. */
  59588. post(url, data = {}, done, fail) {
  59589. if (url.indexOf("isLogin") == -1) {
  59590. http.__loading && $waiting.show();
  59591. }
  59592. return this.__request($.post(url, data), "post", url, data, done, fail)
  59593. },
  59594. /**
  59595. * PostJson 请求
  59596. * @param {String} url 请求地址
  59597. * @param {Object?} data 请求参数
  59598. * @param {Function?} done 成功回调
  59599. * @param {Function?} fail 失败回调
  59600. */
  59601. postJson(url, data = {}, done, fail) {
  59602. http.__loading && $waiting.show();
  59603. return this.__request(
  59604. $.ajax({
  59605. type: "POST",
  59606. url: url,
  59607. contentType: "application/json",
  59608. data: JSON.stringify(data),
  59609. }),
  59610. "postJson",
  59611. url,
  59612. data,
  59613. done,
  59614. fail
  59615. )
  59616. },
  59617. /**
  59618. * Post 表单 支持文件上传
  59619. * @param {String} url 请求地址
  59620. * @param {FormData?} formData 请求参数
  59621. * @param {Function?} done 成功回调
  59622. * @param {Function?} fail 失败回调
  59623. */
  59624. postForm(url, formData, done, fail, onProgress) {
  59625. if (typeof onProgress === "function") {
  59626. return this.__request(
  59627. $.ajax({
  59628. type: "POST",
  59629. url: url,
  59630. processData: false,
  59631. contentType: false,
  59632. data: formData,
  59633. xhr: function() {
  59634. const xhr = new XMLHttpRequest();
  59635. xhr.upload.addEventListener("progress", function(e) {
  59636. onProgress((e.loaded / e.total) * 100 + "%");
  59637. });
  59638. return xhr
  59639. },
  59640. }),
  59641. "postForm",
  59642. url,
  59643. formData,
  59644. done,
  59645. fail
  59646. )
  59647. } else {
  59648. http.__loading && $waiting.show();
  59649. return this.__request(
  59650. $.ajax({
  59651. type: "POST",
  59652. url: url,
  59653. processData: false,
  59654. contentType: false,
  59655. data: formData,
  59656. }),
  59657. "postForm",
  59658. url,
  59659. formData,
  59660. done,
  59661. fail
  59662. )
  59663. }
  59664. },
  59665. /**
  59666. * 加载图片
  59667. * @param {String} url 请求地址
  59668. * @param {Number?} retry 重试次数,默认为3
  59669. */
  59670. loadImage(url, retry = 3) {
  59671. const def = $.Deferred();
  59672. const img = new Image();
  59673. /* if (process.env.VUE_APP_REGION == "AWS" && url.indexOf("x-oss-process=image") != -1) {
  59674. var arr = url.split("?")
  59675. url = arr[0] + encodeURIComponent("?" + arr[1].replace(/\//g, "@"))
  59676. } */
  59677. const load = () => {
  59678. console.warn("Retrying load image: " + url);
  59679. this.loadImage(url, retry - 1)
  59680. .done(def.resolve.bind(def))
  59681. .progress(def.notify.bind(def))
  59682. .fail(def.reject.bind(def));
  59683. };
  59684. img.onerror = function() {
  59685. retry > 0 ? setTimeout(() => load(), 1e3) : def.reject(`[${url}]加载失败`);
  59686. };
  59687. img.onload = function() {
  59688. def.resolve(img);
  59689. };
  59690. img.crossOrigin = "anonymous";
  59691. img.src = url;
  59692. return def
  59693. },
  59694. /**
  59695. * 上传文件
  59696. * @param {String} url 请求地址
  59697. * @param {Object?} data 请求参数
  59698. * @param {Function?} done 成功回调
  59699. * @param {Function?} fail 失败回调
  59700. */
  59701. uploadFile(url, data = {}, done, fail, onProgress) {
  59702. const form = new FormData();
  59703. // if (file.needTransfer) { //ie和苹果都不支持dataURLtoFile得传送,所以只能用blob
  59704. // form.append("file", common.dataURLtoBlob(file.file), file.name || file.file.name);
  59705. // } else {
  59706. // form.append("file", file.file, file.name || file.file.name);
  59707. // }
  59708. for (let key in data) {
  59709. if (key == "file") {
  59710. form.append("file", data[key], data.filename || data[key].name);
  59711. } else if (key != "filename") {
  59712. form.append(key, data[key]);
  59713. }
  59714. }
  59715. return this.postForm(url, form, done, fail, onProgress)
  59716. },
  59717. /**
  59718. * 上传文件
  59719. * @param {String} url 请求地址
  59720. * @param {Object?} data 请求参数 {file:'base64 string',filename:'image.jpg',...}
  59721. * @param {Function?} done 成功回调
  59722. * @param {Function?} fail 失败回调
  59723. */
  59724. uploadBlobFile(url, data = {}, done, fail) {
  59725. const form = new FormData();
  59726. for (let key in data) {
  59727. if (key === "file") {
  59728. form.append("file", base64ToBlob(data.file), data.filename);
  59729. } else if (key != "filename") {
  59730. form.append(key, data[key]);
  59731. }
  59732. }
  59733. return this.postForm(url, form, done, fail)
  59734. },
  59735. };
  59736. window.downloaded = {};
  59737. window.startdownloads = [];
  59738. class TileDownloader extends EventDispatcher{
  59739. constructor( ) {
  59740. super();
  59741. this.panos = null;
  59742. this.retryMinimumTime = 1e4;
  59743. this.panoLoadCallbacks = {};
  59744. this.downloadDescriptors = {};
  59745. this.priorityQueue = [];
  59746. this.forceQueue = [];
  59747. this.activeDownloads = [];
  59748. this.tilePrioritizer = null;
  59749. this.refreshInterval = null;
  59750. this.processPriorityQueue = !1;
  59751. this.concurrentDownloads = 6;//e.concurrentDownloads || 1;
  59752. this.downloadTestResults = {};
  59753. this.freeze = Object.freeze({
  59754. Testing: 1,
  59755. Success: 2,
  59756. Fail: 3
  59757. });
  59758. this.visible = true; //add 借用viewer.updateVisible来判断是否start
  59759. viewer.addEventListener('pageVisible', (e)=>{//不可见时不refreshUpdateInterval
  59760. //console.log('visibilitychange:', state)
  59761. viewer.updateVisible(this, 'pageVisible', e.v);
  59762. this.judgeStart();
  59763. });
  59764. }
  59765. setPanoData(e, t /* , i */) {
  59766. this.panos = e,
  59767. this.imagePanos = t;
  59768. // this.panoGroupId = i
  59769. }
  59770. start() {
  59771. this.downloadCubeTex = true;
  59772. if(!Potree.settings.useDepthTex){
  59773. viewer.updateVisible(this,'pano', true );
  59774. this.judgeStart();
  59775. }else {
  59776. this.refreshInterval || this.judgeStart();
  59777. }
  59778. }
  59779. stop() {
  59780. this.downloadCubeTex = false;
  59781. if(!Potree.settings.useDepthTex){
  59782. viewer.updateVisible(this,'pano', false );
  59783. this.judgeStart();
  59784. }
  59785. }
  59786. judgeStart(){//add
  59787. if(this.visible){
  59788. //console.log('judgeStart true')
  59789. this.started = true;
  59790. this.refreshUpdateInterval(0);
  59791. }else {
  59792. //console.log('judgeStart false')
  59793. this.started = false;
  59794. window.clearTimeout(this.refreshInterval);
  59795. }
  59796. }
  59797. refreshUpdateInterval(e) {
  59798. e || (e = 0),
  59799. this.refreshInterval = window.setTimeout(function() {
  59800. var e = this.update();
  59801. e ? this.refreshUpdateInterval(TileDownloader.ACTIVE_REFRESH_DELAY) : this.refreshUpdateInterval(TileDownloader.IDLE_REFRESH_DELAY);
  59802. }
  59803. .bind(this), e);
  59804. }
  59805. update() {
  59806. if(this.downloadCubeTex){ //可以下载贴图
  59807. var e = this.forceQueue.length > 0;
  59808. this.processQueueForDownloading(this.forceQueue);
  59809. if (this.processPriorityQueue) {
  59810. this.queuePrioritizedTilesForPanos(this.panos);
  59811. this.priorityQueue.length > 0 && (e = !0);
  59812. this.processQueueForDownloading(this.priorityQueue);
  59813. }
  59814. return e
  59815. }else {//仅下载depthTex
  59816. this.tilePrioritizer.filterDepthTex(this.panos);
  59817. }
  59818. }
  59819. queuePrioritizedTilesForPanos(e) {
  59820. this.tilePrioritizer && (this.clearQueue(this.priorityQueue),
  59821. this.tilePrioritizer.filterAndPrioritize(this.priorityQueue, e, this),
  59822. this.clearFromQueue(this.priorityQueue, DownloadStatus.None, !0), //去除state为DownloadStatus.None的(可能是去除已经在下载的)
  59823. this.setStatusOrRemoveForAllDescriptors(this.priorityQueue, DownloadStatus.Queued));
  59824. }
  59825. clearQueue(e) {//停止下载并清空
  59826. this.setStatusForAllDescriptors(e, DownloadStatus.None),
  59827. e.length = 0;
  59828. }
  59829. clearForceQueue() {
  59830. this.clearQueue(this.forceQueue);
  59831. }
  59832. clearFromQueue(e, t, i) {
  59833. for (var n = 0; n < e.length; n++) {
  59834. var r = e[n];
  59835. r && (t === r.status && !i || t !== r.status && i) && (e[n] = null);
  59836. }
  59837. }
  59838. setStatusForAllDescriptors(e, t) {
  59839. for (var i = 0; i < e.length; i++) {
  59840. var n = e[i];
  59841. n && (n.status = t);
  59842. }
  59843. }
  59844. setStatusOrRemoveForAllDescriptors(e, t) {
  59845. for (var i = 0; i < e.length; i++) {
  59846. var n = e[i];
  59847. n && (n.status !== t ? n.status = t : e[i] = null);
  59848. }
  59849. }
  59850. getTileDownloadDescriptors(pano, size) {//获取该pano的该size的全部的tile的descriptor
  59851. var i = this.getAllTileDownloadDescriptorsForPano(pano),
  59852. n = i[size];
  59853. return n || (n = this.buildDownloadDescriptorArray(size),//创建的全部是空的
  59854. i[size] = n,
  59855. this.initTileDownloadDescriptors(n, pano, size)),//绑定到该pano size
  59856. n
  59857. }
  59858. getAllTileDownloadDescriptorsForPano(pano) {//新建空Descriptors
  59859. var t = this.downloadDescriptors[pano.id];
  59860. return t || (t = {},
  59861. this.downloadDescriptors[pano.id] = t),
  59862. t
  59863. }
  59864. processQueueForDownloading(e, t) {//执行下载任务
  59865. this.cleanupActiveDownloads();
  59866. if (this.activeDownloads.length < this.concurrentDownloads || t) {
  59867. var i = t ? e.length : this.concurrentDownloads - this.activeDownloads.length;
  59868. for (var n = 0, r = 0; n < i && e.length > 0; r++) {
  59869. var o = e.shift();
  59870. if(o){
  59871. //add 为了防止1024的在512前下载完,这里强行等待512下载完毕再开始下载
  59872. if(o.panoSize > 512 && !this.isPanoDownloaded(o.pano, 512) ){
  59873. //console.log('512的还没下载好呢!')
  59874. e.push(o);
  59875. break;//一般512的都是连续下载的,所以后面就都不是512了直接中断
  59876. }
  59877. this.startDownload(o);
  59878. n++;
  59879. }
  59880. }
  59881. }
  59882. }
  59883. testDownload(panoSize, tileSize, callback) {
  59884. var n = this.downloadTestResults[panoSize];
  59885. if (n)
  59886. return void(n === this.freeze.Success ? callback(!0) : n === this.freeze.Fail && callback(!1));
  59887. this.downloadTestResults[panoSize] = this.freeze.Testing;
  59888. var r = this.panos[0],
  59889. o = this.getTileUrl({pano:r, panoSize, tileSize, tileIndex:0} /* r.id, panoSize, tileSize, 0 */),
  59890. a = function(t) {
  59891. this.downloadTestResults[panoSize] = this.freeze.Success,
  59892. callback(!0);
  59893. }
  59894. .bind(this),
  59895. s = function() {
  59896. this.downloadTestResults[panoSize] = this.freeze.Fail,
  59897. callback(!1);
  59898. }
  59899. .bind(this);
  59900. this.loadImage(o, 0, a, s);
  59901. }
  59902. startDownload(e) {//开始下载啦
  59903. //console.log('startDownload')
  59904. startdownloads.push(e);
  59905. e.status = DownloadStatus.Downloading;
  59906. var t = this.getTileUrl(e/* e.pano.id, e.panoSize, e.tileSize, e.tileIndex, e.pano.alignmentType */);//xzw add alignmentType
  59907. if(!t)return;
  59908. this.activeDownloads.push(e);
  59909. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  59910. }
  59911. downloadFailed(e, t) {}
  59912. downloadComplete(e, t) {//下载成功时
  59913. //if (e.panoGroupId === this.panoGroupId) {
  59914. var i = this.getPanoLoadCallbacks(e.pano, e.panoSize);
  59915. e.status = DownloadStatus.Downloaded,
  59916. i && i.onProgress && i.onProgress(e.pano, e.panoSize);
  59917. var n = {
  59918. panoId: e.pano.id,
  59919. image: t,
  59920. tileSize: e.tileSize,
  59921. panoSize: e.panoSize,
  59922. tileIndex: e.tileIndex,
  59923. faceTileIndex: e.faceTileIndex,
  59924. totalTiles: e.totalTiles,
  59925. face: e.face,
  59926. tileX: e.tileX,
  59927. tileY: e.tileY,
  59928. direction: e.direction
  59929. };
  59930. downloaded[e.pano.id] || (downloaded[e.pano.id]={512:[],1024:[],2048:[]});
  59931. downloaded[e.pano.id][e.panoSize] || (downloaded[e.pano.id][e.panoSize] = []);
  59932. downloaded[e.pano.id][e.panoSize].push(e);
  59933. if(e.panoSize != 512 && downloaded[e.pano.id][512].length<6){
  59934. console.warn('没下完');
  59935. }
  59936. e.image = t,
  59937. this.dispatchEvent({type:TileDownloaderEvents.TileDownloadSuccess, desc:n} );
  59938. this.isPanoDownloaded(e.pano, e.panoSize) && (n = {
  59939. panoId: e.pano.id,
  59940. tileSize: e.tileSize,
  59941. panoSize: e.panoSize
  59942. },
  59943. this.dispatchEvent({type:TileDownloaderEvents.PanoDownloadComplete, desc:n}),
  59944. i && i.onLoad && i.onLoad(e.pano, e.panoSize));
  59945. //}
  59946. }
  59947. isPanoDownloaded(e, t) {
  59948. var i = this.getTileDownloadDescriptors(e, t);
  59949. if (i.length <= 0)
  59950. return !1;
  59951. for (var n = 0; n < i.length; n++) {
  59952. var r = i[n];
  59953. if (r.status !== DownloadStatus.Downloaded)
  59954. return !1
  59955. }
  59956. return !0
  59957. }
  59958. setPanoLoadCallbacks(e, t, i, n, r) {
  59959. var o = e.id + ":" + this.qualityManager.getPanoSize(t);
  59960. this.panoLoadCallbacks[o] = {
  59961. onLoad: i,
  59962. onFail: n,
  59963. onProgress: r
  59964. };
  59965. }
  59966. getPanoLoadCallbacks(e, t) {
  59967. var i = e.id + ":" + t;
  59968. return this.panoLoadCallbacks[i]
  59969. }
  59970. buildDownloadDescriptorArray(e) {
  59971. for (var t = TileUtils.getTileCountForSize(e), i = [], n = 0; n < t; n++) {
  59972. var r = this.buildDownloadDescriptor();
  59973. i.push(r);
  59974. }
  59975. return i
  59976. }
  59977. buildDownloadDescriptor() {//Descriptor!
  59978. var e = {
  59979. panoGroupId: null,
  59980. pano: null,
  59981. panoSize: -1,
  59982. tileSize: -1,
  59983. tileIndex: -1,
  59984. totalTiles: -1,
  59985. faceTileIndex: -1,
  59986. status: DownloadStatus.None,
  59987. url: null,
  59988. image: null,
  59989. direction: new Vector3, //该tile在cube中的方向
  59990. face: -1,
  59991. cubeFace: -1,
  59992. tileX: -1,
  59993. tileY: -1
  59994. };
  59995. return e
  59996. }
  59997. initTileDownloadDescriptors(e, t, i) {
  59998. for (var n = 0; n < e.length; n++) {
  59999. var r = e[n];
  60000. this.initTileDownloadDescriptor(r, t, i, n);
  60001. }
  60002. }
  60003. initTileDownloadDescriptor(desc, pano, size, index) {
  60004. var r = size >= TileUtils.TILE_SIZE ? TileUtils.TILE_SIZE : size;
  60005. desc.face = TileUtils.getFaceForTile(size, index);//根据顺序得到的face的index
  60006. desc.cubeFace = TileUtils.mapFaceToCubemapFace(desc.face);//为了贴图而转化的face index
  60007. //desc.panoGroupId = this.panoGroupId;//就是场景号
  60008. desc.pano = pano;
  60009. desc.panoSize = size;
  60010. desc.tileSize = r; //瓦片图size 512
  60011. desc.tileIndex = index;
  60012. desc.totalTiles = TileUtils.getTileCountForSize(size);
  60013. desc.status = DownloadStatus.None;
  60014. desc.image = null;
  60015. TileUtils.getTileLocation(desc.panoSize, desc.tileIndex, desc);//得到该tile在这个face中的具体位置(tileX等)
  60016. TileUtils.getTileVector(desc.panoSize, desc.tileSize, desc.cubeFace, desc.tileX, desc.tileY, TileUtils.LocationOnTile.Center, 0, desc.direction);
  60017. }
  60018. getTiles(d, sceneNum){
  60019. if(Potree.settings.isLocal2){//新的地址 scene_view_data/场景码/images/tiles
  60020. return `${Potree.settings.urls.prefix3}/scene_view_data/${sceneNum}/images/${d}`
  60021. }
  60022. return `${Potree.settings.urls.prefix3}/images/images${sceneNum}/${d}`
  60023. }
  60024. loadImage(e, t, i, n) {
  60025. //自己修改了ajax,把getImage改成了loadImg
  60026. http.loadImage(e, t).then(function(e) {
  60027. i(e);
  60028. }).fail(n);
  60029. }
  60030. }
  60031. TileDownloader.prototype.forceQueueTilesForPano = function() {//根据条件开始加载tile
  60032. var e = [],
  60033. t = [];
  60034. return function(pano, size, dir, hFov, vFov, download) {
  60035. e.length = 0;
  60036. for (var u = this.getTileDownloadDescriptors(pano, size), d = 0; d < u.length; d++) {
  60037. var p = u[d];
  60038. p.status !== DownloadStatus.None && p.status !== DownloadStatus.Queued || e.push(p);
  60039. }
  60040. if (dir && e.length > 0) {
  60041. TilePrioritizer.sortPanoTiles(e, pano, dir); //按最佳方向排序e
  60042. t.length = 0;
  60043. TileUtils.matchingTilesInDirection(pano, size, dir, hFov, vFov, t);//得到在符合视野标准的集合t
  60044. for (var f = 0, g = function(e) {
  60045. return e.face === m.face && e.faceTileIndex === m.faceTileIndex
  60046. }; f < e.length;) { //过滤掉不符合角度要求的
  60047. var m = e[f],
  60048. v = t.findIndex(g);
  60049. v < 0 ? e.splice(f, 1) : f++;
  60050. }
  60051. }
  60052. for (var A = 0; A < e.length; A++){
  60053. this.forceQueue.push(e[A]); //装载
  60054. }
  60055. /* if(e.length){
  60056. console.log(e)
  60057. } */
  60058. this.setStatusForAllDescriptors(this.forceQueue, DownloadStatus.ForceQueued);
  60059. this.clearFromQueue(this.priorityQueue, DownloadStatus.ForceQueued, !1);
  60060. download && this.processQueueForDownloading(this.forceQueue, !0);
  60061. }
  60062. }();
  60063. TileDownloader.prototype.cleanupActiveDownloads = function() {
  60064. var e = [];
  60065. return function() {
  60066. e.length = 0;
  60067. for (var t = 0; t < this.activeDownloads.length; t++) {
  60068. var i = this.activeDownloads[t];
  60069. i.status !== DownloadStatus.Downloaded && i.status !== DownloadStatus.Failed && e.push(i);
  60070. }
  60071. this.activeDownloads.length = 0,
  60072. this.activeDownloads.push.apply(this.activeDownloads, e);
  60073. }
  60074. }();
  60075. TileDownloader.prototype.getTileUrl = function() {
  60076. var e = {
  60077. 256: "256",
  60078. 512: "512",
  60079. 1024: "1k",
  60080. 2048: "2k",
  60081. 4096: "4k"
  60082. },
  60083. t = {
  60084. face: -1,
  60085. faceTileIndex: -1,
  60086. tileX: -1,
  60087. tileY: -1
  60088. };
  60089. return function(o={} ) {
  60090. var id = o.pano.originID, ////////
  60091. panoSize = o.panoSize,
  60092. tileSize = o.tileSize,
  60093. tileIndex = o.tileIndex,
  60094. sceneCode = o.pano.pointcloud.sceneCode;
  60095. var metadata = {sceneScheme:10};
  60096. TileUtils.getTileLocation(panoSize, tileIndex, t);
  60097. var s = Math.floor(panoSize / tileSize),
  60098. l = s * s,
  60099. h = Math.floor(tileIndex / l),
  60100. u = "",
  60101. d = '', g = '';
  60102. if(Potree.settings.isLocal){//原始规则
  60103. //1 === config.tiling.customCompression && (u = "_" + config.tiling["q" + e[panoSize]]);
  60104. //1 === o.tiling.customCompression && (u = "_" + o.tiling["q" + e[n]]);
  60105. d = "tiles/" + id + "/" + e[panoSize] + u + "_face" + h + "_" + t.tileX + "_" + t.tileY + ".jpg";
  60106. d = this.getTiles(d, sceneCode);
  60107. g = "?";
  60108. }else {//阿里云oss的规则 if (metadata.sceneScheme == 10)
  60109. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=';
  60110. if (e[panoSize] == '512') {
  60111. d += 'image/resize,h_512';
  60112. } else {
  60113. //4k的图,移动端是1k,pc端是2k,放大才是4k
  60114. 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
  60115. d += 'image/resize,m_lfit,w_' + panoSize + '/crop,w_512,h_512,';
  60116. } else {
  60117. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=image/crop,w_512,h_512,';
  60118. }
  60119. //起始位置
  60120. if (t.tileX == 0) {
  60121. d += 'x_0,';
  60122. } else {
  60123. d += 'x_' + (512 * t.tileX - 1) + ',';
  60124. }
  60125. if (t.tileY == 0) {
  60126. d += 'y_0';
  60127. } else {
  60128. d += 'y_' + (512 * t.tileY - 1);
  60129. }
  60130. }
  60131. d = this.getTiles(d, sceneCode);
  60132. g = "&";
  60133. }
  60134. d += g + 'time='+o.pano.pointcloud.timeStamp; //加后缀
  60135. return d;
  60136. }
  60137. }();
  60138. TileDownloader.tilegen = true;
  60139. TileDownloader.IDLE_REFRESH_DELAY = 500;
  60140. TileDownloader.ACTIVE_REFRESH_DELAY = 16;
  60141. TileDownloader.DOWNLOAD_RETRIES = 4;
  60142. function Node$1(e, t) {
  60143. this.tree = e, //所属树(TileTree)
  60144. this.parent = t,
  60145. this.children = [],
  60146. this.id = ++u$1;
  60147. }
  60148. function o(e, t, i, r, a, s, l, h) {
  60149. if (e) {
  60150. l = l || TileTree.TraversalType.PreOrder;
  60151. var u = r * c + i;
  60152. if (l === TileTree.TraversalType.PreOrder && (a && a(e, t, u, i, r),
  60153. s && s.push(e)),
  60154. e.children && 0 !== e.children.length) {
  60155. for (var d = r * c, p = i * c, f = 0; f < c; f++)
  60156. for (var g = 0; g < c; g++)
  60157. o(e.children[g * c + f], t + 1, p + f, d + g, a, s, l, h);
  60158. l === TileTree.TraversalType.PostOrder && (a && a(e, t, u, i, r),
  60159. s && s.push(e));
  60160. }
  60161. }
  60162. }
  60163. function Plant(seed) {
  60164. seed.root = Branch(seed, null, 0);
  60165. }
  60166. function Branch(seed, parent, level) {
  60167. if (level > seed.levels)
  60168. return null;
  60169. var node = new Node$1(seed, parent);
  60170. seed.allNodes.push(node);
  60171. for (var o = 0; o < h$1; o++)
  60172. node.children[o] = Branch(seed, node, level + 1);
  60173. return node
  60174. }
  60175. function l(parent, t, level, n, r) {
  60176. if (!parent)
  60177. return null;
  60178. if (0 === level)
  60179. return parent;
  60180. if (!parent.children || 0 === parent.children.length)
  60181. return null;
  60182. var o = Math.pow(c, level),
  60183. a = o / c,
  60184. s = n % a,
  60185. h = r % a,
  60186. u = Math.floor(r / a),
  60187. d = Math.floor(n / a),
  60188. p = u * c + d,
  60189. f = parent.children[p];
  60190. return l(f, t + 1, level - 1, s, h)
  60191. }
  60192. /* cube每个面都有一个分层树 用于代表瓦片图的细分?
  60193. 树4096的分为三层,每层有4个子节点。(最后一层的四个子节点都是null)
  60194. */
  60195. var c = 2,
  60196. h$1 = c * c; //4个子节点
  60197. var u$1 = 0;
  60198. class TileTree {
  60199. constructor(e, t) {
  60200. this.levels = t,
  60201. this.tileSize = e,
  60202. this.root = null,
  60203. this.allNodes = [],
  60204. Plant(this);
  60205. }
  60206. getSubNode(e, t, i) {
  60207. (!t || e < this.tileSize) && (t = 0),
  60208. (!i || e < this.tileSize) && (i = 0),
  60209. e < this.tileSize && (e = this.tileSize);
  60210. var level = TileTree.getLevelCountForSize(this.tileSize, e),
  60211. o = l(this.root, 0, level, t, i);
  60212. return o
  60213. }
  60214. breadthFirst(e) {//广度优先搜索
  60215. e = e || {};
  60216. var t = !!e.nullLevelEnd,
  60217. i = e.maxLevel,
  60218. n = e.minLevel,
  60219. r = e.callback,
  60220. o = e.saveVisited,
  60221. a = [],
  60222. s = {},
  60223. l = 0,
  60224. c = 0;
  60225. for (a.push(this.root),
  60226. a.push(s); a.length > 0 && !(i && l > i);) {
  60227. var h = a.shift();
  60228. if (h === s)
  60229. (!n || l >= n) && (r && t && r(null),
  60230. o && t && o.push(null)),
  60231. a.length > 0 && a.push(s),
  60232. l++,
  60233. c = 0;
  60234. else {
  60235. if (h.children)
  60236. for (var u = 0; u < h.children.length; u++) {
  60237. var d = h.children[u];
  60238. d && a.push(h.children[u]);
  60239. }
  60240. var p = this.getFaceIndexFromNode(h);
  60241. (!n || l >= n) && (r && r(h, l, p),
  60242. o && o.push(h)),
  60243. c++;
  60244. }
  60245. }
  60246. }
  60247. getFaceIndexFromNode(e) {
  60248. if (!e)
  60249. return -1;
  60250. for (var t = 1, i = e, n = 0, r = 0;;) {
  60251. var o = i.parent;
  60252. if (!o)
  60253. break;
  60254. for (var a = -1, s = 0; s < o.children.length; s++)
  60255. o.children[s] === i && (a = s);
  60256. var l = a % c,
  60257. h = Math.floor(a / c);
  60258. n = l * t + n,
  60259. r = h * t + r,
  60260. t *= c,
  60261. i = o;
  60262. }
  60263. return r * t + n
  60264. }
  60265. depthFirst(e, t, i) {
  60266. o(this.root, 0, 0, 0, e, t, i, this.tileSize);
  60267. }
  60268. }
  60269. TileTree.TraversalType = Object.freeze({
  60270. PreOrder: 0,
  60271. PostOrder: 1
  60272. });
  60273. TileTree.getLevelCountForSize = function(tileSize, size) {//512->0 2024->1
  60274. var i = 0;
  60275. for (size < tileSize && (size = tileSize);;) {
  60276. if (size /= c,
  60277. size < tileSize)
  60278. break;
  60279. i++;
  60280. }
  60281. return i
  60282. };
  60283. TileTree.getSizeForLevel = function(e, t) {
  60284. return Math.pow(c, t) * e
  60285. };
  60286. function createDescriptor() {
  60287. var e = {
  60288. renderTarget: null,
  60289. inUse: !1,
  60290. size: -1,
  60291. pano: null
  60292. };
  60293. return e
  60294. }
  60295. function c$1() {
  60296. if (!this.uploadIntervalCancelled) {
  60297. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  60298. b = !0,
  60299. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  60300. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(w) : this.uploadInterval = null;
  60301. } else {
  60302. this.refreshUploadInterval(this.uploadIntervalDelay);
  60303. }
  60304. }
  60305. }
  60306. var b = !1,
  60307. w = config$1.tiling.uploadIntervalDelay,
  60308. _ = config$1.tiling.initialIntervalDelay,
  60309. T = config$1.tiling.maxNonBaseUploadsPerFrame,
  60310. x$1 = config$1.tiling.maxBaseUploadsPerFrame,
  60311. S = {
  60312. Base: 0,
  60313. Remaining: 1
  60314. };/* ,
  60315. M = []; */
  60316. class PanoRenderer extends EventDispatcher{
  60317. constructor(viewer, tileDownloader, qualityManager) {
  60318. super();
  60319. this.tileDirectory = {};
  60320. this.activeRenderTargetDescriptors = {};
  60321. this.activePanos = [];
  60322. this.panoLODDescriptors = {};
  60323. this.panoDescriptors = {};
  60324. this.tileTrees = {};
  60325. this.forceQueue = [];
  60326. this.uploadQueues = {};
  60327. this.uploadInterval = null;
  60328. this.uploadIntervalCancelled = !1;
  60329. this.usingTileOverlay = !1;
  60330. this.overlayTilesLoaded = !1;
  60331. this.overlayTileBase = null;
  60332. this.overlayTilesBasic = {};
  60333. this.overlayTilesEnhanced = {};
  60334. this.zoomRenderTarget = null; //用于缩放的rendertarget
  60335. this.zoomPano = null;
  60336. this.zoomingActive = !1;
  60337. this.zoomPanoId = null;
  60338. this.zoomPanoRenderingDisabled = !1;
  60339. this.direction = [];//new THREE.Vector3;
  60340. this.maxBaseUploadsPerFrame = x$1;
  60341. this.maxNonBaseUploadsPerFrame = T;
  60342. this.M = [];//move M to here 似乎列表里会有两个
  60343. this.viewer = viewer;
  60344. this.tileDownloader = tileDownloader;
  60345. this.qualityManager = qualityManager;
  60346. this.initTime = performance.now();
  60347. this.bindEvents();
  60348. }
  60349. getActivePanoTextures(e) {
  60350. e = e || [];
  60351. for (var t = 0; t < M.length; t++) {
  60352. var i = M[t];
  60353. i.renderTarget && i.renderTarget.texture && e.push(i.renderTarget.texture);
  60354. }
  60355. }
  60356. hasQueuedTiles() {
  60357. var e = this.peekNextFromUploadQueue();
  60358. return null !== e && void 0 !== e
  60359. }
  60360. getActiveRenderTargetDescriptor(e) {
  60361. return this.activeRenderTargetDescriptors[e]
  60362. }
  60363. setActiveRenderTargetDescriptor(e, t) {
  60364. this.activeRenderTargetDescriptors[e] = t;
  60365. }
  60366. bindEvents() {
  60367. this.tileDownloader.addEventListener(TileDownloaderEvents.TileDownloadSuccess, this.onTileDownloaded.bind(this));
  60368. }
  60369. enableUltraHighQualityMode(e) {
  60370. if(config$1.tileClass == "2k"||config$1.tileClass == "1k")return this.enableHighQuality(e)//xzw add 濡傛灉鏈€澶氬彧瑕?k鐨勮瘽
  60371. if (!this.qualityManager.ultraHighQualityModeEnabled()) {
  60372. var t = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
  60373. this.tileDownloader.testDownload(t, TileUtils.TILE_SIZE, function (t) {
  60374. t && (this.qualityManager.enableUltraHighQualityMode(),
  60375. this.setupZoomRenderTarget(),
  60376. e());
  60377. }
  60378. .bind(this));
  60379. }
  60380. }
  60381. activateTiledPano(pano, size, i) {
  60382. i && this.clearAllQueuedUploads();
  60383. for (var n = 0; n < TileUtils.FACES_PER_PANO; n++)
  60384. this.initTileTree(pano.id, n, this.qualityManager.getMaxPossiblePanoSize()); //得到this.tileTrees[pano.id],arr[6]
  60385. this.linkAllTilesAndNodes(pano);
  60386. var r = this.getActiveRenderTargetDescriptor(pano.id),
  60387. l = size;
  60388. l > this.qualityManager.getMaxNavPanoSize() && (l = this.qualityManager.getMaxNavPanoSize());
  60389. if ( !r || l !== r.size) {
  60390. r && this.deactiveDescripor(r.renderTarget);
  60391. r = this.activeDescripor(l);
  60392. if (!r) {
  60393. var ren = this.initTiledPano(l, !1);
  60394. r = this.initDescriptor(ren.width);
  60395. r.renderTarget = ren;
  60396. }
  60397. r.pano = pano;
  60398. this.resetPanoDescriptor(pano.id);
  60399. this.resetPanoLODDescriptors(pano.id);
  60400. this.resetRenderStatus(pano.id, !0, !0);
  60401. }
  60402. this.setActiveRenderTargetDescriptor(pano.id, r);
  60403. var h = i ? 0 : 1;
  60404. this.updateActivePanos(pano, h);
  60405. //console.log(`index:${this.viewer.index} ${r.renderTarget.texture.id} ${pano.id}`)
  60406. return r.renderTarget
  60407. }
  60408. deactivateTiledPano(e) {
  60409. var t = this.getActiveRenderTargetDescriptor(e.id);
  60410. if(this.isRenderTargetDescriptorValid(t)){
  60411. this.deactiveDescripor(t.renderTarget);
  60412. this.setActiveRenderTargetDescriptor(e.id, null);
  60413. }
  60414. var i = this.getUploadQueueForPano(e.id);
  60415. this.clearUploadQueue(i);
  60416. this.updateActivePanos();
  60417. }
  60418. getActivePanoCount() {
  60419. return this.activePanos.length
  60420. }
  60421. resetRenderStatus(e, t, i, n) {
  60422. var r = null;
  60423. n && (r = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, n) + 1);
  60424. for (var o = function (e, n, r, o) {
  60425. i && (n.tile.zoomUploaded = !1),
  60426. t && (n.tile.uploaded = !1);
  60427. }, a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  60428. var s = this.getTileTree(e, a);
  60429. s.breadthFirst({
  60430. callback: o.bind(this, a),
  60431. minLevel: r
  60432. });
  60433. }
  60434. }
  60435. copyBaseRenderStatusToZoomed(e) {
  60436. for (var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, this.qualityManager.getMaxNavPanoSize()), i = function (e, t, i, n) {
  60437. t.tile.zoomUploaded = t.tile.uploaded,
  60438. t.zoomCovered = t.covered;
  60439. }, n = 0; n < TileUtils.FACES_PER_PANO; n++) {
  60440. var r = this.getTileTree(e, n);
  60441. r.breadthFirst({
  60442. callback: i.bind(this, n),
  60443. maxLevel: t
  60444. });
  60445. }
  60446. }
  60447. isRenderTargetDescriptorValid(e) {
  60448. return e && e.renderTarget
  60449. }
  60450. isPanoActive(e) {
  60451. var t = this.getActiveRenderTargetDescriptor(e);
  60452. return this.isRenderTargetDescriptorValid(t)
  60453. }
  60454. isPanoZoomed(e) {
  60455. return this.zoomingActive && this.zoomPanoId === e
  60456. }
  60457. initTileTree(e, t, i) {
  60458. var n = this.tileTrees[e];
  60459. n || (n = [],
  60460. this.tileTrees[e] = n);
  60461. var r = n[t];
  60462. if (!r) {
  60463. var o = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i);
  60464. r = new TileTree(TileUtils.TILE_SIZE, o),
  60465. n[t] = r;
  60466. }
  60467. }
  60468. getTileTree(e, t) {
  60469. var i = this.tileTrees[e];
  60470. if (!i)
  60471. console.error("PanoRenderer.getTileTree() -> Tree array not yet initialized!");
  60472. var n = i[t];
  60473. if (!n)
  60474. console.error("PanoRenderer.getTileTree() -> Tree not yet initialized!");
  60475. return n
  60476. }
  60477. /*
  60478. * 创建tile的renderTarget, 包括pano.tiledPanoRenderTarget和zoomRenderTarget
  60479. * @param {number} size 当前的panoSize,每个面的分辨率
  60480. */
  60481. initTiledPano(size, t) {//创建 RenderTargetCube
  60482. var renderer = this.viewer.renderer;
  60483. var renderTarget, texture;
  60484. renderTarget = new WebGLCubeRenderTarget(size,{ //THREE.WebGLRenderTargetCube(size, size, {
  60485. stencilBuffer: !1
  60486. });
  60487. texture = new CubeTexture([]);
  60488. texture.image = [null, null, null, null, null, null];
  60489. texture.flipY = !0,
  60490. texture.format = RGBAFormat;
  60491. t ? (texture.generateMipmaps = !0,
  60492. texture.magFilter = LinearFilter,
  60493. texture.minFilter = LinearMipMapLinearFilter)
  60494. : (texture.generateMipmaps = !1,
  60495. texture.magFilter = LinearFilter,
  60496. texture.minFilter = LinearFilter);
  60497. renderer.setRenderTarget(renderTarget);
  60498. renderer.setRenderTarget(null);
  60499. var o = renderer.properties.get(texture);
  60500. o.__image__webglTextureCube = o.__webglTexture;
  60501. //window.tex[r.id] = {texture:r, index:this.viewer.index }
  60502. return renderTarget
  60503. }
  60504. getUploadQueueForPano(e) {
  60505. var t = this.uploadQueues[e];
  60506. return t || (t = [],
  60507. this.uploadQueues[e] = t),
  60508. t
  60509. }
  60510. isTileUploaded(e) {
  60511. return this.isPanoZoomed(e.panoId) ? e.zoomUploaded : e.uploaded
  60512. }
  60513. setUploaded(e, t) {
  60514. this.isPanoZoomed(e.panoId) ? e.zoomUploaded = t : e.uploaded = t;
  60515. }
  60516. queueTileUpload(e, t, i) {
  60517. var n = this.getActiveRenderTargetDescriptor(e.panoId);
  60518. if (this.isRenderTargetDescriptorValid(n) && e.downloaded && !this.isTileUploaded(e) && (!e.uploadQueued || i)
  60519. && (!(e.panoSize > this.qualityManager.getMaxNavPanoSize())|| this.zoomingActive)) {
  60520. var r = this.getUploadQueueForPano(e.panoId);
  60521. if(i){
  60522. this.uploadTile(e, !1);//提交
  60523. }else {
  60524. if(this.shoulPushToFrontOfQueue(e)){//如果是512的优先
  60525. this.forceQueue.push(e);
  60526. }else {
  60527. if(t && this.direction){
  60528. TilePrioritizer.insertSortedPanoTile(r, e, n.pano, this.direction);
  60529. }else r.push(e);
  60530. }
  60531. e.uploadQueued = !0;
  60532. this.uploadInterval || this.uploadIntervalCancelled || this.refreshUploadInterval(0);
  60533. }
  60534. }
  60535. }
  60536. shoulPushToFrontOfQueue(e) {
  60537. return 0 === TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize)
  60538. }
  60539. getTopUploadQueue() {
  60540. for (var e = null, t = null, i = S.Base; i <= S.Remaining; i++)
  60541. for (var n = 0; n < this.activePanos.length; n++)
  60542. if (e = this.activePanos[n],
  60543. t = this.getUploadQueueForPano(e.id),
  60544. t.length > 0)
  60545. switch (i) {
  60546. case S.Base:
  60547. if (0 === t[0].level)
  60548. return t;
  60549. break;
  60550. case S.Remaining:
  60551. return t
  60552. }
  60553. return null
  60554. }
  60555. peekNextFromUploadQueue() {
  60556. if (this.forceQueue.length > 0)
  60557. return this.forceQueue[0];
  60558. var e = this.getTopUploadQueue();
  60559. return e && e.length > 0 ? e[0] : null
  60560. }
  60561. clearAllQueuedUploads() {
  60562. this.clearAllUploadQueues(null, 0);
  60563. }
  60564. clearAllQueuedUploadsForPano(e) {
  60565. this.clearAllUploadQueues(e, 0);
  60566. }
  60567. clearAllUploadQueues(e, t) {
  60568. if (e)
  60569. this.clearUploadQueue(this.getUploadQueueForPano(e), t),
  60570. this.clearUploadQueue(this.forceQueue, t, e);
  60571. else {
  60572. for (var i = 0; i < this.activePanos.length; i++) {
  60573. var n = this.activePanos[i];
  60574. this.clearUploadQueue(this.getUploadQueueForPano(n.id), t);
  60575. }
  60576. this.clearUploadQueue(this.forceQueue, t);
  60577. }
  60578. }
  60579. clearUploadQueue(e, t, i) {
  60580. void 0 !== t && null !== t || (t = 0);
  60581. for (var n = 0; n < e.length;) {
  60582. var r = e[n];
  60583. (!i || i && i === r.tile.panoId) && r.level >= t ? (r.uploadQueued = !1,
  60584. e.splice(n, 1)) : n++;
  60585. }
  60586. //若报错, r.tile.panoId改为 r.panoId
  60587. }
  60588. updateUploadQueue(maxNPF,maxPF/* e, t */) {//参数是 maxNonBaseUploadsPerFrame and maxBaseUploadsPerFrame, 优先上传512
  60589. maxNPF || (maxNPF = 1);
  60590. for (var i = 0, n = 0;;) {
  60591. let old = this.forceQueue.slice(0);
  60592. if (n >= maxPF || i >= maxNPF)
  60593. break;
  60594. var r = this.getNextFromUploadQueue();
  60595. if (!r)
  60596. break;
  60597. //r.panoSize <2048 && console.log('panoId', r.panoId, 'panoSize', r.panoSize , old)
  60598. 0 !== r.level ? i++ : n++;
  60599. if (!(r.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive) {
  60600. var o = this.getActiveRenderTargetDescriptor(r.panoId);
  60601. this.isRenderTargetDescriptorValid(o) && this.uploadTile(r, r.forceUpload);
  60602. }
  60603. }
  60604. }
  60605. updateDirection(e) {
  60606. if (e = e || this.direction) {
  60607. this.direction = e;
  60608. for (var t = 0; t < this.activePanos.length; t++) {
  60609. var i = this.activePanos[t],
  60610. n = this.getUploadQueueForPano(i.id);
  60611. TilePrioritizer.sortPanoTiles(n, i, this.direction);
  60612. }
  60613. }
  60614. }
  60615. anyUploaded(e) {
  60616. if (!e)
  60617. return !1;
  60618. if (e.tile && this.isTileUploaded(e.tile))
  60619. return !0;
  60620. if (e.children)
  60621. for (var t = 0; t < e.children.length; t++) {
  60622. var i = e.children[t];
  60623. if (this.anyUploaded(i))
  60624. return !0
  60625. }
  60626. return !1
  60627. }
  60628. setNodeCovered(e, t) {
  60629. this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered = t : e.covered = t;
  60630. }
  60631. isNodeCovered(e) {
  60632. return !!e && (this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered : e.covered)
  60633. }
  60634. addCoverageForNode(e) {
  60635. if (this.setNodeCovered(e, !0),
  60636. e.parent && e.covered) {
  60637. var t = e.parent;
  60638. this.nodeSubcovered(t) && this.addCoverageForNode(t, !0);
  60639. }
  60640. }
  60641. calcFullCoverage(e) {
  60642. var t = !1;
  60643. if (e.children)
  60644. for (var i = 0; i < e.children.length; i++) {
  60645. var n = e.children[i];
  60646. t = t || this.calcFullCoverage(n);
  60647. }
  60648. e.covered = e.tile.uploaded || t;
  60649. }
  60650. nodeSubcovered(e) {
  60651. if (!e.children)
  60652. return !1;
  60653. for (var t = 0; t < e.children.length; t++)
  60654. if (!e.children[t] || !this.isNodeCovered(e.children[t]))
  60655. return !1;
  60656. return !0
  60657. }
  60658. resetPanoDescriptor(e) {
  60659. this.getPanoDescriptor(e);
  60660. }
  60661. getPanoDescriptor(e) {
  60662. var t = this.panoDescriptors[e];
  60663. return t || (t = {},
  60664. this.panoDescriptors[e] = t),
  60665. t
  60666. }
  60667. resetPanoLODDescriptors(e) {
  60668. var t = this.getPanoLODDescriptors(e);
  60669. for (var i in t)
  60670. if (t.hasOwnProperty(i)) {
  60671. var n = t[i];
  60672. n.uploadCount = 0,
  60673. n.uploadAttempts = 0;
  60674. n.uploaded = [];
  60675. }
  60676. }
  60677. getPanoLODDescriptor(e, t) {
  60678. var i = this.getPanoLODDescriptors(e),
  60679. n = i[t];
  60680. return n || (n = {
  60681. uploadCount: 0,
  60682. uploadAttempts: 0,
  60683. uploaded:[],//add
  60684. },
  60685. i[t] = n),
  60686. n
  60687. }
  60688. getPanoLODDescriptors(e) {
  60689. var t = this.panoLODDescriptors[e];
  60690. return t || (t = {},
  60691. this.panoLODDescriptors[e] = t),
  60692. t
  60693. }
  60694. onTileDownloaded(o) {
  60695. var e = o.desc;
  60696. var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize),
  60697. i = this.getTileDirectoryEntry(e.panoId, e.face, t, e.faceTileIndex);
  60698. i.downloaded = !0;
  60699. i.image = e.image;
  60700. i.panoSize = e.panoSize;
  60701. i.tileX = e.tileX;
  60702. i.tileY = e.tileY;
  60703. i.totalTiles = e.totalTiles;
  60704. i.tileIndex = e.tileIndex;
  60705. i.faceTileIndex = e.faceTileIndex;
  60706. i.face = e.face;
  60707. i.cubeFace = TileUtils.mapFaceToCubemapFace(e.face);
  60708. i.panoId = e.panoId;
  60709. i.tileSize = e.tileSize;
  60710. i.direction = (new Vector3).copy(e.direction);
  60711. i.node = null;
  60712. i.level = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i.panoSize);
  60713. if (this.isPanoActive(i.panoId)) {
  60714. var n = this.getTileTree(i.panoId, i.face);
  60715. var r = n.getSubNode(i.panoSize, i.tileX, i.tileY);
  60716. this.linkTileAndNode(i, r);
  60717. this.queueTileUpload(i, !0);
  60718. }
  60719. }
  60720. getTileDirectoryEntry(panoId, t, i, n) {
  60721. var r = this.tileDirectory[panoId];
  60722. r || (r = {}, this.tileDirectory[panoId] = r);
  60723. var o = 16384 * t + 1024 * i + n, //t:4096级别
  60724. a = r[o];
  60725. return a || (a = {
  60726. downloaded: !1,
  60727. uploaded: !1,
  60728. zoomUploaded: !1
  60729. },
  60730. r[o] = a),
  60731. a._key = panoId + ":" + t + ":" + i + ":" + n,//panoId : face : level : faceTileIndex
  60732. a._tileKey = o,
  60733. a
  60734. }
  60735. setZoomingActive(active, pano, i) {//设置当前正在zoom的pano
  60736. this.zoomPanoRenderingDisabled || active === this.zoomingActive && this.zoomPanoId === pano.id || (this.zoomingActive = active,
  60737. this.zoomPanoId = pano.id,
  60738. this.zoomingActive && (this.zoomPanoId !== pano.id || i) && this.updateZoomedPanoFromBase(pano));
  60739. }
  60740. updateZoomedPanoFromBase(pano) {//因更换pano所以将pano的rendertarget渲染到panoRenderer的zoomRenderTarget上
  60741. if (!this.zoomPanoRenderingDisabled && this.zoomRenderTarget) {
  60742. var t = this.getActiveRenderTargetDescriptor(pano.id);
  60743. if (t && t.renderTarget ) {
  60744. var i = Math.min(this.qualityManager.maxRenderTargetSize, this.qualityManager.getMaxZoomPanoSize()), //change
  60745. n = t.renderTarget,
  60746. r = t.size;
  60747. this.copyCubeMap(n.texture, this.zoomRenderTarget, r, r, i, i),
  60748. this.copyBaseRenderStatusToZoomed(pano.id);
  60749. }
  60750. }
  60751. }
  60752. add(e) {
  60753. this.M.push(e);
  60754. }
  60755. initDescriptor(size) {
  60756. var t = createDescriptor();
  60757. t.inUse = !0;
  60758. t.size = size;
  60759. this.add(t);
  60760. return t
  60761. }
  60762. activeDescripor(e) {
  60763. for (var t = 0; t < this.M.length; t++) {
  60764. var i = this.M[t];
  60765. if (!i.inUse && i.size === e){
  60766. i.inUse = !0;
  60767. return i
  60768. }
  60769. }
  60770. return null
  60771. }
  60772. deactiveDescripor(e) {
  60773. for (var t = 0; t < this.M.length; t++) {
  60774. var i = this.M[t];
  60775. if (i.renderTarget === e){
  60776. i.inUse = !1;
  60777. return !0
  60778. }
  60779. }
  60780. return !1
  60781. }
  60782. enableHighQuality(e){//xzw add 如果最多只要2k图的话enableUltraHighQualityMode替换成这个
  60783. if (!this.qualityManager.highQualityModeStarted) {
  60784. this.setupZoomRenderTarget();
  60785. e();
  60786. //this.qualityManager.updateHighResolutionSettings(e)////////?
  60787. this.qualityManager.highQualityModeStarted = true;
  60788. }
  60789. }
  60790. linkTileAndNode(e, t) {
  60791. t.tile = e,
  60792. e.node = t;
  60793. }
  60794. linkAllTilesAndNodes(e) {
  60795. var t = function (t, i, n, r, o) {
  60796. var a = this.getTileDirectoryEntry(e.id, i, r, o);
  60797. this.linkTileAndNode(a, n);
  60798. };
  60799. for (var i = 0; i < TileUtils.FACES_PER_PANO; i++) {
  60800. var n = this.getTileTree(e.id, i);
  60801. n.breadthFirst({
  60802. callback: t.bind(this, n, i)
  60803. });
  60804. }
  60805. }
  60806. //--------------sceneRenderer
  60807. initSizedTexture2D(e, t, i) {
  60808. var renderer = this.viewer.renderer,
  60809. o = renderer.getContext(),
  60810. a = renderer.state,
  60811. s = new Texture(null);
  60812. s.flipY = !1,
  60813. i !== !0 && (i = !1),
  60814. s.generateMipmaps = i;
  60815. var l = renderer.paramThreeToGL(s.format),
  60816. c = renderer.paramThreeToGL(s.type),
  60817. h = renderer.properties.get(s),
  60818. u = o.createTexture();
  60819. a.bindTexture(o.TEXTURE_2D, u),
  60820. o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL, s.flipY),
  60821. o.texImage2D(o.TEXTURE_2D, 0, l, e, e, 0, l, c, null),
  60822. s.wrapS = t,
  60823. s.wrapT = t;
  60824. var d = renderer.paramThreeToGL(t);
  60825. return o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, d),
  60826. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, d),
  60827. i ? (s.magFilter = LinearFilter,
  60828. s.minFilter = LinearMipMapLinearFilter,
  60829. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  60830. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR_MIPMAP_NEAREST),
  60831. o.generateMipmap(o.TEXTURE_2D)) : (s.magFilter = LinearFilter,
  60832. s.minFilter = LinearFilter,
  60833. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  60834. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR)),
  60835. a.bindTexture(o.TEXTURE_2D, null),
  60836. h.__webglTexture = u,
  60837. s
  60838. }
  60839. deallocateCubeTexture(e) {
  60840. var t = this.viewer.renderer,
  60841. i = t.getContext(),
  60842. renderer = t.properties.get(e);
  60843. i.deleteTexture(renderer.__image__webglTextureCube);
  60844. }
  60845. uploadTexture2D(img, tex, startX, startY, width, height) {
  60846. var renderer = this.viewer.renderer,
  60847. gl = renderer.getContext(),
  60848. webglState = renderer.state,
  60849. c = renderer.properties.get(tex);
  60850. webglState.bindTexture(gl.TEXTURE_2D, c.__webglTexture),
  60851. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, tex.flipY),
  60852. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, tex.premultiplyAlpha),
  60853. gl.pixelStorei(gl.UNPACK_ALIGNMENT, tex.unpackAlignment),
  60854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, renderer.paramThreeToGL(tex.wrapS)),
  60855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, renderer.paramThreeToGL(tex.wrapT)),
  60856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, renderer.paramThreeToGL(tex.magFilter)),
  60857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, renderer.paramThreeToGL(tex.minFilter)),
  60858. gl.texSubImage2D(gl.TEXTURE_2D, 0, startX, startY, gl.RGBA, gl.UNSIGNED_BYTE, img),
  60859. tex.generateMipmaps && gl.generateMipmap(gl.TEXTURE_2D),
  60860. webglState.bindTexture(gl.TEXTURE_2D, null);
  60861. }
  60862. getCubeOrientationForCubeFace(e, t) {
  60863. switch (e) {
  60864. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  60865. t.set(0, -Math.PI / 2, 0);
  60866. break;
  60867. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  60868. t.set(0, Math.PI / 2, 0);
  60869. break;
  60870. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  60871. t.set(Math.PI / 2, Math.PI, 0);
  60872. break;
  60873. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  60874. t.set(-Math.PI / 2, Math.PI, 0);
  60875. break;
  60876. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  60877. t.set(0, -Math.PI, 0);
  60878. break;
  60879. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  60880. t.set(0, 0, 0);
  60881. }
  60882. }
  60883. }
  60884. PanoRenderer.prototype.setupZoomRenderTarget = function(){
  60885. var targets = {};
  60886. return function(){
  60887. if(this.qualityManager.maxRenderTargetSize == '2k' && this.qualityManager.getMaxNavPanoSize()=='2k')return; //不使用zoomTarget 直接用pano的tiledPanoRenderTarget,防崩溃
  60888. if (this.qualityManager.getMaxZoomPanoSize() >= this.qualityManager.getMaxNavPanoSize() /* && (config.tileClass != "2k" ||config.tileClass != "1k") */) {
  60889. //部分手机2k时copyCubeMap会重载 , 所以如果没有超出当前分辨率,就不使用zoomRenderTarget。但在微信依旧会重载,只是优化了些,safari几乎不会。
  60890. if (this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize())
  60891. return;
  60892. var e = this.zoomRenderTarget;
  60893. var size = this.qualityManager.getMaxZoomPanoSize();
  60894. if(size > this.qualityManager.maxRenderTargetSize){
  60895. return
  60896. }
  60897. if(targets[size]){
  60898. this.zoomRenderTarget = targets[size];
  60899. }else {
  60900. this.zoomRenderTarget = this.initTiledPano(size, !1);
  60901. targets[size] = this.zoomRenderTarget;
  60902. }
  60903. if (e) {//将旧的zoomRenderTarget渲染到新zoomRenderTarget上
  60904. var t = e.width,
  60905. i = this.zoomRenderTarget.width;
  60906. this.copyCubeMap(e.texture, this.zoomRenderTarget, t, t, i, i),
  60907. e.texture.dispose(),
  60908. e.texture.loaded = !1,
  60909. e.texture.version = 0,
  60910. this.deallocateCubeTexture(e.texture),
  60911. e.texture = null;
  60912. }
  60913. this.zoomPanoRenderingDisabled = !1;
  60914. } else
  60915. this.zoomPanoRenderingDisabled = !0;
  60916. }
  60917. }();
  60918. PanoRenderer.prototype.updateActivePanos = function () {
  60919. var e = [];
  60920. return function (t, i) {
  60921. e.length = 0;
  60922. for (var n = 0; n < this.activePanos.length; n++) {
  60923. t && e.length === i && e.push(t);
  60924. var r = this.activePanos[n],
  60925. o = this.getActiveRenderTargetDescriptor(r.id);
  60926. t && r.id === t.id || !this.isRenderTargetDescriptorValid(o) || e.push(r);
  60927. }
  60928. t && i >= e.length && e.push(t),
  60929. this.activePanos.length = 0,
  60930. this.activePanos.push.apply(this.activePanos, e);
  60931. }
  60932. }();
  60933. PanoRenderer.prototype.renderPanoTiles = function () {
  60934. var e = [];
  60935. return function (panoId, i, n, r) {
  60936. this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize() || this.zoomPanoRenderingDisabled || this.setupZoomRenderTarget(),//如果ZoomRenderTarget大小需要变动就重新创建
  60937. i = i || this.direction || Vectors.FORWARD; // [{1:Vectors.FORWARD}]?
  60938. var o = this.getActiveRenderTargetDescriptor(panoId);
  60939. if (!this.isRenderTargetDescriptorValid(o))
  60940. console.error("PanoRenderer.renderPanoTiles() -> Cannot render to a pano that is not activated.");
  60941. for (var a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  60942. var s = this.getTileTree(panoId, a);
  60943. e.length = 0;
  60944. s.breadthFirst({//获取所有node? 85个
  60945. saveVisited: e
  60946. });
  60947. for (var l = 0; l < e.length; l++) {
  60948. var c = e[l];
  60949. this.queueTileUpload(c.tile, !1, r || 0 === l && n);//为什么第0个会直接uploadTile??
  60950. }
  60951. }
  60952. this.updateDirection(i);
  60953. }
  60954. }();
  60955. PanoRenderer.prototype.getNextFromUploadQueue = function () {
  60956. var e = function (e) {
  60957. var t = e.shift();
  60958. return t.uploadQueued = !1,
  60959. t
  60960. };
  60961. return function () {
  60962. if (this.forceQueue.length > 0)
  60963. return e(this.forceQueue);
  60964. var t = this.getTopUploadQueue();
  60965. return t && t.length > 0 ? e(t) : null
  60966. }
  60967. }();
  60968. PanoRenderer.prototype.refreshUploadInterval = function () {
  60969. var e = null;
  60970. return function (t) {
  60971. this.uploadIntervalCancelled || (e || (e = c$1.bind(this)),
  60972. null !== t && void 0 !== t || (t = w),
  60973. b || (t = _),
  60974. this.uploadInterval = window.setTimeout(e, t),
  60975. this.uploadIntervalDelay = t);
  60976. }
  60977. }();
  60978. PanoRenderer.prototype.update = function () {
  60979. var e = performance.now(),
  60980. t = 0;
  60981. return function () {
  60982. this.uploadIntervalCancelled = !0;
  60983. window.clearTimeout(this.uploadInterval);
  60984. this.uploadInterval = null;
  60985. var i = performance.now() - e;
  60986. //!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay || (this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  60987. //e = performance.now()),
  60988. if (!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay) {} else {
  60989. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame);
  60990. e = performance.now();
  60991. }
  60992. t++;
  60993. }
  60994. }();
  60995. PanoRenderer.prototype.uploadTile = function () {//重写
  60996. var collection = {},
  60997. overlayStyle = config$1.tiling.overlayStyle;
  60998. var failHistory = {};
  60999. return function (info, n) {
  61000. var id = info.panoId,
  61001. img = info.image,
  61002. tileSize = info.tileSize,
  61003. panoSize = info.panoSize,
  61004. tileIndex = info.tileIndex,
  61005. totalTiles = info.totalTiles,
  61006. tileX = info.tileX,
  61007. tileY = info.tileY,
  61008. p = !0,
  61009. g = !1,
  61010. ignore = false, //add
  61011. LodDescripor = (this.getPanoDescriptor(id), this.getPanoLODDescriptor(id, panoSize)),
  61012. activeDescripor = this.getActiveRenderTargetDescriptor(id),
  61013. renderTarget = activeDescripor.renderTarget,
  61014. size = activeDescripor.size;//当前要渲染的面的分辨率,也就是MaxNavPanoSize
  61015. if (this.isPanoZoomed(id) && this.zoomRenderTarget) {
  61016. renderTarget = this.zoomRenderTarget;
  61017. size = this.zoomRenderTarget.width; //this.qualityManager.getMaxZoomPanoSize(); //放大后可能2048或4096
  61018. }
  61019. let done = ()=>{
  61020. if(!LodDescripor.uploaded.includes(tileIndex)){//已经upload过(本来这时候直接返回,但发现缩放后这不会归零,导致清晰度不更新,所以还是redraw且emit吧)
  61021. //console.log('try to reupload and return',tileIndex)
  61022. LodDescripor.uploaded.push(tileIndex);
  61023. LodDescripor.uploadCount++;
  61024. }
  61025. this.dispatchEvent({type:PanoRendererEvents.TileRenderSuccess, id, panoSize, tileIndex, totalTiles});
  61026. LodDescripor.uploadCount === totalTiles && this.dispatchEvent({type:PanoRendererEvents.PanoRenderComplete, id, panoSize, totalTiles, updateFullComplete:true});
  61027. this.setUploaded(info, !0);
  61028. this.addCoverageForNode(info.node);
  61029. };
  61030. {//已经uploadTile过了不再uploadTile
  61031. if(!this.isRenderTargetDescriptorValid(activeDescripor)){
  61032. p = !1; g = !1;
  61033. }
  61034. if(!n){
  61035. this.anyUploaded(info.node) && (p = !1, g = !0,ignore = true ); //包括子集也uploadTile了
  61036. this.isTileUploaded(info) && (p = !1, g = !1,ignore = true ); //当前tile uploadTile了
  61037. }
  61038. }
  61039. if (p) {
  61040. /*if(failHistory[id+':'+ panoSize+ ':' +tileIndex]){
  61041. console.log('uploadTile retry',id, panoSize, tileIndex)
  61042. }
  61043. console.log('uploadTile 成功', id, panoSize, tileIndex) */
  61044. var C = tileX * tileSize,
  61045. I = tileY * tileSize,
  61046. E = tileSize / panoSize * size, // tile在renderTarget上渲染出的宽度
  61047. b = C / panoSize * size, // tile在renderTarget上渲染的startX
  61048. w = I / panoSize * size; // tile在renderTarget上渲染的startY
  61049. collection[tileSize] || (collection[tileSize] = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping));
  61050. if(panoSize > this.qualityManager.maxRenderTargetSize ){ //4096 改
  61051. var tex = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping);
  61052. var loaded = this.viewer.images360.isHighMapLoaded(info.cubeFace, tileX,tileY);
  61053. }else {
  61054. var tex = collection[tileSize];
  61055. }
  61056. this.uploadTexture2D(img, tex, 0, 0, tileSize, tileSize);//只替换tex对应的img,不新建
  61057. if(panoSize > this.qualityManager.maxRenderTargetSize){
  61058. loaded || this.viewer.images360.updateHighMap(tex, info.cubeFace, tileX,tileY);
  61059. }else {
  61060. if (1 === overlayStyle || 2 === overlayStyle) {
  61061. var T = 1 === overlayStyle ? this.overlayTilesBasic : this.overlayTilesEnhanced;
  61062. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  61063. this.renderToCubeMap(T[panoSize], renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace, NormalBlending, !0, .5);
  61064. } else {
  61065. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  61066. }
  61067. }
  61068. done();
  61069. }else if(ignore){
  61070. //console.log('finish because anyUploaded',id,panoSize,tileIndex)
  61071. done(); //改: 如果因为这部分更高清的贴图已加载所以才不绘制的话,直接完成
  61072. }else {
  61073. //console.log('uploadTile 失败', id, panoSize, tileIndex)
  61074. if(panoSize == 512){
  61075. //console.log("!!!!!!!!!!!!!")
  61076. }
  61077. failHistory[id+':'+ panoSize+ ':' +tileIndex] = true;
  61078. this.setUploaded(info, !1);
  61079. }
  61080. info.uploadAttempted || (LodDescripor.uploadAttempts++, this.dispatchEvent({type:PanoRendererEvents.TileUploadAttempted, id, panoSize, tileIndex, totalTiles})),
  61081. info.uploadAttempted = !0;
  61082. LodDescripor.uploadAttempts === totalTiles && this.dispatchEvent({type:PanoRendererEvents.UploadAttemptedForAllTiles, id, panoSize, totalTiles});
  61083. return g;
  61084. }
  61085. }();
  61086. /*
  61087. 注:tileY的方向同UV,从下到上
  61088. renderToCubeMap里的画布or镜头的xy范围是-0.5到0.5
  61089. */
  61090. PanoRenderer.prototype.renderToCubeMap = function() {
  61091. var inited = !1,
  61092. scene = null,
  61093. camera = null,
  61094. material = null,
  61095. geo = null,
  61096. plane = null,
  61097. l = 1;
  61098. return function(texture, renderTarget, tileWidth, tileHeight, startXinTile, startYinTile, widthinTile, heightinTile, startX, startY, width, height, cubeFace, E, b, w) {
  61099. var renderer = this.viewer.renderer;
  61100. inited || (camera = new OrthographicCamera(l / -2, l / 2, l / 2, l / -2, -200, 200),
  61101. camera.position.z = 150,
  61102. scene = new Scene,
  61103. scene.add(camera),
  61104. material = new ShaderMaterial({
  61105. uniforms: {
  61106. tDiffuse: {
  61107. type: "scene",
  61108. value: null
  61109. },
  61110. alpha: {
  61111. type: "startYinTile",
  61112. value: 1
  61113. }
  61114. },
  61115. vertexShader: Shaders['basicTextured.vs'],
  61116. fragmentShader: Shaders['basicTextured.fs'],
  61117. depthWrite: !1,
  61118. depthTest: !1,
  61119. side: DoubleSide
  61120. }),
  61121. geo = new PlaneBufferGeometry(l, l),
  61122. plane = new Mesh(geo, material),
  61123. plane.position.z = 0,
  61124. scene.add(plane),
  61125. inited = !0);
  61126. var uv = geo.getAttribute("uv");
  61127. uv.setDynamic(!0), //setUsage
  61128. uv.needsUpdate = !0;
  61129. var uvArr = uv.array,
  61130. S = startXinTile / tileWidth, //uv这几个值基本是固定的startXinTile:0,startYinTile:0,widthinTile:512,widthinTile:512,tileWidth:512,tileHeight:512 也就是说uv不会变、每张tile的有效范围是100%
  61131. M = startYinTile / tileHeight,
  61132. R = widthinTile / tileWidth,
  61133. P = heightinTile / tileHeight;
  61134. uvArr[0] = S,
  61135. uvArr[1] = M + P,
  61136. uvArr[2] = S + R,
  61137. uvArr[3] = M + P,
  61138. uvArr[4] = S,
  61139. uvArr[5] = M,
  61140. uvArr[6] = S + R,
  61141. uvArr[7] = M;
  61142. //修改posistion,使该plane只占据需要绘制的部分。类似拼图。
  61143. //startX startY width height 都是在画布上的大小,比如画布大小为2048*2048,此tile为16分之一,tileX是1,tileY是1,则startX=2048/4,startY=2048/4
  61144. var pos = geo.getAttribute("position");
  61145. pos.setDynamic(!0),
  61146. pos.needsUpdate = !0;
  61147. var posArr = pos.array,
  61148. D = startX / renderTarget.width - l / 2 // 起始x
  61149. ,
  61150. N = startY / renderTarget.height - l / 2 // 起始y
  61151. ,
  61152. B = width / renderTarget.width // 宽
  61153. ,
  61154. F = height / renderTarget.height; // 高
  61155. posArr[0] = D,
  61156. posArr[1] = N + F,
  61157. posArr[3] = D + B,
  61158. posArr[4] = N + F,
  61159. posArr[6] = D,
  61160. posArr[7] = N,
  61161. posArr[9] = D + B,
  61162. posArr[10] = N;
  61163. renderer.properties.get(scene);
  61164. material.uniforms.tDiffuse.value = texture;
  61165. material.blending = E || NoBlending,
  61166. material.transparent = !!b;
  61167. void 0 !== w && null !== w || (w = 1),
  61168. material.uniforms.alpha.value = w,
  61169. material.needUpdate = !0;
  61170. //renderTarget.activeCubeFace = cubeFace, //0-5 应该是指定渲染h中的面 失效
  61171. /* renderer.setScissorTest(!0)
  61172. //指定绘制区域,类似遮罩(相对于屏幕)
  61173. renderer.setScissor(startX,startY,width,height) //加上这个会不会快一些,尤其是spherical
  61174. //指定绘制视口位置和大小(相对于屏幕)
  61175. */
  61176. renderTarget.viewport.set(0, 0, renderTarget.width, renderTarget.height);
  61177. var V = renderer.autoClear;
  61178. var oldTarget = renderer.getRenderTarget();
  61179. renderer.autoClear = !1;
  61180. renderer.setRenderTarget(renderTarget, cubeFace);
  61181. renderer.render(scene, camera/* , renderTarget, !1 */);
  61182. renderer.setRenderTarget(oldTarget);
  61183. renderer.autoClear = V;
  61184. //renderer.setScissorTest(!1)
  61185. /* this.renderer.render(scene, camera, this.planeTargets[cubeFace], !1),//针对有的场景app第一个点图加载不成功的问题
  61186. console.log(`图index ${cubeFace} , ${startX}, ${startY}, ${width}, ${height}`)
  61187. this.targetList[cubeFace] || (this.targetList[cubeFace] = [])
  61188. this.targetList[cubeFace].push([startX,startY,width,height])*/
  61189. }
  61190. }();
  61191. /*
  61192. * 将texture渲染到zoomRenderTarget上(目的是复制贴图到zoomRenderTarget)
  61193. */
  61194. PanoRenderer.prototype.copyCubeMap = function() {//将texture渲染到zoomRenderTarget上
  61195. var inited = !1,
  61196. scene = null,
  61197. camera = null,
  61198. material = null,
  61199. geo = null,
  61200. mesh = null,
  61201. testCube = null, //add
  61202. c = new Euler;
  61203. return function(texture, renderTarget, tWidth, tHeight, rWidth, rHeight, m, v, A) {
  61204. if(rWidth > this.qualityManager.maxRenderTargetSize) return; //add
  61205. if (!inited) {
  61206. var w = 2;
  61207. camera = new OrthographicCamera(w / -2, w / 2, w / 2, w / -2, 0, 200),
  61208. camera.position.set(0, 0, 0),
  61209. scene = new Scene,
  61210. scene.add(camera);
  61211. material = new ShaderMaterial({
  61212. uniforms: {
  61213. tDiffuse: {
  61214. type: "t",
  61215. value: null
  61216. },
  61217. alpha: {
  61218. type: "f",
  61219. value: 1
  61220. }
  61221. },
  61222. vertexShader: Shaders['copyCubeMap.vs'],
  61223. fragmentShader:Shaders['copyCubeMap.fs'],
  61224. depthWrite: !1,
  61225. depthTest: !1,
  61226. side: DoubleSide
  61227. });
  61228. geo = new BoxGeometry(w, w, w),
  61229. mesh = new Mesh(geo, material),
  61230. scene.add(mesh);
  61231. inited = !0;
  61232. /* testCube = mesh.clone();
  61233. viewer.scene.scene.add(testCube);
  61234. viewer.setObjectLayers(testCube, 'sceneObjects')
  61235. */
  61236. }
  61237. let autoClear = this.viewer.renderer.autoClear;
  61238. let oldTarget = this.viewer.renderer.getRenderTarget();
  61239. this.viewer.renderer.autoClear = false;
  61240. material.uniforms.tDiffuse.value = texture;
  61241. material.blending = m || NoBlending;
  61242. material.transparent = !!v;
  61243. void 0 !== A && null !== A || (A = 1);
  61244. material.uniforms.alpha.value = A;
  61245. material.needUpdate = !0;
  61246. for (var C = 0; C < 6; C++){
  61247. this.getCubeOrientationForCubeFace(C, c);
  61248. mesh.rotation.copy(c);
  61249. mesh.matrixWorldNeedsUpdate = !0;
  61250. mesh.updateMatrixWorld();
  61251. renderTarget.viewport.set(0, 0, rWidth, rHeight);
  61252. this.viewer.renderer.setRenderTarget(renderTarget, C ); //renderTarget.activeCubeFace = C//失效
  61253. this.viewer.renderer.render(scene, camera);
  61254. }
  61255. //console.warn('copyCubeMap' + rWidth)
  61256. this.viewer.renderer.autoClear = autoClear;
  61257. this.viewer.renderer.setRenderTarget(oldTarget);
  61258. }
  61259. }();
  61260. class DepthImageSampler {
  61261. constructor(){
  61262. var canvas = document.createElement("canvas");
  61263. this.canvas = canvas;
  61264. this.context = canvas.getContext("2d");
  61265. /* document.getElementsByTagName('body')[0].appendChild(canvas);
  61266. canvas.style.position = 'fixed';
  61267. canvas.style.width = '1024px';
  61268. canvas.style.top = canvas.style.left = 0
  61269. canvas.style['z-index'] = 100
  61270. */
  61271. }
  61272. changeImg(img){
  61273. if(this.img == img)return
  61274. this.canvas.width = img.width;
  61275. this.canvas.height = img.height;
  61276. this.context.drawImage(img, 0, 0);
  61277. this.img = img;
  61278. }
  61279. getDepth(UVx, UVy) {//根据图片像素获取深度值
  61280. var x = Math.round(UVx * (this.canvas.width - 1))
  61281. , y = Math.round(UVy * (this.canvas.height - 1));
  61282. if (!(x < 0 || y < 0 || x >= this.width || y >= this.height)) {
  61283. var r = this.context.getImageData(x, y, 1, 1).data;
  61284. //console.log('color', r, x,y)
  61285. return r[1] + r[0] / 256
  61286. }
  61287. }
  61288. sample( intersect, currentPano, onlyPos ) {//通过和skybox的intersect得到真实的intersect的位置
  61289. if(!intersect)return
  61290. let location = new THREE.Vector3;
  61291. let normal;
  61292. currentPano = currentPano || viewer.images360.currentPano;
  61293. if(currentPano != this.currentPano){
  61294. if(!currentPano.depthTex/* || !currentPano.depthTex.image */) return //未加载
  61295. this.changeImg(currentPano.depthTex.image);
  61296. this.currentPano = currentPano;
  61297. }
  61298. let origin = currentPano.position;
  61299. let dir = intersect.dir || new THREE.Vector3().subVectors(intersect.point, origin).normalize();
  61300. //var uv = intersect.uv
  61301. //let dirInPano = math.getNormalDir(dir, currentPano)//转化为考虑漫游点旋转的方向
  61302. let dirInPano = dir.clone().applyMatrix4(currentPano.panoMatrix2Inverse).normalize(); //转化为考虑漫游点旋转的方向
  61303. let uv = math.getUVfromDir(dirInPano);//转化为uv
  61304. let distance = this.getDepth(uv.x, uv.y);
  61305. //console.log('depth', depth, uv.y)
  61306. if (!distance){
  61307. if(uv.y > 0.75){//漫游点底部识别不到的区域,给一个地板高度
  61308. //let height = origin.distanceTo(currentPano.floorPosition);
  61309. const margin = 0.1;
  61310. distance = (currentPano.floorPosition.z - origin.z - margin) / dir.z;
  61311. location.copy(dir).multiplyScalar(distance).add(origin);
  61312. let normal = new THREE.Vector3(0,0,1);
  61313. return {location, normal, distance}
  61314. }
  61315. else return !1; //应该是天空或模型外 , 因为很少有漫游点的地方还拍不到地板
  61316. }
  61317. //this.mainDepth = depth
  61318. location.copy(dir).multiplyScalar(distance).add(origin);
  61319. if(!onlyPos){
  61320. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  61321. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  61322. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  61323. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  61324. normal = this.planeFit(dir,location, pL,pR,pB,pT );
  61325. }
  61326. /* if(normal.x != normal.x ){
  61327. console.log('NAN', normal)
  61328. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  61329. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  61330. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  61331. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  61332. } */
  61333. //console.log('normal',normal)
  61334. return {location, normal, distance}
  61335. }
  61336. getNearbyPoint( origin, uv, x, y) { //获取附近的若干像素距离的点
  61337. let uv2 = uv.clone();
  61338. uv2.x += x/(this.canvas.width-1);
  61339. uv2.x = this.clampUV(uv2.x);
  61340. uv2.y += y/(this.canvas.height-1);
  61341. uv2.y = this.clampUV(uv2.y);
  61342. /* if(uv2.x < 0 || uv2.y < 0 || uv2.x > 1 || uv2.y > 1){
  61343. console.log('will nan')
  61344. } */
  61345. let dir = math.getDirFromUV(uv2);//从uv获取到方向
  61346. dir.applyMatrix4(viewer.images360.currentPano.panoMatrix2);
  61347. let depth = this.getDepth(uv2.x, uv2.y);
  61348. /* if(Math.abs(depth - this.mainDepth) > 0.3){
  61349. console.log('Math.abs(depth - this.mainDepth) > 0.3')
  61350. } */
  61351. //let dir = new THREE.Vector3().subVectors(intersect.point, origin).normalize()
  61352. let position = new THREE.Vector3().copy(dir).multiplyScalar(depth).add(origin);
  61353. //console.log('getNearbyPoint', uv2, depth, dir, position )
  61354. return position
  61355. }
  61356. clampUV(v){
  61357. return (v + 1) % 1; // 使输出在 0-1
  61358. }
  61359. planeFit(dir, position, pL,pR,pB,pT ) {//求平均法线
  61360. let normal = new THREE.Vector3;
  61361. let plane = new THREE.Plane;
  61362. function addNormal(p1, p2) {//根据临接的四个点,分别求法线,然后法线相加能得到平均法线
  61363. if(!p1 || !p2)return
  61364. plane.setFromCoplanarPoints(position, p1, p2);
  61365. //console.log('normalSub', plane.normal)
  61366. normal.addScaledVector(plane.normal, dir.dot(plane.normal) < 0 ? 1 : -1);//根据面的朝向判断加还是减
  61367. }
  61368. addNormal(pL, pB);
  61369. addNormal(pL, pT);
  61370. addNormal(pR, pB);
  61371. addNormal(pR, pT);
  61372. if(0 !== normal.x || 0 !== normal.y || 0 !== normal.z){
  61373. normal.normalize();
  61374. //console.log(normal)
  61375. return normal
  61376. }
  61377. /* 四个面拼成一个菱形 */
  61378. }
  61379. /* makeUvToPosMap(intersect, matrix1, vec1, vec2) {
  61380. var o = intersect.object.geometry
  61381. , a = o.attributes.position.array
  61382. , 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)
  61383. , 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)
  61384. , 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);
  61385. vec1.subVectors(s, c),
  61386. vec2.subVectors(l, c);
  61387. var u = o.attributes.uv.array
  61388. , d = new THREE.Vector2(u[2 * intersect.face.a],u[2 * intersect.face.a + 1])
  61389. , p = new THREE.Vector2(u[2 * intersect.face.b],u[2 * intersect.face.b + 1])
  61390. , h = new THREE.Vector2(u[2 * intersect.face.c],u[2 * intersect.face.c + 1])
  61391. , f = d.sub(p)
  61392. , g = h.sub(p);
  61393. matrix1.set(f.x, g.x, 0, f.y, g.y, 0, 0, 0, 1),
  61394. matrix1.getInverse(matrix1)
  61395. } */
  61396. /* getNearbyPoint( point, origin, uv, o, a, s, x, y) {
  61397. var add = new THREE.Vector3(x, y , 0 )
  61398. , depth = this.getDepth(uv.x + add.x, uv.y + add.y );
  61399. if (void 0 !== depth) {
  61400. var f = add.applyMatrix3(o);
  61401. return (new THREE.Vector3).addScaledVector(a, f.x).addScaledVector(s, f.y).add(point).sub(origin).normalize().multiplyScalar(depth).add(origin)
  61402. }
  61403. } */
  61404. }
  61405. /* var i = n(4)
  61406. , r = function() {
  61407. function t(t) {
  61408. }
  61409. return t.prototype.getDepth = function(t, e) {
  61410. var n = Math.round(t)
  61411. , i = Math.round(e);
  61412. if (!(n < 0 || i < 0 || n >= this.width || i >= this.height)) {
  61413. var r = this.context.getImageData(n, i, 1, 1).data;
  61414. return r[1] + r[0] / 256
  61415. }
  61416. }
  61417. ,
  61418. Object.defineProperty(t.prototype, "width", {
  61419. get: function() {
  61420. return this.context.canvas.width
  61421. },
  61422. enumerable: !0,
  61423. configurable: !0
  61424. }),
  61425. Object.defineProperty(t.prototype, "height", {
  61426. get: function() {
  61427. return this.context.canvas.height
  61428. },
  61429. enumerable: !0,
  61430. configurable: !0
  61431. }),
  61432. t
  61433. }();
  61434. e.CanvasDepthImage = r;
  61435. var o = function() {
  61436. function t() {}
  61437. return t.sample = function(e, n, r, o, a) {
  61438. var s = n.uv
  61439. , c = s.x * (e.width - 1)
  61440. , l = (1 - s.y) * (e.height - 1)
  61441. , u = e.getDepth(c, l);
  61442. if (!u)
  61443. return !1;
  61444. o.copy(n.point).sub(r).normalize().multiplyScalar(u).add(r);
  61445. var d = new i.Matrix3
  61446. , p = new i.Vector3
  61447. , h = new i.Vector3;
  61448. t.makeUvToPosMap(n, d, p, h);
  61449. var f = this.getNearbyPoint(e, n.point, r, s, d, p, h, -1, 0)
  61450. , g = this.getNearbyPoint(e, n.point, r, s, d, p, h, 1, 0)
  61451. , m = this.getNearbyPoint(e, n.point, r, s, d, p, h, 0, -1)
  61452. , v = this.getNearbyPoint(e, n.point, r, s, d, p, h, 0, 1);
  61453. return this.planeFit(o, r, f, g, m, v, a)
  61454. }
  61455. ,
  61456. t.makeUvToPosMap = function(t, e, n, r) {
  61457. var o = t.object.geometry
  61458. , a = o.attributes.position.array
  61459. , 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)
  61460. , 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)
  61461. , 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);
  61462. n.subVectors(s, c),
  61463. r.subVectors(l, c);
  61464. var u = o.attributes.uv.array
  61465. , d = new i.Vector2(u[2 * t.face.a],u[2 * t.face.a + 1])
  61466. , p = new i.Vector2(u[2 * t.face.b],u[2 * t.face.b + 1])
  61467. , h = new i.Vector2(u[2 * t.face.c],u[2 * t.face.c + 1])
  61468. , f = d.sub(p)
  61469. , g = h.sub(p);
  61470. e.set(f.x, g.x, 0, f.y, g.y, 0, 0, 0, 1),
  61471. e.getInverse(e)
  61472. }
  61473. ,
  61474. t.getNearbyPoint = function(t, e, n, r, o, a, s, c, l) {
  61475. var u = new i.Vector3(c / (t.width - 1),l / (t.height - 1))
  61476. , d = (r.x + u.x) * (t.width - 1)
  61477. , p = (1 - (r.y + u.y)) * (t.height - 1)
  61478. , h = t.getDepth(d, p);
  61479. if (void 0 !== h) {
  61480. var f = u.applyMatrix3(o);
  61481. return (new i.Vector3).addScaledVector(a, f.x).addScaledVector(s, f.y).add(e).sub(n).normalize().multiplyScalar(h).add(n)
  61482. }
  61483. }
  61484. ,
  61485. t.planeFit = function(t, e, n, r, o, a, s) {
  61486. s.set(0, 0, 0);
  61487. var c = t.clone().sub(e)
  61488. , l = new i.Plane;
  61489. function u(e, n) {
  61490. e && n && (l.setFromCoplanarPoints(t, e, n),
  61491. s.addScaledVector(l.normal, c.dot(l.normal) < 0 ? 1 : -1))
  61492. }
  61493. return u(n, o),
  61494. u(n, a),
  61495. u(r, o),
  61496. u(r, a),
  61497. (0 !== s.x || 0 !== s.y || 0 !== s.z) && (s.normalize(),
  61498. !0)
  61499. }
  61500. ,
  61501. t
  61502. }();
  61503. */
  61504. var rot90$1 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  61505. let raycaster = new Raycaster();
  61506. //let currentlyHovered = null;
  61507. let texLoader$3 = new TextureLoader();
  61508. let sm$1 = new MeshBasicMaterial({side: BackSide});
  61509. let tileArr = [];
  61510. let previousView = {
  61511. controls: null,
  61512. position: null,
  61513. target: null,
  61514. };
  61515. const HighMapCubeWidth = 1;
  61516. const directionFactor = 200; //原先10,几乎只往距离近的走了;设置太大楼梯上不去
  61517. class Images360 extends EventDispatcher{
  61518. constructor(viewer ){
  61519. super();
  61520. this.viewer = viewer;
  61521. this.selectingEnabled = true;
  61522. this.panos = [];
  61523. this.neighbourMap = {};
  61524. this.node = new Object3D();
  61525. this.node.name = 'ImagesNode';
  61526. //this.node2 = new THREE.Object3D();
  61527. this.cubePanos = [];
  61528. this.cube = new Mesh(new BoxBufferGeometry(1,1,1,1),new ModelTextureMaterial());
  61529. viewer.updateVisible(this.cube,'showSkybox', false );
  61530. this.cube.layers.set(Potree.config.renderLayers.skybox);
  61531. this.cube.name = 'skyboxCube';
  61532. viewer.scene.scene.add(this.cube);
  61533. this._visible = true;
  61534. this.currentPano = null;
  61535. this.mouseLastMoveTime = Date.now();
  61536. this.scrollZoomSpeed = 0.06;
  61537. this.zoomLevel = 1;
  61538. this.tileDownloader = new TileDownloader;
  61539. this.qualityManager = new QualityManager;
  61540. this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager);
  61541. this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE);
  61542. this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD);
  61543. this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.HIGH);
  61544. this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
  61545. this.tileDownloader.processPriorityQueue = !1;
  61546. this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize);
  61547. this.flying_ = false;
  61548. {//高分辨率cube 放大
  61549. this.addHighMapCube();
  61550. viewer.addEventListener(PanoramaEvents.Enter,(e)=>{
  61551. this.setHighMap(e.newPano);
  61552. });
  61553. viewer.addEventListener('panoSetZoom',(e)=>{
  61554. if(Potree.settings.displayMode == 'showPanos'){
  61555. e.zoomed ? this.showHighMap() : this.hideHighMap(); //add
  61556. }
  61557. });
  61558. }
  61559. this.depthSampler = new DepthImageSampler();
  61560. this.addEventListener('loadedDepthImg',(e)=>{
  61561. e.loaded && this.updateDepthTex(e.pano);
  61562. });
  61563. let scroll = (e)=>{
  61564. if(e.hoverViewport != viewer.mainViewport)return
  61565. /* if(Potree.settings.displayMode == 'showPanos' && Potree.settings.zoom.enabled){
  61566. } */
  61567. };
  61568. viewer.fpControls.addEventListener('dollyStopCauseUnable',(e)=>{
  61569. if(/* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled)return
  61570. if(e.scale != void 0){//触屏
  61571. this.zoomBy(e.scale, e.pointer);
  61572. }else {//滚轮
  61573. let zoom;
  61574. if(e.delta > 0){
  61575. zoom = 1 + this.scrollZoomSpeed;
  61576. }else {
  61577. zoom = 1 - this.scrollZoomSpeed;
  61578. }
  61579. e.delta != 0 && this.zoomBy(zoom);
  61580. }
  61581. });
  61582. let click = (e) => {//不用"mouseup" 是因为 mouseup有drag object时也会触发
  61583. if(e.clickElement ||
  61584. Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算
  61585. || Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView'
  61586. || Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance
  61587. ) return
  61588. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  61589. if( e.hoverViewport == viewer.mapViewer.viewports[0]){
  61590. return viewer.mapViewer.dispatchEvent(e/* {type:'global_click',e } */)
  61591. }else if(e.hoverViewport != viewer.mainViewport){ //如数据集校准其他viewport
  61592. return
  61593. }
  61594. }
  61595. /* if(currentlyHovered && currentlyHovered.pano){
  61596. this.focusPano(currentlyHovered.pano);
  61597. }else{//add */
  61598. if(!Potree.settings.dblToFocusPoint/* && this.currentPano */){//双击不会focus点云 或者 已经focusPano了
  61599. this.flyToPanoClosestToMouse();
  61600. }
  61601. //}
  61602. };
  61603. viewer.addEventListener('global_click' , click);
  61604. viewer.addEventListener("global_mousemove", (e) => {
  61605. if(!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport){//如果不显示marker,就在点击时再更新
  61606. this.updateClosestPano(e.intersect);
  61607. }
  61608. });
  61609. this.addEventListener('markerHover',(e)=>{
  61610. this.updateClosestPano(e.pano, e.hovered);
  61611. });
  61612. if(!Potree.settings.isOfficial){
  61613. this.domRoot = viewer.renderer.domElement.parentElement;
  61614. let elUnfocus = $("<input type='button' value='unfocus'></input>");
  61615. elUnfocus.css({
  61616. position : "absolute",
  61617. right : '25%',
  61618. bottom: '20px',
  61619. zIndex: "10000",
  61620. fontSize:'1em', color:"black",
  61621. display:'none',
  61622. background:'rgba(255,255,255,0.8)',
  61623. });
  61624. elUnfocus.on("click", () => this.unfocus());
  61625. this.elUnfocus = elUnfocus;
  61626. this.domRoot.appendChild(elUnfocus[0]);
  61627. if(Potree.settings.editType != 'merge'){
  61628. let elHide = $("<input type='button' value='隐藏点云'></input>");
  61629. elHide.css({
  61630. position : "absolute",
  61631. right : '40%',
  61632. bottom: '20px',
  61633. zIndex: "10000",
  61634. fontSize:'1em' ,color:"black",
  61635. width : '100px',
  61636. background:'rgba(255,255,255,0.8)',
  61637. });
  61638. this.domRoot.appendChild(elHide[0]);
  61639. elHide.on("click", (e) => {
  61640. let visi = viewer.getObjVisiByReason(viewer.scene.pointclouds[0], 'force');
  61641. viewer.scene.pointclouds.forEach(e=>{
  61642. viewer.updateVisible(e, 'force', !visi);
  61643. });
  61644. elHide.val(!visi ? "隐藏点云" : "显示点云");
  61645. });
  61646. }
  61647. let elDisplayModel = $("<input type='button' value='>>全景'></input>");
  61648. elDisplayModel.css({
  61649. position : "absolute",
  61650. right : '65%',
  61651. bottom: '20px',
  61652. zIndex: "10000",
  61653. fontSize:'1em',color:"black",
  61654. width : '100px',
  61655. background:'rgba(255,255,255,0.8)',
  61656. });
  61657. this.domRoot.appendChild(elDisplayModel[0]);
  61658. elDisplayModel.on("click", (e) => {
  61659. if(Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0)return
  61660. Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud';
  61661. });
  61662. this.elDisplayModel = elDisplayModel;
  61663. }
  61664. {//切换模式
  61665. let displayMode = '';
  61666. let latestRequestMode = '';//因为可能延迟,所以记录下每次的请求模式,延迟后判断这个
  61667. Object.defineProperty(Potree.settings , "displayMode",{
  61668. get: function() {
  61669. return displayMode
  61670. },
  61671. set: (mode)=> {
  61672. latestRequestMode = mode;
  61673. //console.warn('Request setMode: ' + mode)
  61674. if(mode != displayMode){
  61675. let config = Potree.config.displayMode[mode];
  61676. let config2;
  61677. let camera = viewer.scene.getActiveCamera();
  61678. if(mode == 'showPanos' && viewer.mainViewport.view.isFlying()){//飞完才能切换全景
  61679. let f = ()=>{
  61680. if(latestRequestMode == mode){//如果ui还是停在这个模式的话
  61681. Potree.settings.displayMode = mode;
  61682. }
  61683. viewer.mainViewport.view.removeEventListener('flyingDone', f);
  61684. };
  61685. viewer.mainViewport.view.addEventListener('flyingDone', f); //once
  61686. return
  61687. }
  61688. if(this.isAtPano() ){//this.currentPano
  61689. if(this.flying)config2 = config.transition;
  61690. else config2 = config.atPano;
  61691. }else {
  61692. config2 = config.atPano;
  61693. if(mode == 'showPanos'){//自动飞入一个pano
  61694. //要改成飞进最近的。。。
  61695. if(this.panos.length == 0)return
  61696. //this.modeChanging = true //主要是因为到全景图不会立刻成功
  61697. let wait = ()=>{
  61698. this.removeEventListener('flyToPanoDone',wait);
  61699. if(latestRequestMode == mode ){
  61700. Potree.settings.displayMode = mode;
  61701. }
  61702. };
  61703. this.flyToPano({
  61704. pano: this.findNearestPano(),
  61705. //dealDoneWhenCancel:true,
  61706. /* callback: ()=>{
  61707. setTimeout(()=>{ //防止循环,所以延迟
  61708. if(latestRequestMode == mode ){
  61709. Potree.settings.displayMode = mode
  61710. }
  61711. },1)
  61712. } */
  61713. });
  61714. this.addEventListener('flyToPanoDone',wait); //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel
  61715. return;
  61716. }else {
  61717. }
  61718. }
  61719. if(config2.showSkybox || config2.showPoint && config2.pointUsePanoTex){
  61720. this.tileDownloader.start();
  61721. }else {
  61722. this.tileDownloader.stop();
  61723. }
  61724. if(config2.showSkybox || config2.pointUsePanoTex){
  61725. let wait = ()=> {
  61726. setTimeout( ()=>{
  61727. if(latestRequestMode == mode ){
  61728. Potree.settings.displayMode = mode;
  61729. }
  61730. },1);
  61731. this.removeEventListener('loadedDepthImg', wait);
  61732. };
  61733. if(!this.currentPano.depthTex && this.currentPano.pointcloud.hasDepthTex){
  61734. this.addEventListener('loadedDepthImg', wait);
  61735. return this.currentPano.loadDepthImg()
  61736. }
  61737. //this.updateDepthTex()
  61738. if(this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, wait)){
  61739. return
  61740. }
  61741. }
  61742. viewer.scene.pointclouds.forEach(e=>{
  61743. viewer.updateVisible(e, 'displayMode', config2.showPoint, 2 );
  61744. });
  61745. if(config2.pointUsePanoTex){
  61746. viewer.scene.pointclouds.forEach(e=>{
  61747. e.material.setProjectedPanos(this.currentPano,this.currentPano, 1);
  61748. });
  61749. }else {
  61750. viewer.scene.pointclouds.forEach(e=>{
  61751. e.material.stopProjectedPanos();
  61752. });
  61753. }
  61754. viewer.updateVisible(this.cube,'showSkybox',config2.showSkybox );// this.cube.visible = config2.showSkybox
  61755. //this.cube.visible = config.atPano.showSkybox
  61756. if(this.cube.visible){
  61757. //this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1)
  61758. this.setProjectedPanos({
  61759. progress:1,
  61760. ifSkybox: true,
  61761. ifPointcloud : false,
  61762. easeInOutRatio : 0,
  61763. pano0:this.currentPano,
  61764. pano1:this.currentPano
  61765. });
  61766. }else {
  61767. this.smoothZoomTo(1);
  61768. this.resetHighMap();
  61769. this.hideHighMap();
  61770. }
  61771. /* viewer.dispatchEvent({
  61772. type: "enableChangePos",
  61773. canLeavePano : config.canLeavePano ,
  61774. viewport:
  61775. }) */
  61776. //viewer.mainViewport.unableChangePos = !config.canLeavePano
  61777. displayMode = mode;
  61778. if(mode == 'showPanos'){
  61779. camera.far = viewer.farWhenShowPano; //修改far
  61780. Potree.settings.pointDensity = 'panorama';
  61781. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  61782. viewer.scene.pointclouds.forEach(e=>{
  61783. e.material.pointSizeType = 'FIXED';
  61784. });
  61785. }
  61786. this.updateCube(this.currentPano);
  61787. }else {
  61788. if(camera.limitFar) camera.far = Potree.settings.cameraFar;//修改far
  61789. Potree.settings.pointDensity = Potree.settings.UserPointDensity;
  61790. //Potree.sdk && Potree.sdk.scene.changePointOpacity()
  61791. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  61792. viewer.scene.pointclouds.forEach(e=>{
  61793. e.material.pointSizeType = Potree.config.material.pointSizeType;
  61794. });
  61795. }
  61796. }
  61797. camera.updateProjectionMatrix();
  61798. if(this.elDisplayModel){
  61799. this.elDisplayModel.val( mode == 'showPointCloud' ? ">>全景" : '>>点云');
  61800. }
  61801. /* this.panos.forEach(e=>{
  61802. viewer.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') //
  61803. }) */
  61804. this.dispatchEvent({type:'endChangeMode',mode});
  61805. //console.log('setModeSuccess: ' + mode)
  61806. }else {
  61807. //this.dispatchEvent({type:'endChangeMode',mode})
  61808. }
  61809. }
  61810. });
  61811. Potree.settings.displayMode = 'showPointCloud';
  61812. }// 切换模式 end
  61813. {//
  61814. let currentPano = null;
  61815. Object.defineProperty(this , "currentPano",{
  61816. get: function() {
  61817. return currentPano
  61818. },
  61819. set: function(e) {
  61820. if(e != currentPano){
  61821. currentPano && currentPano.exit();
  61822. e && e.enter();
  61823. currentPano = e;
  61824. }
  61825. }
  61826. });
  61827. }
  61828. {//是否显示marker
  61829. let ifShowMarker = true;
  61830. Object.defineProperty(Potree.settings, "ifShowMarker",{
  61831. get: function() {
  61832. return ifShowMarker
  61833. },
  61834. set: (show)=>{
  61835. show = !!show;
  61836. if(show != ifShowMarker){
  61837. this.panos.forEach(pano=>{
  61838. viewer.updateVisible(pano, 'ifShowMarker', show, 1 );
  61839. });
  61840. //this.emit('markersDisplayChange', show)
  61841. ifShowMarker = show;
  61842. }
  61843. }
  61844. });
  61845. }
  61846. viewer.addEventListener("update", () => {
  61847. this.update(viewer);
  61848. });
  61849. //viewer.inputHandler.addInputListener(this);
  61850. var keys = {
  61851. FORWARD: ['W'.charCodeAt(0), 38],
  61852. BACKWARD: ['S'.charCodeAt(0), 40],
  61853. LEFT: ['A'.charCodeAt(0), 37],
  61854. RIGHT: ['D'.charCodeAt(0), 39],
  61855. };
  61856. viewer.inputHandler.addEventListener('keydown',(e)=>{
  61857. if(Potree.settings.displayMode == 'showPanos'){
  61858. for(let i in keys){
  61859. if(keys[i].some(a => a == e.keyCode)){
  61860. switch(i){
  61861. case 'FORWARD':
  61862. this.flyLocalDirection(Vectors.FORWARD.clone());
  61863. break;
  61864. case 'BACKWARD':
  61865. this.flyLocalDirection(Vectors.BACK.clone());
  61866. break;
  61867. case 'LEFT':
  61868. this.flyLocalDirection(Vectors.LEFT.clone());
  61869. break;
  61870. case 'RIGHT':
  61871. this.flyLocalDirection(Vectors.RIGHT.clone());
  61872. break;
  61873. }
  61874. break;
  61875. }
  61876. }
  61877. }
  61878. });
  61879. };
  61880. updateDepthTex(pano){
  61881. if(this.currentPano != pano || !pano.depthTex)return
  61882. //this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的
  61883. this.cube.material.updateDepthTex(pano); //确保一下
  61884. }
  61885. findNearestPano(pos){
  61886. pos = pos ? new Vector3().copy(pos) : this.position;
  61887. let result = Common.sortByScore(this.panos,[Images360.filters.isEnabled()],[e=>-e.position.distanceTo(pos)]);
  61888. let pano = result && result[0] && result[0].item;
  61889. return pano
  61890. }
  61891. /* set flying(v){//正在飞向pano
  61892. this.flying_ = !!v
  61893. //console.log('this.flying_ ', !!v )
  61894. //this.emit('flying', this.flying_)
  61895. let config = Potree.config.displayMode[Potree.settings.displayMode]
  61896. viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v
  61897. }
  61898. get flying(){
  61899. return this.flying_
  61900. } */
  61901. flyLocalDirection(dir) {
  61902. var direction = this.getDirection(dir),
  61903. option1 = 1 === dir.y ? .4 : .75,
  61904. option2 = 1 === Math.abs(dir.x);
  61905. return this.flyDirection(direction, option1, option2)
  61906. }
  61907. getDirection(e) {
  61908. if(!e){
  61909. return viewer.scene.view.direction
  61910. }else {
  61911. return e = e ? e : (new Vector3).copy(Vectors.FORWARD),
  61912. e.applyQuaternion(viewer.scene.getActiveCamera().quaternion)
  61913. }
  61914. }
  61915. get position(){
  61916. return this.viewer.scene.view.position.clone()
  61917. }
  61918. get visible(){
  61919. return this._visible;
  61920. }
  61921. set visible(visible){
  61922. if(this._visible === visible){
  61923. return;
  61924. }
  61925. /* for(const image of this.panos){
  61926. image.mesh.visible = visible && (this.currentPano == null);
  61927. } */
  61928. //this.sphere.visible = visible && (this.currentPano != null);
  61929. this._visible = visible;
  61930. this.dispatchEvent({
  61931. type: "visibility_changed",
  61932. panos: this,
  61933. });
  61934. }
  61935. isAtPano(){//是否在某个漫游点上
  61936. return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position)
  61937. }
  61938. updateProjectedPanos(){//更新材质贴图
  61939. //console.warn('updateProjectedPanos')
  61940. this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({pano0:this.projectedPano0, pano1:this.projectedPano1});
  61941. }
  61942. setProjectedPanos(o={}){//设置cube和点云的材质贴图
  61943. this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress);
  61944. if(o.ifPointcloud){
  61945. viewer.scene.pointclouds.forEach(e=>{
  61946. e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio);
  61947. });
  61948. }
  61949. //console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id)
  61950. this.projectedPano0 = o.pano0;
  61951. this.projectedPano1 = o.pano1;
  61952. }
  61953. cancelFlyToPano(){//取消当前已有的飞行准备,前提是相机还未移动
  61954. if(viewer.mainViewport.view.isFlying())return
  61955. this.nextPano = null;
  61956. this.latestToPano = null;
  61957. //this.flying = false
  61958. }
  61959. flyToPano(toPano) { //飞向漫游点
  61960. if(!toPano)return
  61961. if(toPano instanceof Panorama){
  61962. toPano = {pano: toPano};
  61963. }
  61964. if(!toPano.pano.enabled)return
  61965. /* if(!this.currentPano){
  61966. return this.focusPano(toPano)
  61967. } */
  61968. let done = (makeIt, disturb)=>{
  61969. //console.log('flyToPano done ', toPano.pano.id, makeIt )
  61970. if(makeIt || disturb) { // disturb已经开始飞行但中途取消
  61971. toPano.callback && toPano.callback(makeIt);
  61972. //this.flying = false
  61973. this.cancelFlyToPano();
  61974. this.updateClosestPano(this.closestPano,false); //飞行结束后取消点击漫游点时得到的closestPano
  61975. }else {
  61976. console.log('makeit fail');
  61977. }
  61978. this.dispatchEvent({type:'flyToPanoDone', makeIt});
  61979. //this.dispatchEvent('cameraMoveDone')
  61980. toPano.deferred && toPano.deferred.resolve(makeIt); //测量线截图时发现,resolve需要写在flying=false 后才行。
  61981. };
  61982. if(this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion ){
  61983. this.dispatchEvent({type:'flyToPano', toPano});
  61984. return done(true);
  61985. }
  61986. if(this.latestToPano && this.latestToPano != toPano){
  61987. return done(false)
  61988. }
  61989. let target = toPano.target;
  61990. let easeName = toPano.easeName || 'easeInOutQuad'; // 'easeInOutSine'//'easeOutSine'
  61991. let config = Potree.config.displayMode[Potree.settings.displayMode];
  61992. var pointcloudVisi = config.atPano.showPoint; //viewer.scene.pointclouds[0].visible
  61993. var pano = toPano.pano;
  61994. let T = Potree.config.transitionsTime;
  61995. let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn;
  61996. var duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * this.position.distanceTo(pano.position), maxTime)) : toPano.duration;
  61997. toPano.duration = duration;
  61998. //console.warn("flyto "+pano.id + ' duration: ' + duration )
  61999. this.nextPano = pano;
  62000. this.latestToPano = toPano;
  62001. //this.flying = true //防止新的请求
  62002. {//不飞的话是否不要执行这段?
  62003. let wait = ()=> {
  62004. if(this.latestToPano != toPano)return //如果取消了
  62005. setTimeout(()=>{
  62006. if(this.latestToPano != toPano)return
  62007. this.flyToPano(toPano);
  62008. },1);
  62009. this.removeEventListener('loadedDepthImg', wait);
  62010. };
  62011. if(!pano.depthTex && pano.pointcloud.hasDepthTex){ //需要用到depthTex计算neighbour
  62012. this.addEventListener('loadedDepthImg', wait);
  62013. return pano.loadDepthImg()
  62014. }
  62015. if(config.atPano.showSkybox || config.atPano.pointUsePanoTex){
  62016. this.updateCube(this.currentPano, toPano.pano);
  62017. if(this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait)){
  62018. return
  62019. }
  62020. }
  62021. }
  62022. viewer.updateVisible(this.cube,'showSkybox', config.atPano.showSkybox ); // this.cube.visible = config.atPano.showSkybox
  62023. /* this.cube.visible && this.cube.material.setProjectedPanos(this.currentPano, pano, 0)
  62024. if(config.transition.showPoint){
  62025. viewer.scene.pointclouds.forEach(e=>{
  62026. viewer.updateVisible(e, 'displayMode', true)
  62027. })
  62028. if(config.transition.pointUsePanoTex){
  62029. let easeInOutRatio = pointcloudVisi ? 0.3 : 0
  62030. viewer.scene.pointclouds.forEach(e=>{
  62031. e.material.setProjectedPanos(this.currentPano, pano, 0, easeInOutRatio)
  62032. })
  62033. }
  62034. } */
  62035. if(config.transition.showPoint){
  62036. viewer.scene.pointclouds.forEach(e=>{
  62037. viewer.updateVisible(e, 'displayMode', true);
  62038. });
  62039. }
  62040. if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  62041. this.setProjectedPanos({
  62042. progress:0,
  62043. ifSkybox: this.cube.visible,
  62044. ifPointcloud : config.transition.pointUsePanoTex,
  62045. easeInOutRatio : pointcloudVisi ? 0.3 : 0,
  62046. pano0:this.currentPano,
  62047. pano1:pano
  62048. });
  62049. }
  62050. const endPosition = pano.position.clone();
  62051. {
  62052. toPano.duration = duration;
  62053. toPano.easeName = easeName;
  62054. this.beforeFlyToPano(toPano);
  62055. }
  62056. let fly = ()=>{
  62057. this.dispatchEvent({type:'flyToPano', toPano});
  62058. viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration,
  62059. callback:()=>{
  62060. if(!config.atPano.pointUsePanoTex){
  62061. viewer.scene.pointclouds.forEach(e=>{
  62062. e.material.stopProjectedPanos();
  62063. });
  62064. }
  62065. //this.currentPano.exit()
  62066. //pano.enter()
  62067. this.currentPano = pano;
  62068. this.nextPano = null;
  62069. if(Potree.settings.displayMode == 'showPanos'){
  62070. viewer.scene.pointclouds.forEach(e=>{
  62071. viewer.updateVisible(e, 'displayMode',pointcloudVisi);
  62072. });
  62073. }
  62074. done(true);
  62075. //this.updateCube(this.currentPano)
  62076. this.updateDepthTex(this.currentPano);
  62077. }, onUpdate:(progress)=>{
  62078. this.cube.material.uniforms.progress.value = progress;
  62079. viewer.scene.pointclouds.forEach(e=>{
  62080. e.material.uniforms.progress.value = progress;
  62081. });
  62082. },
  62083. cancelFun:()=>{ done(false, true); },
  62084. Easing:easeName
  62085. });
  62086. //duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false
  62087. };
  62088. if(Potree.settings.displayMode == 'showPanos'){
  62089. setTimeout(fly, 40); //更新geo后缓冲
  62090. }else {
  62091. fly();
  62092. }
  62093. //console.log('flyToPano:', toPano.pano.id)
  62094. }
  62095. beforeFlyToPano(toPano){
  62096. if(this.currentPano != toPano.pano) {
  62097. if(Potree.settings.displayMode == 'showPanos'){
  62098. this.resetHighMap();
  62099. }
  62100. this.smoothZoomTo(1, toPano.duration / 2);
  62101. }
  62102. }
  62103. /* focusPano(toPano ){
  62104. if(this.currentPano !== null){
  62105. return this.flyToPano(toPano);
  62106. }
  62107. if(toPano instanceof Panorama){
  62108. toPano = {pano: toPano}
  62109. }
  62110. let done = (makeIt)=>{
  62111. toPano.deferred && toPano.deferred.resolve(makeIt)
  62112. makeIt && toPano.callback && toPano.callback()
  62113. }
  62114. var pano = toPano.pano
  62115. let config = Potree.config.displayMode[Potree.settings.displayMode]
  62116. previousView = {
  62117. //controls: this.viewer.controls,
  62118. position: this.position,
  62119. target: viewer.scene.view.getPivot(),
  62120. };
  62121. //this.viewer.setControls(this.viewer.orbitControls);
  62122. this.viewer.orbitControls.doubleClockZoomEnabled = false;
  62123. for(let image of this.panos){
  62124. image.mesh.visible = false;
  62125. }
  62126. this.selectingEnabled = false;
  62127. //console.warn("flyto "+pano.file.split('/').pop() )
  62128. var dur = toPano.duration == void 0 ? 700 : toPano.duration
  62129. if(config.atPano.showSkybox){
  62130. if ( this.checkAndWaitForPanoLoad(pano, this.basePanoSize, ()=> {
  62131. setTimeout( ()=>{
  62132. this.focusPano(toPano)
  62133. },1)
  62134. })
  62135. ) {
  62136. return ;
  62137. }
  62138. }
  62139. this.cube.visible = config.atPano.showSkybox
  62140. //if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  62141. this.setProjectedPanos({
  62142. progress:0,
  62143. ifSkybox: this.cube.visible,
  62144. ifPointcloud : config.atPano.pointUsePanoTex,
  62145. pano0:pano,
  62146. pano1:pano
  62147. })
  62148. //}
  62149. let newCamPos = pano.position.clone()
  62150. let target = newCamPos.clone().add(viewer.scene.view.direction)
  62151. viewer.scene.view.setView( {position:newCamPos, target, duration:dur ,
  62152. callback:()=>{//done
  62153. //pano.enter()
  62154. this.flying = false
  62155. this.currentPano = pano;
  62156. this.updateCube(this.currentPano)
  62157. done(true)
  62158. },onUpdate:(progress)=>{
  62159. },
  62160. cancelFun:()=>{this.flying = false}
  62161. })
  62162. this.flying = true
  62163. this.elUnfocus && (this.elUnfocus[0].style.display = "");
  62164. }
  62165. unfocus(o={}){
  62166. this.selectingEnabled = true;
  62167. Potree.settings.displayMode = 'showPointCloud'
  62168. if(!this.currentPano && !o.position){
  62169. return;
  62170. }
  62171. this.cube.visible = false
  62172. viewer.orbitControls.doubleClockZoomEnabled = true;
  62173. viewer.scene.view.setView($.extend({
  62174. position: previousView.position,
  62175. target:previousView.target,
  62176. duration:500
  62177. },o,{
  62178. callback:()=>{ //done
  62179. for(let pano of this.panos){
  62180. pano.mesh.visible = true;
  62181. //pano.marker.material.depthTest = true
  62182. }
  62183. o.callback && o.callback()
  62184. }
  62185. ,
  62186. cancelFun:()=>{this.flying = false},
  62187. }))
  62188. //this.currentPano.exit()
  62189. this.currentPano = null;
  62190. this.elUnfocus && (this.elUnfocus[0].style.display = "none");
  62191. } */
  62192. updateCube(pano0, pano1){
  62193. if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话
  62194. if(Potree.settings.displayMode != 'showPanos')return
  62195. let f = (bound, size)=>{
  62196. size = size || bound.getSize(new Vector3);
  62197. let center = bound.getCenter(new Vector3);
  62198. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62199. this.cube.scale.copy(size);
  62200. this.cube.position.copy(center);
  62201. };
  62202. let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离
  62203. if(bound1.intersectsBox(bound2))return 0
  62204. let center1 = bound1.getCenter(new Vector3);
  62205. let center2 = bound2.getCenter(new Vector3);
  62206. let dis = center1.distanceTo(center2);
  62207. let dis1 = bound1.distanceToPoint(center2);
  62208. let dis2 = bound2.distanceToPoint(center1);
  62209. return dis1 + dis2 - dis
  62210. };
  62211. if(pano1){//过渡
  62212. if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡
  62213. f(pano0.pointcloud.bound);
  62214. //console.log('updateCube1' )
  62215. }else {//非同一个数据集内的过渡
  62216. let bound = pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound);
  62217. if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){
  62218. f(bound);
  62219. }else {//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用
  62220. let size = bound.getSize(new Vector3);
  62221. let max = Math.max(size.x, size.y, size.z);
  62222. size.set(max,max,max);
  62223. f(bound, size);
  62224. //console.log('updateCube2', size)
  62225. //far可能要修改下
  62226. }
  62227. }
  62228. }else {
  62229. f(pano0.pointcloud.bound); //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小
  62230. //console.log('updateCube3' )
  62231. }
  62232. }
  62233. /* updateCube(pano0, pano1){ //垂直上不分段、 每个pano只有5个方向的版本
  62234. if(Potree.settings.displayMode != 'showPanos')return
  62235. console.log('updateCube',pano0.id, pano1&&pano1.id)
  62236. let f = (bound, size)=>{
  62237. size = size || bound.getSize(new THREE.Vector3)
  62238. let center = bound.getCenter(new THREE.Vector3)
  62239. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  62240. this.cube.scale.copy(size)
  62241. this.cube.position.copy(center)
  62242. }
  62243. this.cube.geometry.dispose();
  62244. if(pano1){//过渡
  62245. let add = (pano, dir, )=>{
  62246. let minZ, maxZ
  62247. minZ = pano.floorPosition.z
  62248. {//天花板高度值
  62249. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62250. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62251. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  62252. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  62253. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62254. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  62255. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  62256. let zs = [dir1,dir2,dir3].map(dir_=>{
  62257. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62258. let z = intersect ? intersect.location.z : pano.position.z
  62259. return z
  62260. })
  62261. zs.sort((a,b)=>{return b-a});//得最大值
  62262. maxZ = zs[0]
  62263. }
  62264. const angle = Math.PI/6 //每次转30度
  62265. let getDir = (angle_)=>{
  62266. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  62267. return dir.clone().applyMatrix4(rotMat)
  62268. }
  62269. let dirs = [getDir(angle*2), getDir(angle),getDir(angle), dir.clone(), getDir(-angle), getDir(-angle*2)]; //总共五个方向,夹角总和180度
  62270. dirs.forEach(dir=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  62271. //上下分别45度 刚好就是
  62272. let dir0 = dir.clone();// 水平方向
  62273. let dir1 = dir.clone().setZ(1).normalize() //上45度方向
  62274. let dir2 = dir.clone().setZ(-1).normalize() // 下45度方向
  62275. let disArr = [dir0,dir1,dir2].map(dir_ =>{
  62276. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62277. let projectLen = intersect.distance ? dir_.dot(dir)*intersect.distance : 0 //得到project在dir的长度
  62278. return projectLen
  62279. })
  62280. disArr.sort((a,b)=>{return b-a});//得最大值
  62281. dir.multiplyScalar( disArr[0] );//得到水平方向上的最远向量
  62282. [minZ,maxZ].forEach(z=>{ //0-9
  62283. posArr.push(pano.position.clone().setZ(z).add(dir))
  62284. })
  62285. });
  62286. [minZ,maxZ].forEach(z=>{ // 10,11
  62287. posArr.push(pano.position.clone().setZ(z))
  62288. })
  62289. }
  62290. let posArr = [];
  62291. 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], //外侧四个面
  62292. [0,2,10],[2,4,10],[4,6,10],[6,8,10],//底部扇形
  62293. [1,3,11],[3,5,11],[5,7,11],[7,9,11],//顶部扇形
  62294. ]
  62295. //两点连线的水平向量
  62296. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  62297. add(pano0, vec)
  62298. add(pano1, vec.negate())
  62299. let faceArr2 = faceArr.map(face=>face.map(i=>i+12))//加上pano2的部分
  62300. faceArr.push(...faceArr2)
  62301. //加上连接的部分,四个面
  62302. faceArr.push([0,1, 8+12],[1, 9+12, 8+12], [8,9,0+12],[9,1+12,0+12],
  62303. [0,8,0+12],[0,0+12,8+12], [1,9,1+12],[1,1+12,9+12],
  62304. )
  62305. let geo = MeshDraw.createGeometry(posArr, faceArr)
  62306. this.cube.geometry = geo
  62307. this.cube.scale.set(1,1,1);
  62308. this.cube.position.set(0,0,0)
  62309. }else{
  62310. if(this.hasUpdateOnePano)return
  62311. this.hasUpdateOnePano = true
  62312. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  62313. f(pano0.pointcloud.bound)
  62314. }
  62315. } */
  62316. /* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个
  62317. if(Potree.settings.displayMode != 'showPanos')return
  62318. console.log('updateCube',pano0.id, pano1&&pano1.id)
  62319. let f = (bound, size)=>{
  62320. size = size || bound.getSize(new THREE.Vector3)
  62321. let center = bound.getCenter(new THREE.Vector3)
  62322. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  62323. this.cube.scale.copy(size)
  62324. this.cube.position.copy(center)
  62325. }
  62326. this.cube.geometry.dispose();
  62327. if(pano1){//过渡
  62328. let count1, count2;
  62329. let panoIndex = 0
  62330. let add = (pano, dir )=>{
  62331. let getPI = function(index, panoIndex_){
  62332. if(panoIndex_ == void 0) panoIndex_ = panoIndex
  62333. return (count1 * count2 + 2 ) * panoIndex_ + index + 2
  62334. }
  62335. let minZ, maxZ
  62336. minZ = pano.floorPosition.z
  62337. {//天花板高度值
  62338. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62339. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62340. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  62341. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  62342. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62343. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  62344. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  62345. let zs = [dir1,dir2,dir3].map(dir_=>{
  62346. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62347. let z = intersect ? intersect.location.z : pano.position.z
  62348. return z
  62349. })
  62350. zs.sort((a,b)=>{return b-a});//得最大值
  62351. maxZ = zs[0]
  62352. let min = pano.position.z + 1
  62353. if(maxZ < pano.position.z + 0.04){//户外
  62354. maxZ = pano.position.z + 50
  62355. }
  62356. maxZ = Math.max(min,maxZ)
  62357. console.log(pano.id, 'maxZ:',maxZ )
  62358. console.log(pano.id, 'minZ:',minZ )
  62359. }
  62360. [maxZ, minZ ].forEach(z=>{
  62361. posArr.push(pano.position.clone().setZ(z))
  62362. })
  62363. const angle = Math.PI/8
  62364. let getDir = (angle_)=>{
  62365. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  62366. return dir.clone().applyMatrix4(rotMat)
  62367. }
  62368. 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度
  62369. count1 = dirs.length
  62370. dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  62371. let dirs_ = [
  62372. dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(),
  62373. dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(),
  62374. dir.clone(), // 水平方向
  62375. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(),
  62376. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62377. ];
  62378. count2 = dirs_.length
  62379. dirs_.forEach((dir_, i) =>{
  62380. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62381. let location
  62382. if(!intersect){ //超级远
  62383. let distance = 100
  62384. location = dir_.clone().multiplyScalar(distance).add(pano.position)
  62385. intersect = {distance,location}
  62386. }
  62387. //intersect.distance
  62388. location = intersect.location.clone()
  62389. let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ);
  62390. let needShrink = false
  62391. if(i == 0){//最上方的点高度直接等于天花板
  62392. shouldZ = maxZ
  62393. if(location.z<maxZ)location.z = maxZ
  62394. else needShrink = true
  62395. }else if(i == count2-1){//最下方的点高度直接等于地板
  62396. shouldZ = minZ
  62397. if(location.z>minZ)location.z = minZ
  62398. else needShrink = true
  62399. }
  62400. if(needShrink ){//需要在保持dir_不变的情况下修改z
  62401. let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance
  62402. location = dir_.clone().multiplyScalar(len).add(pano.position)
  62403. }
  62404. posArr.push(location)
  62405. if(index!=0 && i!=0){//加入一块四方面
  62406. let curIndex = getPI(count2 * index + i);
  62407. faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2],
  62408. [curIndex-1, curIndex, curIndex-count2])
  62409. }
  62410. })
  62411. if(index!=0){
  62412. let top = -2;
  62413. let btm = -1
  62414. faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形
  62415. faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形
  62416. }else{
  62417. //加入和另一个pano连接的其中一个侧边
  62418. let panoIndex2 = (panoIndex + 1) % 2;
  62419. for(let i=1;i<count2;i++){
  62420. faceArr.push([getPI(i-1), getPI(i), getPI((count1-1)*count2 +i, panoIndex2)],
  62421. [getPI(i-1), getPI((count1-1)*count2+i , panoIndex2) , getPI((count1-1)*count2+i-1 ,panoIndex2)])
  62422. }
  62423. faceArr.push([getPI(0), getPI((count1-1)*count2), getPI(0, panoIndex2)])//加入顶部的一半
  62424. faceArr.push([getPI(count2-1), getPI(count1*count2-1), getPI(count2-1, panoIndex2)])//加入底部的一半
  62425. }
  62426. });
  62427. panoIndex ++
  62428. }
  62429. let posArr = [];
  62430. let faceArr = []
  62431. //两点连线的水平向量
  62432. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  62433. add(pano0, vec)
  62434. add(pano1, vec.negate())
  62435. let geo = MeshDraw.createGeometry(posArr, faceArr)
  62436. this.cube.geometry = geo
  62437. this.cube.scale.set(1,1,1);
  62438. this.cube.position.set(0,0,0)
  62439. }else{
  62440. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  62441. f(pano0.pointcloud.bound)
  62442. }
  62443. } */
  62444. updateCube3(pano0, pano1){//增加细分的版本,且垂直方向上取中位数... 侧边只有一条
  62445. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  62446. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  62447. ) return
  62448. this.cubePanos = [pano0, pano1];
  62449. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  62450. let f = (bound, size)=>{
  62451. size = size || bound.getSize(new Vector3);
  62452. let center = bound.getCenter(new Vector3);
  62453. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62454. this.cube.scale.copy(size);
  62455. this.cube.position.copy(center);
  62456. };
  62457. this.cube.geometry.dispose();
  62458. if(pano1){//过渡
  62459. const half = pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex ? ( browser.isMobile() ? 3 : 6 ) : (browser.isMobile() ? 2 : 3); //自行输入 (点云计算的慢,还不准)
  62460. let count1 = 2*half;//偶数个 dir 个数
  62461. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  62462. let panoIndex = 0;
  62463. let getIntersect = (pano, dir, origin)=>{
  62464. if(pano && pano.pointcloud.hasDepthTex ){
  62465. return this.depthSampler.sample( {dir }, pano, true )
  62466. }else {
  62467. origin = origin || pano.position;
  62468. return viewer.inputHandler.getIntersect(viewer.inputHandler.hoverViewport, true, null, null, true, {
  62469. point: origin.clone().add(dir),
  62470. cameraPos: origin
  62471. })
  62472. }
  62473. };
  62474. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  62475. let rotMat = new Matrix4().makeRotationZ(angle_);
  62476. return vec.clone().applyMatrix4(rotMat)
  62477. };
  62478. let getFar = (dir, pano, origin)=>{//获取在这个方向上和墙体intersect的最远距离
  62479. let dirs_ = [
  62480. //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 户外时需要更多向上的方向,所以上方向多一个
  62481. dir.clone().setZ(Math.tan(MathUtils.degToRad(30))).normalize(),
  62482. dir.clone().setZ(Math.tan(MathUtils.degToRad(7))).normalize(),
  62483. dir.clone(), // 水平方向
  62484. dir.clone().setZ(-Math.tan(MathUtils.degToRad(5))).normalize(),
  62485. //dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62486. ];
  62487. let max = 50;
  62488. let count2 = dirs_.length;
  62489. let disArr = dirs_.map((dir_, i) =>{
  62490. let intersect = getIntersect(pano, dir_, origin);
  62491. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  62492. return projectLen
  62493. });
  62494. disArr.sort((a,b)=>{return b-a}); //从大到小
  62495. //console.log(pano ? pano.id : 'side','disArr', disArr)
  62496. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  62497. return dis
  62498. };
  62499. let add = (pano, vec )=>{
  62500. let getPI = function(index, panoIndex_){
  62501. if(panoIndex_ == void 0) panoIndex_ = panoIndex;
  62502. return (count1*2 + 2 ) * panoIndex_ + index + 2
  62503. };
  62504. let minZ, maxZ;
  62505. minZ = pano.floorPosition.z;
  62506. if(pano.ceilZ != void 0){
  62507. maxZ = pano.ceilZ;
  62508. }else {//天花板高度值
  62509. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62510. let rotMat = new Matrix4().makeRotationX(MathUtils.degToRad(40));// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62511. let dir1 = new Vector3(0,0,1).applyMatrix4(rotMat);
  62512. let rotMat1 = new Matrix4().makeRotationZ(Math.PI*2 / 3);
  62513. let rotMat2 = new Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62514. let dir2 = dir1.clone().applyMatrix4(rotMat1);
  62515. let dir3 = dir1.clone().applyMatrix4(rotMat2);
  62516. let zs = [dir1,dir2,dir3].map(dir_=>{
  62517. let intersect = getIntersect(pano, dir_);
  62518. let z = intersect ? intersect.location.z : pano.position.z+50;
  62519. return z
  62520. });
  62521. zs.sort((a,b)=>{return b-a});//得最大值
  62522. maxZ = zs[0];
  62523. let min = pano.position.z + 1;
  62524. maxZ = Math.max(min,maxZ);
  62525. pano.ceilZ = maxZ;
  62526. //console.log(pano.id, 'maxZ:',maxZ )
  62527. //console.log(pano.id, 'minZ:',minZ )
  62528. }
  62529. [maxZ, minZ ].forEach(z=>{
  62530. posArr.push(pano.position.clone().setZ(z));
  62531. });
  62532. const angle = Math.PI/(count1-1);
  62533. //在画面上线条从左往右数
  62534. let dirs = [];
  62535. for(let i=0;i<count1;i++){
  62536. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  62537. }
  62538. let sideDis = [];
  62539. dirs.forEach((dir, index)=>{
  62540. let dis = getFar(dir, pano);
  62541. if(index == 0 || index == count1-1){
  62542. sideDis.push(dis);
  62543. }
  62544. dir.multiplyScalar( dis );
  62545. [maxZ,minZ].forEach(z=>{
  62546. posArr.push(pano.position.clone().setZ(z).add(dir));
  62547. });
  62548. if(index!=0){//加入一块四方面
  62549. let m = index*2;
  62550. faceArr.push([getPI(m), getPI(m-1), getPI(m-2)],
  62551. [getPI(m), getPI(m+1), getPI(m-1)]);
  62552. let top = -2;
  62553. let btm = -1;
  62554. faceArr.push([getPI(m), getPI(m-2), getPI(top) ]);//天花板扇形
  62555. faceArr.push([getPI(btm), getPI(m-1), getPI(m+1) ] );//地板扇形
  62556. }
  62557. });
  62558. let panoIndex2 = (panoIndex + 1) % 2;
  62559. //let m = (count1-1)*2
  62560. /* faceArr.push([getPI(0), getPI(1), getPI(count1*2-1, panoIndex2)],
  62561. [getPI(0), getPI(count1*2-1,panoIndex2) , getPI(count1*2-2,panoIndex2)])
  62562. faceArr.push([getPI(0, panoIndex2), getPI(count1*2-2), getPI(0)])//加入顶部的一半
  62563. faceArr.push([getPI(1), getPI(count1*2-1), getPI(1, panoIndex2)])//加入底部的一半 */
  62564. //加入和另一个pano连接
  62565. let sideMid = count1*4+4; //侧边点start
  62566. //侧边的一半
  62567. faceArr.push([getPI(0), getPI(1), sideMid+panoIndex*2],
  62568. [sideMid+panoIndex*2, getPI(1) , sideMid+panoIndex*2+1 ],
  62569. [getPI(count1*2-2), sideMid+panoIndex2*2+1, getPI(count1*2-1)],
  62570. [getPI(count1*2-2), sideMid+panoIndex2*2, sideMid+panoIndex2*2+1 ]
  62571. );
  62572. faceArr.push([getPI(0), sideMid+panoIndex2*2, getPI(count1*2-2)],
  62573. [getPI(0),sideMid+panoIndex*2, sideMid+panoIndex2*2]
  62574. );//加入顶部的一半
  62575. faceArr.push([getPI(count1*2-1), sideMid+panoIndex2*2+1, getPI(1)],
  62576. [sideMid+panoIndex2*2+1, sideMid+panoIndex*2+1, getPI(1)]
  62577. );//加入底部的一半
  62578. panoIndex ++;
  62579. return sideDis;
  62580. };
  62581. let addSide = ()=>{//两个漫游点间两边各加一条侧线,为了适应四方形房间漫游点在对角方向的那种情况
  62582. //侧边为了取中点,没办法用全景图获取了,用点云
  62583. let sideMaxZ = (pano0.ceilZ + pano1.ceilZ)/2;
  62584. let sideMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  62585. let sideDis_ = [(sideDis0[0] + sideDis1[1])/2, (sideDis0[1] + sideDis1[0])/2];
  62586. let sideDis = [Math.min(sideDis0[0] , sideDis1[1]), Math.min(sideDis0[1] , sideDis1[0])];//
  62587. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  62588. let sideDirs = [getDir(-Math.PI/2, vec), getDir(Math.PI/2, vec)];
  62589. if(pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  62590. let panos = [pano0,pano1];
  62591. let vecs = [vec.negate(), vec];
  62592. let axis = [[-1,1],[1,-1]];
  62593. let dis2d = new Vector2$1().subVectors(pano0.position, pano1.position).length();//水平上的距离
  62594. let angles = [MathUtils.degToRad(45), MathUtils.degToRad(60)];
  62595. sideDirs.forEach((dir, index0)=>{
  62596. let disToSides = [];
  62597. panos.forEach((pano,index)=>{
  62598. let dirs = [getDir(axis[index0][index]*angles[0], vecs[index]), getDir(axis[index0][index]*angles[1], vecs[index])];//一侧的若干角度
  62599. dirs.forEach((dir_,i)=>{
  62600. let dis1 = getFar(dir_, pano);
  62601. //dir_.multiplyScalar( dis1 );
  62602. let disToPano2d = dis1 * Math.cos(angles[i]);
  62603. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入
  62604. let disToSide = dis1 * Math.sin(angles[i]);
  62605. disToSides.push(disToSide);
  62606. }
  62607. });
  62608. });
  62609. let disToSide;
  62610. if(disToSides.length){
  62611. disToSides.sort((a,b)=>{return b-a});//从大到小
  62612. disToSide = disToSides[0];
  62613. console.log('disToSides', index0, disToSides);
  62614. }else {
  62615. disToSide = sideDis[index0];
  62616. }
  62617. dir.multiplyScalar( disToSide );
  62618. [sideMaxZ,sideMinZ].forEach(z=>{
  62619. posArr.push(mid.clone().setZ(z).add(dir)); //是直接使用最长dis的那个intersect点好还是mid
  62620. });
  62621. });
  62622. }else {
  62623. sideDirs.forEach((dir_ ,index)=>{
  62624. let dis = getFar(dir_, null, mid);
  62625. dir_.multiplyScalar( /* sideDis_[index] */ Math.max(dis, sideDis[index]) );
  62626. [sideMaxZ,sideMinZ].forEach(z=>{
  62627. posArr.push(mid.clone().setZ(z).add(dir_));
  62628. });
  62629. });
  62630. }
  62631. };
  62632. let posArr = [];
  62633. let faceArr = [];
  62634. //两点连线的水平向量
  62635. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  62636. let sideDis0 = add(pano0, vec);
  62637. let sideDis1 = add(pano1, vec.negate());
  62638. addSide();
  62639. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  62640. let geo = MeshDraw.createGeometry(posArr, faceArr);
  62641. this.cube.geometry = geo;
  62642. this.cube.scale.set(1,1,1);
  62643. this.cube.position.set(0,0,0);
  62644. //this.cube.scale.set(100,100,100);
  62645. //this.cube.position.copy(pano1.position).multiplyScalar(-100)
  62646. }else {
  62647. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  62648. f(pano0.pointcloud.bound);
  62649. }
  62650. }
  62651. updateCube2(pano0, pano1){//增加细分的版本,且垂直方向上取中位数 侧边多条
  62652. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  62653. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  62654. ) return
  62655. this.cubePanos = [pano0, pano1];
  62656. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  62657. let useBound = (bound, size)=>{
  62658. size = size || bound.getSize(new Vector3);
  62659. let center = bound.getCenter(new Vector3);
  62660. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62661. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  62662. this.cube.scale.copy(size);
  62663. this.cube.position.copy(center);
  62664. };
  62665. this.cube.geometry.dispose();
  62666. if(pano1){//过渡
  62667. if(pano0.pointcloud != pano1.pointcloud){ //距离太远的数据集,过渡会畸变。所以扩大skybox
  62668. let dis = pano0.position.distanceTo(pano1.position);
  62669. if(dis > 100){
  62670. let bound = pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound);
  62671. let size = bound.getSize(new Vector3);
  62672. let max = Math.max(size.x, size.y, size.z);
  62673. size.set(max,max,max);
  62674. return useBound(bound, size)
  62675. }
  62676. }
  62677. const half = pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex ? 6 : (browser.isMobile() ? 2 : 3); //自行输入 (点云计算的慢,还不准)
  62678. let count1 = 2*half;//偶数个 每个pano向 外dir 个数
  62679. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  62680. //let panoIndex = 0
  62681. let getIntersect = (pano, dir, origin)=>{
  62682. if(pano && pano.pointcloud.hasDepthTex ){
  62683. return this.depthSampler.sample( {dir }, pano, true )
  62684. }else {
  62685. origin = origin || pano.position;
  62686. return viewer.inputHandler.getIntersect(viewer.inputHandler.hoverViewport, true, null, null, true, {
  62687. point: origin.clone().add(dir),
  62688. cameraPos: origin
  62689. })
  62690. }
  62691. };
  62692. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  62693. let rotMat = new Matrix4().makeRotationZ(angle_);
  62694. return vec.clone().applyMatrix4(rotMat)
  62695. };
  62696. let getFar = (dir, pano, origin)=>{//获取在这个方向上和墙体intersect的距离
  62697. //在垂直方向上分出多个方向,取一个最可能的接近真实的距离
  62698. let dirs_ = [
  62699. //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 户外时需要更多向上的方向,所以上方向多一个
  62700. dir.clone().setZ(Math.tan(MathUtils.degToRad(30))).normalize(),
  62701. dir.clone().setZ(Math.tan(MathUtils.degToRad(7))).normalize(),
  62702. dir.clone(), // 水平方向
  62703. dir.clone().setZ(-Math.tan(MathUtils.degToRad(5))).normalize(),
  62704. //dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62705. ];
  62706. let max = 50;
  62707. let count2 = dirs_.length;
  62708. let disArr = dirs_.map((dir_, i) =>{
  62709. let intersect = getIntersect(pano, dir_, origin);
  62710. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  62711. return projectLen //得水平距离
  62712. });
  62713. disArr.sort((a,b)=>{return b-a}); //从大到小
  62714. //console.log(pano ? pano.id : 'side','disArr', disArr)
  62715. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  62716. return dis
  62717. };
  62718. let sideCount = [];
  62719. let addPos = (pano, vec )=>{//添加这个pano这一侧向外半圆的顶点
  62720. //添加pano位置对应的最高点最低点:
  62721. let minZ, maxZ;
  62722. minZ = pano.floorPosition.z;
  62723. if(pano.ceilZ != void 0){
  62724. maxZ = pano.ceilZ;
  62725. }else {//天花板高度值
  62726. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62727. let rotMat = new Matrix4().makeRotationX(MathUtils.degToRad(40));// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62728. let dir1 = new Vector3(0,0,1).applyMatrix4(rotMat);
  62729. let rotMat1 = new Matrix4().makeRotationZ(Math.PI*2 / 3);
  62730. let rotMat2 = new Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62731. let dir2 = dir1.clone().applyMatrix4(rotMat1);
  62732. let dir3 = dir1.clone().applyMatrix4(rotMat2);
  62733. let skyHeight = 50;
  62734. let zs = [dir1,dir2,dir3].map(dir_=>{
  62735. let intersect = getIntersect(pano, dir_);
  62736. let z = intersect ? intersect.location.z : pano.position.z+skyHeight; //没有intersect代表可能是天空
  62737. return z
  62738. });
  62739. zs.sort((a,b)=>{return b-a});//得最大值 (不用中位数的原因:在屋檐处,如果仅有一个intersect是天空,因到了室外所以也用天空高度)
  62740. maxZ = zs[0];
  62741. let min = pano.position.z + 1; // 防止意外太低
  62742. maxZ = Math.max(min,maxZ);
  62743. pano.ceilZ = maxZ;
  62744. //console.log(pano.id, 'maxZ:',maxZ )
  62745. //console.log(pano.id, 'minZ:',minZ )
  62746. }
  62747. [maxZ, minZ ].forEach(z=>{
  62748. posArr.push(pano.position.clone().setZ(z));
  62749. });
  62750. //在画面上线条从左往右数
  62751. const angle = Math.PI/(count1-1);
  62752. const dirs = []; //平分这半边180度
  62753. for(let i=0;i<count1;i++){
  62754. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  62755. }
  62756. // let sideDis = []
  62757. dirs.forEach((dir, index)=>{
  62758. let dis = getFar(dir, pano);
  62759. // if(index == 0 || index == count1-1){
  62760. // sideDis.push(dis)
  62761. // }
  62762. dir.multiplyScalar( dis );
  62763. [maxZ,minZ].forEach(z=>{
  62764. posArr.push(pano.position.clone().setZ(z).add(dir)); //获取到外墙点
  62765. });
  62766. });
  62767. //panoIndex ++
  62768. //return sideDis;
  62769. };
  62770. let addSide = ()=>{//两个漫游点间两边各加一些侧线
  62771. //中点处的
  62772. let midMaxZ = (pano0.ceilZ + pano1.ceilZ)/2;
  62773. let midMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  62774. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  62775. /* let sideDis_ = [(sideDis0[0] + sideDis1[1])/2, (sideDis0[1] + sideDis1[0])/2];
  62776. let sideDis = [Math.min(sideDis0[0] , sideDis1[1]), Math.min(sideDis0[1] , sideDis1[0])]//
  62777. */
  62778. if(pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  62779. let panos = [pano0,pano1];
  62780. let vecs = [vec.clone().negate(), vec];
  62781. let axis = [[-1,1],[1,-1]];
  62782. let dis2d = new Vector2$1().subVectors(pano0.position, pano1.position).length();//水平上的距离
  62783. let angles = [MathUtils.degToRad(40), MathUtils.degToRad(70)]; //正的在左边 尽量能够平分中间这段墙体
  62784. axis.forEach((axis_, index0)=>{
  62785. let disToSides = [];
  62786. let accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点
  62787. panos.forEach((pano,index)=>{
  62788. let dirs = [getDir(axis_[index]*angles[0], vecs[index]), getDir(axis_[index]*angles[1], vecs[index])];//一侧的若干角度
  62789. dirs.forEach((dir_,i)=>{
  62790. let dis1 = getFar(dir_, pano);
  62791. let disToPano2d = dis1 * Math.cos(angles[i]);
  62792. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入
  62793. let disToSide = dis1 * Math.sin(angles[i]);
  62794. if(pano != accordingPano){
  62795. disToPano2d = dis2d - disToPano2d; //反一下
  62796. }
  62797. dir_.multiplyScalar( dis1 );
  62798. disToSides.push({disToSide,disToPano2d, pano, dir_});
  62799. }
  62800. });
  62801. });
  62802. sideCount[index0] = disToSides.length; //记录侧边个数
  62803. if(disToSides.length){
  62804. //disToSides.sort((a,b)=>{return b-a});//从大到小
  62805. //由距离accordingPano的近到远:
  62806. disToSides.sort((a,b)=>{return a.disToPano2d-b.disToPano2d});
  62807. //console.log('disToSides', index0, disToSides)
  62808. disToSides.forEach(e=>{//求z
  62809. let ratio = e.disToPano2d / dis2d;
  62810. let r = accordingPano == pano0 ? (1-ratio) : ratio;
  62811. let sideMaxZ_ = pano0.ceilZ * r + pano1.ceilZ * (1-r);
  62812. let sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1-r);
  62813. [sideMaxZ_,sideMinZ_].forEach(z=>{
  62814. posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)); //是直接使用最长dis的那个intersect点好还是mid
  62815. });
  62816. });
  62817. }
  62818. });
  62819. }else {
  62820. //这段针对点云时,仅测试才会执行到
  62821. sideCount = [1,1];
  62822. let sideDirs = [getDir(Math.PI/2, vec), getDir(-Math.PI/2, vec)];
  62823. sideDirs.forEach((dir_ ,index)=>{
  62824. let dis = getFar(dir_, null, mid); //直接从中点求两侧的距离
  62825. dir_.multiplyScalar( /* Math.max( */dis/* , sideDis[index]) */ );
  62826. [midMaxZ,midMinZ].forEach(z=>{
  62827. posArr.push(mid.clone().setZ(z).add(dir_));
  62828. });
  62829. });
  62830. }
  62831. //中心:
  62832. [midMaxZ,midMinZ].forEach(z=>{
  62833. posArr.push(mid.clone().setZ(z));
  62834. });
  62835. };
  62836. //positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点
  62837. let addFaces = ()=>{
  62838. let getPI = function(index, posType, panoIndex){//获取顶点序号
  62839. return 2 + (count1*2 + 2 ) * panoIndex + index*2 + (posType == 'top' ? 0 : 1)
  62840. };
  62841. let getSidePI = function(index, posType, panoIndex){//获取侧边顶点序号
  62842. if(panoIndex == 1) index += sideCount[0];
  62843. return getPI(index, posType, 2)-2
  62844. };
  62845. let getPanoPI = function(posType, panoIndex){//获取pano处对应的点序号
  62846. return getPI(-1, posType, panoIndex)
  62847. };
  62848. let topCenter = posArr.length-2; //最后添加的两个中心点
  62849. let btmCenter = posArr.length-1;
  62850. for(let i=0;i<2;i++){
  62851. for(let index=1; index<count1; index++){
  62852. //pano外侧半圆围墙
  62853. faceArr.push([getPI(index,'top',i), getPI(index-1,'btm',i), getPI(index-1,'top',i)],//加入一块四方面
  62854. [getPI(index,'top',i), getPI(index,'btm',i), getPI(index-1,'btm',i)]);
  62855. faceArr.push([getPI(index,'top',i), getPI(index-1,'top',i), getPanoPI('top',i)]);//天花板扇形
  62856. faceArr.push([getPI(index,'btm',i), getPI(index-1,'btm',i), getPanoPI('btm',i)]);//地板扇形
  62857. }
  62858. let j = (i + 1) % 2; //另一个pano
  62859. //侧边
  62860. for(let u=0; u<=sideCount[i]; u++){
  62861. //侧边每个四方的左上右上左下右下四个点
  62862. let pLT = u == 0 ? getPI(0,'top',i) : getSidePI(u-1, 'top',i);
  62863. let pRT = u == sideCount[i] ? getPI(count1-1,'top',j) : getSidePI(u, 'top',i);
  62864. let pLB = u == 0 ? getPI(0,'btm',i) : getSidePI(u-1, 'btm',i);
  62865. let pRB = u == sideCount[i] ? getPI(count1-1,'btm',j) : getSidePI(u, 'btm',i);
  62866. faceArr.push([pLT,pLB,pRB],[pLT,pRB,pRT]);//外侧四方面
  62867. faceArr.push([pLT,topCenter,pRT] ,[pLB,btmCenter,pRB] );//顶部和底部到整体中心的扇形(由于点的顺序是根据和两个pano的距离,因此到中心的夹角并没按顺序排列,所以可能会重叠)
  62868. if(i==0){//只需要算一次
  62869. //顶部和底部中心与两个pano边构成的三角形
  62870. if(u == 0){
  62871. faceArr.push([pLT,getPI(count1-1,'top',i),topCenter],
  62872. [pLB,getPI(count1-1,'btm',i),btmCenter],
  62873. );
  62874. }
  62875. //不能用else 因为当length==0时u==0也==sideCount[i],此时就是要两个面
  62876. if(u == sideCount[i]){
  62877. faceArr.push([pRT,getPI(0,'top',j),topCenter],
  62878. [pRB,getPI(0,'btm',j),btmCenter],
  62879. );
  62880. }
  62881. }
  62882. }
  62883. }
  62884. };
  62885. let posArr = [];
  62886. let faceArr = [];
  62887. //两点连线的水平向量
  62888. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  62889. /* let sideDis0 = */addPos(pano0, vec);
  62890. /* let sideDis1 = */addPos(pano1, vec.clone().negate());
  62891. addSide();
  62892. addFaces();
  62893. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  62894. let geo = MeshDraw.createGeometry(posArr, faceArr);
  62895. this.cube.geometry = geo;
  62896. this.cube.scale.set(1,1,1);
  62897. this.cube.position.set(0,0,0);
  62898. //this.cube.scale.set(100,100,100);
  62899. //this.cube.position.copy(pano1.position).multiplyScalar(-100)
  62900. }else {
  62901. useBound(pano0.pointcloud.bound);
  62902. }
  62903. }
  62904. /*
  62905. 注: 修改skybox,若不准的话,会遮住其他mesh,比如marker。尤其在没有深度贴图时。
  62906. */
  62907. /* updateCube(params){
  62908. let size = params.boundSize
  62909. this.cube.scale.set(Math.max(size.x, HighMapCubeWidth), Math.max(size.y, HighMapCubeWidth), Math.max(size.z, HighMapCubeWidth) )
  62910. this.cube.position.copy(params.center)
  62911. } */
  62912. bump(direction) {//撞墙弹回效果
  62913. if (!this.bumping && !this.latestToPano) {
  62914. let distance = Potree.settings.displayMode == 'showPanos' ? 0.3 : 0.2;//感觉点云模式比全景模式更明显,所以降低
  62915. let currentPos = this.position.clone();
  62916. let endPosition = new Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance));
  62917. let duration = 150;
  62918. viewer.scene.view.setView({position:endPosition, duration,
  62919. callback:()=>{
  62920. viewer.scene.view.setView({position:currentPos, duration: duration*5,
  62921. callback: ()=>{
  62922. this.bumping = false;
  62923. //this.dispatchEvent('cameraMoveDone')
  62924. },
  62925. Easing:'easeInOutSine',
  62926. cancelFun:()=>{this.bumping = false;}
  62927. });
  62928. this.bumping = true;
  62929. },
  62930. cancelFun:()=>{this.bumping = false;},
  62931. Easing:'easeInOutSine'
  62932. });
  62933. this.bumping = true;
  62934. }
  62935. //备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。
  62936. }
  62937. /* load(pano, ){
  62938. return new Promise(resolve => {
  62939. let texture = texLoader.load(pano.file, resolve);
  62940. texture.wrapS = THREE.RepeatWrapping;
  62941. texture.repeat.x = -1;
  62942. texture.flipY = false//add
  62943. pano.texture = texture;
  62944. //add
  62945. texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
  62946. texture.minFilter = THREE.LinearFilter;
  62947. texture.magFilter = THREE.LinearFilter;
  62948. texture.generateMipmaps = true;
  62949. });
  62950. } */
  62951. flyToPanoClosestToMouse() {
  62952. /* if (Date.now() - this.mouseLastMoveTime > 50) {
  62953. //this.intersect = this.getMouseIntersect();
  62954. this.intersect && this.updateClosestPano(this.intersect);
  62955. } */
  62956. if(!Potree.settings.ifShowMarker){//不显示marker的时候mousemove没更新鼠标最近点所以更新
  62957. this.updateClosestPano(viewer.inputHandler.intersect);
  62958. }
  62959. //console.log('flyToPanoClosestToMouse',this.closestPano)
  62960. if (this.closestPano) {
  62961. let pano = this.closestPano;
  62962. return this.flyToPano({
  62963. pano
  62964. });
  62965. }
  62966. var direction = this.viewer.inputHandler.getMouseDirection().direction;
  62967. this.flyDirection(direction);
  62968. }
  62969. flyDirection(direction, option1, option2) {
  62970. var deferred = $.Deferred();
  62971. //this.history.invalidate();
  62972. var panoSet = this.closestPanoInDirection(direction, option1, option2);
  62973. if (panoSet) {
  62974. this.flyToPano({
  62975. pano: panoSet,
  62976. callback: deferred.resolve.bind(deferred, !0)
  62977. } );
  62978. } else {
  62979. this.bump(direction);
  62980. deferred.resolve(!1);
  62981. }
  62982. return deferred.promise();
  62983. }
  62984. closestPanoInDirection(direction, option1, option2) {
  62985. return this.rankedPanoInDirection(0, direction, option1, option2)
  62986. }
  62987. rankedPanoInDirection(t, direction, option1, option2){
  62988. var panoSet = {
  62989. pano: null,
  62990. candidates: [] //缓存顺序--如果需要打印的话
  62991. };
  62992. t || (t = 0);
  62993. option1 = void 0 !== option1 ? option1 : .75;
  62994. var o = option2 ? "angle" : "direction";
  62995. var floor = viewer.modules.SiteModel.currentFloor;
  62996. var entity = viewer.modules.SiteModel.inEntity;
  62997. var getHeightDis = (pano)=>{
  62998. if(floor && !floor.panos.includes(pano) && pano.position.z < this.position.z){ //若是上方的漫游点,就正常走。因为一般不会点击天花板。
  62999. return this.position.z - pano.position.z
  63000. }else {
  63001. return 0
  63002. }
  63003. };
  63004. var request = [//必要条件
  63005. Images360.filters.inPanoDirection( this.position, direction, option1),
  63006. //Images360.filters.isNeighbourPanoTo(this.currentPano),
  63007. Images360.filters.not(this.currentPano),
  63008. Images360.filters.isEnabled(),
  63009. /* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。
  63010. let dis = getHeightDis(pano)
  63011. //console.log('getHeightDis',pano.id,dis)
  63012. if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行)
  63013. return true
  63014. }else{
  63015. return this.isNeighbour(this.currentPano, pano)
  63016. }
  63017. } */
  63018. ];
  63019. var list = [//决胜项目
  63020. Images360.scoreFunctions.distanceSquared(this.position,1, true),
  63021. Images360.scoreFunctions[o]( this.position, direction,true),
  63022. (pano)=>{
  63023. let neighbour = this.isNeighbour(this.currentPano, pano);
  63024. //console.log('neighbour', pano.id, neighbour ? directionFactor*0.4 : 0)
  63025. return neighbour ? directionFactor*1 : 0;
  63026. }
  63027. /* (pano)=>{//尽量不穿越地板到下一层
  63028. let dis = getHeightDis(pano)
  63029. return -dis * directionFactor * 0.1;
  63030. }, */
  63031. /* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙
  63032. if(entity && !entity.panos.includes(pano) ){
  63033. return - directionFactor * 0.05; //- directionFactor * 0.2;
  63034. }else{ //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外
  63035. return 0
  63036. }
  63037. } */
  63038. ];
  63039. if(viewer.inputHandler.intersectPoint && this.currentPano ){//方便上下楼, 考虑panos之间的角度差
  63040. let pos1 = this.currentPano.floorPosition;
  63041. let vec1 = new Vector3().subVectors(viewer.inputHandler.intersectPoint.location, pos1 ).normalize();//应该只有atPano时才会执行到这吧?
  63042. list.push( function(pano) {
  63043. var pos2 = pano.floorPosition;
  63044. var vec2 = pos2.clone().sub(pos1).normalize();
  63045. //console.log('direction2', pano.id, vec2.dot(vec1) * directionFactor * 1 );
  63046. return vec2.dot(vec1) * directionFactor * 1
  63047. });
  63048. }
  63049. this.findRankedByScore(t,request,list,panoSet);
  63050. return panoSet.pano;
  63051. }
  63052. findRankedByScore(e, t, i, n) {
  63053. n && (n.candidates = null, //candidates 缓存顺序--如果需要打印的话
  63054. n.pano = null),
  63055. e || (e = 0);
  63056. var r = Common.sortByScore(this.panos, t, i);
  63057. //console.log('findRankedByScore', r && r.map(u=>u.item.id + '|' + u.score))
  63058. return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r,
  63059. n.pano = r[e].item),
  63060. r[e].item)
  63061. }
  63062. isNeighbour(pano0, pano1){//是否之间没有遮挡(在加载visibles之前,自己算) 最好pano0是currentPano
  63063. if(!pano0 || !pano1)return
  63064. let map0 = this.neighbourMap[pano0.id];
  63065. if(!map0){
  63066. map0 = {};
  63067. this.neighbourMap[pano0.id] = map0;
  63068. }
  63069. let map1 = this.neighbourMap[pano1.id];
  63070. if(!map1){
  63071. map1 = {};
  63072. this.neighbourMap[pano1.id] = map1;
  63073. }
  63074. let ifNeighbour = map0[pano1.id];//map0.get(pano1)
  63075. if(ifNeighbour == void 0){
  63076. ifNeighbour = true;
  63077. let margin = 0.1;
  63078. let usePointcloud = pano0.depthTex;
  63079. if(pano0.depthTex || pano1.depthTex){
  63080. let mainPano = pano0.depthTex ? pano0 : pano1;
  63081. let subPano = pano0.depthTex ? pano1 : pano0;
  63082. //暂时只判断到pano,不判断到marker的方向
  63083. let dir = new Vector3().subVectors(subPano.position, mainPano.position).normalize();
  63084. let intersectPoint = viewer.images360.depthSampler.sample({dir}, mainPano, true);
  63085. if(intersectPoint && intersectPoint.distance+margin <= pano0.position.distanceTo(pano1.position)){
  63086. ifNeighbour = false;
  63087. }
  63088. }else {
  63089. //使用点云判断(有深度贴图时不会执行到这)
  63090. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect(pano1.position, margin, true, pano0.position);
  63091. console.log('使用点云判断');
  63092. if(ifNeighbour){//点云模式下未加载的点云会判断为true
  63093. let dir = new Vector3().subVectors(pano1.position,pano0.position).normalize();
  63094. let dis = pano1.position.distanceTo(pano0.position);
  63095. let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true );
  63096. let max = Math.cos(MathUtils.degToRad(10));
  63097. let min = Math.cos(MathUtils.degToRad(80));
  63098. if(this.getDirection().dot(dir) < MathUtils.clamp(Math.cos(hfov/2/* THREE.Math.degToRad(40) */) * dis / 10, min, max )){//距离越远要求和视线角度越接近
  63099. ifNeighbour = undefined; //不确定
  63100. }
  63101. }
  63102. }
  63103. map0[pano1.id] = ifNeighbour;//map0.set(pano1, ifNeighbour)
  63104. map1[pano0.id] = ifNeighbour;//map1.set(pano0, ifNeighbour)
  63105. }
  63106. return ifNeighbour
  63107. }
  63108. updateClosestPano(intersect, state) {//hover到的pano 大多数时候是null
  63109. /*
  63110. var pano
  63111. if(this.isAtPano() ){ //为什么之前Panorama要加这个限制?
  63112. if(intersect instanceof Panorama){
  63113. pano = state ? intersect : null
  63114. }else{
  63115. return
  63116. }
  63117. }else{
  63118. if(this.flying)return;
  63119. var filterFuncs = [];
  63120. intersect = intersect && intersect.location
  63121. if(!intersect)return
  63122. let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)]
  63123. pano = Common.find(this.panos, filterFuncs, sortFuncs);
  63124. }
  63125. */
  63126. var pano;
  63127. if(intersect instanceof Panorama){
  63128. pano = state ? intersect : null;
  63129. }else {
  63130. if(this.isAtPano()){
  63131. return
  63132. }else {
  63133. if(this.flying)return;
  63134. var filterFuncs = [];
  63135. intersect = intersect && intersect.location;
  63136. if(!intersect)return
  63137. let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)];
  63138. pano = Common.find(this.panos, filterFuncs, sortFuncs);
  63139. }
  63140. }
  63141. if (pano != this.closestPano) {
  63142. pano && (this.isPanoHover = !0);
  63143. this.closestPanoChanging(this.closestPano, pano); // 高亮marker
  63144. //console.log('closestPano '+ (pano ? pano.id : 'null' ))
  63145. this.closestPano = pano;
  63146. } else {
  63147. this.isPanoHover = !1;
  63148. }
  63149. }
  63150. closestPanoChanging(oldPano, newPano){
  63151. if(!Potree.settings.ifShowMarker)return
  63152. oldPano && oldPano.hoverOff({byImages360:true});
  63153. newPano && newPano.hoverOn({byImages360:true});
  63154. }
  63155. getTileDirection(){//根据不同dataset的来存储
  63156. var vectorForward = viewer.scene.view.direction.clone();
  63157. var vectorForwards = viewer.scene.pointclouds.map(e=>{
  63158. var inv = new Matrix4().copy(e.rotateMatrix).invert();//乘上dataset的旋转的反转
  63159. var direction = vectorForward.clone().applyMatrix4(inv);
  63160. return {
  63161. datasetId: e.dataset_id,
  63162. direction: math.convertVector.ZupToYup(direction)
  63163. }
  63164. });
  63165. //return vectorForwards[0].direction
  63166. return {
  63167. datasetsLocal: vectorForwards,
  63168. vectorForward
  63169. }
  63170. }
  63171. update(){
  63172. let {viewer} = this;
  63173. /* if(currentlyHovered){
  63174. currentlyHovered.material = sm;
  63175. currentlyHovered = null;
  63176. }
  63177. if(this.selectingEnabled){
  63178. this.handleHovering();
  63179. } */
  63180. if(this.tileDownloader.started){
  63181. var vectorForwards = this.getTileDirection();
  63182. //vectorForwards = vectorForwards[0].direction
  63183. this.updateTileDownloader(tileArr, vectorForwards);
  63184. this.updatePanoRenderer(vectorForwards);
  63185. }
  63186. this.updateZoomPano();
  63187. }
  63188. updateTileDownloader(t, vectorForward) {
  63189. var i = this.nextPano || this.currentPano;
  63190. if(i){
  63191. this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone() , vectorForward, t.length > 0 ? t : null),
  63192. this.tileDownloader.processPriorityQueue = !0;
  63193. }
  63194. }
  63195. updatePanoRenderer(vectorForward) {
  63196. var i = this.nextPano || this.currentPano;
  63197. if(i){
  63198. if (this.panoRenderer.hasQueuedTiles() && i) {
  63199. this.panoRenderer.updateDirection(vectorForward);
  63200. }
  63201. }
  63202. }
  63203. //等待部分加载完
  63204. checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) {
  63205. if (!pano) {
  63206. console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano.");
  63207. }
  63208. var vectorForward = this.getTileDirection();
  63209. if (!pano.isLoaded(basePanoSize)) {
  63210. iswait && viewer.waitForLoad(pano, function() {//发送loading
  63211. return pano.isLoaded(basePanoSize)
  63212. });
  63213. /* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。
  63214. hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ),
  63215. vFov: viewer.scene.getActiveCamera().fov
  63216. }//原先是null,不要求方向 */
  63217. var fov = null; //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办
  63218. pano.loadTiledPano(/* 1024 */ basePanoSize , vectorForward, fov, isclear, l, null).done(function(e, t) {
  63219. callback1 && callback1(e, t);
  63220. }
  63221. .bind(this)).fail(function(msg) {
  63222. callback2 && callback2(msg);
  63223. }
  63224. .bind(this)).progress(function(e, t, i) {
  63225. progressCallback && progressCallback(e, t, i);
  63226. }
  63227. .bind(this));
  63228. return !0;
  63229. }
  63230. }
  63231. /* load(){//quickstart里的
  63232. var lowSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE),
  63233. highSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD),
  63234. d = cameraLight.getHFOVForCamera(this.quickStartcamera, $('#player').width(), $('#player').height()),
  63235. p = this.quickStartcamera.fov,
  63236. r = Vectors.FORWARD.clone().applyQuaternion(this.view.quaternion)
  63237. var promise1 = this.view.pano.loadTiledPano(highSize, r, {
  63238. hFov: d,
  63239. vFov: p
  63240. }, !1, !1 , !0 )
  63241. var promise2 = this.view.pano.loadTiledPano(lowSize, r.clone().negate(), null, !1, !1, !0)
  63242. this.loadPromise = this.pano.hasVideo ? promise2 : promise1;
  63243. //this.loadPromise = promise1;
  63244. }
  63245. */
  63246. fitPanoTowardPoint(o){ //寻找最适合的点位
  63247. var point = o.point, //相机最佳位置
  63248. target = o.target, //实际要看的位置
  63249. require = o.require || [],
  63250. rank = o.rank || [],
  63251. force = o.force,
  63252. getAll = o.getAll,
  63253. bestDistance = o.bestDistance || 0;
  63254. let camera = viewer.scene.getActiveCamera();
  63255. if(target){
  63256. var vec = new Vector3().subVectors(target,point).normalize();
  63257. }
  63258. //if(o.floor)require.push(Panorama.filters.atFloor(o.floor))
  63259. if(o.boundSphere){//只接受boundSphere
  63260. let aspect = 1;//size.x / size.y
  63261. let dis;
  63262. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  63263. dis = /* size.y */o.boundSphere.radius/* / 2 *// MathUtils.degToRad(camera.fov / 2);
  63264. }else {
  63265. let hfov = cameraLight.getHFOVForCamera(camera , true );
  63266. dis = /* size.x */ o.boundSphere.radius /* / 2 */ / (hfov / 2);
  63267. }
  63268. bestDistance = dis;//*0.8
  63269. }
  63270. let bestDisSquared = bestDistance * bestDistance;
  63271. rank.push((pano)=>{
  63272. let dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置
  63273. if(!target){
  63274. return -dis1
  63275. }else {
  63276. let dis2 = pano.position.distanceToSquared(target); //距离目标点
  63277. let vec2 = new Vector3().subVectors(target,pano.position).normalize();
  63278. let cos = vec.dot(vec2);
  63279. let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2); // cos+2是为了调整到1-3, 尽量贴近最佳位置的角度;
  63280. //console.log(pano.id, dis1,dis2, cos, result)
  63281. return result
  63282. }
  63283. },(pano)=>{
  63284. if(pano.depthTex && o.checkIntersect){ //没加载好的话,不管了
  63285. let intersect = viewer.inputHandler.ifBlockedByIntersect(target, 0.1 , null, null, null, pano);
  63286. if(intersect){
  63287. //console.log('intersected', pano.id )
  63288. return -10000
  63289. }else return 0
  63290. }else return 0
  63291. });
  63292. /* var temp = {position:point}
  63293. rank.push(Panorama.scoreFunctions.distanceSquared(temp, -2)); */
  63294. var g = Common.sortByScore(this.panos, require, rank);
  63295. if(getAll)return g;
  63296. return g && g.length > 0 && g[0].item
  63297. }
  63298. //---------------scroll zoom ------------------------------------------
  63299. /* zoomIn = function() { //放大
  63300. this.zoomBy(1 + this.zoomSpeed);
  63301. }
  63302. zoomOut = function() {//缩小
  63303. this.zoomBy(1 - this.zoomSpeed);
  63304. } */
  63305. zoomBy(e, pointer) {//以倍数
  63306. this.zoomTo(this.zoomLevel * e, pointer);
  63307. }
  63308. zoomTo(zoomLevel, pointer) {//缩放到某绝对zoomLevel
  63309. let zoom = Potree.settings.zoom;
  63310. if (zoom.enabled) {
  63311. zoomLevel = MathUtils.clamp(zoomLevel, zoom.min, zoom.max);
  63312. //console.log(zoomLevel)
  63313. if(zoomLevel == this.zoomLevel) return;
  63314. /* if (zoomLevel > this.zoomLevel) {
  63315. this.emit(ZoomEvents.ZoomIn);
  63316. zoomLevel === settings.zoom.max && this.emit(ZoomEvents.ZoomMax);
  63317. } else if (zoomLevel < this.zoomLevel) {
  63318. this.emit(ZoomEvents.ZoomOut);
  63319. zoomLevel === settings.zoom.min && this.emit(ZoomEvents.ZoomMin);
  63320. } */
  63321. this.zoomLevel = zoomLevel;
  63322. //定点缩放:使当前鼠标所在的位置缩放后不变
  63323. let view = viewer.scene.view;
  63324. let originDir = viewer.scene.view.direction;
  63325. let oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  63326. viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel));
  63327. let newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  63328. view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch
  63329. let oldPitch = view.pitch, oldYaw = view.yaw;
  63330. view.direction = newPointerDir;
  63331. let newPitch = view.pitch, newYaw = view.yaw;
  63332. view.direction = originDir; //还原
  63333. viewer.scene.view.pitch -= newPitch - oldPitch;
  63334. viewer.scene.view.yaw -= newYaw - oldYaw;
  63335. }
  63336. }
  63337. zoomFovTo( fov ) { //通过fov来算zoomLevel
  63338. let zoomLevel = this.baseFov / fov;
  63339. this.zoomTo( zoomLevel );
  63340. }
  63341. smoothZoomTo(aimLevel, dur=0) {
  63342. var currentLevel = this.zoomLevel;
  63343. if(currentLevel == aimLevel)return;
  63344. var fun = (progress)=>{
  63345. //progress > 1 && (progress = 1)
  63346. let level = currentLevel * (1 - progress) + aimLevel * progress;
  63347. this.zoomTo(level, !0);
  63348. };
  63349. transitions.start(fun, dur, null, null, 0 , easing['easeInOutQuad'] );
  63350. }
  63351. /* zoomDefault{
  63352. this.zoomTo(1, !0)
  63353. }
  63354. smoothZoomToDefault(e, t) {
  63355. var i, n = this.zoomLevel,
  63356. r = function(e) {
  63357. e > 1 && (e = 1),
  63358. i = n * (1 - e) + e,
  63359. this.zoomTo(i, !0)
  63360. }
  63361. .bind(this),
  63362. o = function() {
  63363. this.zoomDefault(),
  63364. t && window.setTimeout(t, 50)
  63365. }
  63366. .bind(this);
  63367. transitions.start(r, e, o, null, 0, easing[settings.transition.blendEasing])
  63368. } */
  63369. updateZoomPano() {
  63370. if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') {
  63371. var currentPano = this.currentPano;
  63372. if (currentPano) {
  63373. var activationThreshold = Potree.settings.navTileClass == '2k' && Potree.settings.tileClass == '4k' ? 1.7 : Potree.settings.zoom.activationThreshold;//1.1
  63374. var t = this.zoomLevel > activationThreshold,
  63375. n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano),
  63376. r = t && n;
  63377. this.tileDownloader.tilePrioritizer.setZoomingActive(r);
  63378. this.panoRenderer.setZoomingActive(r, currentPano, !0);
  63379. var o = (pano, zoomedFlag)=>{
  63380. this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize());
  63381. this.panoRenderer.clearAllQueuedUploadsForPano(pano.id);
  63382. this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1);
  63383. pano.setZoomed(zoomedFlag);
  63384. };
  63385. if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) {
  63386. currentPano.zoomed || o(currentPano, !0);
  63387. if(Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < 2){
  63388. this.panoRenderer.enableHighQuality( function() {//开启2k
  63389. if(Potree.settings.tileClass != '4k') o(currentPano, !0);
  63390. }.bind(this));
  63391. }else {
  63392. this.panoRenderer.enableUltraHighQualityMode(function() {//开启4k getMaxZoomPanoSize
  63393. this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom);
  63394. o(currentPano, !0);
  63395. }.bind(this));
  63396. }
  63397. } else {
  63398. !t && currentPano.zoomed && o(currentPano, !1);
  63399. }
  63400. if(r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k' ){ //目前只有手机端navTileClass == '1k'
  63401. var change = (zoomedFlag)=>{
  63402. this.qualityManager.updateMaximums();//更新maxZoomPanoSize
  63403. this.panoRenderer.setupZoomRenderTarget(); //更新renderTarget
  63404. //currentPano.setZoomed(t);//更新uniforms贴图
  63405. };
  63406. this.qualityManager.zoomLevelResolution = this.zoomLevel >= 2 ? '4k' : this.zoomLevel > 1.1 ? '2k' : '1k';
  63407. if(this.oldZoomLevel < 2 && this.zoomLevel >= 2){//1k/2k-4k
  63408. change();
  63409. o(currentPano, t);
  63410. }else if(this.oldZoomLevel <= Potree.settings.zoom.activationThreshold && this.zoomLevel > Potree.settings.zoom.activationThreshold){//1k-2k
  63411. change();
  63412. }else if(this.oldZoomLevel > 2 && this.zoomLevel <= 2){//4k-2k/1k
  63413. change();
  63414. o(currentPano, t);
  63415. }else if(this.oldZoomLevel > Potree.settings.zoom.activationThreshold && this.zoomLevel <= Potree.settings.zoom.activationThreshold){//2k-1k
  63416. change();
  63417. }
  63418. this.oldZoomLevel = this.zoomLevel;
  63419. }
  63420. }
  63421. }
  63422. }
  63423. //--------------------
  63424. addHighMapCube(){//创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize
  63425. if( Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048){
  63426. var geo = new PlaneGeometry(1, 1, 1, 1);
  63427. var cube = new Object3D;
  63428. for(var cubeIndex=0; cubeIndex<6; cubeIndex++){
  63429. var face = new Object3D;
  63430. for(var i=0;i<8;i++){
  63431. for(var j=0;j<8;j++){
  63432. var tile = new Mesh(geo, new MeshBasicMaterial({
  63433. //side:THREE.DoubleSide
  63434. }));
  63435. tile.position.set(i-3.5, j-3.5, -4);
  63436. tile.material.opacity = 0.4;
  63437. tile.material.transparent = true;
  63438. if(Potree.settings.isTest){
  63439. var colorHue = Math.random();
  63440. tile.material.color = (new Color()).setHSL(colorHue, 0.5, 0.9);
  63441. }
  63442. tile.visible = false;
  63443. face.add(tile);
  63444. }
  63445. }
  63446. switch(cubeIndex){
  63447. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  63448. face.rotation.set(0,Math.PI/2,0);
  63449. break;
  63450. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  63451. face.rotation.set(0,-Math.PI/2,0);
  63452. break;
  63453. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  63454. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  63455. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),Math.PI/2);
  63456. face.quaternion.copy(rot1).multiply(rot2);
  63457. //face.rotation.set(Math.PI/2,0,0);
  63458. break;
  63459. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  63460. //face.rotation.set(-Math.PI/2,0,0);
  63461. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  63462. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),-Math.PI/2);
  63463. face.quaternion.copy(rot1).multiply(rot2);
  63464. break;
  63465. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  63466. face.rotation.set(0,Math.PI,0);
  63467. break;
  63468. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  63469. face.rotation.set(0,0,0);
  63470. }
  63471. face.scale.set(1,-1,1);
  63472. cube.add(face);
  63473. }
  63474. cube.name = 'highMapCube';
  63475. this.highMapCube = cube;
  63476. viewer.scene.scene.add(cube);
  63477. //cube.scale.set(0.01,0.01,0.01)
  63478. this.highMapCube.visible = false;
  63479. viewer.setObjectLayers(this.highMapCube, 'sceneObjects'/* 'skybox' */); //如果是skybox层,点云可见时会被遮住,depthTest为false呢? 但不会遮住场景物体
  63480. //console.warn('addHighMapCube')
  63481. }
  63482. }
  63483. isHighMapLoaded( cubeFace, tileX, tileY){
  63484. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  63485. return !!tile.material.map
  63486. }
  63487. updateHighMap(tex, cubeFace, tileX, tileY){
  63488. //console.warn('updateHighMap')
  63489. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  63490. tile.material.map = tex;
  63491. tile.material.opacity = 1;
  63492. tile.material.transparent = false;
  63493. tile.visible = true;
  63494. tile.material.needsUpdate = true; //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载
  63495. }
  63496. resetHighMap(){
  63497. if(!this.highMapCube) return
  63498. //console.warn('resetHighMap')
  63499. this.highMapCube.children.forEach(e=>e.children.forEach(tile=>{
  63500. if(tile.material.map){
  63501. tile.material.map.dispose();
  63502. tile.material.map.loaded = !1;
  63503. tile.material.map.version = 0;
  63504. var h = viewer.renderer.properties.get(tile.material.map);
  63505. viewer.renderer.getContext().deleteTexture(h.__webglTexture);
  63506. //类似app.sceneRenderer.deallocateCubeTexture(tile.material.map)
  63507. tile.material.map = null;
  63508. /* tile.material.opacity = 0.4;
  63509. tile.material.transparent = true */
  63510. tile.material.needsUpdate = true;
  63511. tile.visible = false;
  63512. }
  63513. }));
  63514. this.highMapCube.visible = false;
  63515. }
  63516. setHighMap(pano){
  63517. if(!this.highMapCube) return
  63518. this.highMapCube.position.copy(pano.position);
  63519. //可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的
  63520. this.highMapCube.quaternion.copy( math.convertQuaternion.YupToZup( pano.quaternion4dkk ) );
  63521. //乘上数据集整体的旋转:
  63522. let modelRotQua = new Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix);
  63523. this.highMapCube.quaternion.premultiply(modelRotQua);
  63524. }
  63525. showHighMap(){
  63526. if(!this.highMapCube) return
  63527. //console.warn('showHighMap')
  63528. this.highMapCube.visible = true;
  63529. }
  63530. hideHighMap(){
  63531. if(!this.highMapCube) return
  63532. //console.warn('hideHighMap')
  63533. this.highMapCube.visible = false;
  63534. }
  63535. //缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示???
  63536. addPanoData(data, datasetId ){
  63537. //data[0].file_id = '00019'
  63538. if(data.data) data = data.data;
  63539. if(data.length == 0)console.error(datasetId + ' 没有漫游点');
  63540. //data = data.sort(function(a,b){return a.id-b.id})
  63541. data.forEach((info)=>{
  63542. //if(Potree.fileServer){
  63543. info.id = this.panos.length; //把info的id的一长串数字改简单点
  63544. //}
  63545. let pano = new Panorama( info, this );
  63546. /* pano.mesh.layers.set(Potree.config.renderLayers.marker)
  63547. pano.marker.layers.set(Potree.config.renderLayers.marker) */
  63548. pano.addEventListener('dispose',(e)=>{
  63549. if(this.closestPano == pano) this.closestPano = null;
  63550. });
  63551. this.panos.push(pano);
  63552. if(Potree.settings.editType == 'pano'){
  63553. Potree.settings.datasetsPanos[datasetId].panos.push(pano);
  63554. }
  63555. });
  63556. }
  63557. loadDone(){
  63558. viewer.setObjectLayers(this.node, 'sceneObjects');
  63559. //this.updateCube(/* viewer.bound */)
  63560. this.panos.forEach(e=>{
  63561. e.label && viewer.setObjectLayers(e.label, 'bothMapAndScene');
  63562. });
  63563. this.tileDownloader.setPanoData(this.panos, [] /* , Potree.settings.number */);
  63564. {
  63565. /* var panosBound = new THREE.Box3
  63566. this.panos.forEach(pano=>{
  63567. panosBound.expandByPoint(pano.position)
  63568. })
  63569. let center = panosBound.getCenter(new THREE.Vector3)
  63570. let minBound = (new THREE.Box3()).setFromCenterAndSize(center, new THREE.Vector3(1,1,1))
  63571. panosBound.union(minBound)
  63572. this.bound = {
  63573. bounding:panosBound,
  63574. size: panosBound.getSize(new THREE.Vector3),
  63575. center,
  63576. } */
  63577. let minSize = new Vector3(1,1,1);
  63578. this.bound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  63579. viewer.scene.pointclouds.forEach(pointcloud=>pointcloud.getPanosBound());
  63580. }
  63581. if(viewer.scene.pointclouds.some(e=>e.panos.length == 0)){
  63582. //console.warn('存在数据集没有pano');
  63583. viewer.hasNoPanoDataset = true;
  63584. }
  63585. }
  63586. getPano(value, typeName='id'){ //默认找的是id,也可以是sid、uuid
  63587. return this.panos.find(p=>p[typeName] == value)
  63588. }
  63589. };
  63590. //判断当前点是否加载了全景图
  63591. Images360.prototype.checkAndWaitForPanoLoad = function() {
  63592. var isLoadedPanos = {},
  63593. LoadedTimePanos = {},
  63594. loadedCallback = {}, //add
  63595. maxTime = 5e3;
  63596. var withinTime = function() {
  63597. for (var panoId in isLoadedPanos)
  63598. if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) {
  63599. var differTime = performance.now() - LoadedTimePanos[panoId];
  63600. if (differTime < maxTime)
  63601. return !0
  63602. }
  63603. return !1
  63604. };
  63605. return function(pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p ) {
  63606. loadedCallback[pano.id] = doneFun1;//add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1
  63607. if (withinTime()){//距离上次请求时间很近
  63608. return !0; //这里感觉应该是!1
  63609. }
  63610. var callback1 = (param1, param2)=>{
  63611. setTimeout(()=>{
  63612. isLoadedPanos[pano.id] = !1;
  63613. loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2);
  63614. },1);
  63615. };
  63616. var callback2 = (param)=>{//没有看到有传doneFun2的
  63617. setTimeout(()=>{
  63618. isLoadedPanos[pano.id] = !1;
  63619. doneFun2 && doneFun2(param);
  63620. },1);
  63621. };
  63622. try {
  63623. null !== iswait && void 0 !== iswait || (iswait = !0);
  63624. isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p );
  63625. //true代表没加载好
  63626. isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now());
  63627. return isLoadedPanos[pano.id];
  63628. } catch (msg) {
  63629. isLoadedPanos[pano.id] = !1;
  63630. LoadedTimePanos[pano.id] = performance.now() - maxTime;
  63631. throw msg;
  63632. }
  63633. }
  63634. }();
  63635. Images360.filters = {
  63636. inPanoDirection : function(pos, dir, i) {
  63637. return function(pano) {
  63638. var r = pano.floorPosition.clone().sub(pos).normalize();
  63639. var o = pano.position.clone().sub(pos).normalize();
  63640. return r.dot(dir) > i || o.dot(dir) > i
  63641. }
  63642. },
  63643. inFloorDirection: function(pos, e, o) {//许钟文 改 for鱼眼
  63644. return function(n) {
  63645. var i = n.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动
  63646. return i.dot(e) > o
  63647. }
  63648. },
  63649. isNotBehindNormal: function(e, t) {
  63650. var i = new Vector3;
  63651. return t = t.clone(),
  63652. function(n) {
  63653. var r = i.copy(n.position).sub(e).normalize();
  63654. return r.dot(t) > 0
  63655. }
  63656. },
  63657. isCloseEnoughTo: function(e, t) {
  63658. return function(i) {//因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近)
  63659. return e.distanceTo(i.floorPosition) < t //许钟文
  63660. }
  63661. },
  63662. not: function(e) {
  63663. return function(t) {
  63664. return t !== e
  63665. }
  63666. } ,
  63667. isEnabled:function() {
  63668. return function(t) {
  63669. return t.enabled
  63670. }
  63671. },
  63672. isVisible:function() {
  63673. return function(t) {
  63674. return t.visible
  63675. }
  63676. }
  63677. };
  63678. Images360.scoreFunctions = {
  63679. direction: function(curPos, dir, ifLog) {
  63680. return function(pano) {
  63681. var pos1 = /* pano.floorPosition */ pano.position; //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到
  63682. var n = pos1.clone().sub(curPos).normalize();
  63683. //ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor )
  63684. return n.dot(dir) * directionFactor
  63685. }
  63686. },
  63687. distanceSquared: function(pos1, r, ifLog) {
  63688. if(pos1.position)pos1 = pos1.position;
  63689. return function(pano) {//许钟文 改
  63690. var pos2 = pano.position.clone();
  63691. //ifLog && console.log('distanceSquared', pano.id, pos1.distanceToSquared(pos2) * -1 )
  63692. return pos1.distanceToSquared(pos2) * -1 * r;
  63693. }
  63694. },
  63695. angle: function(e, t) {
  63696. return function(i) {
  63697. var n = i.position.clone().sub(e).normalize();
  63698. return n.angleTo(t) * Potree.config.navigation.angleFactor
  63699. }
  63700. },
  63701. };
  63702. Images360.sortFunctions = {//排序函数,涉及到两个item相减
  63703. floorDisSquaredToPoint: function(e) {
  63704. return function(t, i) {
  63705. return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e)
  63706. }
  63707. },
  63708. disSquaredToPoint: function(e) {
  63709. return function(t, i) {
  63710. return t.position.distanceToSquared(e) - i.position.distanceToSquared(e)
  63711. }
  63712. },
  63713. };
  63714. /* var centerCross = new THREE.Mesh(new THREE.SphereGeometry(1, 4, 4),new THREE.MeshBasicMaterial({
  63715. transparent:true, color:"#ff0000", opacity:0.5
  63716. })); */
  63717. /* const mapHeight = -1000;//要比点云低。最低
  63718. const cameraHeight = 1000; //最高 */
  63719. const panosHeight = config$1.map.mapHeight + 100; //要比点云低 (marker)
  63720. const cursorHeight = 0;//比地图高就行
  63721. const routeLayerHeight = config$1.map.mapHeight + 105;
  63722. const texLoader$4 = new TextureLoader();
  63723. const planeGeo$2 = new PlaneBufferGeometry(1,1);
  63724. const markerSize = 1;
  63725. var initCameraFeildWidth = 50;
  63726. var panoMarkerMats;
  63727. class MapViewer extends ViewerBase{
  63728. constructor(dom){
  63729. super(dom, {
  63730. clearColor: Potree.config.mapBG,
  63731. name: 'mapViewer'
  63732. });
  63733. this.visible = true;
  63734. this.initScene();
  63735. this.mapLayer = new MapLayer(this, this.viewports[0]);
  63736. this.scene.add(this.mapLayer.sceneGroup);
  63737. this.mapLayer.sceneGroup.position.setZ(Potree.config.map.mapHeight);
  63738. this.mapRatio = 0.5;
  63739. this.splitDir = 'leftRight';
  63740. //this.scene.add(centerCross)
  63741. viewer.addEventListener("camera_changed", (e)=>{
  63742. if(e.viewport == viewer.mainViewport) this.updateCursor();
  63743. else this.updateWhenAtViewer();
  63744. });
  63745. //viewer.addEventListener("global_mousemove", this.updateWhenAtViewer.bind(this)) //鼠标移动时reticule也动,所以直接就needRender
  63746. viewer.reticule.addEventListener('update',(e)=>{
  63747. if(this.attachedToViewer)this.needRender = true;
  63748. });
  63749. viewer.scene.addEventListener("360_images_added", this.addPanos.bind(this));
  63750. viewer.addEventListener("loadPointCloudDone", this.initProjection.bind(this));
  63751. this.addEventListener('global_click',(e)=>{
  63752. if(!e.isTouch && e.button != MOUSE.LEFT)return
  63753. this.updateClosestPano(e.intersect);
  63754. });
  63755. this.addEventListener('add',(e)=>{//添加其他mesh
  63756. this.scene.add(e.object);
  63757. if(e.name == 'route'){
  63758. e.object.position.z = routeLayerHeight;
  63759. }
  63760. viewer.setObjectLayers(e.object, 'mapObjects' );
  63761. });
  63762. if(!Potree.settings.isOfficial){
  63763. let domRoot = viewer.renderer.domElement.parentElement;
  63764. let elAttach = $("<input type='button' value='map绑定'></input>");
  63765. elAttach.css({
  63766. position : "absolute",
  63767. right : '80%',
  63768. bottom: '20px',
  63769. zIndex: "10000",
  63770. fontSize:'1em', color:"black",
  63771. background:'rgba(255,255,255,0.8)',
  63772. });
  63773. let state = false;
  63774. elAttach.on("click", () => {
  63775. state = !state;
  63776. this.attachToMainViewer(state, 'measure');
  63777. elAttach.val(state ? 'map分离':'map绑定');
  63778. });
  63779. domRoot.appendChild(elAttach[0]);
  63780. }
  63781. }
  63782. waitLoadDone(callback){//确保加载完后执行
  63783. if(this.mapLayer.loadingInProgress == 0){
  63784. callback();
  63785. }else {
  63786. var f = ()=>{
  63787. callback();
  63788. this.mapLayer.removeEventListener('loadDone', f);
  63789. };
  63790. this.mapLayer.addEventListener('loadDone', f);
  63791. }
  63792. }
  63793. addListener(images360){
  63794. images360.addEventListener('flyToPano',e=>{
  63795. let toPano = e.toPano;
  63796. if(toPano.dontMoveMap) return
  63797. /* transitions.start(lerp.vector(this.view.position, toPano.pano.position.clone().setZ(cameraHeight),
  63798. (pos, progress)=>{
  63799. }), toPano.duration, null, 0, easing[toPano.easeName] ); */
  63800. let boundSize;// = new THREE.Vector2(10,10)
  63801. this.moveTo(toPano.pano.position.clone().setZ(Potree.config.map.cameraHeight), boundSize, toPano.duration, toPano.easeName);
  63802. });
  63803. }
  63804. initProjection(){
  63805. this.started = true;
  63806. this.mapLayer.initProjection();
  63807. }
  63808. initScene(){
  63809. let w = initCameraFeildWidth;
  63810. let width = this.renderArea.clientWidth;
  63811. let height = this.renderArea.clientHeight;
  63812. //let aspect = width / height
  63813. 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);
  63814. this.camera.zoom = width / w; //zoom越大视野越小
  63815. //this.camera.position.set(0,0,10);
  63816. this.camera.up.set(0,0,1);
  63817. //this.camera.lookAt(new THREE.Vector3())
  63818. //this.camera.updateMatrixWorld()
  63819. this.view = new View();
  63820. this.view.position.set(0,0,Potree.config.map.cameraHeight);
  63821. this.view.lookAt(0,0,0);
  63822. this.setViewLimit('standard');
  63823. let viewport = new Viewport( this.view, this.camera, {
  63824. left:0, bottom:0, width:1, height: 1, name:'mapViewport'
  63825. });
  63826. viewport.axis = ["x","y"];
  63827. viewport.axisSign = [1,1];
  63828. viewport.noPointcloud = true; //不要渲染点云
  63829. viewport.render = this.render.bind(this);//标志给mainView渲染
  63830. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  63831. this.viewports = [viewport];
  63832. this.controls = new FirstPersonControls(this, this.viewports[0]);
  63833. this.controls.setEnable(true);
  63834. this.scene = new Scene();
  63835. this.inputHandler = new InputHandler(this, this.scene);
  63836. this.inputHandler.name = 'mapInputHandler';
  63837. //this.inputHandler.addInputListener(this.controls);
  63838. this.inputHandler.registerInteractiveScene(this.scene);//interactiveScenes
  63839. this.viewports[0].interactiveScenes = this.inputHandler.interactiveScenes;//供viewer的inputHandler使用
  63840. var cursor = new Mesh(planeGeo$2, new MeshBasicMaterial({
  63841. transparent:true,
  63842. opacity:0.9,
  63843. depthTest : false, //防止透明冲突
  63844. map: texLoader$4.load(Potree.resourcePath+'/textures/pic_location128.png' )
  63845. }));
  63846. cursor.position.set(0,0,cursorHeight);
  63847. this.cursor = cursor;
  63848. this.scene.add(cursor);
  63849. viewer.setObjectLayers(this.scene, 'mapObjects' );
  63850. }
  63851. setViewLimit(state){//设置边界,当编辑空间模型等时要解禁
  63852. let setting = Potree.config.OrthoCameraLimit[state];
  63853. if(setting){
  63854. this.view.limitBound = new Box3().copy(setting.posBound);
  63855. this.camera.zoomLimit = $.extend({},setting.zoom);
  63856. }else {
  63857. this.view.limitBound = null;
  63858. this.camera.zoomLimit = null;
  63859. }
  63860. }
  63861. updateCursor(){
  63862. var scale = math.getScaleForConstantSize( {//规定下最小最大像素
  63863. minSize : 80, maxSize : 200, nearBound : initCameraFeildWidth*0.1 , farBound : initCameraFeildWidth*2,
  63864. camera:this.camera , position: this.cursor.getWorldPosition(new Vector3()),
  63865. resolution: this.viewports[0].resolution//2
  63866. });
  63867. this.cursor.scale.set(scale, scale, scale);//当地图缩放时
  63868. this.cursor.position.copy(viewer.mainViewport.camera.position).setZ(cursorHeight);//当场景镜头旋转移动时
  63869. this.cursor.rotation.z = viewer.mainViewport.view.yaw;
  63870. this.needRender = true;
  63871. }
  63872. addPanos(e){
  63873. var panosGroup = new Object3D;
  63874. panoMarkerMats = {
  63875. default: new MeshBasicMaterial({
  63876. transparent:true,
  63877. opacity: 0.5,
  63878. map: texLoader$4.load(Potree.resourcePath+'/textures/map_marker.png' ),
  63879. }),
  63880. selected: new MeshBasicMaterial({
  63881. transparent:true,
  63882. opacity: 1,
  63883. map: texLoader$4.load(Potree.resourcePath+'/textures/map_marker.png' ),
  63884. })
  63885. };
  63886. e.images.panos.forEach(pano=>{
  63887. pano.mapMarker = new Mesh(planeGeo$2, panoMarkerMats.default);
  63888. pano.mapMarker.position.copy(pano.position).setZ(0);
  63889. pano.mapMarker.scale.set(markerSize,markerSize,markerSize);
  63890. pano.mapMarker.name = 'mapMarker';
  63891. panosGroup.add(pano.mapMarker);
  63892. let mouseover = (e)=>{
  63893. if(!e.byMap){
  63894. pano.mapMarker.material = panoMarkerMats.selected;
  63895. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true});
  63896. this.needRender = true;
  63897. }
  63898. };
  63899. let mouseleave = (e)=>{
  63900. if(!e.byMap){
  63901. pano.mapMarker.material = panoMarkerMats.default;
  63902. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true});
  63903. this.needRender = true;
  63904. }
  63905. };
  63906. pano.mapMarker.addEventListener('mouseover', mouseover);
  63907. pano.mapMarker.addEventListener('mouseleave', mouseleave);
  63908. pano.addEventListener('hoverOn', mouseover);
  63909. pano.addEventListener('hoverOff', mouseleave);
  63910. let onclick = (e)=>{
  63911. viewer.images360.flyToPano(pano);
  63912. };
  63913. pano.mapMarker.addEventListener('click', onclick);
  63914. pano.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  63915. //console.log('panoMarker isVisible', pano.id, e.visible)
  63916. viewer.updateVisible(pano.mapMarker, 'panoVisible', e.visible );
  63917. this.needRender = true;
  63918. });
  63919. pano.addEventListener('rePos',(e)=>{
  63920. pano.mapMarker.position.copy(pano.position).setZ(0);
  63921. });
  63922. });
  63923. this.scene.add(panosGroup);
  63924. panosGroup.position.z = panosHeight;
  63925. this.panosGroup = panosGroup;
  63926. viewer.setObjectLayers(panosGroup, 'mapObjects' );
  63927. /* e.images.on('markersDisplayChange', (show)=>{
  63928. panosGroup.visible = show
  63929. this.needRender = true
  63930. }) */
  63931. //-------
  63932. //this.fitPanosToViewport()
  63933. this.initFitView();
  63934. }
  63935. updateClosestPano(intersect){
  63936. if(viewer.images360.flying)return;
  63937. intersect = intersect && intersect.orthoIntersect;
  63938. if(!intersect)return
  63939. intersect = intersect.clone().setZ(0);
  63940. const minDis = 20; //距离鼠标不能太远
  63941. var filterFuncs = [
  63942. (pano)=>{
  63943. return pano.position.clone().setZ(0).distanceTo(intersect) < minDis
  63944. },
  63945. Images360.filters.isEnabled(),
  63946. Images360.filters.isVisible(),//只走显示的点,否则会走到别的层
  63947. ];
  63948. var pano = Common.find(viewer.images360.panos, filterFuncs, [Images360.sortFunctions.floorDisSquaredToPoint(intersect)]);
  63949. if (pano && pano != viewer.images360.currentPano ) {
  63950. viewer.images360.flyToPano(pano);
  63951. }
  63952. }
  63953. fitPanosToViewport(){//使所有漫游点占满viewport
  63954. //var w = viewer.bound.boundSize.x;
  63955. var boundSize = viewer.images360.bound.size.clone().multiplyScalar(1.1);
  63956. boundSize.max(new Vector3(4,4,4));
  63957. let endPosition = viewer.images360.bound.center.clone();
  63958. this.moveTo(endPosition, boundSize, 0);
  63959. }
  63960. fitToPointcloud(pointcloud, duration=400){
  63961. var boundSize = pointcloud.bound.getSize(new Vector3);/* .multiplyScalar(1.1); */
  63962. boundSize.max(new Vector3(4,4,4));
  63963. let endPosition = pointcloud.bound.getCenter(new Vector3);
  63964. this.moveTo(endPosition, boundSize, duration); //给点duration去变化 否则地图放大后所占的还是很小
  63965. }
  63966. initFitView(){
  63967. let dis = 5 , px = 70; //地图上px像素长度代表的距离为dis //px是手动缩放到5m后发现是这个长度
  63968. let zoom = px / dis;
  63969. this.camera.zoom = zoom;
  63970. this.moveTo(viewer.images360.position/* viewer.images360.bound.center */);
  63971. this.camera.updateProjectionMatrix();
  63972. }
  63973. fitToDatasets(datasets){
  63974. let bound = new Box3;
  63975. datasets.forEach(e=>bound.union(e.bound));
  63976. let center = bound.getCenter(new Vector3);
  63977. let size = bound.getSize(new Vector3);
  63978. this.moveTo(center, size, 200 ); //给duration是为了顺应视口大小改变,缓冲
  63979. }
  63980. moveTo(endPosition, boundSize, duration=0, easeName){//前两个参数有xy即可
  63981. endPosition = new Vector3(endPosition.x,endPosition.y,Potree.config.map.cameraHeight);
  63982. this.view.moveOrthoCamera(this.viewports[0], {endPosition, boundSize }, duration, easeName);
  63983. /* let endZoom, startZoom = this.camera.zoom
  63984. //修改相机为bound中心,这样能看到全部(宽度范围内)
  63985. this.view.setView({ position:endPosition, duration,
  63986. callback:()=>{//done
  63987. },
  63988. onUpdate:(progress)=>{
  63989. if(boundSize){
  63990. let aspect = boundSize.x / boundSize.y
  63991. let w, h;
  63992. if(this.camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  63993. h = boundSize.y
  63994. //w = h * this.camera.aspect
  63995. endZoom = this.viewports[0].resolution.y / h
  63996. }else{
  63997. w = boundSize.x;
  63998. //h = w / this.camera.aspect
  63999. endZoom = this.viewports[0].resolution.x / w
  64000. }
  64001. //onUpdate时更新endzoom是因为画布大小可能更改
  64002. this.camera.zoom = endZoom * progress + startZoom * (1 - progress)
  64003. this.camera.updateProjectionMatrix()
  64004. }
  64005. },
  64006. Easing:easeName
  64007. }) */
  64008. }
  64009. updateWhenAtViewer(e){
  64010. if(this.attachedToViewer){
  64011. if(this.started) this.mapLayer.update();
  64012. this.updateCursor();
  64013. this.needRender = true;
  64014. }
  64015. }
  64016. update(delta, areaSize ){
  64017. if(!this.visible && !this.attachedToViewer )return
  64018. if(this.attachedToViewer){
  64019. if(this.mapLayer.needUpdate){//必须更新。(较少触发)
  64020. this.updateWhenAtViewer();
  64021. }
  64022. return
  64023. }
  64024. this.updateScreenSize();
  64025. this.controls.update(delta);
  64026. this.view.applyToCamera(this.camera);
  64027. let changed = this.cameraChanged();
  64028. if(this.started && (changed || this.mapLayer.needUpdate))this.mapLayer.update();
  64029. if(changed /*|| || this.needRender */){
  64030. this.dispatchEvent({
  64031. type: "camera_changed",
  64032. camera: this.camera,
  64033. viewport : this.viewports[0]
  64034. });
  64035. this.needRender = true;
  64036. this.updateCursor();//更改大小
  64037. }
  64038. this.render();
  64039. }
  64040. attachToMainViewer(state, desc, mapRatio=0.5, options={}){//转移到viewer中。测量时展示or截图需要
  64041. if(!Potree.settings.isOfficial)this.renderArea.style.display = state ? 'none':'block';
  64042. if(state){
  64043. this.enabledOld = this.enabled;
  64044. this.enabled = true;
  64045. if(mapRatio != 'dontSet'){
  64046. this.changeSplitScreenDir(options.dir, mapRatio);
  64047. if(this.attachedToViewer){
  64048. //this.fitPanosToViewport()
  64049. viewer.updateScreenSize({forceUpdateSize:true});
  64050. return
  64051. }
  64052. viewer.viewports = [viewer.mainViewport, viewer.mapViewer.viewports[0] ];//因为mainViewer的相机变化会触发map的变化,所以先渲染mainViewer
  64053. }
  64054. if(desc == 'measure') this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene);//虽然用的是viewer的inputHandler,但借用了this.inputHandler的interactiveScenes
  64055. else if(desc == 'split4Screens') {
  64056. this.inputHandler.registerInteractiveScene(viewer.scene.scene);
  64057. }
  64058. }else {
  64059. if(!this.attachedToViewer)return
  64060. viewer.mainViewport.left = 0;
  64061. viewer.mainViewport.bottom = 0;
  64062. viewer.mainViewport.width = 1;
  64063. viewer.mainViewport.height = 1;
  64064. this.viewports[0].width = 1;
  64065. this.viewports[0].bottom = 0;
  64066. this.viewports[0].height = 1;
  64067. this.viewports[0].left = 0;
  64068. this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene);
  64069. this.inputHandler.unregisterInteractiveScene(viewer.scene.scene);
  64070. viewer.viewports = [viewer.mainViewport];
  64071. this.updateScreenSize({forceUpdateSize:true}); //更新相机projectionMatrix
  64072. }
  64073. //if(desc == 'measure')this.renderMeasure = state
  64074. this.attachedToViewer = state;
  64075. viewer.updateScreenSize({forceUpdateSize:true});
  64076. //mapRatio != 'dontSet' && !options.dontFit && this.moveTo(...)//要写在updateScreenSize后面,因为要根据视图大小来fit
  64077. if(options.moveToCurrentPos){
  64078. let boundSize = new Vector2$1(10,10);
  64079. let duration = 1000;
  64080. this.moveTo(viewer.images360.position.clone(), boundSize, duration);
  64081. }
  64082. this.needRender = true;
  64083. }
  64084. changeSplitScreenDir(dir, mapRatio){//左右 | 上下
  64085. //if(!dir || dir == this.dir)return
  64086. if(dir )this.splitDir = dir;
  64087. this.updateSplitSize(mapRatio);
  64088. /* if(this.attachedToViewer){ //如果已经分屏了,中途修改方向的话……
  64089. this.updateSplitSize()
  64090. } */
  64091. }
  64092. updateSplitSize(mapRatio){
  64093. if(mapRatio != void 0) this.mapRatio = mapRatio;
  64094. //console.log(this.mapRatio)
  64095. if(this.splitDir == 'leftRight'){//地图在左方
  64096. viewer.mainViewport.left = this.mapRatio;
  64097. viewer.mainViewport.width = 1-this.mapRatio;
  64098. this.viewports[0].width = this.mapRatio;
  64099. viewer.mainViewport.bottom = this.viewports[0].bottom = 0;
  64100. viewer.mainViewport.height = this.viewports[0].height = 1;
  64101. }else if(this.splitDir == 'upDown'){ //地图在下方
  64102. viewer.mainViewport.bottom = this.mapRatio;
  64103. viewer.mainViewport.height = 1-this.mapRatio;
  64104. this.viewports[0].height = this.mapRatio;
  64105. viewer.mainViewport.left = this.viewports[0].left = 0;
  64106. viewer.mainViewport.width = this.viewports[0].width = 1;
  64107. }
  64108. if(this.attachedToViewer){
  64109. viewer.updateScreenSize({forceUpdateSize:true});
  64110. }
  64111. }
  64112. render(params={}){
  64113. if(!this.visible && !this.attachedToViewer || !this.needRender && !params.force)return
  64114. let renderer = params.renderer || this.renderer;
  64115. if(params.target){
  64116. renderer.setRenderTarget(params.target);
  64117. }
  64118. /* if(params.resize){
  64119. this.emitResizeMsg(new THREE.Vector2(params.width,params.height, viewport:params.viewport))
  64120. } */
  64121. params.clear ? params.clear() : renderer.clear();
  64122. if(!this.attachedToViewer){
  64123. viewer.dispatchEvent({type: "render.begin", viewer: this, viewport:this.viewports[0], params });
  64124. }
  64125. viewer.setCameraLayers(this.camera, ['map','mapObjects' , 'bothMapAndScene' ]);
  64126. if(this.mapGradientBG){//渲染背景
  64127. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  64128. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  64129. }
  64130. renderer.render(this.scene, this.camera);
  64131. renderer.render(viewer.scene.scene, this.camera);
  64132. //测量线等
  64133. //params.renderOverlay && params.renderOverlay({camera:this.camera, isMap:true, viewport: this.viewports[0] })//其余如reticule 等场景层
  64134. params.renderOverlay && params.renderOverlay( $.extend({}, params, { isMap:true }));
  64135. renderer.setRenderTarget(null);
  64136. this.needRender = false;
  64137. }
  64138. /* render(){
  64139. let camera = viewer.scene.getActiveCamera();
  64140. viewer.scene.view.position.x += 0.01
  64141. viewer.setCameraLayers(camera, ['sceneObjects','marker','reticule','skybox' ])
  64142. this.renderer.render(viewer.scene.scene, camera);
  64143. } */
  64144. }
  64145. //本地调试地图白屏是因为代码自动更新了 但没刷新
  64146. class CSVExporter {
  64147. static toString (points) {
  64148. let string = '';
  64149. let attributes = Object.keys(points.data)
  64150. .filter(a => a !== 'normal')
  64151. .sort((a, b) => {
  64152. if (a === 'position') return -1;
  64153. if (b === 'position') return 1;
  64154. if (a === 'rgba') return -1;
  64155. if (b === 'rgba') return 1;
  64156. });
  64157. let headerValues = [];
  64158. for (let attribute of attributes) {
  64159. let itemSize = points.data[attribute].length / points.numPoints;
  64160. if (attribute === 'position') {
  64161. headerValues = headerValues.concat(['x', 'y', 'z']);
  64162. } else if (attribute === 'rgba') {
  64163. headerValues = headerValues.concat(['r', 'g', 'b', 'a']);
  64164. } else if (itemSize > 1) {
  64165. for (let i = 0; i < itemSize; i++) {
  64166. headerValues.push(`${attribute}_${i}`);
  64167. }
  64168. } else {
  64169. headerValues.push(attribute);
  64170. }
  64171. }
  64172. string = headerValues.join(', ') + '\n';
  64173. for (let i = 0; i < points.numPoints; i++) {
  64174. let values = [];
  64175. for (let attribute of attributes) {
  64176. let itemSize = points.data[attribute].length / points.numPoints;
  64177. let value = points.data[attribute]
  64178. .subarray(itemSize * i, itemSize * i + itemSize)
  64179. .join(', ');
  64180. values.push(value);
  64181. }
  64182. string += values.join(', ') + '\n';
  64183. }
  64184. return string;
  64185. }
  64186. };
  64187. class LASExporter {
  64188. static toLAS (points) {
  64189. // TODO Unused: let string = '';
  64190. let boundingBox = points.boundingBox;
  64191. let offset = boundingBox.min.clone();
  64192. let diagonal = boundingBox.min.distanceTo(boundingBox.max);
  64193. let scale = new Vector3(0.001, 0.001, 0.001);
  64194. if (diagonal > 1000 * 1000) {
  64195. scale = new Vector3(0.01, 0.01, 0.01);
  64196. } else {
  64197. scale = new Vector3(0.001, 0.001, 0.001);
  64198. }
  64199. let setString = function (string, offset, buffer) {
  64200. let view = new Uint8Array(buffer);
  64201. for (let i = 0; i < string.length; i++) {
  64202. let charCode = string.charCodeAt(i);
  64203. view[offset + i] = charCode;
  64204. }
  64205. };
  64206. let buffer = new ArrayBuffer(227 + 28 * points.numPoints);
  64207. let view = new DataView(buffer);
  64208. let u8View = new Uint8Array(buffer);
  64209. // let u16View = new Uint16Array(buffer);
  64210. setString('LASF', 0, buffer);
  64211. u8View[24] = 1;
  64212. u8View[25] = 2;
  64213. // system identifier o:26 l:32
  64214. // generating software o:58 l:32
  64215. setString('Potree 1.7', 58, buffer);
  64216. // file creation day of year o:90 l:2
  64217. // file creation year o:92 l:2
  64218. // header size o:94 l:2
  64219. view.setUint16(94, 227, true);
  64220. // offset to point data o:96 l:4
  64221. view.setUint32(96, 227, true);
  64222. // number of letiable length records o:100 l:4
  64223. // point data record format 104 1
  64224. u8View[104] = 2;
  64225. // point data record length 105 2
  64226. view.setUint16(105, 28, true);
  64227. // number of point records 107 4
  64228. view.setUint32(107, points.numPoints, true);
  64229. // number of points by return 111 20
  64230. // x scale factor 131 8
  64231. view.setFloat64(131, scale.x, true);
  64232. // y scale factor 139 8
  64233. view.setFloat64(139, scale.y, true);
  64234. // z scale factor 147 8
  64235. view.setFloat64(147, scale.z, true);
  64236. // x offset 155 8
  64237. view.setFloat64(155, offset.x, true);
  64238. // y offset 163 8
  64239. view.setFloat64(163, offset.y, true);
  64240. // z offset 171 8
  64241. view.setFloat64(171, offset.z, true);
  64242. // max x 179 8
  64243. view.setFloat64(179, boundingBox.max.x, true);
  64244. // min x 187 8
  64245. view.setFloat64(187, boundingBox.min.x, true);
  64246. // max y 195 8
  64247. view.setFloat64(195, boundingBox.max.y, true);
  64248. // min y 203 8
  64249. view.setFloat64(203, boundingBox.min.y, true);
  64250. // max z 211 8
  64251. view.setFloat64(211, boundingBox.max.z, true);
  64252. // min z 219 8
  64253. view.setFloat64(219, boundingBox.min.z, true);
  64254. let boffset = 227;
  64255. for (let i = 0; i < points.numPoints; i++) {
  64256. let px = points.data.position[3 * i + 0];
  64257. let py = points.data.position[3 * i + 1];
  64258. let pz = points.data.position[3 * i + 2];
  64259. let ux = parseInt((px - offset.x) / scale.x);
  64260. let uy = parseInt((py - offset.y) / scale.y);
  64261. let uz = parseInt((pz - offset.z) / scale.z);
  64262. view.setUint32(boffset + 0, ux, true);
  64263. view.setUint32(boffset + 4, uy, true);
  64264. view.setUint32(boffset + 8, uz, true);
  64265. if (points.data.intensity) {
  64266. view.setUint16(boffset + 12, (points.data.intensity[i]), true);
  64267. }
  64268. let rt = 0;
  64269. if (points.data.returnNumber) {
  64270. rt += points.data.returnNumber[i];
  64271. }
  64272. if (points.data.numberOfReturns) {
  64273. rt += (points.data.numberOfReturns[i] << 3);
  64274. }
  64275. view.setUint8(boffset + 14, rt);
  64276. if (points.data.classification) {
  64277. view.setUint8(boffset + 15, points.data.classification[i]);
  64278. }
  64279. // scan angle rank
  64280. // user data
  64281. // point source id
  64282. if (points.data.pointSourceID) {
  64283. view.setUint16(boffset + 18, points.data.pointSourceID[i]);
  64284. }
  64285. if (points.data.rgba) {
  64286. let rgba = points.data.rgba;
  64287. view.setUint16(boffset + 20, (rgba[4 * i + 0] * 255), true);
  64288. view.setUint16(boffset + 22, (rgba[4 * i + 1] * 255), true);
  64289. view.setUint16(boffset + 24, (rgba[4 * i + 2] * 255), true);
  64290. }
  64291. boffset += 28;
  64292. }
  64293. return buffer;
  64294. }
  64295. }
  64296. function copyMaterial(source, target){
  64297. for(let name of Object.keys(target.uniforms)){
  64298. target.uniforms[name].value = source.uniforms[name].value;
  64299. }
  64300. target.gradientTexture = source.gradientTexture;
  64301. target.visibleNodesTexture = source.visibleNodesTexture;
  64302. target.classificationTexture = source.classificationTexture;
  64303. target.matcapTexture = source.matcapTexture;
  64304. target.activeAttributeName = source.activeAttributeName;
  64305. target.ranges = source.ranges;
  64306. //target.updateShaderSource();
  64307. }
  64308. class Batch{
  64309. constructor(geometry, material){
  64310. this.geometry = geometry;
  64311. this.material = material;
  64312. this.sceneNode = new Points(geometry, material);
  64313. this.geometryNode = {
  64314. estimatedSpacing: 1.0,
  64315. geometry: geometry,
  64316. };
  64317. }
  64318. getLevel(){
  64319. return 0;
  64320. }
  64321. }
  64322. class ProfileFakeOctree extends PointCloudTree{
  64323. constructor(octree){
  64324. super();
  64325. this.trueOctree = octree;
  64326. this.pcoGeometry = octree.pcoGeometry;
  64327. this.points = [];
  64328. this.visibleNodes = [];
  64329. //this.material = this.trueOctree.material;
  64330. this.material = new PointCloudMaterial$1();
  64331. //this.material.copy(this.trueOctree.material);
  64332. copyMaterial(this.trueOctree.material, this.material);
  64333. this.material.pointSizeType = PointSizeType.FIXED;
  64334. this.batchSize = 100 * 1000;
  64335. this.currentBatch = null;
  64336. }
  64337. getAttribute(name){
  64338. return this.trueOctree.getAttribute(name);
  64339. }
  64340. dispose(){
  64341. for(let node of this.visibleNodes){
  64342. node.geometry.dispose();
  64343. }
  64344. this.visibleNodes = [];
  64345. this.currentBatch = null;
  64346. this.points = [];
  64347. }
  64348. addPoints(data){
  64349. // since each call to addPoints can deliver very very few points,
  64350. // we're going to batch them into larger buffers for efficiency.
  64351. if(this.currentBatch === null){
  64352. this.currentBatch = this.createNewBatch(data);
  64353. }
  64354. this.points.push(data);
  64355. let updateRange = {
  64356. start: this.currentBatch.geometry.drawRange.count,
  64357. count: 0
  64358. };
  64359. let projectedBox = new Box3();
  64360. let truePos = new Vector3();
  64361. for(let i = 0; i < data.numPoints; i++){
  64362. if(updateRange.start + updateRange.count >= this.batchSize){
  64363. // current batch full, start new batch
  64364. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  64365. let attribute = this.currentBatch.geometry.attributes[key];
  64366. attribute.updateRange.offset = updateRange.start;
  64367. attribute.updateRange.count = updateRange.count;
  64368. attribute.needsUpdate = true;
  64369. }
  64370. this.currentBatch.geometry.computeBoundingBox();
  64371. this.currentBatch.geometry.computeBoundingSphere();
  64372. this.currentBatch = this.createNewBatch(data);
  64373. updateRange = {
  64374. start: 0,
  64375. count: 0
  64376. };
  64377. }
  64378. truePos.set(
  64379. data.data.position[3 * i + 0] + this.trueOctree.position.x,
  64380. data.data.position[3 * i + 1] + this.trueOctree.position.y,
  64381. data.data.position[3 * i + 2] + this.trueOctree.position.z,
  64382. );
  64383. let x = data.data.mileage[i];
  64384. let y = 0;
  64385. let z = truePos.z;
  64386. projectedBox.expandByPoint(new Vector3(x, y, z));
  64387. let index = updateRange.start + updateRange.count;
  64388. let geometry = this.currentBatch.geometry;
  64389. for(let attributeName of Object.keys(data.data)){
  64390. let source = data.data[attributeName];
  64391. let target = geometry.attributes[attributeName];
  64392. let numElements = target.itemSize;
  64393. for(let item = 0; item < numElements; item++){
  64394. target.array[numElements * index + item] = source[numElements * i + item];
  64395. }
  64396. }
  64397. {
  64398. let position = geometry.attributes.position;
  64399. position.array[3 * index + 0] = x;
  64400. position.array[3 * index + 1] = y;
  64401. position.array[3 * index + 2] = z;
  64402. }
  64403. updateRange.count++;
  64404. this.currentBatch.geometry.drawRange.count++;
  64405. }
  64406. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  64407. let attribute = this.currentBatch.geometry.attributes[key];
  64408. attribute.updateRange.offset = updateRange.start;
  64409. attribute.updateRange.count = updateRange.count;
  64410. attribute.needsUpdate = true;
  64411. }
  64412. data.projectedBox = projectedBox;
  64413. this.projectedBox = this.points.reduce( (a, i) => a.union(i.projectedBox), new Box3());
  64414. }
  64415. createNewBatch(data){
  64416. let geometry = new BufferGeometry();
  64417. // create new batches with batch_size elements of the same type as the attribute
  64418. for(let attributeName of Object.keys(data.data)){
  64419. let buffer = data.data[attributeName];
  64420. let numElements = buffer.length / data.numPoints; // 3 for pos, 4 for col, 1 for scalars
  64421. let constructor = buffer.constructor;
  64422. let normalized = false;
  64423. if(this.trueOctree.root.sceneNode){
  64424. if(this.trueOctree.root.sceneNode.geometry.attributes[attributeName]){
  64425. normalized = this.trueOctree.root.sceneNode.geometry.attributes[attributeName].normalized;
  64426. }
  64427. }
  64428. let batchBuffer = new constructor(numElements * this.batchSize);
  64429. let bufferAttribute = new BufferAttribute(batchBuffer, numElements, normalized);
  64430. bufferAttribute.potree = {
  64431. range: [0, 1],
  64432. };
  64433. geometry.setAttribute(attributeName, bufferAttribute);
  64434. }
  64435. geometry.drawRange.start = 0;
  64436. geometry.drawRange.count = 0;
  64437. let batch = new Batch(geometry, this.material);
  64438. this.visibleNodes.push(batch);
  64439. return batch;
  64440. }
  64441. computeVisibilityTextureData(){
  64442. let data = new Uint8Array(this.visibleNodes.length * 4);
  64443. let offsets = new Map();
  64444. for(let i = 0; i < this.visibleNodes.length; i++){
  64445. let node = this.visibleNodes[i];
  64446. offsets[node] = i;
  64447. }
  64448. return {
  64449. data: data,
  64450. offsets: offsets,
  64451. };
  64452. }
  64453. }
  64454. class ProfileWindow extends EventDispatcher {
  64455. constructor (viewer) {
  64456. super();
  64457. this.viewer = viewer;
  64458. this.elRoot = $('#profile_window');
  64459. this.renderArea = this.elRoot.find('#profileCanvasContainer');
  64460. this.svg = d3.select('svg#profileSVG');
  64461. this.mouseIsDown = false;
  64462. this.projectedBox = new Box3();
  64463. this.pointclouds = new Map();
  64464. this.numPoints = 0;
  64465. this.lastAddPointsTimestamp = undefined;
  64466. this.mouse = new Vector2$1(0, 0);
  64467. this.scale = new Vector3(1, 1, 1);
  64468. this.autoFitEnabled = true; // completely disable/enable
  64469. this.autoFit = false; // internal
  64470. let cwIcon = `${exports.resourcePath}/icons/arrow_cw.svg`;
  64471. $('#potree_profile_rotate_cw').attr('src', cwIcon);
  64472. let ccwIcon = `${exports.resourcePath}/icons/arrow_ccw.svg`;
  64473. $('#potree_profile_rotate_ccw').attr('src', ccwIcon);
  64474. let forwardIcon = `${exports.resourcePath}/icons/arrow_up.svg`;
  64475. $('#potree_profile_move_forward').attr('src', forwardIcon);
  64476. let backwardIcon = `${exports.resourcePath}/icons/arrow_down.svg`;
  64477. $('#potree_profile_move_backward').attr('src', backwardIcon);
  64478. let csvIcon = `${exports.resourcePath}/icons/file_csv_2d.svg`;
  64479. $('#potree_download_csv_icon').attr('src', csvIcon);
  64480. let lasIcon = `${exports.resourcePath}/icons/file_las_3d.svg`;
  64481. $('#potree_download_las_icon').attr('src', lasIcon);
  64482. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  64483. $('#closeProfileContainer').attr("src", closeIcon);
  64484. this.initTHREE();
  64485. this.initSVG();
  64486. this.initListeners();
  64487. this.pRenderer = new Renderer(this.renderer);
  64488. this.elRoot.i18n();
  64489. }
  64490. initListeners () {
  64491. $(window).resize(() => {
  64492. if (this.enabled) {
  64493. this.render();
  64494. }
  64495. });
  64496. this.renderArea.mousedown(e => {
  64497. this.mouseIsDown = true;
  64498. });
  64499. this.renderArea.mouseup(e => {
  64500. this.mouseIsDown = false;
  64501. });
  64502. let viewerPickSphereSizeHandler = () => {
  64503. let camera = this.viewer.scene.getActiveCamera();
  64504. let domElement = this.viewer.renderer.domElement;
  64505. let distance = this.viewerPickSphere.position.distanceTo(camera.position);
  64506. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  64507. let scale = (10 / pr);
  64508. this.viewerPickSphere.scale.set(scale, scale, scale);
  64509. };
  64510. this.renderArea.mousemove(e => {
  64511. if (this.pointclouds.size === 0) {
  64512. return;
  64513. }
  64514. let rect = this.renderArea[0].getBoundingClientRect();
  64515. let x = e.clientX - rect.left;
  64516. let y = e.clientY - rect.top;
  64517. let newMouse = new Vector2$1(x, y);
  64518. if (this.mouseIsDown) {
  64519. // DRAG
  64520. this.autoFit = false;
  64521. this.lastDrag = new Date().getTime();
  64522. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64523. let ncPos = [this.scaleX.invert(newMouse.x), this.scaleY.invert(newMouse.y)];
  64524. this.camera.position.x -= ncPos[0] - cPos[0];
  64525. this.camera.position.z -= ncPos[1] - cPos[1];
  64526. this.render();
  64527. } else if (this.pointclouds.size > 0) {
  64528. // FIND HOVERED POINT
  64529. let radius = Math.abs(this.scaleX.invert(0) - this.scaleX.invert(40));
  64530. let mileage = this.scaleX.invert(newMouse.x);
  64531. let elevation = this.scaleY.invert(newMouse.y);
  64532. let closest = this.selectPoint(mileage, elevation, radius);
  64533. if (closest) {
  64534. let point = closest.point;
  64535. let position = new Float64Array([
  64536. point.position[0] + closest.pointcloud.position.x,
  64537. point.position[1] + closest.pointcloud.position.y,
  64538. point.position[2] + closest.pointcloud.position.z
  64539. ]);
  64540. this.elRoot.find('#profileSelectionProperties').fadeIn(200);
  64541. this.pickSphere.visible = true;
  64542. this.pickSphere.scale.set(0.5 * radius, 0.5 * radius, 0.5 * radius);
  64543. this.pickSphere.position.set(point.mileage, 0, position[2]);
  64544. this.viewerPickSphere.position.set(...position);
  64545. if(!this.viewer.scene.scene.children.includes(this.viewerPickSphere)){
  64546. this.viewer.scene.scene.add(this.viewerPickSphere);
  64547. if(!this.viewer.hasEventListener("update", viewerPickSphereSizeHandler)){
  64548. this.viewer.addEventListener("update", viewerPickSphereSizeHandler);
  64549. }
  64550. }
  64551. let info = this.elRoot.find('#profileSelectionProperties');
  64552. let html = '<table>';
  64553. for (let attributeName of Object.keys(point)) {
  64554. let value = point[attributeName];
  64555. let attribute = closest.pointcloud.getAttribute(attributeName);
  64556. let transform = value => value;
  64557. if(attribute && attribute.type.size > 4){
  64558. let range = attribute.initialRange;
  64559. let scale = 1 / (range[1] - range[0]);
  64560. let offset = range[0];
  64561. transform = value => value / scale + offset;
  64562. }
  64563. if (attributeName === 'position') {
  64564. let values = [...position].map(v => Utils.addCommas(v.toFixed(3)));
  64565. html += `
  64566. <tr>
  64567. <td>x</td>
  64568. <td>${values[0]}</td>
  64569. </tr>
  64570. <tr>
  64571. <td>y</td>
  64572. <td>${values[1]}</td>
  64573. </tr>
  64574. <tr>
  64575. <td>z</td>
  64576. <td>${values[2]}</td>
  64577. </tr>`;
  64578. } else if (attributeName === 'rgba') {
  64579. html += `
  64580. <tr>
  64581. <td>${attributeName}</td>
  64582. <td>${value.join(', ')}</td>
  64583. </tr>`;
  64584. } else if (attributeName === 'normal') {
  64585. continue;
  64586. } else if (attributeName === 'mileage') {
  64587. html += `
  64588. <tr>
  64589. <td>${attributeName}</td>
  64590. <td>${value.toFixed(3)}</td>
  64591. </tr>`;
  64592. } else {
  64593. html += `
  64594. <tr>
  64595. <td>${attributeName}</td>
  64596. <td>${transform(value)}</td>
  64597. </tr>`;
  64598. }
  64599. }
  64600. html += '</table>';
  64601. info.html(html);
  64602. this.selectedPoint = point;
  64603. } else {
  64604. // this.pickSphere.visible = false;
  64605. // this.selectedPoint = null;
  64606. this.viewer.scene.scene.add(this.viewerPickSphere);
  64607. let index = this.viewer.scene.scene.children.indexOf(this.viewerPickSphere);
  64608. if(index >= 0){
  64609. this.viewer.scene.scene.children.splice(index, 1);
  64610. }
  64611. this.viewer.removeEventListener("update", viewerPickSphereSizeHandler);
  64612. }
  64613. this.render();
  64614. }
  64615. this.mouse.copy(newMouse);
  64616. });
  64617. let onWheel = e => {
  64618. this.autoFit = false;
  64619. let delta = 0;
  64620. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  64621. delta = e.wheelDelta;
  64622. } else if (e.detail !== undefined) { // Firefox
  64623. delta = -e.detail;
  64624. }
  64625. let ndelta = Math.sign(delta);
  64626. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64627. if (ndelta > 0) {
  64628. // + 10%
  64629. this.scale.multiplyScalar(1.1);
  64630. } else {
  64631. // - 10%
  64632. this.scale.multiplyScalar(100 / 110);
  64633. }
  64634. this.updateScales();
  64635. let ncPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64636. this.camera.position.x -= ncPos[0] - cPos[0];
  64637. this.camera.position.z -= ncPos[1] - cPos[1];
  64638. this.render();
  64639. this.updateScales();
  64640. };
  64641. $(this.renderArea)[0].addEventListener('mousewheel', onWheel, false);
  64642. $(this.renderArea)[0].addEventListener('DOMMouseScroll', onWheel, false); // Firefox
  64643. $('#closeProfileContainer').click(() => {
  64644. this.hide();
  64645. });
  64646. let getProfilePoints = () => {
  64647. let points = new Points$1();
  64648. for(let [pointcloud, entry] of this.pointclouds){
  64649. for(let pointSet of entry.points){
  64650. let originPos = pointSet.data.position;
  64651. let trueElevationPosition = new Float32Array(originPos);
  64652. for(let i = 0; i < pointSet.numPoints; i++){
  64653. trueElevationPosition[3 * i + 2] += pointcloud.position.z;
  64654. }
  64655. pointSet.data.position = trueElevationPosition;
  64656. points.add(pointSet);
  64657. pointSet.data.position = originPos;
  64658. }
  64659. }
  64660. return points;
  64661. };
  64662. $('#potree_download_csv_icon').click(() => {
  64663. let points = getProfilePoints();
  64664. let string = CSVExporter.toString(points);
  64665. let blob = new Blob([string], {type: "text/string"});
  64666. $('#potree_download_profile_ortho_link').attr('href', URL.createObjectURL(blob));
  64667. });
  64668. $('#potree_download_las_icon').click(() => {
  64669. let points = getProfilePoints();
  64670. let buffer = LASExporter.toLAS(points);
  64671. let blob = new Blob([buffer], {type: "application/octet-binary"});
  64672. $('#potree_download_profile_link').attr('href', URL.createObjectURL(blob));
  64673. });
  64674. }
  64675. selectPoint (mileage, elevation, radius) {
  64676. let closest = {
  64677. distance: Infinity,
  64678. pointcloud: null,
  64679. points: null,
  64680. index: null
  64681. };
  64682. let pointBox = new Box2(
  64683. new Vector2$1(mileage - radius, elevation - radius),
  64684. new Vector2$1(mileage + radius, elevation + radius));
  64685. let numTested = 0;
  64686. let numSkipped = 0;
  64687. let numTestedPoints = 0;
  64688. let numSkippedPoints = 0;
  64689. for (let [pointcloud, entry] of this.pointclouds) {
  64690. for(let points of entry.points){
  64691. let collisionBox = new Box2(
  64692. new Vector2$1(points.projectedBox.min.x, points.projectedBox.min.z),
  64693. new Vector2$1(points.projectedBox.max.x, points.projectedBox.max.z)
  64694. );
  64695. let intersects = collisionBox.intersectsBox(pointBox);
  64696. if(!intersects){
  64697. numSkipped++;
  64698. numSkippedPoints += points.numPoints;
  64699. continue;
  64700. }
  64701. numTested++;
  64702. numTestedPoints += points.numPoints;
  64703. for (let i = 0; i < points.numPoints; i++) {
  64704. let m = points.data.mileage[i] - mileage;
  64705. let e = points.data.position[3 * i + 2] - elevation + pointcloud.position.z;
  64706. let r = Math.sqrt(m * m + e * e);
  64707. const withinDistance = r < radius && r < closest.distance;
  64708. let unfilteredClass = true;
  64709. if(points.data.classification){
  64710. const classification = pointcloud.material.classification;
  64711. const pointClassID = points.data.classification[i];
  64712. const pointClassValue = classification[pointClassID];
  64713. if(pointClassValue && (!pointClassValue.visible || pointClassValue.color.w === 0)){
  64714. unfilteredClass = false;
  64715. }
  64716. }
  64717. if (withinDistance && unfilteredClass) {
  64718. closest = {
  64719. distance: r,
  64720. pointcloud: pointcloud,
  64721. points: points,
  64722. index: i
  64723. };
  64724. }
  64725. }
  64726. }
  64727. }
  64728. //console.log(`nodes: ${numTested}, ${numSkipped} || points: ${numTestedPoints}, ${numSkippedPoints}`);
  64729. if (closest.distance < Infinity) {
  64730. let points = closest.points;
  64731. let point = {};
  64732. let attributes = Object.keys(points.data);
  64733. for (let attribute of attributes) {
  64734. let attributeData = points.data[attribute];
  64735. let itemSize = attributeData.length / points.numPoints;
  64736. let value = attributeData.subarray(itemSize * closest.index, itemSize * closest.index + itemSize);
  64737. if (value.length === 1) {
  64738. point[attribute] = value[0];
  64739. } else {
  64740. point[attribute] = value;
  64741. }
  64742. }
  64743. closest.point = point;
  64744. return closest;
  64745. } else {
  64746. return null;
  64747. }
  64748. }
  64749. initTHREE () {
  64750. this.renderer = new WebGLRenderer({alpha: true, premultipliedAlpha: false});
  64751. this.renderer.setClearColor(0x000000, 0);
  64752. this.renderer.setSize(10, 10);
  64753. this.renderer.autoClear = false;
  64754. this.renderArea.append($(this.renderer.domElement));
  64755. this.renderer.domElement.tabIndex = '2222';
  64756. $(this.renderer.domElement).css('width', '100%');
  64757. $(this.renderer.domElement).css('height', '100%');
  64758. {
  64759. let gl = this.renderer.getContext();
  64760. if(gl.createVertexArray == null){
  64761. let extVAO = gl.getExtension('OES_vertex_array_object');
  64762. if(!extVAO){
  64763. throw new Error("OES_vertex_array_object extension not supported");
  64764. }
  64765. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  64766. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  64767. }
  64768. }
  64769. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  64770. /* */
  64771. if(window.axisYup){
  64772. }else {
  64773. this.camera.up.set(0, 0, 1);
  64774. this.camera.rotation.order = "ZXY";
  64775. this.camera.rotation.x = Math.PI / 2.0;
  64776. }
  64777. this.scene = new Scene();
  64778. this.profileScene = new Scene();
  64779. let sg = new SphereGeometry(1, 16, 16);
  64780. let sm = new MeshNormalMaterial();
  64781. this.pickSphere = new Mesh(sg, sm);
  64782. this.scene.add(this.pickSphere);
  64783. this.viewerPickSphere = new Mesh(sg, sm);
  64784. }
  64785. initSVG () {
  64786. let width = this.renderArea[0].clientWidth;
  64787. let height = this.renderArea[0].clientHeight;
  64788. let marginLeft = this.renderArea[0].offsetLeft;
  64789. this.svg.selectAll('*').remove();
  64790. this.scaleX = d3.scale.linear()
  64791. .domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  64792. .range([0, width]);
  64793. this.scaleY = d3.scale.linear()
  64794. .domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  64795. .range([height, 0]);
  64796. this.xAxis = d3.svg.axis()
  64797. .scale(this.scaleX)
  64798. .orient('bottom')
  64799. .innerTickSize(-height)
  64800. .outerTickSize(1)
  64801. .tickPadding(10)
  64802. .ticks(width / 50);
  64803. this.yAxis = d3.svg.axis()
  64804. .scale(this.scaleY)
  64805. .orient('left')
  64806. .innerTickSize(-width)
  64807. .outerTickSize(1)
  64808. .tickPadding(10)
  64809. .ticks(height / 20);
  64810. this.elXAxis = this.svg.append('g')
  64811. .attr('class', 'x axis')
  64812. .attr('transform', `translate(${marginLeft}, ${height})`)
  64813. .call(this.xAxis);
  64814. this.elYAxis = this.svg.append('g')
  64815. .attr('class', 'y axis')
  64816. .attr('transform', `translate(${marginLeft}, 0)`)
  64817. .call(this.yAxis);
  64818. }
  64819. addPoints (pointcloud, points) {
  64820. if(points.numPoints === 0){
  64821. return;
  64822. }
  64823. let entry = this.pointclouds.get(pointcloud);
  64824. if(!entry){
  64825. entry = new ProfileFakeOctree(pointcloud);
  64826. this.pointclouds.set(pointcloud, entry);
  64827. this.profileScene.add(entry);
  64828. let materialChanged = () => {
  64829. this.render();
  64830. };
  64831. materialChanged();
  64832. pointcloud.material.addEventListener('material_property_changed', materialChanged);
  64833. this.addEventListener("on_reset_once", () => {
  64834. pointcloud.material.removeEventListener('material_property_changed', materialChanged);
  64835. });
  64836. }
  64837. entry.addPoints(points);
  64838. this.projectedBox.union(entry.projectedBox);
  64839. if (this.autoFit && this.autoFitEnabled) {
  64840. let width = this.renderArea[0].clientWidth;
  64841. let height = this.renderArea[0].clientHeight;
  64842. let size = this.projectedBox.getSize(new Vector3());
  64843. let sx = width / size.x;
  64844. let sy = height / size.z;
  64845. let scale = Math.min(sx, sy);
  64846. let center = this.projectedBox.getCenter(new Vector3());
  64847. this.scale.set(scale, scale, 1);
  64848. this.camera.position.copy(center);
  64849. //console.log("camera: ", this.camera.position.toArray().join(", "));
  64850. }
  64851. //console.log(entry);
  64852. this.render();
  64853. let numPoints = 0;
  64854. for (let [key, value] of this.pointclouds.entries()) {
  64855. numPoints += value.points.reduce( (a, i) => a + i.numPoints, 0);
  64856. }
  64857. $(`#profile_num_points`).html(Utils.addCommas(numPoints));
  64858. }
  64859. reset () {
  64860. this.lastReset = new Date().getTime();
  64861. this.dispatchEvent({type: "on_reset_once"});
  64862. this.removeEventListeners("on_reset_once");
  64863. this.autoFit = true;
  64864. this.projectedBox = new Box3();
  64865. for(let [key, entry] of this.pointclouds){
  64866. entry.dispose();
  64867. }
  64868. this.pointclouds.clear();
  64869. this.mouseIsDown = false;
  64870. this.mouse.set(0, 0);
  64871. if(this.autoFitEnabled){
  64872. this.scale.set(1, 1, 1);
  64873. }
  64874. this.pickSphere.visible = false;
  64875. this.elRoot.find('#profileSelectionProperties').hide();
  64876. this.render();
  64877. }
  64878. show () {
  64879. this.elRoot.fadeIn();
  64880. this.enabled = true;
  64881. }
  64882. hide () {
  64883. this.elRoot.fadeOut();
  64884. this.enabled = false;
  64885. }
  64886. updateScales () {
  64887. let width = this.renderArea[0].clientWidth;
  64888. let height = this.renderArea[0].clientHeight;
  64889. let left = (-width / 2) / this.scale.x;
  64890. let right = (+width / 2) / this.scale.x;
  64891. let top = (+height / 2) / this.scale.y;
  64892. let bottom = (-height / 2) / this.scale.y;
  64893. this.camera.left = left;
  64894. this.camera.right = right;
  64895. this.camera.top = top;
  64896. this.camera.bottom = bottom;
  64897. this.camera.updateProjectionMatrix();
  64898. this.scaleX.domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  64899. .range([0, width]);
  64900. this.scaleY.domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  64901. .range([height, 0]);
  64902. let marginLeft = this.renderArea[0].offsetLeft;
  64903. this.xAxis.scale(this.scaleX)
  64904. .orient('bottom')
  64905. .innerTickSize(-height)
  64906. .outerTickSize(1)
  64907. .tickPadding(10)
  64908. .ticks(width / 50);
  64909. this.yAxis.scale(this.scaleY)
  64910. .orient('left')
  64911. .innerTickSize(-width)
  64912. .outerTickSize(1)
  64913. .tickPadding(10)
  64914. .ticks(height / 20);
  64915. this.elXAxis
  64916. .attr('transform', `translate(${marginLeft}, ${height})`)
  64917. .call(this.xAxis);
  64918. this.elYAxis
  64919. .attr('transform', `translate(${marginLeft}, 0)`)
  64920. .call(this.yAxis);
  64921. }
  64922. requestScaleUpdate(){
  64923. let threshold = 100;
  64924. let allowUpdate = ((this.lastReset === undefined) || (this.lastScaleUpdate === undefined))
  64925. || ((new Date().getTime() - this.lastReset) > threshold && (new Date().getTime() - this.lastScaleUpdate) > threshold);
  64926. if(allowUpdate){
  64927. this.updateScales();
  64928. this.lastScaleUpdate = new Date().getTime();
  64929. this.scaleUpdatePending = false;
  64930. }else if(!this.scaleUpdatePending) {
  64931. setTimeout(this.requestScaleUpdate.bind(this), 100);
  64932. this.scaleUpdatePending = true;
  64933. }
  64934. }
  64935. render () {
  64936. let width = this.renderArea[0].clientWidth;
  64937. let height = this.renderArea[0].clientHeight;
  64938. let {renderer, pRenderer, camera, profileScene, scene} = this;
  64939. let {scaleX, pickSphere} = this;
  64940. renderer.setSize(width, height);
  64941. renderer.setClearColor(0x000000, 0);
  64942. renderer.clear(true, true, false);
  64943. for(let pointcloud of this.pointclouds.keys()){
  64944. let source = pointcloud.material;
  64945. let target = this.pointclouds.get(pointcloud).material;
  64946. copyMaterial(source, target);
  64947. target.size = 2;
  64948. }
  64949. pRenderer.render(profileScene, camera, null);
  64950. let radius = Math.abs(scaleX.invert(0) - scaleX.invert(5));
  64951. if (radius === 0) {
  64952. pickSphere.visible = false;
  64953. } else {
  64954. pickSphere.scale.set(radius, radius, radius);
  64955. pickSphere.visible = true;
  64956. }
  64957. renderer.render(scene, camera);
  64958. this.requestScaleUpdate();
  64959. }
  64960. };
  64961. class ProfileWindowController {
  64962. constructor (viewer) {
  64963. this.viewer = viewer;
  64964. this.profileWindow = viewer.profileWindow;
  64965. this.profile = null;
  64966. this.numPoints = 0;
  64967. this.threshold = 60 * 1000;
  64968. this.rotateAmount = 10;
  64969. this.scheduledRecomputeTime = null;
  64970. this.enabled = true;
  64971. this.requests = [];
  64972. this._recompute = () => { this.recompute(); };
  64973. this.viewer.addEventListener("scene_changed", e => {
  64974. e.oldScene.removeEventListener("pointcloud_added", this._recompute);
  64975. e.scene.addEventListener("pointcloud_added", this._recompute);
  64976. });
  64977. this.viewer.scene.addEventListener("pointcloud_added", this._recompute);
  64978. $("#potree_profile_rotate_amount").val(parseInt(this.rotateAmount));
  64979. $("#potree_profile_rotate_amount").on("input", (e) => {
  64980. const str = $("#potree_profile_rotate_amount").val();
  64981. if(!isNaN(str)){
  64982. const value = parseFloat(str);
  64983. this.rotateAmount = value;
  64984. $("#potree_profile_rotate_amount").css("background-color", "");
  64985. }else {
  64986. $("#potree_profile_rotate_amount").css("background-color", "#ff9999");
  64987. }
  64988. });
  64989. const rotate = (radians) => {
  64990. const profile = this.profile;
  64991. const points = profile.points;
  64992. const start = points[0];
  64993. const end = points[points.length - 1];
  64994. const center = start.clone().add(end).multiplyScalar(0.5);
  64995. const mMoveOrigin = new Matrix4().makeTranslation(-center.x, -center.y, -center.z);
  64996. const mRotate = new Matrix4().makeRotationZ(radians);
  64997. const mMoveBack = new Matrix4().makeTranslation(center.x, center.y, center.z);
  64998. //const transform = mMoveOrigin.multiply(mRotate).multiply(mMoveBack);
  64999. const transform = mMoveBack.multiply(mRotate).multiply(mMoveOrigin);
  65000. const rotatedPoints = points.map( point => point.clone().applyMatrix4(transform) );
  65001. this.profileWindow.autoFitEnabled = false;
  65002. for(let i = 0; i < points.length; i++){
  65003. profile.setPosition(i, rotatedPoints[i]);
  65004. }
  65005. };
  65006. $("#potree_profile_rotate_cw").click( () => {
  65007. const radians = MathUtils.degToRad(this.rotateAmount);
  65008. rotate(-radians);
  65009. });
  65010. $("#potree_profile_rotate_ccw").click( () => {
  65011. const radians = MathUtils.degToRad(this.rotateAmount);
  65012. rotate(radians);
  65013. });
  65014. $("#potree_profile_move_forward").click( () => {
  65015. const profile = this.profile;
  65016. const points = profile.points;
  65017. const start = points[0];
  65018. const end = points[points.length - 1];
  65019. const dir = end.clone().sub(start).normalize();
  65020. const up = new Vector3(0, 0, 1);
  65021. const forward = up.cross(dir);
  65022. const move = forward.clone().multiplyScalar(profile.width / 2);
  65023. this.profileWindow.autoFitEnabled = false;
  65024. for(let i = 0; i < points.length; i++){
  65025. profile.setPosition(i, points[i].clone().add(move));
  65026. }
  65027. });
  65028. $("#potree_profile_move_backward").click( () => {
  65029. const profile = this.profile;
  65030. const points = profile.points;
  65031. const start = points[0];
  65032. const end = points[points.length - 1];
  65033. const dir = end.clone().sub(start).normalize();
  65034. const up = new Vector3(0, 0, 1);
  65035. const forward = up.cross(dir);
  65036. const move = forward.clone().multiplyScalar(-profile.width / 2);
  65037. this.profileWindow.autoFitEnabled = false;
  65038. for(let i = 0; i < points.length; i++){
  65039. profile.setPosition(i, points[i].clone().add(move));
  65040. }
  65041. });
  65042. }
  65043. setProfile (profile) {
  65044. if (this.profile !== null && this.profile !== profile) {
  65045. this.profile.removeEventListener('marker_moved', this._recompute);
  65046. this.profile.removeEventListener('marker_added', this._recompute);
  65047. this.profile.removeEventListener('marker_removed', this._recompute);
  65048. this.profile.removeEventListener('width_changed', this._recompute);
  65049. }
  65050. this.profile = profile;
  65051. {
  65052. this.profile.addEventListener('marker_moved', this._recompute);
  65053. this.profile.addEventListener('marker_added', this._recompute);
  65054. this.profile.addEventListener('marker_removed', this._recompute);
  65055. this.profile.addEventListener('width_changed', this._recompute);
  65056. }
  65057. this.recompute();
  65058. }
  65059. reset () {
  65060. this.profileWindow.reset();
  65061. this.numPoints = 0;
  65062. if (this.profile) {
  65063. for (let request of this.requests) {
  65064. request.cancel();
  65065. }
  65066. }
  65067. }
  65068. progressHandler (pointcloud, progress) {
  65069. for (let segment of progress.segments) {
  65070. this.profileWindow.addPoints(pointcloud, segment.points);
  65071. this.numPoints += segment.points.numPoints;
  65072. }
  65073. }
  65074. cancel () {
  65075. for (let request of this.requests) {
  65076. request.cancel();
  65077. // request.finishLevelThenCancel();
  65078. }
  65079. this.requests = [];
  65080. };
  65081. finishLevelThenCancel(){
  65082. for (let request of this.requests) {
  65083. request.finishLevelThenCancel();
  65084. }
  65085. this.requests = [];
  65086. }
  65087. recompute () {
  65088. if (!this.profile) {
  65089. return;
  65090. }
  65091. if (this.scheduledRecomputeTime !== null && this.scheduledRecomputeTime > new Date().getTime()) {
  65092. return;
  65093. } else {
  65094. this.scheduledRecomputeTime = new Date().getTime() + 100;
  65095. }
  65096. this.scheduledRecomputeTime = null;
  65097. this.reset();
  65098. for (let pointcloud of this.viewer.scene.pointclouds.filter(p => p.visible)) {
  65099. let request = pointcloud.getPointsInProfile(this.profile, null, {
  65100. 'onProgress': (event) => {
  65101. if (!this.enabled) {
  65102. return;
  65103. }
  65104. this.progressHandler(pointcloud, event.points);
  65105. if (this.numPoints > this.threshold) {
  65106. this.finishLevelThenCancel();
  65107. }
  65108. },
  65109. 'onFinish': (event) => {
  65110. if (!this.enabled) {
  65111. }
  65112. },
  65113. 'onCancel': () => {
  65114. if (!this.enabled) {
  65115. }
  65116. }
  65117. });
  65118. this.requests.push(request);
  65119. }
  65120. }
  65121. };
  65122. /**
  65123. *
  65124. * @author sigeom sa / http://sigeom.ch
  65125. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  65126. * @author Markus Schütz / http://potree.org
  65127. *
  65128. */
  65129. class GeoJSONExporter{
  65130. static measurementToFeatures (measurement) {
  65131. let coords = measurement.points.map(e => e.position.toArray());
  65132. let features = [];
  65133. if (coords.length === 1) {
  65134. let feature = {
  65135. type: 'Feature',
  65136. geometry: {
  65137. type: 'Point',
  65138. coordinates: coords[0]
  65139. },
  65140. properties: {
  65141. name: measurement.name
  65142. }
  65143. };
  65144. features.push(feature);
  65145. } else if (coords.length > 1 && !measurement.closed) {
  65146. let object = {
  65147. 'type': 'Feature',
  65148. 'geometry': {
  65149. 'type': 'LineString',
  65150. 'coordinates': coords
  65151. },
  65152. 'properties': {
  65153. name: measurement.name
  65154. }
  65155. };
  65156. features.push(object);
  65157. } else if (coords.length > 1 && measurement.closed) {
  65158. let object = {
  65159. 'type': 'Feature',
  65160. 'geometry': {
  65161. 'type': 'Polygon',
  65162. 'coordinates': [[...coords, coords[0]]]
  65163. },
  65164. 'properties': {
  65165. name: measurement.name
  65166. }
  65167. };
  65168. features.push(object);
  65169. }
  65170. if (measurement.showDistances) {
  65171. measurement.edgeLabels.forEach((label) => {
  65172. let labelPoint = {
  65173. type: 'Feature',
  65174. geometry: {
  65175. type: 'Point',
  65176. coordinates: label.position.toArray()
  65177. },
  65178. properties: {
  65179. distance: label.text
  65180. }
  65181. };
  65182. features.push(labelPoint);
  65183. });
  65184. }
  65185. if (measurement.showArea) {
  65186. let point = measurement.areaLabel.position;
  65187. let labelArea = {
  65188. type: 'Feature',
  65189. geometry: {
  65190. type: 'Point',
  65191. coordinates: point.toArray()
  65192. },
  65193. properties: {
  65194. area: measurement.areaLabel.text
  65195. }
  65196. };
  65197. features.push(labelArea);
  65198. }
  65199. return features;
  65200. }
  65201. static toString (measurements) {
  65202. if (!(measurements instanceof Array)) {
  65203. measurements = [measurements];
  65204. }
  65205. measurements = measurements.filter(m => m instanceof Measure);
  65206. let features = [];
  65207. for (let measure of measurements) {
  65208. let f = GeoJSONExporter.measurementToFeatures(measure);
  65209. features = features.concat(f);
  65210. }
  65211. let geojson = {
  65212. 'type': 'FeatureCollection',
  65213. 'features': features
  65214. };
  65215. return JSON.stringify(geojson, null, '\t');
  65216. }
  65217. }
  65218. /**
  65219. *
  65220. * @author sigeom sa / http://sigeom.ch
  65221. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  65222. * @author Markus Schuetz / http://potree.org
  65223. *
  65224. */
  65225. class DXFExporter {
  65226. static measurementPointSection (measurement) {
  65227. let position = measurement.points[0].position;
  65228. if (!position) {
  65229. return '';
  65230. }
  65231. let dxfSection = `0
  65232. CIRCLE
  65233. 8
  65234. layer_point
  65235. 10
  65236. ${position.x}
  65237. 20
  65238. ${position.y}
  65239. 30
  65240. ${position.z}
  65241. 40
  65242. 1.0
  65243. `;
  65244. return dxfSection;
  65245. }
  65246. static measurementPolylineSection (measurement) {
  65247. // bit code for polygons/polylines:
  65248. // https://www.autodesk.com/techpubs/autocad/acad2000/dxf/polyline_dxf_06.htm
  65249. let geomCode = 8;
  65250. if (measurement.closed) {
  65251. geomCode += 1;
  65252. }
  65253. let dxfSection = `0
  65254. POLYLINE
  65255. 8
  65256. layer_polyline
  65257. 62
  65258. 1
  65259. 66
  65260. 1
  65261. 10
  65262. 0.0
  65263. 20
  65264. 0.0
  65265. 30
  65266. 0.0
  65267. 70
  65268. ${geomCode}
  65269. `;
  65270. let xMax = 0.0;
  65271. let yMax = 0.0;
  65272. let zMax = 0.0;
  65273. for (let point of measurement.points) {
  65274. point = point.position;
  65275. xMax = Math.max(xMax, point.x);
  65276. yMax = Math.max(yMax, point.y);
  65277. zMax = Math.max(zMax, point.z);
  65278. dxfSection += `0
  65279. VERTEX
  65280. 8
  65281. 0
  65282. 10
  65283. ${point.x}
  65284. 20
  65285. ${point.y}
  65286. 30
  65287. ${point.z}
  65288. 70
  65289. 32
  65290. `;
  65291. }
  65292. dxfSection += `0
  65293. SEQEND
  65294. `;
  65295. return dxfSection;
  65296. }
  65297. static measurementSection (measurement) {
  65298. // if(measurement.points.length <= 1){
  65299. // return "";
  65300. // }
  65301. if (measurement.points.length === 0) {
  65302. return '';
  65303. } else if (measurement.points.length === 1) {
  65304. return DXFExporter.measurementPointSection(measurement);
  65305. } else if (measurement.points.length >= 2) {
  65306. return DXFExporter.measurementPolylineSection(measurement);
  65307. }
  65308. }
  65309. static toString(measurements){
  65310. if (!(measurements instanceof Array)) {
  65311. measurements = [measurements];
  65312. }
  65313. measurements = measurements.filter(m => m instanceof Measure);
  65314. let points = measurements.filter(m => (m instanceof Measure))
  65315. .map(m => m.points)
  65316. .reduce((a, v) => a.concat(v))
  65317. .map(p => p.position);
  65318. let min = new Vector3(Infinity, Infinity, Infinity);
  65319. let max = new Vector3(-Infinity, -Infinity, -Infinity);
  65320. for (let point of points) {
  65321. min.min(point);
  65322. max.max(point);
  65323. }
  65324. let dxfHeader = `999
  65325. DXF created from potree
  65326. 0
  65327. SECTION
  65328. 2
  65329. HEADER
  65330. 9
  65331. $ACADVER
  65332. 1
  65333. AC1006
  65334. 9
  65335. $INSBASE
  65336. 10
  65337. 0.0
  65338. 20
  65339. 0.0
  65340. 30
  65341. 0.0
  65342. 9
  65343. $EXTMIN
  65344. 10
  65345. ${min.x}
  65346. 20
  65347. ${min.y}
  65348. 30
  65349. ${min.z}
  65350. 9
  65351. $EXTMAX
  65352. 10
  65353. ${max.x}
  65354. 20
  65355. ${max.y}
  65356. 30
  65357. ${max.z}
  65358. 0
  65359. ENDSEC
  65360. `;
  65361. let dxfBody = `0
  65362. SECTION
  65363. 2
  65364. ENTITIES
  65365. `;
  65366. for (let measurement of measurements) {
  65367. dxfBody += DXFExporter.measurementSection(measurement);
  65368. }
  65369. dxfBody += `0
  65370. ENDSEC
  65371. `;
  65372. let dxf = dxfHeader + dxfBody + '0\nEOF';
  65373. return dxf;
  65374. }
  65375. }
  65376. class MeasurePanel{
  65377. constructor(viewer, measurement, propertiesPanel){
  65378. this.viewer = viewer;
  65379. this.measurement = measurement;
  65380. this.propertiesPanel = propertiesPanel;
  65381. this._update = () => { this.update(); };
  65382. }
  65383. createCoordinatesTable(points){
  65384. let table = $(`
  65385. <table class="measurement_value_table">
  65386. <tr>
  65387. <th>x</th>
  65388. <th>y</th>
  65389. <th>z</th>
  65390. <th></th>
  65391. </tr>
  65392. </table>
  65393. `);
  65394. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  65395. for (let point of points) {
  65396. let x = Utils.addCommas(point.x.toFixed(3));
  65397. let y = Utils.addCommas(point.y.toFixed(3));
  65398. let z = Utils.addCommas(point.z.toFixed(3));
  65399. let row = $(`
  65400. <tr>
  65401. <td><span>${x}</span></td>
  65402. <td><span>${y}</span></td>
  65403. <td><span>${z}</span></td>
  65404. <td align="right" style="width: 25%">
  65405. <img name="copy" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65406. </td>
  65407. </tr>
  65408. `);
  65409. this.elCopy = row.find("img[name=copy]");
  65410. this.elCopy.click( () => {
  65411. let msg = point.toArray().map(c => c.toFixed(3)).join(", ");
  65412. Utils.clipboardCopy(msg);
  65413. this.viewer.postMessage(
  65414. `Copied value to clipboard: <br>'${msg}'`,
  65415. {duration: 3000});
  65416. });
  65417. table.append(row);
  65418. }
  65419. return table;
  65420. };
  65421. createAttributesTable(){
  65422. let elTable = $('<table class="measurement_value_table"></table>');
  65423. let point = this.measurement.points[0];
  65424. /* for(let attributeName of Object.keys(point)){
  65425. if(attributeName === "position"){
  65426. }else if(attributeName === "rgba"){
  65427. let color = point.rgba;
  65428. let text = color.join(', ');
  65429. elTable.append($(`
  65430. <tr>
  65431. <td>rgb</td>
  65432. <td>${text}</td>
  65433. </tr>
  65434. `));
  65435. }else{
  65436. let value = point[attributeName];
  65437. let text = value.join(', ');
  65438. elTable.append($(`
  65439. <tr>
  65440. <td>${attributeName}</td>
  65441. <td>${text}</td>
  65442. </tr>
  65443. `));
  65444. }
  65445. } */
  65446. return elTable;
  65447. }
  65448. update(){
  65449. }
  65450. };
  65451. class DistancePanel extends MeasurePanel{
  65452. constructor(viewer, measurement, propertiesPanel){
  65453. super(viewer, measurement, propertiesPanel);
  65454. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65455. this.elContent = $(`
  65456. <div class="measurement_content selectable">
  65457. <span class="coordinates_table_container"></span>
  65458. <br>
  65459. <table id="distances_table" class="measurement_value_table"></table>
  65460. <!-- ACTIONS -->
  65461. <div style="display: flex; margin-top: 12px">
  65462. <span>
  65463. <input type="button" name="make_profile" value="profile from measure" />
  65464. </span>
  65465. <span style="flex-grow: 1"></span>
  65466. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65467. </div>
  65468. </div>
  65469. `);
  65470. this.elRemove = this.elContent.find("img[name=remove]");
  65471. this.elRemove.click( () => {
  65472. this.viewer.scene.removeMeasurement(measurement);
  65473. });
  65474. this.elMakeProfile = this.elContent.find("input[name=make_profile]");
  65475. this.elMakeProfile.click( () => {
  65476. //measurement.points;
  65477. const profile = new Profile();
  65478. profile.name = measurement.name;
  65479. profile.width = measurement.getTotalDistance() / 50;
  65480. for(const point of measurement.points){
  65481. profile.addMarker(point.position.clone());
  65482. }
  65483. this.viewer.scene.addProfile(profile);
  65484. });
  65485. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65486. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65487. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65488. this.update();
  65489. }
  65490. update(){
  65491. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65492. elCoordiantesContainer.empty();
  65493. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65494. let positions = this.measurement.points;
  65495. let distances = [];
  65496. for (let i = 0; i < positions.length - 1; i++) {
  65497. let d = positions[i].distanceTo(positions[i + 1]);
  65498. distances.push(d.toFixed(3));
  65499. }
  65500. let totalDistance = this.measurement.getTotalDistance().toFixed(3);
  65501. let elDistanceTable = this.elContent.find(`#distances_table`);
  65502. elDistanceTable.empty();
  65503. for (let i = 0; i < distances.length; i++) {
  65504. let label = (i === 0) ? 'Distances: ' : '';
  65505. let distance = distances[i];
  65506. let elDistance = $(`
  65507. <tr>
  65508. <th>${label}</th>
  65509. <td style="width: 100%; padding-left: 10px">${distance}</td>
  65510. </tr>`);
  65511. elDistanceTable.append(elDistance);
  65512. }
  65513. let elTotal = $(`
  65514. <tr>
  65515. <th>Total: </td><td style="width: 100%; padding-left: 10px">${totalDistance}</th>
  65516. </tr>`);
  65517. elDistanceTable.append(elTotal);
  65518. }
  65519. };
  65520. class PointPanel extends MeasurePanel{
  65521. constructor(viewer, measurement, propertiesPanel){
  65522. super(viewer, measurement, propertiesPanel);
  65523. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65524. this.elContent = $(`
  65525. <div class="measurement_content selectable">
  65526. <span class="coordinates_table_container"></span>
  65527. <br>
  65528. <span class="attributes_table_container"></span>
  65529. <!-- ACTIONS -->
  65530. <div style="display: flex; margin-top: 12px">
  65531. <span></span>
  65532. <span style="flex-grow: 1"></span>
  65533. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65534. </div>
  65535. </div>
  65536. `);
  65537. this.elRemove = this.elContent.find("img[name=remove]");
  65538. this.elRemove.click( () => {
  65539. this.viewer.scene.removeMeasurement(measurement);
  65540. });
  65541. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65542. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65543. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65544. this.update();
  65545. }
  65546. update(){
  65547. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65548. elCoordiantesContainer.empty();
  65549. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65550. let elAttributesContainer = this.elContent.find('.attributes_table_container');
  65551. elAttributesContainer.empty();
  65552. elAttributesContainer.append(this.createAttributesTable());
  65553. }
  65554. };
  65555. class AreaPanel extends MeasurePanel{
  65556. constructor(viewer, measurement, propertiesPanel){
  65557. super(viewer, measurement, propertiesPanel);
  65558. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65559. this.elContent = $(`
  65560. <div class="measurement_content selectable">
  65561. <span class="coordinates_table_container"></span>
  65562. <br>
  65563. <span style="font-weight: bold">Area: </span>
  65564. <span id="measurement_area"></span>
  65565. <!-- ACTIONS -->
  65566. <div style="display: flex; margin-top: 12px">
  65567. <span></span>
  65568. <span style="flex-grow: 1"></span>
  65569. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65570. </div>
  65571. </div>
  65572. `);
  65573. this.elRemove = this.elContent.find("img[name=remove]");
  65574. this.elRemove.click( () => {
  65575. this.viewer.scene.removeMeasurement(measurement);
  65576. });
  65577. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65578. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65579. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65580. this.update();
  65581. }
  65582. update(){
  65583. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65584. elCoordiantesContainer.empty();
  65585. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65586. let elArea = this.elContent.find(`#measurement_area`);
  65587. elArea.html(this.measurement.area.value.toFixed(3));
  65588. }
  65589. };
  65590. class AnglePanel extends MeasurePanel{
  65591. constructor(viewer, measurement, propertiesPanel){
  65592. super(viewer, measurement, propertiesPanel);
  65593. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65594. this.elContent = $(`
  65595. <div class="measurement_content selectable">
  65596. <span class="coordinates_table_container"></span>
  65597. <br>
  65598. <table class="measurement_value_table">
  65599. <tr>
  65600. <th>\u03b1</th>
  65601. <th>\u03b2</th>
  65602. <th>\u03b3</th>
  65603. </tr>
  65604. <tr>
  65605. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  65606. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  65607. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  65608. </tr>
  65609. </table>
  65610. <!-- ACTIONS -->
  65611. <div style="display: flex; margin-top: 12px">
  65612. <span></span>
  65613. <span style="flex-grow: 1"></span>
  65614. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65615. </div>
  65616. </div>
  65617. `);
  65618. this.elRemove = this.elContent.find("img[name=remove]");
  65619. this.elRemove.click( () => {
  65620. this.viewer.scene.removeMeasurement(measurement);
  65621. });
  65622. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65623. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65624. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65625. this.update();
  65626. }
  65627. update(){
  65628. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65629. elCoordiantesContainer.empty();
  65630. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65631. let angles = [];
  65632. for(let i = 0; i < this.measurement.points.length; i++){
  65633. angles.push(this.measurement.getAngle(i) * (180.0 / Math.PI));
  65634. }
  65635. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  65636. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  65637. let elBetta = this.elContent.find(`#angle_cell_betta`);
  65638. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  65639. elAlpha.html(angles[0]);
  65640. elBetta.html(angles[1]);
  65641. elGamma.html(angles[2]);
  65642. }
  65643. };
  65644. class CirclePanel extends MeasurePanel{
  65645. constructor(viewer, measurement, propertiesPanel){
  65646. super(viewer, measurement, propertiesPanel);
  65647. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65648. this.elContent = $(`
  65649. <div class="measurement_content selectable">
  65650. <span class="coordinates_table_container"></span>
  65651. <br>
  65652. <table id="infos_table" class="measurement_value_table"></table>
  65653. <!-- ACTIONS -->
  65654. <div style="display: flex; margin-top: 12px">
  65655. <span></span>
  65656. <span style="flex-grow: 1"></span>
  65657. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65658. </div>
  65659. </div>
  65660. `);
  65661. this.elRemove = this.elContent.find("img[name=remove]");
  65662. this.elRemove.click( () => {
  65663. this.viewer.scene.removeMeasurement(measurement);
  65664. });
  65665. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65666. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65667. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65668. this.update();
  65669. }
  65670. update(){
  65671. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65672. elCoordiantesContainer.empty();
  65673. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65674. const elInfos = this.elContent.find(`#infos_table`);
  65675. if(this.measurement.points.length !== 3){
  65676. elInfos.empty();
  65677. return;
  65678. }
  65679. const A = this.measurement.points[0].position;
  65680. const B = this.measurement.points[1].position;
  65681. const C = this.measurement.points[2].position;
  65682. const center = Potree.Utils.computeCircleCenter(A, B, C);
  65683. const radius = center.distanceTo(A);
  65684. const circumference = 2 * Math.PI * radius;
  65685. const format = (number) => {
  65686. return Potree.Utils.addCommas(number.toFixed(3));
  65687. };
  65688. const txtCenter = `${format(center.x)} ${format(center.y)} ${format(center.z)}`;
  65689. const txtRadius = format(radius);
  65690. const txtCircumference = format(circumference);
  65691. const thStyle = `style="text-align: left"`;
  65692. const tdStyle = `style="width: 100%; padding: 5px;"`;
  65693. elInfos.html(`
  65694. <tr>
  65695. <th ${thStyle}>Center: </th>
  65696. <td ${tdStyle}></td>
  65697. </tr>
  65698. <tr>
  65699. <td ${tdStyle} colspan="2">
  65700. ${txtCenter}
  65701. </td>
  65702. </tr>
  65703. <tr>
  65704. <th ${thStyle}>Radius: </th>
  65705. <td ${tdStyle}>${txtRadius}</td>
  65706. </tr>
  65707. <tr>
  65708. <th ${thStyle}>Circumference: </th>
  65709. <td ${tdStyle}>${txtCircumference}</td>
  65710. </tr>
  65711. `);
  65712. }
  65713. };
  65714. class HeightPanel extends MeasurePanel{
  65715. constructor(viewer, measurement, propertiesPanel){
  65716. super(viewer, measurement, propertiesPanel);
  65717. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65718. this.elContent = $(`
  65719. <div class="measurement_content selectable">
  65720. <span class="coordinates_table_container"></span>
  65721. <br>
  65722. <span id="height_label">Height: </span><br>
  65723. <!-- ACTIONS -->
  65724. <div style="display: flex; margin-top: 12px">
  65725. <span></span>
  65726. <span style="flex-grow: 1"></span>
  65727. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65728. </div>
  65729. </div>
  65730. `);
  65731. this.elRemove = this.elContent.find("img[name=remove]");
  65732. this.elRemove.click( () => {
  65733. this.viewer.scene.removeMeasurement(measurement);
  65734. });
  65735. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65736. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65737. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65738. this.update();
  65739. }
  65740. update(){
  65741. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65742. elCoordiantesContainer.empty();
  65743. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65744. {
  65745. let points = this.measurement.points;
  65746. let sorted = points.slice().sort((a, b) => a.position.z - b.position.z);
  65747. let lowPoint = sorted[0].position.clone();
  65748. let highPoint = sorted[sorted.length - 1].position.clone();
  65749. let min = lowPoint.z;
  65750. let max = highPoint.z;
  65751. let height = max - min;
  65752. height = height.toFixed(3);
  65753. this.elHeightLabel = this.elContent.find(`#height_label`);
  65754. this.elHeightLabel.html(`<b>Height:</b> ${height}`);
  65755. }
  65756. }
  65757. };
  65758. class VolumePanel extends MeasurePanel{
  65759. constructor(viewer, measurement, propertiesPanel){
  65760. super(viewer, measurement, propertiesPanel);
  65761. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  65762. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65763. let lblLengthText = new Map([
  65764. [BoxVolume, "length"],
  65765. [SphereVolume, "rx"],
  65766. ]).get(measurement.constructor);
  65767. let lblWidthText = new Map([
  65768. [BoxVolume, "width"],
  65769. [SphereVolume, "ry"],
  65770. ]).get(measurement.constructor);
  65771. let lblHeightText = new Map([
  65772. [BoxVolume, "height"],
  65773. [SphereVolume, "rz"],
  65774. ]).get(measurement.constructor);
  65775. this.elContent = $(`
  65776. <div class="measurement_content selectable">
  65777. <span class="coordinates_table_container"></span>
  65778. <table class="measurement_value_table">
  65779. <tr>
  65780. <th>\u03b1</th>
  65781. <th>\u03b2</th>
  65782. <th>\u03b3</th>
  65783. <th></th>
  65784. </tr>
  65785. <tr>
  65786. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  65787. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  65788. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  65789. <td align="right" style="width: 25%">
  65790. <img name="copyRotation" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65791. </td>
  65792. </tr>
  65793. </table>
  65794. <table class="measurement_value_table">
  65795. <tr>
  65796. <th>${lblLengthText}</th>
  65797. <th>${lblWidthText}</th>
  65798. <th>${lblHeightText}</th>
  65799. <th></th>
  65800. </tr>
  65801. <tr>
  65802. <td align="center" id="cell_length" style="width: 33%"></td>
  65803. <td align="center" id="cell_width" style="width: 33%"></td>
  65804. <td align="center" id="cell_height" style="width: 33%"></td>
  65805. <td align="right" style="width: 25%">
  65806. <img name="copyScale" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65807. </td>
  65808. </tr>
  65809. </table>
  65810. <br>
  65811. <span style="font-weight: bold">Volume: </span>
  65812. <span id="measurement_volume"></span>
  65813. <!--
  65814. <li>
  65815. <label style="whitespace: nowrap">
  65816. <input id="volume_show" type="checkbox"/>
  65817. <span>show volume</span>
  65818. </label>
  65819. </li>-->
  65820. <li>
  65821. <label style="whitespace: nowrap">
  65822. <input id="volume_clip" type="checkbox"/>
  65823. <span>make clip volume</span>
  65824. </label>
  65825. </li>
  65826. <li style="margin-top: 10px">
  65827. <input name="download_volume" type="button" value="prepare download" style="width: 100%" />
  65828. <div name="download_message"></div>
  65829. </li>
  65830. <!-- ACTIONS -->
  65831. <li style="display: grid; grid-template-columns: auto auto; grid-column-gap: 5px; margin-top: 10px">
  65832. <input id="volume_reset_orientation" type="button" value="reset orientation"/>
  65833. <input id="volume_make_uniform" type="button" value="make uniform"/>
  65834. </li>
  65835. <div style="display: flex; margin-top: 12px">
  65836. <span></span>
  65837. <span style="flex-grow: 1"></span>
  65838. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65839. </div>
  65840. </div>
  65841. `);
  65842. { // download
  65843. this.elDownloadButton = this.elContent.find("input[name=download_volume]");
  65844. if(this.propertiesPanel.viewer.server){
  65845. this.elDownloadButton.click(() => this.download());
  65846. } else {
  65847. this.elDownloadButton.hide();
  65848. }
  65849. }
  65850. this.elCopyRotation = this.elContent.find("img[name=copyRotation]");
  65851. this.elCopyRotation.click( () => {
  65852. let rotation = this.measurement.rotation.toArray().slice(0, 3);
  65853. let msg = rotation.map(c => c.toFixed(3)).join(", ");
  65854. Utils.clipboardCopy(msg);
  65855. this.viewer.postMessage(
  65856. `Copied value to clipboard: <br>'${msg}'`,
  65857. {duration: 3000});
  65858. });
  65859. this.elCopyScale = this.elContent.find("img[name=copyScale]");
  65860. this.elCopyScale.click( () => {
  65861. let scale = this.measurement.scale.toArray();
  65862. let msg = scale.map(c => c.toFixed(3)).join(", ");
  65863. Utils.clipboardCopy(msg);
  65864. this.viewer.postMessage(
  65865. `Copied value to clipboard: <br>'${msg}'`,
  65866. {duration: 3000});
  65867. });
  65868. this.elRemove = this.elContent.find("img[name=remove]");
  65869. this.elRemove.click( () => {
  65870. this.viewer.scene.removeVolume(measurement);
  65871. });
  65872. this.elContent.find("#volume_reset_orientation").click(() => {
  65873. measurement.rotation.set(0, 0, 0);
  65874. });
  65875. this.elContent.find("#volume_make_uniform").click(() => {
  65876. let mean = (measurement.scale.x + measurement.scale.y + measurement.scale.z) / 3;
  65877. measurement.scale.set(mean, mean, mean);
  65878. });
  65879. this.elCheckClip = this.elContent.find('#volume_clip');
  65880. this.elCheckClip.click(event => {
  65881. this.measurement.clip = event.target.checked;
  65882. });
  65883. this.elCheckShow = this.elContent.find('#volume_show');
  65884. this.elCheckShow.click(event => {
  65885. this.measurement.visible = event.target.checked;
  65886. });
  65887. this.propertiesPanel.addVolatileListener(measurement, "position_changed", this._update);
  65888. this.propertiesPanel.addVolatileListener(measurement, "orientation_changed", this._update);
  65889. this.propertiesPanel.addVolatileListener(measurement, "scale_changed", this._update);
  65890. this.propertiesPanel.addVolatileListener(measurement, "clip_changed", this._update);
  65891. this.update();
  65892. }
  65893. async download(){
  65894. let clipBox = this.measurement;
  65895. let regions = [];
  65896. //for(let clipBox of boxes){
  65897. {
  65898. let toClip = clipBox.matrixWorld;
  65899. let px = new Vector3(+0.5, 0, 0).applyMatrix4(toClip);
  65900. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(toClip);
  65901. let py = new Vector3(0, +0.5, 0).applyMatrix4(toClip);
  65902. let ny = new Vector3(0, -0.5, 0).applyMatrix4(toClip);
  65903. let pz = new Vector3(0, 0, +0.5).applyMatrix4(toClip);
  65904. let nz = new Vector3(0, 0, -0.5).applyMatrix4(toClip);
  65905. let pxN = new Vector3().subVectors(nx, px).normalize();
  65906. let nxN = pxN.clone().multiplyScalar(-1);
  65907. let pyN = new Vector3().subVectors(ny, py).normalize();
  65908. let nyN = pyN.clone().multiplyScalar(-1);
  65909. let pzN = new Vector3().subVectors(nz, pz).normalize();
  65910. let nzN = pzN.clone().multiplyScalar(-1);
  65911. let planes = [
  65912. new Plane().setFromNormalAndCoplanarPoint(pxN, px),
  65913. new Plane().setFromNormalAndCoplanarPoint(nxN, nx),
  65914. new Plane().setFromNormalAndCoplanarPoint(pyN, py),
  65915. new Plane().setFromNormalAndCoplanarPoint(nyN, ny),
  65916. new Plane().setFromNormalAndCoplanarPoint(pzN, pz),
  65917. new Plane().setFromNormalAndCoplanarPoint(nzN, nz),
  65918. ];
  65919. let planeQueryParts = [];
  65920. for(let plane of planes){
  65921. let part = [plane.normal.toArray(), plane.constant].join(",");
  65922. part = `[${part}]`;
  65923. planeQueryParts.push(part);
  65924. }
  65925. let region = "[" + planeQueryParts.join(",") + "]";
  65926. regions.push(region);
  65927. }
  65928. let regionsArg = regions.join(",");
  65929. let pointcloudArgs = [];
  65930. for(let pointcloud of this.viewer.scene.pointclouds){
  65931. if(!pointcloud.visible){
  65932. continue;
  65933. }
  65934. let offset = pointcloud.pcoGeometry.offset.clone();
  65935. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  65936. let matrixWorld = pointcloud.matrixWorld;
  65937. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  65938. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  65939. let arg = {
  65940. path: path,
  65941. transform: transform.elements,
  65942. };
  65943. let argString = JSON.stringify(arg);
  65944. pointcloudArgs.push(argString);
  65945. }
  65946. let pointcloudsArg = pointcloudArgs.join(",");
  65947. let elMessage = this.elContent.find("div[name=download_message]");
  65948. let error = (message) => {
  65949. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  65950. };
  65951. let info = (message) => {
  65952. elMessage.html(`${message}`);
  65953. };
  65954. let handle = null;
  65955. { // START FILTER
  65956. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  65957. //console.log(url);
  65958. info("estimating results ...");
  65959. let response = await fetch(url);
  65960. let jsResponse = await response.json();
  65961. //console.log(jsResponse);
  65962. if(!jsResponse.handle){
  65963. error(jsResponse.message);
  65964. return;
  65965. }else {
  65966. handle = jsResponse.handle;
  65967. }
  65968. }
  65969. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  65970. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  65971. let sleep = (function(duration){
  65972. return new Promise( (res, rej) => {
  65973. setTimeout(() => {
  65974. res();
  65975. }, duration);
  65976. });
  65977. });
  65978. let handleFiltering = (jsResponse) => {
  65979. let {progress, estimate} = jsResponse;
  65980. let progressFract = progress["processed points"] / estimate.points;
  65981. let progressPercents = parseInt(progressFract * 100);
  65982. info(`progress: ${progressPercents}%`);
  65983. };
  65984. let handleFinish = (jsResponse) => {
  65985. let message = "downloads ready: <br>";
  65986. message += "<ul>";
  65987. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  65988. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  65989. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  65990. }
  65991. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  65992. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  65993. message += "</ul>";
  65994. info(message);
  65995. };
  65996. let handleUnexpected = (jsResponse) => {
  65997. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  65998. info(message);
  65999. };
  66000. let handleError = (jsResponse) => {
  66001. let message = `ERROR: ${jsResponse.message}`;
  66002. error(message);
  66003. throw new Error(message);
  66004. };
  66005. let start = Date.now();
  66006. while(true){
  66007. let response = await fetch(url);
  66008. let jsResponse = await response.json();
  66009. if(jsResponse.status === "ERROR"){
  66010. handleError(jsResponse);
  66011. }else if(jsResponse.status === "FILTERING"){
  66012. handleFiltering(jsResponse);
  66013. }else if(jsResponse.status === "FINISHED"){
  66014. handleFinish(jsResponse);
  66015. break;
  66016. }else {
  66017. handleUnexpected(jsResponse);
  66018. }
  66019. let durationS = (Date.now() - start) / 1000;
  66020. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  66021. await sleep(sleepAmountMS);
  66022. }
  66023. }
  66024. }
  66025. update(){
  66026. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  66027. elCoordiantesContainer.empty();
  66028. elCoordiantesContainer.append(this.createCoordinatesTable([this.measurement.position]));
  66029. {
  66030. let angles = this.measurement.rotation.toVector3();
  66031. angles = angles.toArray();
  66032. //angles = [angles.z, angles.x, angles.y];
  66033. angles = angles.map(v => 180 * v / Math.PI);
  66034. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  66035. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  66036. let elBetta = this.elContent.find(`#angle_cell_betta`);
  66037. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  66038. elAlpha.html(angles[0]);
  66039. elBetta.html(angles[1]);
  66040. elGamma.html(angles[2]);
  66041. }
  66042. {
  66043. let dimensions = this.measurement.scale.toArray();
  66044. dimensions = dimensions.map(v => Utils.addCommas(v.toFixed(2)));
  66045. let elLength = this.elContent.find(`#cell_length`);
  66046. let elWidth = this.elContent.find(`#cell_width`);
  66047. let elHeight = this.elContent.find(`#cell_height`);
  66048. elLength.html(dimensions[0]);
  66049. elWidth.html(dimensions[1]);
  66050. elHeight.html(dimensions[2]);
  66051. }
  66052. {
  66053. let elVolume = this.elContent.find(`#measurement_volume`);
  66054. let volume = this.measurement.getVolume();
  66055. elVolume.html(Utils.addCommas(volume.toFixed(2)));
  66056. }
  66057. this.elCheckClip.prop("checked", this.measurement.clip);
  66058. this.elCheckShow.prop("checked", this.measurement.visible);
  66059. }
  66060. };
  66061. class ProfilePanel extends MeasurePanel{
  66062. constructor(viewer, measurement, propertiesPanel){
  66063. super(viewer, measurement, propertiesPanel);
  66064. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  66065. this.elContent = $(`
  66066. <div class="measurement_content selectable">
  66067. <span class="coordinates_table_container"></span>
  66068. <br>
  66069. <span style="display:flex">
  66070. <span style="display:flex; align-items: center; padding-right: 10px">Width: </span>
  66071. <input id="sldProfileWidth" name="sldProfileWidth" value="5.06" style="flex-grow: 1; width:100%">
  66072. </span>
  66073. <br>
  66074. <li style="margin-top: 10px">
  66075. <input name="download_profile" type="button" value="prepare download" style="width: 100%" />
  66076. <div name="download_message"></div>
  66077. </li>
  66078. <br>
  66079. <input type="button" id="show_2d_profile" value="show 2d profile" style="width: 100%"/>
  66080. <!-- ACTIONS -->
  66081. <div style="display: flex; margin-top: 12px">
  66082. <span></span>
  66083. <span style="flex-grow: 1"></span>
  66084. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  66085. </div>
  66086. </div>
  66087. `);
  66088. this.elRemove = this.elContent.find("img[name=remove]");
  66089. this.elRemove.click( () => {
  66090. this.viewer.scene.removeProfile(measurement);
  66091. });
  66092. { // download
  66093. this.elDownloadButton = this.elContent.find(`input[name=download_profile]`);
  66094. if(this.propertiesPanel.viewer.server){
  66095. this.elDownloadButton.click(() => this.download());
  66096. } else {
  66097. this.elDownloadButton.hide();
  66098. }
  66099. }
  66100. { // width spinner
  66101. let elWidthSlider = this.elContent.find(`#sldProfileWidth`);
  66102. elWidthSlider.spinner({
  66103. min: 0, max: 10 * 1000 * 1000, step: 0.01,
  66104. numberFormat: 'n',
  66105. start: () => {},
  66106. spin: (event, ui) => {
  66107. let value = elWidthSlider.spinner('value');
  66108. measurement.setWidth(value);
  66109. },
  66110. change: (event, ui) => {
  66111. let value = elWidthSlider.spinner('value');
  66112. measurement.setWidth(value);
  66113. },
  66114. stop: (event, ui) => {
  66115. let value = elWidthSlider.spinner('value');
  66116. measurement.setWidth(value);
  66117. },
  66118. incremental: (count) => {
  66119. let value = elWidthSlider.spinner('value');
  66120. let step = elWidthSlider.spinner('option', 'step');
  66121. let delta = value * 0.05;
  66122. let increments = Math.max(1, parseInt(delta / step));
  66123. return increments;
  66124. }
  66125. });
  66126. elWidthSlider.spinner('value', measurement.getWidth());
  66127. elWidthSlider.spinner('widget').css('width', '100%');
  66128. let widthListener = (event) => {
  66129. let value = elWidthSlider.spinner('value');
  66130. if (value !== measurement.getWidth()) {
  66131. elWidthSlider.spinner('value', measurement.getWidth());
  66132. }
  66133. };
  66134. this.propertiesPanel.addVolatileListener(measurement, "width_changed", widthListener);
  66135. }
  66136. let elShow2DProfile = this.elContent.find(`#show_2d_profile`);
  66137. elShow2DProfile.click(() => {
  66138. this.propertiesPanel.viewer.profileWindow.show();
  66139. this.propertiesPanel.viewer.profileWindowController.setProfile(measurement);
  66140. });
  66141. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  66142. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  66143. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  66144. this.update();
  66145. }
  66146. update(){
  66147. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  66148. elCoordiantesContainer.empty();
  66149. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  66150. }
  66151. async download(){
  66152. let profile = this.measurement;
  66153. let regions = [];
  66154. {
  66155. let segments = profile.getSegments();
  66156. let width = profile.width;
  66157. for(let segment of segments){
  66158. let start = segment.start.clone().multiply(new Vector3(1, 1, 0));
  66159. let end = segment.end.clone().multiply(new Vector3(1, 1, 0));
  66160. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  66161. let startEndDir = new Vector3().subVectors(end, start).normalize();
  66162. let endStartDir = new Vector3().subVectors(start, end).normalize();
  66163. let upDir = new Vector3(0, 0, 1);
  66164. let rightDir = new Vector3().crossVectors(startEndDir, upDir);
  66165. let leftDir = new Vector3().crossVectors(endStartDir, upDir);
  66166. console.log(leftDir);
  66167. let right = rightDir.clone().multiplyScalar(width * 0.5).add(center);
  66168. let left = leftDir.clone().multiplyScalar(width * 0.5).add(center);
  66169. let planes = [
  66170. new Plane().setFromNormalAndCoplanarPoint(startEndDir, start),
  66171. new Plane().setFromNormalAndCoplanarPoint(endStartDir, end),
  66172. new Plane().setFromNormalAndCoplanarPoint(leftDir, right),
  66173. new Plane().setFromNormalAndCoplanarPoint(rightDir, left),
  66174. ];
  66175. let planeQueryParts = [];
  66176. for(let plane of planes){
  66177. let part = [plane.normal.toArray(), plane.constant].join(",");
  66178. part = `[${part}]`;
  66179. planeQueryParts.push(part);
  66180. }
  66181. let region = "[" + planeQueryParts.join(",") + "]";
  66182. regions.push(region);
  66183. }
  66184. }
  66185. let regionsArg = regions.join(",");
  66186. let pointcloudArgs = [];
  66187. for(let pointcloud of this.viewer.scene.pointclouds){
  66188. if(!pointcloud.visible){
  66189. continue;
  66190. }
  66191. let offset = pointcloud.pcoGeometry.offset.clone();
  66192. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  66193. let matrixWorld = pointcloud.matrixWorld;
  66194. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  66195. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  66196. let arg = {
  66197. path: path,
  66198. transform: transform.elements,
  66199. };
  66200. let argString = JSON.stringify(arg);
  66201. pointcloudArgs.push(argString);
  66202. }
  66203. let pointcloudsArg = pointcloudArgs.join(",");
  66204. let elMessage = this.elContent.find("div[name=download_message]");
  66205. let error = (message) => {
  66206. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  66207. };
  66208. let info = (message) => {
  66209. elMessage.html(`${message}`);
  66210. };
  66211. let handle = null;
  66212. { // START FILTER
  66213. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  66214. //console.log(url);
  66215. info("estimating results ...");
  66216. let response = await fetch(url);
  66217. let jsResponse = await response.json();
  66218. //console.log(jsResponse);
  66219. if(!jsResponse.handle){
  66220. error(jsResponse.message);
  66221. return;
  66222. }else {
  66223. handle = jsResponse.handle;
  66224. }
  66225. }
  66226. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  66227. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  66228. let sleep = (function(duration){
  66229. return new Promise( (res, rej) => {
  66230. setTimeout(() => {
  66231. res();
  66232. }, duration);
  66233. });
  66234. });
  66235. let handleFiltering = (jsResponse) => {
  66236. let {progress, estimate} = jsResponse;
  66237. let progressFract = progress["processed points"] / estimate.points;
  66238. let progressPercents = parseInt(progressFract * 100);
  66239. info(`progress: ${progressPercents}%`);
  66240. };
  66241. let handleFinish = (jsResponse) => {
  66242. let message = "downloads ready: <br>";
  66243. message += "<ul>";
  66244. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  66245. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  66246. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  66247. }
  66248. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  66249. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  66250. message += "</ul>";
  66251. info(message);
  66252. };
  66253. let handleUnexpected = (jsResponse) => {
  66254. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  66255. info(message);
  66256. };
  66257. let handleError = (jsResponse) => {
  66258. let message = `ERROR: ${jsResponse.message}`;
  66259. error(message);
  66260. throw new Error(message);
  66261. };
  66262. let start = Date.now();
  66263. while(true){
  66264. let response = await fetch(url);
  66265. let jsResponse = await response.json();
  66266. if(jsResponse.status === "ERROR"){
  66267. handleError(jsResponse);
  66268. }else if(jsResponse.status === "FILTERING"){
  66269. handleFiltering(jsResponse);
  66270. }else if(jsResponse.status === "FINISHED"){
  66271. handleFinish(jsResponse);
  66272. break;
  66273. }else {
  66274. handleUnexpected(jsResponse);
  66275. }
  66276. let durationS = (Date.now() - start) / 1000;
  66277. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  66278. await sleep(sleepAmountMS);
  66279. }
  66280. }
  66281. }
  66282. };
  66283. class CameraPanel{
  66284. constructor(viewer, propertiesPanel){
  66285. this.viewer = viewer;
  66286. this.propertiesPanel = propertiesPanel;
  66287. this._update = () => { this.update(); };
  66288. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  66289. this.elContent = $(`
  66290. <div class="propertypanel_content">
  66291. <table>
  66292. <tr>
  66293. <th colspan="3">position</th>
  66294. <th></th>
  66295. </tr>
  66296. <tr>
  66297. <td align="center" id="camera_position_x" style="width: 25%"></td>
  66298. <td align="center" id="camera_position_y" style="width: 25%"></td>
  66299. <td align="center" id="camera_position_z" style="width: 25%"></td>
  66300. <td align="right" id="copy_camera_position" style="width: 25%">
  66301. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66302. </td>
  66303. </tr>
  66304. <tr>
  66305. <th colspan="3">target</th>
  66306. <th></th>
  66307. </tr>
  66308. <tr>
  66309. <td align="center" id="camera_target_x" style="width: 25%"></td>
  66310. <td align="center" id="camera_target_y" style="width: 25%"></td>
  66311. <td align="center" id="camera_target_z" style="width: 25%"></td>
  66312. <td align="right" id="copy_camera_target" style="width: 25%">
  66313. <img name="copyTarget" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66314. </td>
  66315. </tr>
  66316. </table>
  66317. </div>
  66318. `);
  66319. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  66320. this.elCopyPosition.click( () => {
  66321. let pos = this.viewer.scene.getActiveCamera().position.toArray();
  66322. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66323. Utils.clipboardCopy(msg);
  66324. this.viewer.postMessage(
  66325. `Copied value to clipboard: <br>'${msg}'`,
  66326. {duration: 3000});
  66327. });
  66328. this.elCopyTarget = this.elContent.find("img[name=copyTarget]");
  66329. this.elCopyTarget.click( () => {
  66330. let pos = this.viewer.scene.view.getPivot().toArray();
  66331. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66332. Utils.clipboardCopy(msg);
  66333. this.viewer.postMessage(
  66334. `Copied value to clipboard: <br>'${msg}'`,
  66335. {duration: 3000});
  66336. });
  66337. this.propertiesPanel.addVolatileListener(viewer, "camera_changed", this._update);
  66338. this.update();
  66339. }
  66340. update(){
  66341. //console.log("updating camera panel");
  66342. let camera = this.viewer.scene.getActiveCamera();
  66343. let view = this.viewer.scene.view;
  66344. let pos = camera.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66345. this.elContent.find("#camera_position_x").html(pos[0]);
  66346. this.elContent.find("#camera_position_y").html(pos[1]);
  66347. this.elContent.find("#camera_position_z").html(pos[2]);
  66348. let target = view.getPivot().toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66349. this.elContent.find("#camera_target_x").html(target[0]);
  66350. this.elContent.find("#camera_target_y").html(target[1]);
  66351. this.elContent.find("#camera_target_z").html(target[2]);
  66352. }
  66353. };
  66354. class AnnotationPanel{
  66355. constructor(viewer, propertiesPanel, annotation){
  66356. this.viewer = viewer;
  66357. this.propertiesPanel = propertiesPanel;
  66358. this.annotation = annotation;
  66359. this._update = () => { this.update(); };
  66360. let copyIconPath = `${Potree.resourcePath}/icons/copy.svg`;
  66361. this.elContent = $(`
  66362. <div class="propertypanel_content">
  66363. <table>
  66364. <tr>
  66365. <th colspan="3">position</th>
  66366. <th></th>
  66367. </tr>
  66368. <tr>
  66369. <td align="center" id="annotation_position_x" style="width: 25%"></td>
  66370. <td align="center" id="annotation_position_y" style="width: 25%"></td>
  66371. <td align="center" id="annotation_position_z" style="width: 25%"></td>
  66372. <td align="right" id="copy_annotation_position" style="width: 25%">
  66373. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66374. </td>
  66375. </tr>
  66376. </table>
  66377. <div>
  66378. <div class="heading">Title</div>
  66379. <div id="annotation_title" contenteditable="true">
  66380. Annotation Title
  66381. </div>
  66382. <div class="heading">Description</div>
  66383. <div id="annotation_description" contenteditable="true">
  66384. A longer description of this annotation.
  66385. Can be multiple lines long. TODO: the user should be able
  66386. to modify title and description.
  66387. </div>
  66388. </div>
  66389. </div>
  66390. `);
  66391. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  66392. this.elCopyPosition.click( () => {
  66393. let pos = this.annotation.position.toArray();
  66394. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66395. Utils.clipboardCopy(msg);
  66396. this.viewer.postMessage(
  66397. `Copied value to clipboard: <br>'${msg}'`,
  66398. {duration: 3000});
  66399. });
  66400. this.elTitle = this.elContent.find("#annotation_title").html(annotation.title);
  66401. this.elDescription = this.elContent.find("#annotation_description").html(annotation.description);
  66402. this.elTitle[0].addEventListener("input", () => {
  66403. const title = this.elTitle.html();
  66404. annotation.title = title;
  66405. }, false);
  66406. this.elDescription[0].addEventListener("input", () => {
  66407. const description = this.elDescription.html();
  66408. annotation.description = description;
  66409. }, false);
  66410. this.update();
  66411. }
  66412. update(){
  66413. const {annotation, elContent, elTitle, elDescription} = this;
  66414. let pos = annotation.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66415. elContent.find("#annotation_position_x").html(pos[0]);
  66416. elContent.find("#annotation_position_y").html(pos[1]);
  66417. elContent.find("#annotation_position_z").html(pos[2]);
  66418. elTitle.html(annotation.title);
  66419. elDescription.html(annotation.description);
  66420. }
  66421. };
  66422. class CameraAnimationPanel{
  66423. constructor(viewer, propertiesPanel, animation){
  66424. this.viewer = viewer;
  66425. this.propertiesPanel = propertiesPanel;
  66426. this.animation = animation;
  66427. this.elContent = $(`
  66428. <div class="propertypanel_content">
  66429. <span id="animation_keyframes"></span>
  66430. <span>
  66431. <span style="display:flex">
  66432. <span style="display:flex; align-items: center; padding-right: 10px">Duration: </span>
  66433. <input name="spnDuration" value="5.0" style="flex-grow: 1; width:100%">
  66434. </span>
  66435. <span>Time: </span><span id="lblTime"></span> <div id="sldTime"></div>
  66436. <input name="play" type="button" value="play"/>
  66437. </span>
  66438. </div>
  66439. `);
  66440. const elPlay = this.elContent.find("input[name=play]");
  66441. elPlay.click( () => {
  66442. animation.play();
  66443. });
  66444. const elSlider = this.elContent.find('#sldTime');
  66445. elSlider.slider({
  66446. value: 0,
  66447. min: 0,
  66448. max: 1,
  66449. step: 0.001,
  66450. slide: (event, ui) => {
  66451. animation.set(ui.value);
  66452. animation.updateFrustum();
  66453. }
  66454. });
  66455. let elDuration = this.elContent.find(`input[name=spnDuration]`);
  66456. elDuration.spinner({
  66457. min: 0, max: 300, step: 0.01,
  66458. numberFormat: 'n',
  66459. start: () => {},
  66460. spin: (event, ui) => {
  66461. let value = elDuration.spinner('value');
  66462. animation.setDuration(value);
  66463. },
  66464. change: (event, ui) => {
  66465. let value = elDuration.spinner('value');
  66466. animation.setDuration(value);
  66467. },
  66468. stop: (event, ui) => {
  66469. let value = elDuration.spinner('value');
  66470. animation.setDuration(value);
  66471. },
  66472. incremental: (count) => {
  66473. let value = elDuration.spinner('value');
  66474. let step = elDuration.spinner('option', 'step');
  66475. let delta = value * 0.05;
  66476. let increments = Math.max(1, parseInt(delta / step));
  66477. return increments;
  66478. }
  66479. });
  66480. elDuration.spinner('value', animation.getDuration());
  66481. elDuration.spinner('widget').css('width', '100%');
  66482. const elKeyframes = this.elContent.find("#animation_keyframes");
  66483. const updateKeyframes = () => {
  66484. elKeyframes.empty();
  66485. //let index = 0;
  66486. // <span style="flex-grow: 0;">
  66487. // <img name="add" src="${Potree.resourcePath}/icons/add.svg" style="width: 1.5em; height: 1.5em"/>
  66488. // </span>
  66489. const addNewKeyframeItem = (index) => {
  66490. let elNewKeyframe = $(`
  66491. <div style="display: flex; margin: 0.2em 0em">
  66492. <span style="flex-grow: 1"></span>
  66493. <input type="button" name="add" value="insert control point" />
  66494. <span style="flex-grow: 1"></span>
  66495. </div>
  66496. `);
  66497. const elAdd = elNewKeyframe.find("input[name=add]");
  66498. elAdd.click( () => {
  66499. animation.createControlPoint(index);
  66500. animation.changeCallback();
  66501. });
  66502. elKeyframes.append(elNewKeyframe);
  66503. };
  66504. const addKeyframeItem = (index) => {
  66505. let elKeyframe = $(`
  66506. <div style="display: flex; margin: 0.2em 0em">
  66507. <span style="flex-grow: 0;">
  66508. <img name="assign" src="${Potree.resourcePath}/icons/assign.svg" style="width: 1.5em; height: 1.5em"/>
  66509. </span>
  66510. <span style="flex-grow: 0;">
  66511. <img name="move" src="${Potree.resourcePath}/icons/circled_dot.svg" style="width: 1.5em; height: 1.5em"/>
  66512. </span>
  66513. <span style="flex-grow: 0; width: 1.5em; height: 1.5em"></span>
  66514. <span style="flex-grow: 0; font-size: 1.5em">keyframe</span>
  66515. <span style="flex-grow: 1"></span>
  66516. <span style="flex-grow: 0;">
  66517. <img name="delete" src="${Potree.resourcePath}/icons/remove.svg" style="width: 1.5em; height: 1.5em"/>
  66518. </span>
  66519. </div>
  66520. `);
  66521. const elAssign = elKeyframe.find("img[name=assign]");
  66522. const elMove = elKeyframe.find("img[name=move]");
  66523. const elDelete = elKeyframe.find("img[name=delete]");
  66524. elAssign.click( () => {
  66525. animation.posCurve.points[index].copy(viewer.scene.view.position);
  66526. animation.targetCurve.points[index].copy(viewer.scene.view.getPivot());
  66527. animation.changeCallback();
  66528. });
  66529. elMove.click( () => {
  66530. viewer.scene.view.position.copy(animation.posCurve.points[index]);
  66531. viewer.scene.view.lookAt(animation.targetCurve.points[index]);
  66532. });
  66533. elDelete.click( () => {
  66534. animation.removeControlPoint(index);
  66535. animation.changeCallback();
  66536. });
  66537. elKeyframes.append(elKeyframe);
  66538. };
  66539. let index = 0;
  66540. addNewKeyframeItem(index);
  66541. animation.posCurve.points.forEach(e=>{
  66542. addKeyframeItem(index);
  66543. index++;
  66544. addNewKeyframeItem(index);
  66545. });
  66546. };
  66547. updateKeyframes();
  66548. animation.addEventListener("controlpoint_added", updateKeyframes);
  66549. animation.addEventListener("controlpoint_removed", updateKeyframes);
  66550. // this._update = () => { this.update(); };
  66551. // this.update();
  66552. }
  66553. update(){
  66554. }
  66555. };
  66556. class PropertiesPanel{
  66557. constructor(container, viewer){
  66558. this.container = container;
  66559. this.viewer = viewer;
  66560. this.object = null;
  66561. this.cleanupTasks = [];
  66562. this.scene = null;
  66563. }
  66564. setScene(scene){
  66565. this.scene = scene;
  66566. }
  66567. set(object){
  66568. if(this.object === object){
  66569. return;
  66570. }
  66571. this.object = object;
  66572. for(let task of this.cleanupTasks){
  66573. task();
  66574. }
  66575. this.cleanupTasks = [];
  66576. this.container.empty();
  66577. if(object instanceof PointCloudTree){
  66578. this.setPointCloud(object);
  66579. }else if(object instanceof Measure || object instanceof Profile || object instanceof Volume){
  66580. this.setMeasurement(object);
  66581. }else if(object instanceof Camera){
  66582. this.setCamera(object);
  66583. }else if(object instanceof Annotation){
  66584. this.setAnnotation(object);
  66585. }else if(object instanceof CameraAnimation){
  66586. this.setCameraAnimation(object);
  66587. }
  66588. }
  66589. //
  66590. // Used for events that should be removed when the property object changes.
  66591. // This is for listening to materials, scene, point clouds, etc.
  66592. // not required for DOM listeners, since they are automatically cleared by removing the DOM subtree.
  66593. //
  66594. addVolatileListener(target, type, callback){
  66595. target.addEventListener(type, callback);
  66596. this.cleanupTasks.push(() => {
  66597. target.removeEventListener(type, callback);
  66598. });
  66599. }
  66600. setPointCloud(pointcloud){
  66601. let material = pointcloud.material;
  66602. let panel = $(`
  66603. <div class="scene_content selectable">
  66604. <ul class="pv-menu-list">
  66605. <li>
  66606. <span data-i18n="appearance.point_size"></span>:&nbsp;<span id="lblPointSize"></span> <div id="sldPointSize"></div>
  66607. </li>
  66608. <li>
  66609. <span data-i18n="appearance.min_point_size"></span>:&nbsp;<span id="lblMinPointSize"></span> <div id="sldMinPointSize"></div>
  66610. </li>
  66611. <!-- SIZE TYPE -->
  66612. <li>
  66613. <label for="optPointSizing" class="pv-select-label" data-i18n="appearance.point_size_type">Point Sizing </label>
  66614. <select id="optPointSizing" name="optPointSizing">
  66615. <option>FIXED</option>
  66616. <option>ATTENUATED</option>
  66617. <option>ADAPTIVE</option>
  66618. </select>
  66619. </li>
  66620. <!-- SHAPE -->
  66621. <li>
  66622. <label for="optShape" class="pv-select-label" data-i18n="appearance.point_shape"></label><br>
  66623. <select id="optShape" name="optShape">
  66624. <option>SQUARE</option>
  66625. <option>CIRCLE</option>
  66626. <option>PARABOLOID</option>
  66627. </select>
  66628. </li>
  66629. <li id="materials_backface_container">
  66630. <label><input id="set_backface_culling" type="checkbox" /><span data-i18n="appearance.backface_culling"></span></label>
  66631. </li>
  66632. <!-- OPACITY -->
  66633. <li><span data-i18n="appearance.point_opacity"></span>:<span id="lblOpacity"></span><div id="sldOpacity"></div></li>
  66634. <div class="divider">
  66635. <span>Attribute</span>
  66636. </div>
  66637. <li>
  66638. <select id="optMaterial" name="optMaterial"></select>
  66639. </li>
  66640. <div id="materials.composite_weight_container">
  66641. <div class="divider">
  66642. <span>Attribute Weights</span>
  66643. </div>
  66644. <li>RGB: <span id="lblWeightRGB"></span> <div id="sldWeightRGB"></div> </li>
  66645. <li>Intensity: <span id="lblWeightIntensity"></span> <div id="sldWeightIntensity"></div> </li>
  66646. <li>Elevation: <span id="lblWeightElevation"></span> <div id="sldWeightElevation"></div> </li>
  66647. <li>Classification: <span id="lblWeightClassification"></span> <div id="sldWeightClassification"></div> </li>
  66648. <li>Return Number: <span id="lblWeightReturnNumber"></span> <div id="sldWeightReturnNumber"></div> </li>
  66649. <li>Source ID: <span id="lblWeightSourceID"></span> <div id="sldWeightSourceID"></div> </li>
  66650. </div>
  66651. <div id="materials.rgb_container">
  66652. <div class="divider">
  66653. <span>RGB</span>
  66654. </div>
  66655. <li>Gamma: <span id="lblRGBGamma"></span> <div id="sldRGBGamma"></div> </li>
  66656. <li>Brightness: <span id="lblRGBBrightness"></span> <div id="sldRGBBrightness"></div> </li>
  66657. <li>Contrast: <span id="lblRGBContrast"></span> <div id="sldRGBContrast"></div> </li>
  66658. </div>
  66659. <div id="materials.extra_container">
  66660. <div class="divider">
  66661. <span>Extra Attribute</span>
  66662. </div>
  66663. <li><span data-i18n="appearance.extra_range"></span>: <span id="lblExtraRange"></span> <div id="sldExtraRange"></div></li>
  66664. <li>Gamma: <span id="lblExtraGamma"></span> <div id="sldExtraGamma"></div></li>
  66665. <li>Brightness: <span id="lblExtraBrightness"></span> <div id="sldExtraBrightness"></div></li>
  66666. <li>Contrast: <span id="lblExtraContrast"></span> <div id="sldExtraContrast"></div></li>
  66667. </div>
  66668. <div id="materials.matcap_container">
  66669. <div class="divider">
  66670. <span>MATCAP</span>
  66671. </div>
  66672. <li>
  66673. <div id="matcap_scheme_selection" style="display: flex; flex-wrap: wrap;"> </div>
  66674. </li>
  66675. </div>
  66676. <div id="materials.color_container">
  66677. <div class="divider">
  66678. <span>Color</span>
  66679. </div>
  66680. <input id="materials.color.picker" />
  66681. </div>
  66682. <div id="materials.elevation_container">
  66683. <div class="divider">
  66684. <span>Elevation</span>
  66685. </div>
  66686. <li><span data-i18n="appearance.elevation_range"></span>: <span id="lblHeightRange"></span> <div id="sldHeightRange"></div> </li>
  66687. <li>
  66688. <selectgroup id="gradient_repeat_option">
  66689. <option id="gradient_repeat_clamp" value="CLAMP">Clamp</option>
  66690. <option id="gradient_repeat_repeat" value="REPEAT">Repeat</option>
  66691. <option id="gradient_repeat_mirrored_repeat" value="MIRRORED_REPEAT">Mirrored Repeat</option>
  66692. </selectgroup>
  66693. </li>
  66694. <li>
  66695. <span>Gradient Scheme:</span>
  66696. <div id="elevation_gradient_scheme_selection" style="display: flex; padding: 1em 0em">
  66697. </div>
  66698. </li>
  66699. </div>
  66700. <div id="materials.transition_container">
  66701. <div class="divider">
  66702. <span>Transition</span>
  66703. </div>
  66704. <li>transition: <span id="lblTransition"></span> <div id="sldTransition"></div> </li>
  66705. </div>
  66706. <div id="materials.intensity_container">
  66707. <div class="divider">
  66708. <span>Intensity</span>
  66709. </div>
  66710. <li>Range: <span id="lblIntensityRange"></span> <div id="sldIntensityRange"></div> </li>
  66711. <li>Gamma: <span id="lblIntensityGamma"></span> <div id="sldIntensityGamma"></div> </li>
  66712. <li>Brightness: <span id="lblIntensityBrightness"></span> <div id="sldIntensityBrightness"></div> </li>
  66713. <li>Contrast: <span id="lblIntensityContrast"></span> <div id="sldIntensityContrast"></div> </li>
  66714. </div>
  66715. <div id="materials.gpstime_container">
  66716. <div class="divider">
  66717. <span>GPS Time</span>
  66718. </div>
  66719. </div>
  66720. <div id="materials.index_container">
  66721. <div class="divider">
  66722. <span>Indices</span>
  66723. </div>
  66724. </div>
  66725. </ul>
  66726. </div>
  66727. `);
  66728. panel.i18n();
  66729. this.container.append(panel);
  66730. { // POINT SIZE
  66731. let sldPointSize = panel.find(`#sldPointSize`);
  66732. let lblPointSize = panel.find(`#lblPointSize`);
  66733. sldPointSize.slider({
  66734. value: material.size,
  66735. min: 0,
  66736. max: 3,
  66737. step: 0.01,
  66738. slide: function (event, ui) { material.size = ui.value; }
  66739. });
  66740. let update = (e) => {
  66741. lblPointSize.html(material.size.toFixed(2));
  66742. sldPointSize.slider({value: material.size});
  66743. };
  66744. this.addVolatileListener(material, "point_size_changed", update);
  66745. update();
  66746. }
  66747. { // MINIMUM POINT SIZE
  66748. let sldMinPointSize = panel.find(`#sldMinPointSize`);
  66749. let lblMinPointSize = panel.find(`#lblMinPointSize`);
  66750. sldMinPointSize.slider({
  66751. value: material.size,
  66752. min: 0,
  66753. max: 3,
  66754. step: 0.01,
  66755. slide: function (event, ui) { material.minSize = ui.value; }
  66756. });
  66757. let update = (e) => {
  66758. lblMinPointSize.html(material.minSize.toFixed(2));
  66759. sldMinPointSize.slider({value: material.minSize});
  66760. };
  66761. this.addVolatileListener(material, "point_size_changed", update);
  66762. update();
  66763. }
  66764. { // POINT SIZING
  66765. let strSizeType = Object.keys(PointSizeType)[material.pointSizeType];
  66766. let opt = panel.find(`#optPointSizing`);
  66767. opt.selectmenu();
  66768. opt.val(strSizeType).selectmenu('refresh');
  66769. opt.selectmenu({
  66770. change: (event, ui) => {
  66771. material.pointSizeType = PointSizeType[ui.item.value];
  66772. }
  66773. });
  66774. }
  66775. { // SHAPE
  66776. let opt = panel.find(`#optShape`);
  66777. opt.selectmenu({
  66778. change: (event, ui) => {
  66779. let value = ui.item.value;
  66780. material.shape = PointShape[value];
  66781. }
  66782. });
  66783. let update = () => {
  66784. let typename = Object.keys(PointShape)[material.shape];
  66785. opt.selectmenu().val(typename).selectmenu('refresh');
  66786. };
  66787. this.addVolatileListener(material, "point_shape_changed", update);
  66788. update();
  66789. }
  66790. { // BACKFACE CULLING
  66791. let opt = panel.find(`#set_backface_culling`);
  66792. opt.click(() => {
  66793. material.backfaceCulling = opt.prop("checked");
  66794. });
  66795. let update = () => {
  66796. let value = material.backfaceCulling;
  66797. opt.prop("checked", value);
  66798. };
  66799. this.addVolatileListener(material, "backface_changed", update);
  66800. update();
  66801. let blockBackface = $('#materials_backface_container');
  66802. blockBackface.css('display', 'none');
  66803. const pointAttributes = pointcloud.pcoGeometry.pointAttributes;
  66804. const hasNormals = pointAttributes.hasNormals ? pointAttributes.hasNormals() : false;
  66805. if(hasNormals) {
  66806. blockBackface.css('display', 'block');
  66807. }
  66808. /*
  66809. opt.checkboxradio({
  66810. clicked: (event, ui) => {
  66811. // let value = ui.item.value;
  66812. let value = ui.item.checked;
  66813. console.log(value);
  66814. material.backfaceCulling = value; // $('#set_freeze').prop("checked");
  66815. }
  66816. });
  66817. */
  66818. }
  66819. { // OPACITY
  66820. let sldOpacity = panel.find(`#sldOpacity`);
  66821. let lblOpacity = panel.find(`#lblOpacity`);
  66822. sldOpacity.slider({
  66823. value: material.opacity,
  66824. min: 0,
  66825. max: 1,
  66826. step: 0.001,
  66827. slide: function (event, ui) {
  66828. material.opacity = ui.value;
  66829. }
  66830. });
  66831. let update = (e) => {
  66832. lblOpacity.html(material.opacity.toFixed(2));
  66833. sldOpacity.slider({value: material.opacity});
  66834. };
  66835. this.addVolatileListener(material, "opacity_changed", update);
  66836. update();
  66837. }
  66838. {
  66839. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  66840. let options = [];
  66841. options.push(...attributes.map(a => a.name));
  66842. const intensityIndex = options.indexOf("intensity");
  66843. if(intensityIndex >= 0){
  66844. options.splice(intensityIndex + 1, 0, "intensity gradient");
  66845. }
  66846. options.push(
  66847. "elevation",
  66848. "color",
  66849. 'matcap',
  66850. 'indices',
  66851. 'level of detail',
  66852. 'composite'
  66853. );
  66854. const blacklist = [
  66855. "POSITION_CARTESIAN",
  66856. "position",
  66857. ];
  66858. options = options.filter(o => !blacklist.includes(o));
  66859. let attributeSelection = panel.find('#optMaterial');
  66860. for(let option of options){
  66861. let elOption = $(`<option>${option}</option>`);
  66862. attributeSelection.append(elOption);
  66863. }
  66864. let updateMaterialPanel = (event, ui) => {
  66865. let selectedValue = attributeSelection.selectmenu().val();
  66866. material.activeAttributeName = selectedValue;
  66867. let attribute = pointcloud.getAttribute(selectedValue);
  66868. if(selectedValue === "intensity gradient"){
  66869. attribute = pointcloud.getAttribute("intensity");
  66870. }
  66871. const isIntensity = attribute ? ["intensity", "intensity gradient"].includes(attribute.name) : false;
  66872. if(isIntensity){
  66873. if(pointcloud.material.intensityRange[0] === Infinity){
  66874. pointcloud.material.intensityRange = attribute.range;
  66875. }
  66876. const [min, max] = attribute.range;
  66877. panel.find('#sldIntensityRange').slider({
  66878. range: true,
  66879. min: min, max: max, step: 0.01,
  66880. values: [min, max],
  66881. slide: (event, ui) => {
  66882. let min = ui.values[0];
  66883. let max = ui.values[1];
  66884. material.intensityRange = [min, max];
  66885. }
  66886. });
  66887. } else if(attribute){
  66888. let [min, max] = attribute.range;
  66889. let selectedRange = material.getRange(attribute.name);
  66890. if(!selectedRange){
  66891. selectedRange = [...attribute.range];
  66892. }
  66893. let minMaxAreNumbers = typeof min === "number" && typeof max === "number";
  66894. /* min = 0 ;max = 50
  66895. selectedRange[0] =min; selectedRange[1] = max; */
  66896. if(minMaxAreNumbers){
  66897. panel.find('#sldExtraRange').slider({
  66898. range: true,
  66899. min: min,
  66900. max: max,
  66901. step: 0.01,
  66902. values: selectedRange,
  66903. slide: (event, ui) => {
  66904. let [a, b] = ui.values;
  66905. material.setRange(attribute.name, [a, b]);
  66906. }
  66907. });
  66908. }
  66909. }
  66910. let blockWeights = $('#materials\\.composite_weight_container');
  66911. let blockElevation = $('#materials\\.elevation_container');
  66912. let blockRGB = $('#materials\\.rgb_container');
  66913. let blockExtra = $('#materials\\.extra_container');
  66914. let blockColor = $('#materials\\.color_container');
  66915. let blockIntensity = $('#materials\\.intensity_container');
  66916. let blockIndex = $('#materials\\.index_container');
  66917. let blockTransition = $('#materials\\.transition_container');
  66918. let blockGps = $('#materials\\.gpstime_container');
  66919. let blockMatcap = $('#materials\\.matcap_container');
  66920. blockIndex.css('display', 'none');
  66921. blockIntensity.css('display', 'none');
  66922. blockElevation.css('display', 'none');
  66923. blockRGB.css('display', 'none');
  66924. blockExtra.css('display', 'none');
  66925. blockColor.css('display', 'none');
  66926. blockWeights.css('display', 'none');
  66927. blockTransition.css('display', 'none');
  66928. blockMatcap.css('display', 'none');
  66929. blockGps.css('display', 'none');
  66930. if (selectedValue === 'composite') {
  66931. blockWeights.css('display', 'block');
  66932. blockElevation.css('display', 'block');
  66933. blockRGB.css('display', 'block');
  66934. blockIntensity.css('display', 'block');
  66935. } else if (selectedValue === 'elevation') {
  66936. blockElevation.css('display', 'block');
  66937. } else if (selectedValue === 'RGB and Elevation') {
  66938. blockRGB.css('display', 'block');
  66939. blockElevation.css('display', 'block');
  66940. } else if (selectedValue === 'rgba') {
  66941. blockRGB.css('display', 'block');
  66942. } else if (selectedValue === 'color') {
  66943. blockColor.css('display', 'block');
  66944. } else if (selectedValue === 'intensity') {
  66945. blockIntensity.css('display', 'block');
  66946. } else if (selectedValue === 'intensity gradient') {
  66947. blockIntensity.css('display', 'block');
  66948. } else if (selectedValue === "indices" ){
  66949. blockIndex.css('display', 'block');
  66950. } else if (selectedValue === "matcap" ){
  66951. blockMatcap.css('display', 'block');
  66952. } else if (selectedValue === "classification" ){
  66953. // add classification color selctor?
  66954. } else if (selectedValue === "gps-time" ){
  66955. blockGps.css('display', 'block');
  66956. } else if(selectedValue === "number of returns"){
  66957. } else if(selectedValue === "return number"){
  66958. } else if(["source id", "point source id"].includes(selectedValue)){
  66959. } else {
  66960. blockExtra.css('display', 'block');
  66961. }
  66962. };
  66963. attributeSelection.selectmenu({change: updateMaterialPanel});
  66964. let update = () => {
  66965. attributeSelection.val(material.activeAttributeName).selectmenu('refresh');
  66966. };
  66967. this.addVolatileListener(material, "point_color_type_changed", update);
  66968. this.addVolatileListener(material, "active_attribute_changed", update);
  66969. update();
  66970. updateMaterialPanel();
  66971. }
  66972. {
  66973. const schemes = Object.keys(Potree.Gradients).map(name => ({name: name, values: Gradients[name]}));
  66974. let elSchemeContainer = panel.find("#elevation_gradient_scheme_selection");
  66975. for(let scheme of schemes){
  66976. let elScheme = $(`
  66977. <span style="flex-grow: 1;">
  66978. </span>
  66979. `);
  66980. const svg = Potree.Utils.createSvgGradient(scheme.values);
  66981. svg.setAttributeNS(null, "class", `button-icon`);
  66982. elScheme.append($(svg));
  66983. elScheme.click( () => {
  66984. material.gradient = Gradients[scheme.name];
  66985. });
  66986. elSchemeContainer.append(elScheme);
  66987. }
  66988. }
  66989. {
  66990. let matcaps = [
  66991. {name: "Normals", icon: `${Potree.resourcePath}/icons/matcap/check_normal+y.jpg`},
  66992. {name: "Basic 1", icon: `${Potree.resourcePath}/icons/matcap/basic_1.jpg`},
  66993. {name: "Basic 2", icon: `${Potree.resourcePath}/icons/matcap/basic_2.jpg`},
  66994. {name: "Basic Dark", icon: `${Potree.resourcePath}/icons/matcap/basic_dark.jpg`},
  66995. {name: "Basic Side", icon: `${Potree.resourcePath}/icons/matcap/basic_side.jpg`},
  66996. {name: "Ceramic Dark", icon: `${Potree.resourcePath}/icons/matcap/ceramic_dark.jpg`},
  66997. {name: "Ceramic Lightbulb", icon: `${Potree.resourcePath}/icons/matcap/ceramic_lightbulb.jpg`},
  66998. {name: "Clay Brown", icon: `${Potree.resourcePath}/icons/matcap/clay_brown.jpg`},
  66999. {name: "Clay Muddy", icon: `${Potree.resourcePath}/icons/matcap/clay_muddy.jpg`},
  67000. {name: "Clay Studio", icon: `${Potree.resourcePath}/icons/matcap/clay_studio.jpg`},
  67001. {name: "Resin", icon: `${Potree.resourcePath}/icons/matcap/resin.jpg`},
  67002. {name: "Skin", icon: `${Potree.resourcePath}/icons/matcap/skin.jpg`},
  67003. {name: "Jade", icon: `${Potree.resourcePath}/icons/matcap/jade.jpg`},
  67004. {name: "Metal_ Anisotropic", icon: `${Potree.resourcePath}/icons/matcap/metal_anisotropic.jpg`},
  67005. {name: "Metal Carpaint", icon: `${Potree.resourcePath}/icons/matcap/metal_carpaint.jpg`},
  67006. {name: "Metal Lead", icon: `${Potree.resourcePath}/icons/matcap/metal_lead.jpg`},
  67007. {name: "Metal Shiny", icon: `${Potree.resourcePath}/icons/matcap/metal_shiny.jpg`},
  67008. {name: "Pearl", icon: `${Potree.resourcePath}/icons/matcap/pearl.jpg`},
  67009. {name: "Toon", icon: `${Potree.resourcePath}/icons/matcap/toon.jpg`},
  67010. {name: "Check Rim Light", icon: `${Potree.resourcePath}/icons/matcap/check_rim_light.jpg`},
  67011. {name: "Check Rim Dark", icon: `${Potree.resourcePath}/icons/matcap/check_rim_dark.jpg`},
  67012. {name: "Contours 1", icon: `${Potree.resourcePath}/icons/matcap/contours_1.jpg`},
  67013. {name: "Contours 2", icon: `${Potree.resourcePath}/icons/matcap/contours_2.jpg`},
  67014. {name: "Contours 3", icon: `${Potree.resourcePath}/icons/matcap/contours_3.jpg`},
  67015. {name: "Reflection Check Horizontal", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_horizontal.jpg`},
  67016. {name: "Reflection Check Vertical", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_vertical.jpg`},
  67017. ];
  67018. let elMatcapContainer = panel.find("#matcap_scheme_selection");
  67019. for(let matcap of matcaps){
  67020. let elMatcap = $(`
  67021. <img src="${matcap.icon}" class="button-icon" style="width: 25%;" />
  67022. `);
  67023. elMatcap.click( () => {
  67024. material.matcap = matcap.icon.substring(matcap.icon.lastIndexOf('/'));
  67025. });
  67026. elMatcapContainer.append(elMatcap);
  67027. }
  67028. }
  67029. {
  67030. panel.find('#sldRGBGamma').slider({
  67031. value: material.rgbGamma,
  67032. min: 0, max: 4, step: 0.01,
  67033. slide: (event, ui) => {material.rgbGamma = ui.value;}
  67034. });
  67035. panel.find('#sldRGBContrast').slider({
  67036. value: material.rgbContrast,
  67037. min: -1, max: 1, step: 0.01,
  67038. slide: (event, ui) => {material.rgbContrast = ui.value;}
  67039. });
  67040. panel.find('#sldRGBBrightness').slider({
  67041. value: material.rgbBrightness,
  67042. min: -1, max: 1, step: 0.01,
  67043. slide: (event, ui) => {material.rgbBrightness = ui.value;}
  67044. });
  67045. panel.find('#sldExtraGamma').slider({
  67046. value: material.extraGamma,
  67047. min: 0, max: 4, step: 0.01,
  67048. slide: (event, ui) => {material.extraGamma = ui.value;}
  67049. });
  67050. panel.find('#sldExtraBrightness').slider({
  67051. value: material.extraBrightness,
  67052. min: -1, max: 1, step: 0.01,
  67053. slide: (event, ui) => {material.extraBrightness = ui.value;}
  67054. });
  67055. panel.find('#sldExtraContrast').slider({
  67056. value: material.extraContrast,
  67057. min: -1, max: 1, step: 0.01,
  67058. slide: (event, ui) => {material.extraContrast = ui.value;}
  67059. });
  67060. panel.find('#sldHeightRange').slider({
  67061. range: true,
  67062. min: 0, max: 1000, step: 0.01,
  67063. values: [0, 1000],
  67064. slide: (event, ui) => {
  67065. material.heightMin = ui.values[0];
  67066. material.heightMax = ui.values[1];
  67067. }
  67068. });
  67069. panel.find('#sldIntensityGamma').slider({
  67070. value: material.intensityGamma,
  67071. min: 0, max: 4, step: 0.01,
  67072. slide: (event, ui) => {material.intensityGamma = ui.value;}
  67073. });
  67074. panel.find('#sldIntensityContrast').slider({
  67075. value: material.intensityContrast,
  67076. min: -1, max: 1, step: 0.01,
  67077. slide: (event, ui) => {material.intensityContrast = ui.value;}
  67078. });
  67079. panel.find('#sldIntensityBrightness').slider({
  67080. value: material.intensityBrightness,
  67081. min: -1, max: 1, step: 0.01,
  67082. slide: (event, ui) => {material.intensityBrightness = ui.value;}
  67083. });
  67084. panel.find('#sldWeightRGB').slider({
  67085. value: material.weightRGB,
  67086. min: 0, max: 1, step: 0.01,
  67087. slide: (event, ui) => {material.weightRGB = ui.value;}
  67088. });
  67089. panel.find('#sldWeightIntensity').slider({
  67090. value: material.weightIntensity,
  67091. min: 0, max: 1, step: 0.01,
  67092. slide: (event, ui) => {material.weightIntensity = ui.value;}
  67093. });
  67094. panel.find('#sldWeightElevation').slider({
  67095. value: material.weightElevation,
  67096. min: 0, max: 1, step: 0.01,
  67097. slide: (event, ui) => {material.weightElevation = ui.value;}
  67098. });
  67099. panel.find('#sldWeightClassification').slider({
  67100. value: material.weightClassification,
  67101. min: 0, max: 1, step: 0.01,
  67102. slide: (event, ui) => {material.weightClassification = ui.value;}
  67103. });
  67104. panel.find('#sldWeightReturnNumber').slider({
  67105. value: material.weightReturnNumber,
  67106. min: 0, max: 1, step: 0.01,
  67107. slide: (event, ui) => {material.weightReturnNumber = ui.value;}
  67108. });
  67109. panel.find('#sldWeightSourceID').slider({
  67110. value: material.weightSourceID,
  67111. min: 0, max: 1, step: 0.01,
  67112. slide: (event, ui) => {material.weightSourceID = ui.value;}
  67113. });
  67114. panel.find(`#materials\\.color\\.picker`).spectrum({
  67115. flat: true,
  67116. showInput: true,
  67117. preferredFormat: 'rgb',
  67118. cancelText: '',
  67119. chooseText: 'Apply',
  67120. color: `#${material.color.getHexString()}`,
  67121. move: color => {
  67122. let cRGB = color.toRgb();
  67123. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  67124. material.color = tc;
  67125. },
  67126. change: color => {
  67127. let cRGB = color.toRgb();
  67128. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  67129. material.color = tc;
  67130. }
  67131. });
  67132. this.addVolatileListener(material, "color_changed", () => {
  67133. panel.find(`#materials\\.color\\.picker`)
  67134. .spectrum('set', `#${material.color.getHexString()}`);
  67135. });
  67136. let updateHeightRange = function () {
  67137. let aPosition = pointcloud.getAttribute("position");
  67138. let bMin, bMax;
  67139. if(aPosition){
  67140. // for new format 2.0 and loader that contain precomputed min/max of attributes
  67141. let min = aPosition.range[0][2];
  67142. let max = aPosition.range[1][2];
  67143. let width = max - min;
  67144. bMin = min - 0.2 * width;
  67145. bMax = max + 0.2 * width;
  67146. }else {
  67147. // for format up until exlusive 2.0
  67148. let box = [pointcloud.pcoGeometry.tightBoundingBox, pointcloud.getBoundingBoxWorld()]
  67149. .find(v => v !== undefined);
  67150. pointcloud.updateMatrixWorld(true);
  67151. box = Utils.computeTransformedBoundingBox(box, pointcloud.matrixWorld);
  67152. let bWidth = box.max.z - box.min.z;
  67153. bMin = box.min.z - 0.2 * bWidth;
  67154. bMax = box.max.z + 0.2 * bWidth;
  67155. }
  67156. let range = material.elevationRange;
  67157. panel.find('#lblHeightRange').html(`${range[0].toFixed(2)} to ${range[1].toFixed(2)}`);
  67158. panel.find('#sldHeightRange').slider({min: bMin, max: bMax, values: range});
  67159. };
  67160. let updateExtraRange = function () {
  67161. let attributeName = material.activeAttributeName;
  67162. let attribute = pointcloud.getAttribute(attributeName);
  67163. if(attribute == null){
  67164. return;
  67165. }
  67166. let range = material.getRange(attributeName);
  67167. if(range == null){
  67168. range = attribute.range;
  67169. }
  67170. // currently only supporting scalar ranges.
  67171. // rgba, normals, positions, etc have vector ranges, however
  67172. let isValidRange = (typeof range[0] === "number") && (typeof range[1] === "number");
  67173. if(!isValidRange){
  67174. return;
  67175. }
  67176. if(range){
  67177. let msg = `${range[0].toFixed(2)} to ${range[1].toFixed(2)}`;
  67178. panel.find('#lblExtraRange').html(msg);
  67179. }else {
  67180. panel.find("could not deduce range");
  67181. }
  67182. };
  67183. let updateIntensityRange = function () {
  67184. let range = material.intensityRange;
  67185. panel.find('#lblIntensityRange').html(`${parseInt(range[0])} to ${parseInt(range[1])}`);
  67186. };
  67187. {
  67188. updateHeightRange();
  67189. panel.find(`#sldHeightRange`).slider('option', 'min');
  67190. panel.find(`#sldHeightRange`).slider('option', 'max');
  67191. }
  67192. {
  67193. let elGradientRepeat = panel.find("#gradient_repeat_option");
  67194. elGradientRepeat.selectgroup({title: "Gradient"});
  67195. elGradientRepeat.find("input").click( (e) => {
  67196. this.viewer.setElevationGradientRepeat(ElevationGradientRepeat[e.target.value]);
  67197. });
  67198. let current = Object.keys(ElevationGradientRepeat)
  67199. .filter(key => ElevationGradientRepeat[key] === this.viewer.elevationGradientRepeat);
  67200. elGradientRepeat.find(`input[value=${current}]`).trigger("click");
  67201. }
  67202. let onIntensityChange = () => {
  67203. let gamma = material.intensityGamma;
  67204. let contrast = material.intensityContrast;
  67205. let brightness = material.intensityBrightness;
  67206. updateIntensityRange();
  67207. panel.find('#lblIntensityGamma').html(gamma.toFixed(2));
  67208. panel.find('#lblIntensityContrast').html(contrast.toFixed(2));
  67209. panel.find('#lblIntensityBrightness').html(brightness.toFixed(2));
  67210. panel.find('#sldIntensityGamma').slider({value: gamma});
  67211. panel.find('#sldIntensityContrast').slider({value: contrast});
  67212. panel.find('#sldIntensityBrightness').slider({value: brightness});
  67213. };
  67214. let onRGBChange = () => {
  67215. let gamma = material.rgbGamma;
  67216. let contrast = material.rgbContrast;
  67217. let brightness = material.rgbBrightness;
  67218. panel.find('#lblRGBGamma').html(gamma.toFixed(2));
  67219. panel.find('#lblRGBContrast').html(contrast.toFixed(2));
  67220. panel.find('#lblRGBBrightness').html(brightness.toFixed(2));
  67221. panel.find('#sldRGBGamma').slider({value: gamma});
  67222. panel.find('#sldRGBContrast').slider({value: contrast});
  67223. panel.find('#sldRGBBrightness').slider({value: brightness});
  67224. };
  67225. this.addVolatileListener(material, "material_property_changed", updateExtraRange);
  67226. this.addVolatileListener(material, "material_property_changed", updateHeightRange);
  67227. this.addVolatileListener(material, "material_property_changed", onIntensityChange);
  67228. this.addVolatileListener(material, "material_property_changed", onRGBChange);
  67229. updateExtraRange();
  67230. updateHeightRange();
  67231. onIntensityChange();
  67232. onRGBChange();
  67233. }
  67234. }
  67235. setMeasurement(object){
  67236. let TYPE = {
  67237. DISTANCE: {panel: DistancePanel},
  67238. AREA: {panel: AreaPanel},
  67239. POINT: {panel: PointPanel},
  67240. ANGLE: {panel: AnglePanel},
  67241. HEIGHT: {panel: HeightPanel},
  67242. PROFILE: {panel: ProfilePanel},
  67243. VOLUME: {panel: VolumePanel},
  67244. CIRCLE: {panel: CirclePanel},
  67245. OTHER: {panel: PointPanel},
  67246. };
  67247. let getType = (measurement) => {
  67248. if (measurement instanceof Measure) {
  67249. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  67250. return TYPE.DISTANCE;
  67251. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  67252. return TYPE.AREA;
  67253. } else if (measurement.maxMarkers === 1) {
  67254. return TYPE.POINT;
  67255. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  67256. return TYPE.ANGLE;
  67257. } else if (measurement.showHeight) {
  67258. return TYPE.HEIGHT;
  67259. } else if (measurement.showCircle) {
  67260. return TYPE.CIRCLE;
  67261. } else {
  67262. return TYPE.OTHER;
  67263. }
  67264. } else if (measurement instanceof Profile) {
  67265. return TYPE.PROFILE;
  67266. } else if (measurement instanceof Volume) {
  67267. return TYPE.VOLUME;
  67268. }
  67269. };
  67270. //this.container.html("measurement");
  67271. let type = getType(object);
  67272. let Panel = type.panel;
  67273. let panel = new Panel(this.viewer, object, this);
  67274. this.container.append(panel.elContent);
  67275. }
  67276. setCamera(camera){
  67277. let panel = new CameraPanel(this.viewer, this);
  67278. this.container.append(panel.elContent);
  67279. }
  67280. setAnnotation(annotation){
  67281. let panel = new AnnotationPanel(this.viewer, this, annotation);
  67282. this.container.append(panel.elContent);
  67283. }
  67284. setCameraAnimation(animation){
  67285. let panel = new CameraAnimationPanel(this.viewer, this, animation);
  67286. this.container.append(panel.elContent);
  67287. }
  67288. }
  67289. function addCommas(nStr){
  67290. nStr += '';
  67291. let x = nStr.split('.');
  67292. let x1 = x[0];
  67293. let x2 = x.length > 1 ? '.' + x[1] : '';
  67294. let rgx = /(\d+)(\d{3})/;
  67295. while (rgx.test(x1)) {
  67296. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  67297. }
  67298. return x1 + x2;
  67299. };
  67300. function format(value){
  67301. return addCommas(value.toFixed(3));
  67302. };
  67303. class HierarchicalSlider{
  67304. constructor(params = {}){
  67305. this.element = document.createElement("div");
  67306. this.labels = [];
  67307. this.sliders = [];
  67308. this.range = params.range != null ? params.range : [0, 1];
  67309. this.slide = params.slide != null ? params.slide : null;
  67310. this.step = params.step != null ? params.step : 0.0001;
  67311. let levels = params.levels != null ? params.levels : 1;
  67312. for(let level = 0; level < levels; level++){
  67313. this.addLevel();
  67314. }
  67315. }
  67316. setRange(range){
  67317. this.range = [...range];
  67318. { // root slider
  67319. let slider = this.sliders[0];
  67320. $(slider).slider({
  67321. min: range[0],
  67322. max: range[1],
  67323. });
  67324. }
  67325. for(let i = 1; i < this.sliders.length; i++){
  67326. let parentSlider = this.sliders[i - 1];
  67327. let slider = this.sliders[i];
  67328. let parentValues = $(parentSlider).slider("option", "values");
  67329. let childRange = [...parentValues];
  67330. $(slider).slider({
  67331. min: childRange[0],
  67332. max: childRange[1],
  67333. });
  67334. }
  67335. this.updateLabels();
  67336. }
  67337. setValues(values){
  67338. for(let slider of this.sliders){
  67339. $(slider).slider({
  67340. values: [...values],
  67341. });
  67342. }
  67343. this.updateLabels();
  67344. }
  67345. addLevel(){
  67346. const elLevel = document.createElement("li");
  67347. const elRange = document.createTextNode("Range: ");
  67348. const label = document.createElement("span");
  67349. const slider = document.createElement("div");
  67350. let level = this.sliders.length;
  67351. let [min, max] = [0, 0];
  67352. if(this.sliders.length === 0){
  67353. [min, max] = this.range;
  67354. }else {
  67355. let parentSlider = this.sliders[this.sliders.length - 1];
  67356. [min, max] = $(parentSlider).slider("option", "values");
  67357. }
  67358. $(slider).slider({
  67359. range: true,
  67360. min: min,
  67361. max: max,
  67362. step: this.step,
  67363. values: [min, max],
  67364. slide: (event, ui) => {
  67365. // set all descendants to same range
  67366. let levels = this.sliders.length;
  67367. for(let i = level + 1; i < levels; i++){
  67368. let descendant = this.sliders[i];
  67369. $(descendant).slider({
  67370. range: true,
  67371. min: ui.values[0],
  67372. max: ui.values[1],
  67373. values: [...ui.values],
  67374. });
  67375. }
  67376. if(this.slide){
  67377. let values = [...ui.values];
  67378. this.slide({
  67379. target: this,
  67380. range: this.range,
  67381. values: values,
  67382. });
  67383. }
  67384. this.updateLabels();
  67385. },
  67386. });
  67387. elLevel.append(elRange, label, slider);
  67388. this.sliders.push(slider);
  67389. this.labels.push(label);
  67390. this.element.append(elLevel);
  67391. this.updateLabels();
  67392. }
  67393. removeLevel(){
  67394. }
  67395. updateSliders(){
  67396. }
  67397. updateLabels(){
  67398. let levels = this.sliders.length;
  67399. for(let i = 0; i < levels; i++){
  67400. let slider = this.sliders[i];
  67401. let label = this.labels[i];
  67402. let [min, max] = $(slider).slider("option", "values");
  67403. let strMin = format(min);
  67404. let strMax = format(max);
  67405. let strLabel = `${strMin} to ${strMax}`;
  67406. label.innerHTML = strLabel;
  67407. }
  67408. }
  67409. }
  67410. class OrientedImageControls extends EventDispatcher{
  67411. constructor(viewer){
  67412. super();
  67413. this.viewer = viewer;
  67414. this.renderer = viewer.renderer;
  67415. this.originalCam = viewer.scene.getActiveCamera();
  67416. this.shearCam = viewer.scene.getActiveCamera().clone();
  67417. this.shearCam.rotation.set(this.originalCam.rotation.toArray());
  67418. this.shearCam.updateProjectionMatrix();
  67419. this.shearCam.updateProjectionMatrix = () => {
  67420. return this.shearCam.projectionMatrix;
  67421. };
  67422. this.image = null;
  67423. this.fadeFactor = 20;
  67424. this.fovDelta = 0;
  67425. this.fovMin = 0.1;
  67426. this.fovMax = 120;
  67427. this.shear = [0, 0];
  67428. // const style = ``;
  67429. this.elUp = $(`<input type="button" value="🡅" style="position: absolute; top: 10px; left: calc(50%); z-index: 1000" />`);
  67430. this.elRight = $(`<input type="button" value="🡆" style="position: absolute; top: calc(50%); right: 10px; z-index: 1000" />`);
  67431. this.elDown = $(`<input type="button" value="🡇" style="position: absolute; bottom: 10px; left: calc(50%); z-index: 1000" />`);
  67432. this.elLeft = $(`<input type="button" value="🡄" style="position: absolute; top: calc(50%); left: 10px; z-index: 1000" />`);
  67433. this.elExit = $(`<input type="button" value="Back to 3D view" style="position: absolute; bottom: 10px; right: 10px; z-index: 1000" />`);
  67434. this.elExit.click( () => {
  67435. this.release();
  67436. });
  67437. this.elUp.click(() => {
  67438. const fovY = viewer.getFOV();
  67439. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67440. this.shear[1] += 0.1 * top;
  67441. });
  67442. this.elRight.click(() => {
  67443. const fovY = viewer.getFOV();
  67444. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67445. this.shear[0] += 0.1 * top;
  67446. });
  67447. this.elDown.click(() => {
  67448. const fovY = viewer.getFOV();
  67449. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67450. this.shear[1] -= 0.1 * top;
  67451. });
  67452. this.elLeft.click(() => {
  67453. const fovY = viewer.getFOV();
  67454. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67455. this.shear[0] -= 0.1 * top;
  67456. });
  67457. this.scene = null;
  67458. this.sceneControls = new Scene();
  67459. let scroll = (e) => {
  67460. this.fovDelta += -e.delta * 1.0;
  67461. };
  67462. this.addEventListener('mousewheel', scroll);
  67463. //this.addEventListener("mousemove", onMove);
  67464. }
  67465. hasSomethingCaptured(){
  67466. return this.image !== null;
  67467. }
  67468. capture(image){
  67469. if(this.hasSomethingCaptured()){
  67470. return;
  67471. }
  67472. this.image = image;
  67473. this.originalFOV = this.viewer.getFOV();
  67474. this.originalControls = this.viewer.getControls();
  67475. this.viewer.setControls(this);
  67476. this.viewer.scene.overrideCamera = this.shearCam;
  67477. const elCanvas = this.viewer.renderer.domElement;
  67478. const elRoot = $(elCanvas.parentElement);
  67479. this.shear = [0, 0];
  67480. elRoot.append(this.elUp);
  67481. elRoot.append(this.elRight);
  67482. elRoot.append(this.elDown);
  67483. elRoot.append(this.elLeft);
  67484. elRoot.append(this.elExit);
  67485. }
  67486. release(){
  67487. this.image = null;
  67488. this.viewer.scene.overrideCamera = null;
  67489. this.elUp.detach();
  67490. this.elRight.detach();
  67491. this.elDown.detach();
  67492. this.elLeft.detach();
  67493. this.elExit.detach();
  67494. this.viewer.setFOV(this.originalFOV);
  67495. this.viewer.setControls(this.originalControls);
  67496. }
  67497. setScene (scene) {
  67498. this.scene = scene;
  67499. }
  67500. update (delta) {
  67501. // const view = this.scene.view;
  67502. // let prevTotal = this.shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  67503. //const progression = Math.min(1, this.fadeFactor * delta);
  67504. //const attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  67505. const progression = 1;
  67506. const attenuation = 0;
  67507. const oldFov = this.viewer.getFOV();
  67508. let fovProgression = progression * this.fovDelta;
  67509. let newFov = oldFov * ((1 + fovProgression / 10));
  67510. newFov = Math.max(this.fovMin, newFov);
  67511. newFov = Math.min(this.fovMax, newFov);
  67512. let diff = newFov / oldFov;
  67513. const mouse = this.viewer.inputHandler.mouse;
  67514. const canvasSize = this.viewer.renderer.getSize(new Vector2$1());
  67515. const uv = [
  67516. (mouse.x / canvasSize.x),
  67517. ((canvasSize.y - mouse.y) / canvasSize.y)
  67518. ];
  67519. const fovY = newFov;
  67520. const aspect = canvasSize.x / canvasSize.y;
  67521. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67522. const height = 2 * top;
  67523. const width = aspect * height;
  67524. const shearRangeX = [
  67525. this.shear[0] - 0.5 * width,
  67526. this.shear[0] + 0.5 * width,
  67527. ];
  67528. const shearRangeY = [
  67529. this.shear[1] - 0.5 * height,
  67530. this.shear[1] + 0.5 * height,
  67531. ];
  67532. const shx = (1 - uv[0]) * shearRangeX[0] + uv[0] * shearRangeX[1];
  67533. const shy = (1 - uv[1]) * shearRangeY[0] + uv[1] * shearRangeY[1];
  67534. const shu = (1 - diff);
  67535. const newShear = [
  67536. (1 - shu) * this.shear[0] + shu * shx,
  67537. (1 - shu) * this.shear[1] + shu * shy,
  67538. ];
  67539. this.shear = newShear;
  67540. this.viewer.setFOV(newFov);
  67541. const {originalCam, shearCam} = this;
  67542. originalCam.fov = newFov;
  67543. originalCam.updateMatrixWorld();
  67544. originalCam.updateProjectionMatrix();
  67545. shearCam.copy(originalCam);
  67546. shearCam.rotation.set(...originalCam.rotation.toArray());
  67547. shearCam.updateMatrixWorld();
  67548. shearCam.projectionMatrix.copy(originalCam.projectionMatrix);
  67549. const [sx, sy] = this.shear;
  67550. const mShear = new Matrix4().set(
  67551. 1, 0, sx, 0,
  67552. 0, 1, sy, 0,
  67553. 0, 0, 1, 0,
  67554. 0, 0, 0, 1,
  67555. );
  67556. const proj = shearCam.projectionMatrix;
  67557. proj.multiply(mShear);
  67558. shearCam.projectionMatrixInverse.copy(proj).invert();
  67559. let total = shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  67560. this.fovDelta *= attenuation;
  67561. }
  67562. };
  67563. // https://support.pix4d.com/hc/en-us/articles/205675256-How-are-yaw-pitch-roll-defined
  67564. // https://support.pix4d.com/hc/en-us/articles/202558969-How-are-omega-phi-kappa-defined
  67565. function createMaterial(){
  67566. let vertexShader = `
  67567. uniform float uNear;
  67568. varying vec2 vUV;
  67569. varying vec4 vDebug;
  67570. void main(){
  67571. vDebug = vec4(0.0, 1.0, 0.0, 1.0);
  67572. vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
  67573. // make sure that this mesh is at least in front of the near plane
  67574. modelViewPosition.xyz += normalize(modelViewPosition.xyz) * uNear;
  67575. gl_Position = projectionMatrix * modelViewPosition;
  67576. vUV = uv;
  67577. }
  67578. `;
  67579. let fragmentShader = `
  67580. uniform sampler2D tColor;
  67581. uniform float uOpacity;
  67582. varying vec2 vUV;
  67583. varying vec4 vDebug;
  67584. void main(){
  67585. vec4 color = texture2D(tColor, vUV);
  67586. gl_FragColor = color;
  67587. gl_FragColor.a = uOpacity;
  67588. }
  67589. `;
  67590. const material = new ShaderMaterial( {
  67591. uniforms: {
  67592. // time: { value: 1.0 },
  67593. // resolution: { value: new THREE.Vector2() }
  67594. tColor: {value: new Texture() },
  67595. uNear: {value: 0.0},
  67596. uOpacity: {value: 1.0},
  67597. },
  67598. vertexShader: vertexShader,
  67599. fragmentShader: fragmentShader,
  67600. side: DoubleSide,
  67601. } );
  67602. material.side = DoubleSide;
  67603. return material;
  67604. }
  67605. const planeGeometry = new PlaneGeometry(1, 1);
  67606. const lineGeometry = new Geometry();
  67607. lineGeometry.vertices.push(
  67608. new Vector3(-0.5, -0.5, 0),
  67609. new Vector3( 0.5, -0.5, 0),
  67610. new Vector3( 0.5, 0.5, 0),
  67611. new Vector3(-0.5, 0.5, 0),
  67612. new Vector3(-0.5, -0.5, 0),
  67613. );
  67614. class OrientedImage{
  67615. constructor(id){
  67616. this.id = id;
  67617. this.fov = 1.0;
  67618. this.position = new Vector3();
  67619. this.rotation = new Vector3();
  67620. this.width = 0;
  67621. this.height = 0;
  67622. this.fov = 1.0;
  67623. const material = createMaterial();
  67624. const lineMaterial = new LineBasicMaterial( { color: 0x00ff00 } );
  67625. this.mesh = new Mesh(planeGeometry, material);
  67626. this.line = new Line(lineGeometry, lineMaterial);
  67627. this.texture = null;
  67628. this.mesh.orientedImage = this;
  67629. }
  67630. set(position, rotation, dimension, fov){
  67631. let radians = rotation.map(MathUtils.degToRad);
  67632. this.position.set(...position);
  67633. this.mesh.position.set(...position);
  67634. this.rotation.set(...radians);
  67635. this.mesh.rotation.set(...radians);
  67636. [this.width, this.height] = dimension;
  67637. this.mesh.scale.set(this.width / this.height, 1, 1);
  67638. this.fov = fov;
  67639. this.updateTransform();
  67640. }
  67641. updateTransform(){
  67642. let {mesh, line, fov} = this;
  67643. mesh.updateMatrixWorld();
  67644. const dir = mesh.getWorldDirection();
  67645. const alpha = MathUtils.degToRad(fov / 2);
  67646. const d = -0.5 / Math.tan(alpha);
  67647. const move = dir.clone().multiplyScalar(d);
  67648. mesh.position.add(move);
  67649. line.position.copy(mesh.position);
  67650. line.scale.copy(mesh.scale);
  67651. line.rotation.copy(mesh.rotation);
  67652. }
  67653. };
  67654. class OrientedImages extends EventDispatcher{
  67655. constructor(){
  67656. super();
  67657. this.node = null;
  67658. this.cameraParams = null;
  67659. this.imageParams = null;
  67660. this.images = null;
  67661. this._visible = true;
  67662. }
  67663. set visible(visible){
  67664. if(this._visible === visible){
  67665. return;
  67666. }
  67667. for(const image of this.images){
  67668. image.mesh.visible = visible;
  67669. image.line.visible = visible;
  67670. }
  67671. this._visible = visible;
  67672. this.dispatchEvent({
  67673. type: "visibility_changed",
  67674. images: this,
  67675. });
  67676. }
  67677. get visible(){
  67678. return this._visible;
  67679. }
  67680. };
  67681. class OrientedImageLoader{
  67682. static async loadCameraParams(path){
  67683. const res = await fetch(path);
  67684. const text = await res.text();
  67685. const parser = new DOMParser();
  67686. const doc = parser.parseFromString(text, "application/xml");
  67687. const width = parseInt(doc.getElementsByTagName("width")[0].textContent);
  67688. const height = parseInt(doc.getElementsByTagName("height")[0].textContent);
  67689. const f = parseFloat(doc.getElementsByTagName("f")[0].textContent);
  67690. let a = (height / 2) / f;
  67691. let fov = 2 * MathUtils.radToDeg(Math.atan(a));
  67692. const params = {
  67693. path: path,
  67694. width: width,
  67695. height: height,
  67696. f: f,
  67697. fov: fov,
  67698. };
  67699. return params;
  67700. }
  67701. static async loadImageParams(path){
  67702. const response = await fetch(path);
  67703. if(!response.ok){
  67704. console.error(`failed to load ${path}`);
  67705. return;
  67706. }
  67707. const content = await response.text();
  67708. const lines = content.split(/\r?\n/);
  67709. const imageParams = [];
  67710. for(let i = 1; i < lines.length; i++){
  67711. const line = lines[i];
  67712. if(line.startsWith("#")){
  67713. continue;
  67714. }
  67715. const tokens = line.split(/\s+/);
  67716. if(tokens.length < 6){
  67717. continue;
  67718. }
  67719. const params = {
  67720. id: tokens[0],
  67721. x: Number.parseFloat(tokens[1]),
  67722. y: Number.parseFloat(tokens[2]),
  67723. z: Number.parseFloat(tokens[3]),
  67724. omega: Number.parseFloat(tokens[4]),
  67725. phi: Number.parseFloat(tokens[5]),
  67726. kappa: Number.parseFloat(tokens[6]),
  67727. };
  67728. // const whitelist = ["47518.jpg"];
  67729. // if(whitelist.includes(params.id)){
  67730. // imageParams.push(params);
  67731. // }
  67732. imageParams.push(params);
  67733. }
  67734. // debug
  67735. //return [imageParams[50]];
  67736. return imageParams;
  67737. }
  67738. static async load(cameraParamsPath, imageParamsPath, viewer){
  67739. const tStart = performance.now();
  67740. const [cameraParams, imageParams] = await Promise.all([
  67741. OrientedImageLoader.loadCameraParams(cameraParamsPath),
  67742. OrientedImageLoader.loadImageParams(imageParamsPath),
  67743. ]);
  67744. const orientedImageControls = new OrientedImageControls(viewer);
  67745. const raycaster = new Raycaster();
  67746. const tEnd = performance.now();
  67747. console.log(tEnd - tStart);
  67748. // const sp = new THREE.PlaneGeometry(1, 1);
  67749. // const lg = new THREE.Geometry();
  67750. // lg.vertices.push(
  67751. // new THREE.Vector3(-0.5, -0.5, 0),
  67752. // new THREE.Vector3( 0.5, -0.5, 0),
  67753. // new THREE.Vector3( 0.5, 0.5, 0),
  67754. // new THREE.Vector3(-0.5, 0.5, 0),
  67755. // new THREE.Vector3(-0.5, -0.5, 0),
  67756. // );
  67757. const {width, height} = cameraParams;
  67758. const orientedImages = [];
  67759. const sceneNode = new Object3D();
  67760. sceneNode.name = "oriented_images";
  67761. for(const params of imageParams){
  67762. // const material = createMaterial();
  67763. // const lm = new THREE.LineBasicMaterial( { color: 0x00ff00 } );
  67764. // const mesh = new THREE.Mesh(sp, material);
  67765. const {x, y, z, omega, phi, kappa} = params;
  67766. // const [rx, ry, rz] = [omega, phi, kappa]
  67767. // .map(THREE.Math.degToRad);
  67768. // mesh.position.set(x, y, z);
  67769. // mesh.scale.set(width / height, 1, 1);
  67770. // mesh.rotation.set(rx, ry, rz);
  67771. // {
  67772. // mesh.updateMatrixWorld();
  67773. // const dir = mesh.getWorldDirection();
  67774. // const alpha = THREE.Math.degToRad(cameraParams.fov / 2);
  67775. // const d = -0.5 / Math.tan(alpha);
  67776. // const move = dir.clone().multiplyScalar(d);
  67777. // mesh.position.add(move);
  67778. // }
  67779. // sceneNode.add(mesh);
  67780. // const line = new THREE.Line(lg, lm);
  67781. // line.position.copy(mesh.position);
  67782. // line.scale.copy(mesh.scale);
  67783. // line.rotation.copy(mesh.rotation);
  67784. // sceneNode.add(line);
  67785. let orientedImage = new OrientedImage(params.id);
  67786. // orientedImage.setPosition(x, y, z);
  67787. // orientedImage.setRotation(omega, phi, kappa);
  67788. // orientedImage.setDimension(width, height);
  67789. let position = [x, y, z];
  67790. let rotation = [omega, phi, kappa];
  67791. let dimension = [width, height];
  67792. orientedImage.set(position, rotation, dimension, cameraParams.fov);
  67793. sceneNode.add(orientedImage.mesh);
  67794. sceneNode.add(orientedImage.line);
  67795. orientedImages.push(orientedImage);
  67796. }
  67797. let hoveredElement = null;
  67798. let clipVolume = null;
  67799. const onMouseMove = (evt) => {
  67800. const tStart = performance.now();
  67801. if(hoveredElement){
  67802. hoveredElement.line.material.color.setRGB(0, 1, 0);
  67803. }
  67804. evt.preventDefault();
  67805. //var array = getMousePosition( container, evt.clientX, evt.clientY );
  67806. const rect = viewer.renderer.domElement.getBoundingClientRect();
  67807. const [x, y] = [evt.clientX, evt.clientY];
  67808. const array = [
  67809. ( x - rect.left ) / rect.width,
  67810. ( y - rect.top ) / rect.height
  67811. ];
  67812. const onClickPosition = new Vector2$1(...array);
  67813. //const intersects = getIntersects(onClickPosition, scene.children);
  67814. const camera = viewer.scene.getActiveCamera();
  67815. const mouse = new Vector3(
  67816. + ( onClickPosition.x * 2 ) - 1,
  67817. - ( onClickPosition.y * 2 ) + 1 );
  67818. const objects = orientedImages.map(i => i.mesh);
  67819. raycaster.setFromCamera( mouse, camera );
  67820. const intersects = raycaster.intersectObjects( objects );
  67821. let selectionChanged = false;
  67822. if ( intersects.length > 0){
  67823. //console.log(intersects);
  67824. const intersection = intersects[0];
  67825. const orientedImage = intersection.object.orientedImage;
  67826. orientedImage.line.material.color.setRGB(1, 0, 0);
  67827. selectionChanged = hoveredElement !== orientedImage;
  67828. hoveredElement = orientedImage;
  67829. }else {
  67830. hoveredElement = null;
  67831. }
  67832. let shouldRemoveClipVolume = clipVolume !== null && hoveredElement === null;
  67833. let shouldAddClipVolume = clipVolume === null && hoveredElement !== null;
  67834. if(clipVolume !== null && (hoveredElement === null || selectionChanged)){
  67835. // remove existing
  67836. viewer.scene.removePolygonClipVolume(clipVolume);
  67837. clipVolume = null;
  67838. }
  67839. if(shouldAddClipVolume || selectionChanged){
  67840. const img = hoveredElement;
  67841. const fov = cameraParams.fov;
  67842. const aspect = cameraParams.width / cameraParams.height;
  67843. const near = 1.0;
  67844. const far = 1000 * 1000;
  67845. const camera = new PerspectiveCamera(fov, aspect, near, far);
  67846. camera.rotation.order = viewer.scene.getActiveCamera().rotation.order;
  67847. camera.rotation.copy(img.mesh.rotation);
  67848. {
  67849. const mesh = img.mesh;
  67850. const dir = mesh.getWorldDirection();
  67851. const pos = mesh.position;
  67852. const alpha = MathUtils.degToRad(fov / 2);
  67853. const d = 0.5 / Math.tan(alpha);
  67854. const newCamPos = pos.clone().add(dir.clone().multiplyScalar(d));
  67855. const newCamDir = pos.clone().sub(newCamPos);
  67856. const newCamTarget = new Vector3().addVectors(
  67857. newCamPos,
  67858. newCamDir.clone().multiplyScalar(viewer.getMoveSpeed()));
  67859. camera.position.copy(newCamPos);
  67860. }
  67861. let volume = new Potree.PolygonClipVolume(camera);
  67862. let m0 = new Mesh();
  67863. let m1 = new Mesh();
  67864. let m2 = new Mesh();
  67865. let m3 = new Mesh();
  67866. m0.position.set(-1, -1, 0);
  67867. m1.position.set( 1, -1, 0);
  67868. m2.position.set( 1, 1, 0);
  67869. m3.position.set(-1, 1, 0);
  67870. volume.markers.push(m0, m1, m2, m3);
  67871. volume.initialized = true;
  67872. viewer.scene.addPolygonClipVolume(volume);
  67873. clipVolume = volume;
  67874. }
  67875. const tEnd = performance.now();
  67876. //console.log(tEnd - tStart);
  67877. };
  67878. const moveToImage = (image) => {
  67879. console.log("move to image " + image.id);
  67880. const mesh = image.mesh;
  67881. const newCamPos = image.position.clone();
  67882. const newCamTarget = mesh.position.clone();
  67883. viewer.scene.view.setView(newCamPos, newCamTarget, 500, () => {
  67884. orientedImageControls.capture(image);
  67885. });
  67886. if(image.texture === null){
  67887. const target = image;
  67888. const tmpImagePath = `${Potree.resourcePath}/images/loading.jpg`;
  67889. new TextureLoader().load(tmpImagePath,
  67890. (texture) => {
  67891. if(target.texture === null){
  67892. target.texture = texture;
  67893. target.mesh.material.uniforms.tColor.value = texture;
  67894. mesh.material.needsUpdate = true;
  67895. }
  67896. }
  67897. );
  67898. const imagePath = `${imageParamsPath}/../${target.id}`;
  67899. new TextureLoader().load(imagePath,
  67900. (texture) => {
  67901. target.texture = texture;
  67902. target.mesh.material.uniforms.tColor.value = texture;
  67903. mesh.material.needsUpdate = true;
  67904. }
  67905. );
  67906. }
  67907. };
  67908. const onMouseClick = (evt) => {
  67909. if(orientedImageControls.hasSomethingCaptured()){
  67910. return;
  67911. }
  67912. if(hoveredElement){
  67913. moveToImage(hoveredElement);
  67914. }
  67915. };
  67916. viewer.renderer.domElement.addEventListener( 'mousemove', onMouseMove, false );
  67917. viewer.renderer.domElement.addEventListener( 'mousedown', onMouseClick, false );
  67918. viewer.addEventListener("update", () => {
  67919. for(const image of orientedImages){
  67920. const world = image.mesh.matrixWorld;
  67921. const {width, height} = image;
  67922. const aspect = width / height;
  67923. const camera = viewer.scene.getActiveCamera();
  67924. const imgPos = image.mesh.getWorldPosition(new Vector3());
  67925. const camPos = camera.position;
  67926. const d = camPos.distanceTo(imgPos);
  67927. const minSize = 1; // in degrees of fov
  67928. const a = MathUtils.degToRad(minSize);
  67929. let r = d * Math.tan(a);
  67930. r = Math.max(r, 1);
  67931. image.mesh.scale.set(r * aspect, r, 1);
  67932. image.line.scale.set(r * aspect, r, 1);
  67933. image.mesh.material.uniforms.uNear.value = camera.near;
  67934. }
  67935. });
  67936. const images = new OrientedImages();
  67937. images.node = sceneNode;
  67938. images.cameraParamsPath = cameraParamsPath;
  67939. images.imageParamsPath = imageParamsPath;
  67940. images.cameraParams = cameraParams;
  67941. images.imageParams = imageParams;
  67942. images.images = orientedImages;
  67943. Potree.debug.moveToImage = moveToImage;
  67944. return images;
  67945. }
  67946. }
  67947. // This is a generated file. Do not edit.
  67948. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
  67949. 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]/;
  67950. 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]/;
  67951. var unicode = {
  67952. Space_Separator: Space_Separator,
  67953. ID_Start: ID_Start,
  67954. ID_Continue: ID_Continue
  67955. };
  67956. var util = {
  67957. isSpaceSeparator (c) {
  67958. return typeof c === 'string' && unicode.Space_Separator.test(c)
  67959. },
  67960. isIdStartChar (c) {
  67961. return typeof c === 'string' && (
  67962. (c >= 'a' && c <= 'z') ||
  67963. (c >= 'A' && c <= 'Z') ||
  67964. (c === '$') || (c === '_') ||
  67965. unicode.ID_Start.test(c)
  67966. )
  67967. },
  67968. isIdContinueChar (c) {
  67969. return typeof c === 'string' && (
  67970. (c >= 'a' && c <= 'z') ||
  67971. (c >= 'A' && c <= 'Z') ||
  67972. (c >= '0' && c <= '9') ||
  67973. (c === '$') || (c === '_') ||
  67974. (c === '\u200C') || (c === '\u200D') ||
  67975. unicode.ID_Continue.test(c)
  67976. )
  67977. },
  67978. isDigit (c) {
  67979. return typeof c === 'string' && /[0-9]/.test(c)
  67980. },
  67981. isHexDigit (c) {
  67982. return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
  67983. },
  67984. };
  67985. let source;
  67986. let parseState;
  67987. let stack;
  67988. let pos;
  67989. let line;
  67990. let column;
  67991. let token;
  67992. let key;
  67993. let root;
  67994. var parse = function parse (text, reviver) {
  67995. source = String(text);
  67996. parseState = 'start';
  67997. stack = [];
  67998. pos = 0;
  67999. line = 1;
  68000. column = 0;
  68001. token = undefined;
  68002. key = undefined;
  68003. root = undefined;
  68004. do {
  68005. token = lex();
  68006. // This code is unreachable.
  68007. // if (!parseStates[parseState]) {
  68008. // throw invalidParseState()
  68009. // }
  68010. parseStates[parseState]();
  68011. } while (token.type !== 'eof')
  68012. if (typeof reviver === 'function') {
  68013. return internalize({'': root}, '', reviver)
  68014. }
  68015. return root
  68016. };
  68017. function internalize (holder, name, reviver) {
  68018. const value = holder[name];
  68019. if (value != null && typeof value === 'object') {
  68020. for (const key in value) {
  68021. const replacement = internalize(value, key, reviver);
  68022. if (replacement === undefined) {
  68023. delete value[key];
  68024. } else {
  68025. value[key] = replacement;
  68026. }
  68027. }
  68028. }
  68029. return reviver.call(holder, name, value)
  68030. }
  68031. let lexState;
  68032. let buffer;
  68033. let doubleQuote;
  68034. let sign$1;
  68035. let c$2;
  68036. function lex () {
  68037. lexState = 'default';
  68038. buffer = '';
  68039. doubleQuote = false;
  68040. sign$1 = 1;
  68041. for (;;) {
  68042. c$2 = peek();
  68043. // This code is unreachable.
  68044. // if (!lexStates[lexState]) {
  68045. // throw invalidLexState(lexState)
  68046. // }
  68047. const token = lexStates[lexState]();
  68048. if (token) {
  68049. return token
  68050. }
  68051. }
  68052. }
  68053. function peek () {
  68054. if (source[pos]) {
  68055. return String.fromCodePoint(source.codePointAt(pos))
  68056. }
  68057. }
  68058. function read () {
  68059. const c = peek();
  68060. if (c === '\n') {
  68061. line++;
  68062. column = 0;
  68063. } else if (c) {
  68064. column += c.length;
  68065. } else {
  68066. column++;
  68067. }
  68068. if (c) {
  68069. pos += c.length;
  68070. }
  68071. return c
  68072. }
  68073. const lexStates = {
  68074. default () {
  68075. switch (c$2) {
  68076. case '\t':
  68077. case '\v':
  68078. case '\f':
  68079. case ' ':
  68080. case '\u00A0':
  68081. case '\uFEFF':
  68082. case '\n':
  68083. case '\r':
  68084. case '\u2028':
  68085. case '\u2029':
  68086. read();
  68087. return
  68088. case '/':
  68089. read();
  68090. lexState = 'comment';
  68091. return
  68092. case undefined:
  68093. read();
  68094. return newToken('eof')
  68095. }
  68096. if (util.isSpaceSeparator(c$2)) {
  68097. read();
  68098. return
  68099. }
  68100. // This code is unreachable.
  68101. // if (!lexStates[parseState]) {
  68102. // throw invalidLexState(parseState)
  68103. // }
  68104. return lexStates[parseState]()
  68105. },
  68106. comment () {
  68107. switch (c$2) {
  68108. case '*':
  68109. read();
  68110. lexState = 'multiLineComment';
  68111. return
  68112. case '/':
  68113. read();
  68114. lexState = 'singleLineComment';
  68115. return
  68116. }
  68117. throw invalidChar(read())
  68118. },
  68119. multiLineComment () {
  68120. switch (c$2) {
  68121. case '*':
  68122. read();
  68123. lexState = 'multiLineCommentAsterisk';
  68124. return
  68125. case undefined:
  68126. throw invalidChar(read())
  68127. }
  68128. read();
  68129. },
  68130. multiLineCommentAsterisk () {
  68131. switch (c$2) {
  68132. case '*':
  68133. read();
  68134. return
  68135. case '/':
  68136. read();
  68137. lexState = 'default';
  68138. return
  68139. case undefined:
  68140. throw invalidChar(read())
  68141. }
  68142. read();
  68143. lexState = 'multiLineComment';
  68144. },
  68145. singleLineComment () {
  68146. switch (c$2) {
  68147. case '\n':
  68148. case '\r':
  68149. case '\u2028':
  68150. case '\u2029':
  68151. read();
  68152. lexState = 'default';
  68153. return
  68154. case undefined:
  68155. read();
  68156. return newToken('eof')
  68157. }
  68158. read();
  68159. },
  68160. value () {
  68161. switch (c$2) {
  68162. case '{':
  68163. case '[':
  68164. return newToken('punctuator', read())
  68165. case 'n':
  68166. read();
  68167. literal('ull');
  68168. return newToken('null', null)
  68169. case 't':
  68170. read();
  68171. literal('rue');
  68172. return newToken('boolean', true)
  68173. case 'f':
  68174. read();
  68175. literal('alse');
  68176. return newToken('boolean', false)
  68177. case '-':
  68178. case '+':
  68179. if (read() === '-') {
  68180. sign$1 = -1;
  68181. }
  68182. lexState = 'sign';
  68183. return
  68184. case '.':
  68185. buffer = read();
  68186. lexState = 'decimalPointLeading';
  68187. return
  68188. case '0':
  68189. buffer = read();
  68190. lexState = 'zero';
  68191. return
  68192. case '1':
  68193. case '2':
  68194. case '3':
  68195. case '4':
  68196. case '5':
  68197. case '6':
  68198. case '7':
  68199. case '8':
  68200. case '9':
  68201. buffer = read();
  68202. lexState = 'decimalInteger';
  68203. return
  68204. case 'I':
  68205. read();
  68206. literal('nfinity');
  68207. return newToken('numeric', Infinity)
  68208. case 'N':
  68209. read();
  68210. literal('aN');
  68211. return newToken('numeric', NaN)
  68212. case '"':
  68213. case "'":
  68214. doubleQuote = (read() === '"');
  68215. buffer = '';
  68216. lexState = 'string';
  68217. return
  68218. }
  68219. throw invalidChar(read())
  68220. },
  68221. identifierNameStartEscape () {
  68222. if (c$2 !== 'u') {
  68223. throw invalidChar(read())
  68224. }
  68225. read();
  68226. const u = unicodeEscape();
  68227. switch (u) {
  68228. case '$':
  68229. case '_':
  68230. break
  68231. default:
  68232. if (!util.isIdStartChar(u)) {
  68233. throw invalidIdentifier()
  68234. }
  68235. break
  68236. }
  68237. buffer += u;
  68238. lexState = 'identifierName';
  68239. },
  68240. identifierName () {
  68241. switch (c$2) {
  68242. case '$':
  68243. case '_':
  68244. case '\u200C':
  68245. case '\u200D':
  68246. buffer += read();
  68247. return
  68248. case '\\':
  68249. read();
  68250. lexState = 'identifierNameEscape';
  68251. return
  68252. }
  68253. if (util.isIdContinueChar(c$2)) {
  68254. buffer += read();
  68255. return
  68256. }
  68257. return newToken('identifier', buffer)
  68258. },
  68259. identifierNameEscape () {
  68260. if (c$2 !== 'u') {
  68261. throw invalidChar(read())
  68262. }
  68263. read();
  68264. const u = unicodeEscape();
  68265. switch (u) {
  68266. case '$':
  68267. case '_':
  68268. case '\u200C':
  68269. case '\u200D':
  68270. break
  68271. default:
  68272. if (!util.isIdContinueChar(u)) {
  68273. throw invalidIdentifier()
  68274. }
  68275. break
  68276. }
  68277. buffer += u;
  68278. lexState = 'identifierName';
  68279. },
  68280. sign () {
  68281. switch (c$2) {
  68282. case '.':
  68283. buffer = read();
  68284. lexState = 'decimalPointLeading';
  68285. return
  68286. case '0':
  68287. buffer = read();
  68288. lexState = 'zero';
  68289. return
  68290. case '1':
  68291. case '2':
  68292. case '3':
  68293. case '4':
  68294. case '5':
  68295. case '6':
  68296. case '7':
  68297. case '8':
  68298. case '9':
  68299. buffer = read();
  68300. lexState = 'decimalInteger';
  68301. return
  68302. case 'I':
  68303. read();
  68304. literal('nfinity');
  68305. return newToken('numeric', sign$1 * Infinity)
  68306. case 'N':
  68307. read();
  68308. literal('aN');
  68309. return newToken('numeric', NaN)
  68310. }
  68311. throw invalidChar(read())
  68312. },
  68313. zero () {
  68314. switch (c$2) {
  68315. case '.':
  68316. buffer += read();
  68317. lexState = 'decimalPoint';
  68318. return
  68319. case 'e':
  68320. case 'E':
  68321. buffer += read();
  68322. lexState = 'decimalExponent';
  68323. return
  68324. case 'x':
  68325. case 'X':
  68326. buffer += read();
  68327. lexState = 'hexadecimal';
  68328. return
  68329. }
  68330. return newToken('numeric', sign$1 * 0)
  68331. },
  68332. decimalInteger () {
  68333. switch (c$2) {
  68334. case '.':
  68335. buffer += read();
  68336. lexState = 'decimalPoint';
  68337. return
  68338. case 'e':
  68339. case 'E':
  68340. buffer += read();
  68341. lexState = 'decimalExponent';
  68342. return
  68343. }
  68344. if (util.isDigit(c$2)) {
  68345. buffer += read();
  68346. return
  68347. }
  68348. return newToken('numeric', sign$1 * Number(buffer))
  68349. },
  68350. decimalPointLeading () {
  68351. if (util.isDigit(c$2)) {
  68352. buffer += read();
  68353. lexState = 'decimalFraction';
  68354. return
  68355. }
  68356. throw invalidChar(read())
  68357. },
  68358. decimalPoint () {
  68359. switch (c$2) {
  68360. case 'e':
  68361. case 'E':
  68362. buffer += read();
  68363. lexState = 'decimalExponent';
  68364. return
  68365. }
  68366. if (util.isDigit(c$2)) {
  68367. buffer += read();
  68368. lexState = 'decimalFraction';
  68369. return
  68370. }
  68371. return newToken('numeric', sign$1 * Number(buffer))
  68372. },
  68373. decimalFraction () {
  68374. switch (c$2) {
  68375. case 'e':
  68376. case 'E':
  68377. buffer += read();
  68378. lexState = 'decimalExponent';
  68379. return
  68380. }
  68381. if (util.isDigit(c$2)) {
  68382. buffer += read();
  68383. return
  68384. }
  68385. return newToken('numeric', sign$1 * Number(buffer))
  68386. },
  68387. decimalExponent () {
  68388. switch (c$2) {
  68389. case '+':
  68390. case '-':
  68391. buffer += read();
  68392. lexState = 'decimalExponentSign';
  68393. return
  68394. }
  68395. if (util.isDigit(c$2)) {
  68396. buffer += read();
  68397. lexState = 'decimalExponentInteger';
  68398. return
  68399. }
  68400. throw invalidChar(read())
  68401. },
  68402. decimalExponentSign () {
  68403. if (util.isDigit(c$2)) {
  68404. buffer += read();
  68405. lexState = 'decimalExponentInteger';
  68406. return
  68407. }
  68408. throw invalidChar(read())
  68409. },
  68410. decimalExponentInteger () {
  68411. if (util.isDigit(c$2)) {
  68412. buffer += read();
  68413. return
  68414. }
  68415. return newToken('numeric', sign$1 * Number(buffer))
  68416. },
  68417. hexadecimal () {
  68418. if (util.isHexDigit(c$2)) {
  68419. buffer += read();
  68420. lexState = 'hexadecimalInteger';
  68421. return
  68422. }
  68423. throw invalidChar(read())
  68424. },
  68425. hexadecimalInteger () {
  68426. if (util.isHexDigit(c$2)) {
  68427. buffer += read();
  68428. return
  68429. }
  68430. return newToken('numeric', sign$1 * Number(buffer))
  68431. },
  68432. string () {
  68433. switch (c$2) {
  68434. case '\\':
  68435. read();
  68436. buffer += escape$1();
  68437. return
  68438. case '"':
  68439. if (doubleQuote) {
  68440. read();
  68441. return newToken('string', buffer)
  68442. }
  68443. buffer += read();
  68444. return
  68445. case "'":
  68446. if (!doubleQuote) {
  68447. read();
  68448. return newToken('string', buffer)
  68449. }
  68450. buffer += read();
  68451. return
  68452. case '\n':
  68453. case '\r':
  68454. throw invalidChar(read())
  68455. case '\u2028':
  68456. case '\u2029':
  68457. separatorChar(c$2);
  68458. break
  68459. case undefined:
  68460. throw invalidChar(read())
  68461. }
  68462. buffer += read();
  68463. },
  68464. start () {
  68465. switch (c$2) {
  68466. case '{':
  68467. case '[':
  68468. return newToken('punctuator', read())
  68469. // This code is unreachable since the default lexState handles eof.
  68470. // case undefined:
  68471. // return newToken('eof')
  68472. }
  68473. lexState = 'value';
  68474. },
  68475. beforePropertyName () {
  68476. switch (c$2) {
  68477. case '$':
  68478. case '_':
  68479. buffer = read();
  68480. lexState = 'identifierName';
  68481. return
  68482. case '\\':
  68483. read();
  68484. lexState = 'identifierNameStartEscape';
  68485. return
  68486. case '}':
  68487. return newToken('punctuator', read())
  68488. case '"':
  68489. case "'":
  68490. doubleQuote = (read() === '"');
  68491. lexState = 'string';
  68492. return
  68493. }
  68494. if (util.isIdStartChar(c$2)) {
  68495. buffer += read();
  68496. lexState = 'identifierName';
  68497. return
  68498. }
  68499. throw invalidChar(read())
  68500. },
  68501. afterPropertyName () {
  68502. if (c$2 === ':') {
  68503. return newToken('punctuator', read())
  68504. }
  68505. throw invalidChar(read())
  68506. },
  68507. beforePropertyValue () {
  68508. lexState = 'value';
  68509. },
  68510. afterPropertyValue () {
  68511. switch (c$2) {
  68512. case ',':
  68513. case '}':
  68514. return newToken('punctuator', read())
  68515. }
  68516. throw invalidChar(read())
  68517. },
  68518. beforeArrayValue () {
  68519. if (c$2 === ']') {
  68520. return newToken('punctuator', read())
  68521. }
  68522. lexState = 'value';
  68523. },
  68524. afterArrayValue () {
  68525. switch (c$2) {
  68526. case ',':
  68527. case ']':
  68528. return newToken('punctuator', read())
  68529. }
  68530. throw invalidChar(read())
  68531. },
  68532. end () {
  68533. // This code is unreachable since it's handled by the default lexState.
  68534. // if (c === undefined) {
  68535. // read()
  68536. // return newToken('eof')
  68537. // }
  68538. throw invalidChar(read())
  68539. },
  68540. };
  68541. function newToken (type, value) {
  68542. return {
  68543. type,
  68544. value,
  68545. line,
  68546. column,
  68547. }
  68548. }
  68549. function literal (s) {
  68550. for (const c of s) {
  68551. const p = peek();
  68552. if (p !== c) {
  68553. throw invalidChar(read())
  68554. }
  68555. read();
  68556. }
  68557. }
  68558. function escape$1 () {
  68559. const c = peek();
  68560. switch (c) {
  68561. case 'b':
  68562. read();
  68563. return '\b'
  68564. case 'f':
  68565. read();
  68566. return '\f'
  68567. case 'n':
  68568. read();
  68569. return '\n'
  68570. case 'r':
  68571. read();
  68572. return '\r'
  68573. case 't':
  68574. read();
  68575. return '\t'
  68576. case 'v':
  68577. read();
  68578. return '\v'
  68579. case '0':
  68580. read();
  68581. if (util.isDigit(peek())) {
  68582. throw invalidChar(read())
  68583. }
  68584. return '\0'
  68585. case 'x':
  68586. read();
  68587. return hexEscape()
  68588. case 'u':
  68589. read();
  68590. return unicodeEscape()
  68591. case '\n':
  68592. case '\u2028':
  68593. case '\u2029':
  68594. read();
  68595. return ''
  68596. case '\r':
  68597. read();
  68598. if (peek() === '\n') {
  68599. read();
  68600. }
  68601. return ''
  68602. case '1':
  68603. case '2':
  68604. case '3':
  68605. case '4':
  68606. case '5':
  68607. case '6':
  68608. case '7':
  68609. case '8':
  68610. case '9':
  68611. throw invalidChar(read())
  68612. case undefined:
  68613. throw invalidChar(read())
  68614. }
  68615. return read()
  68616. }
  68617. function hexEscape () {
  68618. let buffer = '';
  68619. let c = peek();
  68620. if (!util.isHexDigit(c)) {
  68621. throw invalidChar(read())
  68622. }
  68623. buffer += read();
  68624. c = peek();
  68625. if (!util.isHexDigit(c)) {
  68626. throw invalidChar(read())
  68627. }
  68628. buffer += read();
  68629. return String.fromCodePoint(parseInt(buffer, 16))
  68630. }
  68631. function unicodeEscape () {
  68632. let buffer = '';
  68633. let count = 4;
  68634. while (count-- > 0) {
  68635. const c = peek();
  68636. if (!util.isHexDigit(c)) {
  68637. throw invalidChar(read())
  68638. }
  68639. buffer += read();
  68640. }
  68641. return String.fromCodePoint(parseInt(buffer, 16))
  68642. }
  68643. const parseStates = {
  68644. start () {
  68645. if (token.type === 'eof') {
  68646. throw invalidEOF()
  68647. }
  68648. push();
  68649. },
  68650. beforePropertyName () {
  68651. switch (token.type) {
  68652. case 'identifier':
  68653. case 'string':
  68654. key = token.value;
  68655. parseState = 'afterPropertyName';
  68656. return
  68657. case 'punctuator':
  68658. // This code is unreachable since it's handled by the lexState.
  68659. // if (token.value !== '}') {
  68660. // throw invalidToken()
  68661. // }
  68662. pop();
  68663. return
  68664. case 'eof':
  68665. throw invalidEOF()
  68666. }
  68667. // This code is unreachable since it's handled by the lexState.
  68668. // throw invalidToken()
  68669. },
  68670. afterPropertyName () {
  68671. // This code is unreachable since it's handled by the lexState.
  68672. // if (token.type !== 'punctuator' || token.value !== ':') {
  68673. // throw invalidToken()
  68674. // }
  68675. if (token.type === 'eof') {
  68676. throw invalidEOF()
  68677. }
  68678. parseState = 'beforePropertyValue';
  68679. },
  68680. beforePropertyValue () {
  68681. if (token.type === 'eof') {
  68682. throw invalidEOF()
  68683. }
  68684. push();
  68685. },
  68686. beforeArrayValue () {
  68687. if (token.type === 'eof') {
  68688. throw invalidEOF()
  68689. }
  68690. if (token.type === 'punctuator' && token.value === ']') {
  68691. pop();
  68692. return
  68693. }
  68694. push();
  68695. },
  68696. afterPropertyValue () {
  68697. // This code is unreachable since it's handled by the lexState.
  68698. // if (token.type !== 'punctuator') {
  68699. // throw invalidToken()
  68700. // }
  68701. if (token.type === 'eof') {
  68702. throw invalidEOF()
  68703. }
  68704. switch (token.value) {
  68705. case ',':
  68706. parseState = 'beforePropertyName';
  68707. return
  68708. case '}':
  68709. pop();
  68710. }
  68711. // This code is unreachable since it's handled by the lexState.
  68712. // throw invalidToken()
  68713. },
  68714. afterArrayValue () {
  68715. // This code is unreachable since it's handled by the lexState.
  68716. // if (token.type !== 'punctuator') {
  68717. // throw invalidToken()
  68718. // }
  68719. if (token.type === 'eof') {
  68720. throw invalidEOF()
  68721. }
  68722. switch (token.value) {
  68723. case ',':
  68724. parseState = 'beforeArrayValue';
  68725. return
  68726. case ']':
  68727. pop();
  68728. }
  68729. // This code is unreachable since it's handled by the lexState.
  68730. // throw invalidToken()
  68731. },
  68732. end () {
  68733. // This code is unreachable since it's handled by the lexState.
  68734. // if (token.type !== 'eof') {
  68735. // throw invalidToken()
  68736. // }
  68737. },
  68738. };
  68739. function push () {
  68740. let value;
  68741. switch (token.type) {
  68742. case 'punctuator':
  68743. switch (token.value) {
  68744. case '{':
  68745. value = {};
  68746. break
  68747. case '[':
  68748. value = [];
  68749. break
  68750. }
  68751. break
  68752. case 'null':
  68753. case 'boolean':
  68754. case 'numeric':
  68755. case 'string':
  68756. value = token.value;
  68757. break
  68758. // This code is unreachable.
  68759. // default:
  68760. // throw invalidToken()
  68761. }
  68762. if (root === undefined) {
  68763. root = value;
  68764. } else {
  68765. const parent = stack[stack.length - 1];
  68766. if (Array.isArray(parent)) {
  68767. parent.push(value);
  68768. } else {
  68769. parent[key] = value;
  68770. }
  68771. }
  68772. if (value !== null && typeof value === 'object') {
  68773. stack.push(value);
  68774. if (Array.isArray(value)) {
  68775. parseState = 'beforeArrayValue';
  68776. } else {
  68777. parseState = 'beforePropertyName';
  68778. }
  68779. } else {
  68780. const current = stack[stack.length - 1];
  68781. if (current == null) {
  68782. parseState = 'end';
  68783. } else if (Array.isArray(current)) {
  68784. parseState = 'afterArrayValue';
  68785. } else {
  68786. parseState = 'afterPropertyValue';
  68787. }
  68788. }
  68789. }
  68790. function pop () {
  68791. stack.pop();
  68792. const current = stack[stack.length - 1];
  68793. if (current == null) {
  68794. parseState = 'end';
  68795. } else if (Array.isArray(current)) {
  68796. parseState = 'afterArrayValue';
  68797. } else {
  68798. parseState = 'afterPropertyValue';
  68799. }
  68800. }
  68801. // This code is unreachable.
  68802. // function invalidParseState () {
  68803. // return new Error(`JSON5: invalid parse state '${parseState}'`)
  68804. // }
  68805. // This code is unreachable.
  68806. // function invalidLexState (state) {
  68807. // return new Error(`JSON5: invalid lex state '${state}'`)
  68808. // }
  68809. function invalidChar (c) {
  68810. if (c === undefined) {
  68811. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68812. }
  68813. return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  68814. }
  68815. function invalidEOF () {
  68816. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68817. }
  68818. // This code is unreachable.
  68819. // function invalidToken () {
  68820. // if (token.type === 'eof') {
  68821. // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68822. // }
  68823. // const c = String.fromCodePoint(token.value.codePointAt(0))
  68824. // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  68825. // }
  68826. function invalidIdentifier () {
  68827. column -= 5;
  68828. return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
  68829. }
  68830. function separatorChar (c) {
  68831. console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
  68832. }
  68833. function formatChar (c) {
  68834. const replacements = {
  68835. "'": "\\'",
  68836. '"': '\\"',
  68837. '\\': '\\\\',
  68838. '\b': '\\b',
  68839. '\f': '\\f',
  68840. '\n': '\\n',
  68841. '\r': '\\r',
  68842. '\t': '\\t',
  68843. '\v': '\\v',
  68844. '\0': '\\0',
  68845. '\u2028': '\\u2028',
  68846. '\u2029': '\\u2029',
  68847. };
  68848. if (replacements[c]) {
  68849. return replacements[c]
  68850. }
  68851. if (c < ' ') {
  68852. const hexString = c.charCodeAt(0).toString(16);
  68853. return '\\x' + ('00' + hexString).substring(hexString.length)
  68854. }
  68855. return c
  68856. }
  68857. function syntaxError (message) {
  68858. const err = new SyntaxError(message);
  68859. err.lineNumber = line;
  68860. err.columnNumber = column;
  68861. return err
  68862. }
  68863. var stringify = function stringify (value, replacer, space) {
  68864. const stack = [];
  68865. let indent = '';
  68866. let propertyList;
  68867. let replacerFunc;
  68868. let gap = '';
  68869. let quote;
  68870. if (
  68871. replacer != null &&
  68872. typeof replacer === 'object' &&
  68873. !Array.isArray(replacer)
  68874. ) {
  68875. space = replacer.space;
  68876. quote = replacer.quote;
  68877. replacer = replacer.replacer;
  68878. }
  68879. if (typeof replacer === 'function') {
  68880. replacerFunc = replacer;
  68881. } else if (Array.isArray(replacer)) {
  68882. propertyList = [];
  68883. for (const v of replacer) {
  68884. let item;
  68885. if (typeof v === 'string') {
  68886. item = v;
  68887. } else if (
  68888. typeof v === 'number' ||
  68889. v instanceof String ||
  68890. v instanceof Number
  68891. ) {
  68892. item = String(v);
  68893. }
  68894. if (item !== undefined && propertyList.indexOf(item) < 0) {
  68895. propertyList.push(item);
  68896. }
  68897. }
  68898. }
  68899. if (space instanceof Number) {
  68900. space = Number(space);
  68901. } else if (space instanceof String) {
  68902. space = String(space);
  68903. }
  68904. if (typeof space === 'number') {
  68905. if (space > 0) {
  68906. space = Math.min(10, Math.floor(space));
  68907. gap = ' '.substr(0, space);
  68908. }
  68909. } else if (typeof space === 'string') {
  68910. gap = space.substr(0, 10);
  68911. }
  68912. return serializeProperty('', {'': value})
  68913. function serializeProperty (key, holder) {
  68914. let value = holder[key];
  68915. if (value != null) {
  68916. if (typeof value.toJSON5 === 'function') {
  68917. value = value.toJSON5(key);
  68918. } else if (typeof value.toJSON === 'function') {
  68919. value = value.toJSON(key);
  68920. }
  68921. }
  68922. if (replacerFunc) {
  68923. value = replacerFunc.call(holder, key, value);
  68924. }
  68925. if (value instanceof Number) {
  68926. value = Number(value);
  68927. } else if (value instanceof String) {
  68928. value = String(value);
  68929. } else if (value instanceof Boolean) {
  68930. value = value.valueOf();
  68931. }
  68932. switch (value) {
  68933. case null: return 'null'
  68934. case true: return 'true'
  68935. case false: return 'false'
  68936. }
  68937. if (typeof value === 'string') {
  68938. return quoteString(value, false)
  68939. }
  68940. if (typeof value === 'number') {
  68941. return String(value)
  68942. }
  68943. if (typeof value === 'object') {
  68944. return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
  68945. }
  68946. return undefined
  68947. }
  68948. function quoteString (value) {
  68949. const quotes = {
  68950. "'": 0.1,
  68951. '"': 0.2,
  68952. };
  68953. const replacements = {
  68954. "'": "\\'",
  68955. '"': '\\"',
  68956. '\\': '\\\\',
  68957. '\b': '\\b',
  68958. '\f': '\\f',
  68959. '\n': '\\n',
  68960. '\r': '\\r',
  68961. '\t': '\\t',
  68962. '\v': '\\v',
  68963. '\0': '\\0',
  68964. '\u2028': '\\u2028',
  68965. '\u2029': '\\u2029',
  68966. };
  68967. let product = '';
  68968. for (let i = 0; i < value.length; i++) {
  68969. const c = value[i];
  68970. switch (c) {
  68971. case "'":
  68972. case '"':
  68973. quotes[c]++;
  68974. product += c;
  68975. continue
  68976. case '\0':
  68977. if (util.isDigit(value[i + 1])) {
  68978. product += '\\x00';
  68979. continue
  68980. }
  68981. }
  68982. if (replacements[c]) {
  68983. product += replacements[c];
  68984. continue
  68985. }
  68986. if (c < ' ') {
  68987. let hexString = c.charCodeAt(0).toString(16);
  68988. product += '\\x' + ('00' + hexString).substring(hexString.length);
  68989. continue
  68990. }
  68991. product += c;
  68992. }
  68993. const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);
  68994. product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
  68995. return quoteChar + product + quoteChar
  68996. }
  68997. function serializeObject (value) {
  68998. if (stack.indexOf(value) >= 0) {
  68999. throw TypeError('Converting circular structure to JSON5')
  69000. }
  69001. stack.push(value);
  69002. let stepback = indent;
  69003. indent = indent + gap;
  69004. let keys = propertyList || Object.keys(value);
  69005. let partial = [];
  69006. for (const key of keys) {
  69007. const propertyString = serializeProperty(key, value);
  69008. if (propertyString !== undefined) {
  69009. let member = serializeKey(key) + ':';
  69010. if (gap !== '') {
  69011. member += ' ';
  69012. }
  69013. member += propertyString;
  69014. partial.push(member);
  69015. }
  69016. }
  69017. let final;
  69018. if (partial.length === 0) {
  69019. final = '{}';
  69020. } else {
  69021. let properties;
  69022. if (gap === '') {
  69023. properties = partial.join(',');
  69024. final = '{' + properties + '}';
  69025. } else {
  69026. let separator = ',\n' + indent;
  69027. properties = partial.join(separator);
  69028. final = '{\n' + indent + properties + ',\n' + stepback + '}';
  69029. }
  69030. }
  69031. stack.pop();
  69032. indent = stepback;
  69033. return final
  69034. }
  69035. function serializeKey (key) {
  69036. if (key.length === 0) {
  69037. return quoteString(key, true)
  69038. }
  69039. const firstChar = String.fromCodePoint(key.codePointAt(0));
  69040. if (!util.isIdStartChar(firstChar)) {
  69041. return quoteString(key, true)
  69042. }
  69043. for (let i = firstChar.length; i < key.length; i++) {
  69044. if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
  69045. return quoteString(key, true)
  69046. }
  69047. }
  69048. return key
  69049. }
  69050. function serializeArray (value) {
  69051. if (stack.indexOf(value) >= 0) {
  69052. throw TypeError('Converting circular structure to JSON5')
  69053. }
  69054. stack.push(value);
  69055. let stepback = indent;
  69056. indent = indent + gap;
  69057. let partial = [];
  69058. for (let i = 0; i < value.length; i++) {
  69059. const propertyString = serializeProperty(String(i), value);
  69060. partial.push((propertyString !== undefined) ? propertyString : 'null');
  69061. }
  69062. let final;
  69063. if (partial.length === 0) {
  69064. final = '[]';
  69065. } else {
  69066. if (gap === '') {
  69067. let properties = partial.join(',');
  69068. final = '[' + properties + ']';
  69069. } else {
  69070. let separator = ',\n' + indent;
  69071. let properties = partial.join(separator);
  69072. final = '[\n' + indent + properties + ',\n' + stepback + ']';
  69073. }
  69074. }
  69075. stack.pop();
  69076. indent = stepback;
  69077. return final
  69078. }
  69079. };
  69080. const JSON5 = {
  69081. parse,
  69082. stringify,
  69083. };
  69084. var lib = JSON5;
  69085. class Sidebar{
  69086. constructor(viewer){
  69087. this.viewer = viewer;
  69088. this.measuringTool = viewer.measuringTool;
  69089. this.profileTool = viewer.profileTool;
  69090. this.volumeTool = viewer.volumeTool;
  69091. this.dom = $("#sidebar_root");
  69092. }
  69093. createToolIcon(icon, title, callback){
  69094. let element = $(`
  69095. <img src="${icon}"
  69096. style="width: 32px; height: 32px"
  69097. class="button-icon"
  69098. data-i18n="${title}" />
  69099. `);
  69100. element.click(callback);
  69101. return element;
  69102. }
  69103. init(){
  69104. if(Potree.settings.editType == 'merge'){
  69105. this.initMergeBar();
  69106. this.initToolbar();
  69107. this.initScene();
  69108. this.initNavigation();
  69109. }else {
  69110. this.initAccordion();
  69111. this.initAppearance();
  69112. this.initToolbar();
  69113. this.initScene();
  69114. this.initNavigation();
  69115. this.initFilters();
  69116. this.initClippingTool();
  69117. this.initSettings();
  69118. if(Potree.settings.editType != 'pano'){
  69119. this.initAlignment();
  69120. this.initClipModel();
  69121. this.initSiteModel();
  69122. this.initParitcle();
  69123. }else {
  69124. this.initPanosEdit();
  69125. }
  69126. }
  69127. $('#potree_version_number').html(Potree.version.major + "." + Potree.version.minor + Potree.version.suffix);
  69128. }
  69129. initAlignment(){
  69130. let Alignment = viewer.modules.Alignment;
  69131. var pannel = $('#alignment');
  69132. var buttons = pannel.find('[name="transform"] button');
  69133. var applyToPointcloud = (fun, value)=>{
  69134. return function(){
  69135. var selected = $('#alignment li[name="selectPointCloud"] input:checked' );
  69136. Array.from(selected).forEach(e=>{
  69137. var pointcloud = viewer.scene.pointclouds.find(p=>p.name == e.name);
  69138. fun(pointcloud, value);
  69139. });
  69140. }
  69141. };
  69142. //逆时针是正数
  69143. buttons.eq(0).on('click', applyToPointcloud(Alignment.rotate, 10));
  69144. //viewer.scene.pointclouds[0].rotation.z += THREE.Math.degToRad(10)
  69145. buttons.eq(1).on('click' ,applyToPointcloud(Alignment.rotate, 1));
  69146. buttons.eq(2).on('click', applyToPointcloud(Alignment.rotate, 0.1));
  69147. buttons.eq(3).on('click', applyToPointcloud(Alignment.rotate, -10));
  69148. buttons.eq(4).on('click',applyToPointcloud(Alignment.rotate, -1));
  69149. buttons.eq(5).on('click',applyToPointcloud(Alignment.rotate, -0.1));
  69150. buttons.eq(6).on('click', applyToPointcloud(Alignment.translate, new Vector3(-1,0,0)));
  69151. buttons.eq(7).on('click', applyToPointcloud(Alignment.translate, new Vector3(1,0,0)));
  69152. buttons.eq(8).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,-1,0)));
  69153. buttons.eq(9).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,1,0)));
  69154. buttons.eq(10).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,-1)));
  69155. buttons.eq(11).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,1)));
  69156. pannel.find('#startAlignment').on('click', ()=>{
  69157. Alignment.enter();
  69158. });
  69159. pannel.find('#exitAlignment').on('click', ()=>{
  69160. Alignment.save();
  69161. Alignment.leave();
  69162. });
  69163. pannel.find('#rotTool').on('click', ()=>{
  69164. Alignment.switchHandle('rotate');
  69165. });
  69166. pannel.find('#moveTool').on('click', ()=>{
  69167. Alignment.switchHandle('translate');
  69168. });
  69169. }
  69170. initMergeBar(){//多元融合模块
  69171. var pannel = $('#mergeModel');
  69172. var buttons = pannel.find('button');
  69173. let MergeEditor = viewer.modules.MergeEditor;
  69174. let loading = false;
  69175. pannel.find('ul[name="model"] li button').on('click',(e)=>{
  69176. if(loading)return console.log('还在加载', loading)
  69177. let $elem = $(e.target);
  69178. let parent = $elem.parent();
  69179. let name = parent.attr('name');
  69180. if($elem.attr('name') == 'select'){
  69181. return Potree.selectModel(name)
  69182. }
  69183. if($elem.text() == '添加'){
  69184. let startTime = Date.now();
  69185. Potree.addModel(name,()=>{
  69186. loading = false;
  69187. $elem.text('删除');
  69188. let now = Date.now();
  69189. console.log('加载完毕', name, '用时', (now-startTime)/1000, 's');
  69190. });
  69191. loading = name;
  69192. }else {
  69193. Potree.removeModel(name);
  69194. $elem.text('添加');
  69195. }
  69196. });
  69197. pannel.find('li button[name="splitScreen"]').on('click',(e)=>{
  69198. let $elem = $(e.target);
  69199. if($elem.text() == '分屏'){
  69200. $elem.text('恢复');
  69201. MergeEditor.enterSplit();
  69202. }else {
  69203. $elem.text('分屏');
  69204. MergeEditor.leaveSplit();
  69205. }
  69206. });
  69207. let addingTag = false;
  69208. pannel.find('li button[name="tag"]').on('click',(e)=>{
  69209. let $elem = $(e.target);
  69210. viewer.tagTool.startInsertion();
  69211. });
  69212. }
  69213. addAlignmentButton(pointcloud){
  69214. var pannel = $('#alignment li[name="selectPointCloud"]>div');
  69215. var option = $(` <input name="${pointcloud.name}" class="editCheckbox" type="checkbox" >
  69216. <label for="showingLabels">${pointcloud.name}</label>`);
  69217. pannel.append(option);
  69218. /* option.find("input").on('change',function(){
  69219. })
  69220. */
  69221. }
  69222. initClipModel(){
  69223. let Clip = viewer.modules.Clip;
  69224. var pannel = $('#clipModel');
  69225. var buttons = pannel.find('button');
  69226. buttons.eq(0).on('click', Clip.enter.bind(Clip));
  69227. buttons.eq(1).on('click', Clip.download.bind(Clip));
  69228. buttons.eq(2).on('click', Clip.leave.bind(Clip));
  69229. }
  69230. initSiteModel(){
  69231. let SiteModel = viewer.modules.SiteModel;
  69232. var pannel = $('#siteModel');
  69233. pannel.find('button[name="start"] ').on('click', SiteModel.enter.bind(SiteModel));
  69234. pannel.find('button[name="exit"] ').on('click', SiteModel.leave.bind(SiteModel));
  69235. pannel.find('button[name="building"] ').on('click', SiteModel.startInsertion.bind(SiteModel,'building'));
  69236. pannel.find('button[name="floor"] ').on('click', ()=>{
  69237. SiteModel.addFloor(SiteModel.buildings[0], 'top');
  69238. } );
  69239. pannel.find('button[name="room"] ').on('click', ()=>{
  69240. SiteModel.startInsertion('room', SiteModel.buildings[0].buildChildren[0]);
  69241. });
  69242. pannel.find('button[name="digHole"] ').on('click', ()=>{
  69243. SiteModel.selected && SiteModel.startInsertion('hole', SiteModel.selected);
  69244. });
  69245. pannel.find('button[name="selectBuilding"] ').on('click', ()=>{
  69246. SiteModel.selectEntity(SiteModel.buildings[0] );
  69247. } );
  69248. pannel.find('button[name="selectFloor"] ').on('click', ()=>{
  69249. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0]);
  69250. } );
  69251. pannel.find('button[name="selectRoom"] ').on('click', ()=>{
  69252. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  69253. });
  69254. pannel.find('button[name="removeFirstBuilding"] ').on('click', ()=>{
  69255. SiteModel.removeEntity(SiteModel.buildings[0]);
  69256. });
  69257. pannel.find('button[name="removeFirstFloor"] ').on('click', ()=>{
  69258. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0]);
  69259. });
  69260. pannel.find('button[name="removeFirstRoom"] ').on('click', ()=>{
  69261. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  69262. });
  69263. pannel.find('button[name="removeFirstHole"] ').on('click', ()=>{
  69264. SiteModel.selected.removeHole(SiteModel.selected.holes[0]);
  69265. });
  69266. pannel.find('button[name="removeFirstMarker"] ').on('click', ()=>{
  69267. //SiteModel.removeMarker(SiteModel.selected.markers[0])
  69268. SiteModel.selected.removeMarker(0);
  69269. });
  69270. }
  69271. initParitcle(){
  69272. let ParticleEditor = viewer.modules.ParticleEditor;
  69273. var pannel = $('#particle');
  69274. pannel.find('button[name="addFire"] ').on('click', ()=>{
  69275. ParticleEditor.startInsertion('fire+smoke');
  69276. });
  69277. pannel.find('button[name="addExplode"] ').on('click', ()=>{
  69278. ParticleEditor.startInsertion('explode');
  69279. });
  69280. }
  69281. initPanosEdit(){
  69282. let PanoEditor = viewer.modules.PanoEditor;
  69283. let Alignment = viewer.modules.Alignment;
  69284. var pannel = $('#panos');
  69285. pannel.find('button[name="save"] ').on('click', ()=>{
  69286. console.log('saveData',PanoEditor.exportSavingData());
  69287. });
  69288. pannel.find('button[name="translate"] ').on('click', ()=>{
  69289. Alignment.switchHandle('translate');
  69290. });
  69291. pannel.find('button[name="rotate"] ').on('click', ()=>{
  69292. Alignment.switchHandle('rotate');
  69293. });
  69294. pannel.find('button[name="topView"] ').on('click', ()=>{
  69295. PanoEditor.switchView('top');
  69296. });
  69297. pannel.find('button[name="sideView"] ').on('click', ()=>{
  69298. PanoEditor.switchView('right');
  69299. });
  69300. pannel.find('button[name="3DView"] ').on('click', ()=>{
  69301. PanoEditor.switchView('mainView');
  69302. });
  69303. pannel.find('button[name="addLink"] ').on('click', ()=>{
  69304. PanoEditor.setLinkOperateState('addLink', true);
  69305. });
  69306. pannel.find('button[name="removeLink"] ').on('click', ()=>{
  69307. PanoEditor.setLinkOperateState('removeLink', true);
  69308. });
  69309. pannel.find('button[name="getCloser"] ').on('click', ()=>{
  69310. PanoEditor.setZoomInState(true);
  69311. });
  69312. }
  69313. initToolbar(){
  69314. // ANGLE
  69315. let elToolbar = $('#tools');
  69316. elToolbar.append(this.createToolIcon(
  69317. Potree.resourcePath + '/icons/angle.png',
  69318. '[title]tt.angle_measurement',
  69319. () => {
  69320. $('#menu_measurements').next().slideDown();
  69321. let measurement = this.measuringTool.startInsertion({
  69322. showDistances: false,
  69323. showAngles: true,
  69324. showArea: false,
  69325. closed: true,
  69326. maxMarkers: 3,
  69327. minMarkers:3,
  69328. measureType: 'Angle'});
  69329. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69330. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69331. $.jstree.reference(jsonNode.id).deselect_all();
  69332. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69333. }
  69334. ));
  69335. // POINT
  69336. elToolbar.append(this.createToolIcon(
  69337. Potree.resourcePath + '/icons/point.svg',
  69338. '[title]tt.point_measurement',
  69339. () => {
  69340. $('#menu_measurements').next().slideDown();
  69341. let measurement = this.measuringTool.startInsertion({
  69342. showDistances: false,
  69343. showAngles: false,
  69344. showCoordinates: true,
  69345. showEdges:false,
  69346. showArea: false,
  69347. closed: true,
  69348. maxMarkers: 1,
  69349. minMarkers:1,
  69350. measureType: 'Point'});
  69351. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69352. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69353. $.jstree.reference(jsonNode.id).deselect_all();
  69354. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69355. }
  69356. ));
  69357. // DISTANCE
  69358. elToolbar.append(this.createToolIcon(
  69359. Potree.resourcePath + '/icons/distance.svg',
  69360. '[title]tt.distance_measurement',
  69361. () => {
  69362. $('#menu_measurements').next().slideDown();
  69363. let measurement = this.measuringTool.startInsertion({
  69364. showDistances: true,
  69365. showArea: false,
  69366. closed: false,
  69367. minMarkers:2,
  69368. maxMarkers: 2,
  69369. measureType: 'Distance'
  69370. });
  69371. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69372. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69373. $.jstree.reference(jsonNode.id).deselect_all();
  69374. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69375. }
  69376. ));
  69377. // HEIGHT
  69378. elToolbar.append(this.createToolIcon(
  69379. Potree.resourcePath + '/icons/height.svg',
  69380. '[title]tt.height_measurement',
  69381. () => {
  69382. $('#menu_measurements').next().slideDown();
  69383. let measurement = this.measuringTool.startInsertion({
  69384. showDistances: true,//false,
  69385. showHeight: true,
  69386. showArea: false,
  69387. closed: false,
  69388. maxMarkers: 2,
  69389. minMarkers:2,
  69390. //showGuideLine: true: true
  69391. measureType: 'Ver Distance',
  69392. });
  69393. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69394. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69395. $.jstree.reference(jsonNode.id).deselect_all();
  69396. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69397. }
  69398. ));
  69399. // CIRCLE
  69400. elToolbar.append(this.createToolIcon(
  69401. Potree.resourcePath + '/icons/circle.svg',
  69402. '[title]tt.circle_measurement',
  69403. () => {
  69404. $('#menu_measurements').next().slideDown();
  69405. let measurement = this.measuringTool.startInsertion({
  69406. showDistances: false,
  69407. showHeight: false,
  69408. showArea: false,
  69409. showCircle: true,
  69410. showEdges: false,
  69411. closed: false,
  69412. maxMarkers: 3,
  69413. minMarkers:3,
  69414. measureType: 'Circle'
  69415. });
  69416. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69417. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69418. $.jstree.reference(jsonNode.id).deselect_all();
  69419. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69420. }
  69421. ));
  69422. // AZIMUTH
  69423. elToolbar.append(this.createToolIcon(
  69424. Potree.resourcePath + '/icons/azimuth.svg',
  69425. 'Azimuth',
  69426. () => {
  69427. $('#menu_measurements').next().slideDown();
  69428. let measurement = this.measuringTool.startInsertion({
  69429. showDistances: false,
  69430. showHeight: false,
  69431. showArea: false,
  69432. showCircle: false,
  69433. showEdges: false,
  69434. showAzimuth: true,
  69435. closed: false,
  69436. maxMarkers: 2,
  69437. minMarkers:2,
  69438. measureType: 'Azimuth'});
  69439. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69440. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69441. $.jstree.reference(jsonNode.id).deselect_all();
  69442. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69443. }
  69444. ));
  69445. // AREA
  69446. elToolbar.append(this.createToolIcon(
  69447. Potree.resourcePath + '/icons/area.svg',
  69448. '[title]tt.area_measurement',
  69449. () => {
  69450. $('#menu_measurements').next().slideDown();
  69451. let measurement = this.measuringTool.startInsertion({
  69452. showDistances: true,
  69453. showArea: true,
  69454. closed: true,
  69455. minMarkers:3,
  69456. //showGuideLine: true: true,
  69457. measureType: 'Area'});
  69458. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69459. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69460. $.jstree.reference(jsonNode.id).deselect_all();
  69461. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69462. }
  69463. ));
  69464. //Hor AREA
  69465. elToolbar.append(this.createToolIcon(
  69466. Potree.resourcePath + '/icons/area.svg',
  69467. '[title]tt.Hor Area',
  69468. () => {
  69469. $('#menu_measurements').next().slideDown();
  69470. let measurement = this.measuringTool.startInsertion({
  69471. showDistances: true,
  69472. showArea: true,
  69473. closed: true,
  69474. minMarkers:3,
  69475. measureType: 'Hor Area'});
  69476. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69477. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69478. $.jstree.reference(jsonNode.id).deselect_all();
  69479. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69480. }
  69481. ));
  69482. // Ver Area
  69483. elToolbar.append(this.createToolIcon(
  69484. Potree.resourcePath + '/icons/area.svg',
  69485. '[title]tt.Ver Area',
  69486. () => {
  69487. $('#menu_measurements').next().slideDown();
  69488. let measurement = this.measuringTool.startInsertion({
  69489. showDistances: true,
  69490. showArea: true,
  69491. closed: true,
  69492. minMarkers:3,
  69493. measureType: 'Ver Area'});
  69494. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69495. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69496. $.jstree.reference(jsonNode.id).deselect_all();
  69497. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69498. }
  69499. ));
  69500. // rect area freedom direction
  69501. elToolbar.append(this.createToolIcon(
  69502. Potree.resourcePath + '/icons/area.svg',
  69503. '[title]tt.area_freedom_rect',
  69504. () => {
  69505. $('#menu_measurements').next().slideDown();
  69506. let measurement = this.measuringTool.startInsertion({
  69507. showDistances: true,
  69508. showArea: true,
  69509. closed: true,
  69510. minMarkers:4,
  69511. maxMarkers:4,
  69512. //showGuideLine: true: true,
  69513. isRect:true,
  69514. measureType: 'Rect Area'});
  69515. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69516. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69517. $.jstree.reference(jsonNode.id).deselect_all();
  69518. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69519. }
  69520. ));
  69521. // rect area horizontal
  69522. elToolbar.append(this.createToolIcon(
  69523. Potree.resourcePath + '/icons/area.svg',
  69524. '[title]tt.area_horizontal_rect',
  69525. () => {
  69526. $('#menu_measurements').next().slideDown();
  69527. let measurement = this.measuringTool.startInsertion({
  69528. showDistances: true,
  69529. showArea: true,
  69530. closed: true,
  69531. minMarkers:4,
  69532. maxMarkers:4,
  69533. //showGuideLine: true: true,
  69534. isRect:true,
  69535. faceDirection:"horizontal",
  69536. measureType: 'Hor Rect Area'});
  69537. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69538. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69539. $.jstree.reference(jsonNode.id).deselect_all();
  69540. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69541. }
  69542. ));
  69543. // rect area vertical
  69544. elToolbar.append(this.createToolIcon(
  69545. Potree.resourcePath + '/icons/area.svg',
  69546. '[title]tt.area_vertical_rect',
  69547. () => {
  69548. $('#menu_measurements').next().slideDown();
  69549. let measurement = this.measuringTool.startInsertion({
  69550. showDistances: true,
  69551. showArea: true,
  69552. closed: true,
  69553. minMarkers:4,
  69554. maxMarkers:4,
  69555. //showGuideLine: true: true,
  69556. isRect:true,
  69557. faceDirection:"vertical",
  69558. measureType: 'Ver Rect Area'});
  69559. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69560. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69561. $.jstree.reference(jsonNode.id).deselect_all();
  69562. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69563. }
  69564. ));
  69565. // VOLUME
  69566. elToolbar.append(this.createToolIcon(
  69567. Potree.resourcePath + '/icons/volume.svg',
  69568. '[title]tt.volume_measurement',
  69569. () => {
  69570. let volume = this.volumeTool.startInsertion();
  69571. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69572. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  69573. $.jstree.reference(jsonNode.id).deselect_all();
  69574. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69575. }
  69576. ));
  69577. // SPHERE VOLUME
  69578. elToolbar.append(this.createToolIcon(
  69579. Potree.resourcePath + '/icons/sphere_distances.svg',
  69580. '[title]tt.volume_measurement',
  69581. () => {
  69582. let volume = this.volumeTool.startInsertion({type: SphereVolume});
  69583. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69584. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  69585. $.jstree.reference(jsonNode.id).deselect_all();
  69586. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69587. }
  69588. ));
  69589. // PROFILE
  69590. elToolbar.append(this.createToolIcon(
  69591. Potree.resourcePath + '/icons/profile.svg',
  69592. '[title]tt.height_profile',
  69593. () => {
  69594. $('#menu_measurements').next().slideDown(); ;
  69595. let profile = this.profileTool.startInsertion();
  69596. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69597. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === profile.uuid);
  69598. $.jstree.reference(jsonNode.id).deselect_all();
  69599. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69600. }
  69601. ));
  69602. // ANNOTATION
  69603. elToolbar.append(this.createToolIcon(
  69604. Potree.resourcePath + '/icons/annotation.svg',
  69605. '[title]tt.annotation',
  69606. () => {
  69607. $('#menu_measurements').next().slideDown(); ;
  69608. let annotation = this.viewer.annotationTool.startInsertion();
  69609. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  69610. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  69611. $.jstree.reference(jsonNode.id).deselect_all();
  69612. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69613. }
  69614. ));
  69615. // REMOVE ALL
  69616. elToolbar.append(this.createToolIcon(
  69617. Potree.resourcePath + '/icons/reset_tools.svg',
  69618. '[title]tt.remove_all_measurement',
  69619. () => {
  69620. this.viewer.scene.removeAllMeasurements();
  69621. }
  69622. ));
  69623. { // SHOW / HIDE Measurements
  69624. let elShow = $("#measurement_options_show");
  69625. elShow.selectgroup({title: "Show/Hide labels"});
  69626. elShow.find("input").click( (e) => {
  69627. const show = e.target.value === "SHOW";
  69628. this.measuringTool.showLabels = show;
  69629. });
  69630. let currentShow = this.measuringTool.showLabels ? "SHOW" : "HIDE";
  69631. elShow.find(`input[value=${currentShow}]`).trigger("click");
  69632. }
  69633. }
  69634. initScene(){
  69635. let elScene = $("#menu_scene");
  69636. let elObjects = elScene.next().find("#scene_objects");
  69637. let elProperties = elScene.next().find("#scene_object_properties");
  69638. {
  69639. let elExport = elScene.next().find("#scene_export");
  69640. let geoJSONIcon = `${Potree.resourcePath}/icons/file_geojson.svg`;
  69641. let dxfIcon = `${Potree.resourcePath}/icons/file_dxf.svg`;
  69642. let potreeIcon = `${Potree.resourcePath}/icons/file_potree.svg`;
  69643. elExport.append(`
  69644. Export: <br>
  69645. <a href="#" download="measure.json"><img name="geojson_export_button" src="${geoJSONIcon}" class="button-icon" style="height: 24px" /></a>
  69646. <a href="#" download="measure.dxf"><img name="dxf_export_button" src="${dxfIcon}" class="button-icon" style="height: 24px" /></a>
  69647. <a href="#" download="potree.json5"><img name="potree_export_button" src="${potreeIcon}" class="button-icon" style="height: 24px" /></a>
  69648. `);
  69649. let elDownloadJSON = elExport.find("img[name=geojson_export_button]").parent();
  69650. elDownloadJSON.click( (event) => {
  69651. let scene = this.viewer.scene;
  69652. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  69653. if(measurements.length > 0){
  69654. let geoJson = GeoJSONExporter.toString(measurements);
  69655. let url = window.URL.createObjectURL(new Blob([geoJson], {type: 'data:application/octet-stream'}));
  69656. elDownloadJSON.attr('href', url);
  69657. }else {
  69658. this.viewer.postError("nothing to export");
  69659. event.preventDefault();
  69660. }
  69661. });
  69662. let elDownloadDXF = elExport.find("img[name=dxf_export_button]").parent();
  69663. elDownloadDXF.click( (event) => {
  69664. let scene = this.viewer.scene;
  69665. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  69666. if(measurements.length > 0){
  69667. let dxf = DXFExporter.toString(measurements);
  69668. let url = window.URL.createObjectURL(new Blob([dxf], {type: 'data:application/octet-stream'}));
  69669. elDownloadDXF.attr('href', url);
  69670. }else {
  69671. this.viewer.postError("no measurements to export");
  69672. event.preventDefault();
  69673. }
  69674. });
  69675. let elDownloadPotree = elExport.find("img[name=potree_export_button]").parent();
  69676. elDownloadPotree.click( (event) => {
  69677. let data = Potree.saveProject(this.viewer);
  69678. let dataString = lib.stringify(data, null, "\t");
  69679. let url = window.URL.createObjectURL(new Blob([dataString], {type: 'data:application/octet-stream'}));
  69680. elDownloadPotree.attr('href', url);
  69681. });
  69682. }
  69683. let propertiesPanel = new PropertiesPanel(elProperties, this.viewer);
  69684. propertiesPanel.setScene(this.viewer.scene);
  69685. localStorage.removeItem('jstree');
  69686. let tree = $(`<div id="jstree_scene"></div>`);
  69687. elObjects.append(tree);
  69688. tree.jstree({
  69689. 'plugins': ["checkbox", "state"],
  69690. 'core': {
  69691. "dblclick_toggle": false,
  69692. "state": {
  69693. "checked" : true
  69694. },
  69695. 'check_callback': true,
  69696. "expand_selected_onload": true
  69697. },
  69698. "checkbox" : {
  69699. "keep_selected_style": true,
  69700. "three_state": false,
  69701. "whole_node": false,
  69702. "tie_selection": false,
  69703. },
  69704. });
  69705. let createNode = (parent, text, icon, object) => {
  69706. let nodeID = tree.jstree('create_node', parent, {
  69707. "text": text,
  69708. "icon": icon,
  69709. "data": object
  69710. },
  69711. "last", false, false);
  69712. if(object.visible){
  69713. tree.jstree('check_node', nodeID);
  69714. }else {
  69715. tree.jstree('uncheck_node', nodeID);
  69716. }
  69717. return nodeID;
  69718. };
  69719. let pcID = tree.jstree('create_node', "#", { "text": "<b>Point Clouds</b>", "id": "pointclouds"}, "last", false, false);
  69720. let measurementID = tree.jstree('create_node', "#", { "text": "<b>Measurements</b>", "id": "measurements" }, "last", false, false);
  69721. let annotationsID = tree.jstree('create_node', "#", { "text": "<b>Annotations</b>", "id": "annotations" }, "last", false, false);
  69722. let otherID = tree.jstree('create_node', "#", { "text": "<b>Other</b>", "id": "other" }, "last", false, false);
  69723. let vectorsID = tree.jstree('create_node', "#", { "text": "<b>Vectors</b>", "id": "vectors" }, "last", false, false);
  69724. let imagesID = tree.jstree('create_node', "#", { "text": "<b> Images</b>", "id": "images" }, "last", false, false);
  69725. tree.jstree("check_node", pcID);
  69726. tree.jstree("check_node", measurementID);
  69727. tree.jstree("check_node", annotationsID);
  69728. tree.jstree("check_node", otherID);
  69729. tree.jstree("check_node", vectorsID);
  69730. tree.jstree("check_node", imagesID);
  69731. tree.on('create_node.jstree', (e, data) => {
  69732. tree.jstree("open_all");
  69733. });
  69734. tree.on("select_node.jstree", (e, data) => {
  69735. let object = data.node.data;
  69736. propertiesPanel.set(object);
  69737. this.viewer.inputHandler.deselectAll();
  69738. if(object instanceof Volume){
  69739. this.viewer.inputHandler.toggleSelection(object);
  69740. }
  69741. $(this.viewer.renderer.domElement).focus();
  69742. });
  69743. tree.on("deselect_node.jstree", (e, data) => {
  69744. propertiesPanel.set(null);
  69745. });
  69746. tree.on("delete_node.jstree", (e, data) => {
  69747. propertiesPanel.set(null);
  69748. });
  69749. tree.on('dblclick','.jstree-anchor', (e) => {
  69750. let instance = $.jstree.reference(e.target);
  69751. let node = instance.get_node(e.target);
  69752. let object = node.data;
  69753. // ignore double click on checkbox
  69754. if(e.target.classList.contains("jstree-checkbox")){
  69755. return;
  69756. }
  69757. if(object instanceof PointCloudTree){
  69758. let box = this.viewer.getBoundingBox([object]);
  69759. let node = new Object3D();
  69760. node.boundingBox = box;
  69761. this.viewer.zoomTo(node, 1, 500);
  69762. }else if(object instanceof Measure){
  69763. let points = object.points.map(p => p.position);
  69764. let box = new Box3().setFromPoints(points);
  69765. if(box.getSize(new Vector3()).length() == 0){
  69766. box.min = box.max.clone();//禁止相同
  69767. box.expandByVector(new Vector3(1,1,1));
  69768. }
  69769. let node = new Object3D();
  69770. node.boundingBox = box;
  69771. this.viewer.zoomTo(node, 2, 500);
  69772. }else if(object instanceof Profile){
  69773. let points = object.points;
  69774. let box = new Box3().setFromPoints(points);
  69775. if(box.getSize(new Vector3()).length() > 0){
  69776. let node = new Object3D();
  69777. node.boundingBox = box;
  69778. this.viewer.zoomTo(node, 1, 500);
  69779. }
  69780. }else if(object instanceof Volume){
  69781. let box = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  69782. if(box.getSize(new Vector3()).length() > 0){
  69783. let node = new Object3D();
  69784. node.boundingBox = box;
  69785. this.viewer.zoomTo(node, 1, 500);
  69786. }
  69787. }else if(object instanceof Annotation){
  69788. object.moveHere(this.viewer.scene.getActiveCamera());
  69789. }else if(object instanceof PolygonClipVolume){
  69790. let dir = object.camera.getWorldDirection(new Vector3());
  69791. let target;
  69792. if(object.camera instanceof OrthographicCamera){
  69793. dir.multiplyScalar(object.camera.right);
  69794. target = new Vector3().addVectors(object.camera.position, dir);
  69795. this.viewer.setCameraMode(CameraMode.ORTHOGRAPHIC);
  69796. }else if(object.camera instanceof PerspectiveCamera){
  69797. dir.multiplyScalar(this.viewer.scene.view.radius);
  69798. target = new Vector3().addVectors(object.camera.position, dir);
  69799. this.viewer.setCameraMode(CameraMode.PERSPECTIVE);
  69800. }
  69801. this.viewer.scene.view.position.copy(object.camera.position);
  69802. this.viewer.scene.view.lookAt(target);
  69803. }else if(object.type === "SpotLight"){
  69804. let distance = (object.distance > 0) ? object.distance / 4 : 5 * 1000;
  69805. let position = object.position;
  69806. let target = new Vector3().addVectors(
  69807. position,
  69808. object.getWorldDirection(new Vector3()).multiplyScalar(distance));
  69809. this.viewer.scene.view.position.copy(object.position);
  69810. this.viewer.scene.view.lookAt(target);
  69811. }else if(object instanceof Object3D){
  69812. let box = new Box3().setFromObject(object);
  69813. if(box.getSize(new Vector3()).length() > 0){
  69814. let node = new Object3D();
  69815. node.boundingBox = box;
  69816. this.viewer.zoomTo(node, 1, 500);
  69817. }
  69818. }else if(object instanceof OrientedImage){
  69819. // TODO zoom to images
  69820. // let box = new THREE.Box3().setFromObject(object);
  69821. // if(box.getSize(new THREE.Vector3()).length() > 0){
  69822. // let node = new THREE.Object3D();
  69823. // node.boundingBox = box;
  69824. // this.viewer.zoomTo(node, 1, 500);
  69825. // }
  69826. }else if(object instanceof Images360){
  69827. // TODO
  69828. }else if(object instanceof Geopackage){
  69829. // TODO
  69830. }
  69831. });
  69832. tree.on("uncheck_node.jstree", (e, data) => {
  69833. let object = data.node.data;
  69834. if(object){
  69835. object.visible = false;
  69836. }
  69837. });
  69838. tree.on("check_node.jstree", (e, data) => {
  69839. let object = data.node.data;
  69840. if(object){
  69841. object.visible = true;
  69842. }
  69843. });
  69844. let onPointCloudAdded = (e) => {
  69845. let pointcloud = e.pointcloud;
  69846. let cloudIcon = `${Potree.resourcePath}/icons/cloud.svg`;
  69847. let node = createNode(pcID, pointcloud.name, cloudIcon, pointcloud);
  69848. pointcloud.addEventListener("visibility_changed", () => {
  69849. if(pointcloud.visible){
  69850. tree.jstree('check_node', node);
  69851. }else {
  69852. tree.jstree('uncheck_node', node);
  69853. }
  69854. });
  69855. };
  69856. let onMeasurementAdded = (e) => {
  69857. let measurement = e.measurement;
  69858. let icon = Utils.getMeasurementIcon(measurement);
  69859. createNode(measurementID, measurement.name, icon, measurement);
  69860. };
  69861. let onVolumeAdded = (e) => {
  69862. let volume = e.volume;
  69863. let icon = Utils.getMeasurementIcon(volume);
  69864. let node = createNode(measurementID, volume.name, icon, volume);
  69865. volume.addEventListener("visibility_changed", () => {
  69866. if(volume.visible){
  69867. tree.jstree('check_node', node);
  69868. }else {
  69869. tree.jstree('uncheck_node', node);
  69870. }
  69871. });
  69872. };
  69873. let onProfileAdded = (e) => {
  69874. let profile = e.profile;
  69875. let icon = Utils.getMeasurementIcon(profile);
  69876. createNode(measurementID, profile.name, icon, profile);
  69877. };
  69878. let onAnnotationAdded = (e) => {
  69879. let annotation = e.annotation;
  69880. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  69881. let parentID = this.annotationMapping.get(annotation.parent);
  69882. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  69883. this.annotationMapping.set(annotation, annotationID);
  69884. annotation.addEventListener("annotation_changed", (e) => {
  69885. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  69886. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  69887. $.jstree.reference(jsonNode.id).rename_node(jsonNode.id, annotation.title);
  69888. });
  69889. };
  69890. let onCameraAnimationAdded = (e) => {
  69891. const animation = e.animation;
  69892. const animationIcon = `${Potree.resourcePath}/icons/camera_animation.svg`;
  69893. createNode(otherID, "animation", animationIcon, animation);
  69894. };
  69895. let onOrientedImagesAdded = (e) => {
  69896. const images = e.images;
  69897. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  69898. const node = createNode(imagesID, "images", imagesIcon, images);
  69899. images.addEventListener("visibility_changed", () => {
  69900. if(images.visible){
  69901. tree.jstree('check_node', node);
  69902. }else {
  69903. tree.jstree('uncheck_node', node);
  69904. }
  69905. });
  69906. };
  69907. let onImages360Added = (e) => {
  69908. const images = e.images;
  69909. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  69910. const node = createNode(imagesID, "360° images", imagesIcon, images);
  69911. images.addEventListener("visibility_changed", () => {
  69912. if(images.visible){
  69913. tree.jstree('check_node', node);
  69914. }else {
  69915. tree.jstree('uncheck_node', node);
  69916. }
  69917. });
  69918. };
  69919. const onGeopackageAdded = (e) => {
  69920. const geopackage = e.geopackage;
  69921. const geopackageIcon = `${Potree.resourcePath}/icons/triangle.svg`;
  69922. const tree = $(`#jstree_scene`);
  69923. const parentNode = "vectors";
  69924. for(const layer of geopackage.node.children){
  69925. const name = layer.name;
  69926. let shpPointsID = tree.jstree('create_node', parentNode, {
  69927. "text": name,
  69928. "icon": geopackageIcon,
  69929. "object": layer,
  69930. "data": layer,
  69931. },
  69932. "last", false, false);
  69933. tree.jstree(layer.visible ? "check_node" : "uncheck_node", shpPointsID);
  69934. }
  69935. };
  69936. this.viewer.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  69937. this.viewer.scene.addEventListener("measurement_added", onMeasurementAdded);
  69938. this.viewer.scene.addEventListener("profile_added", onProfileAdded);
  69939. this.viewer.scene.addEventListener("volume_added", onVolumeAdded);
  69940. this.viewer.scene.addEventListener("camera_animation_added", onCameraAnimationAdded);
  69941. this.viewer.scene.addEventListener("oriented_images_added", onOrientedImagesAdded);
  69942. this.viewer.scene.addEventListener("360_images_added", onImages360Added);
  69943. this.viewer.scene.addEventListener("geopackage_added", onGeopackageAdded);
  69944. this.viewer.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  69945. this.viewer.scene.annotations.addEventListener("annotation_added", onAnnotationAdded);
  69946. let onMeasurementRemoved = (e) => {
  69947. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69948. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.measurement.uuid);
  69949. tree.jstree("delete_node", jsonNode.id);
  69950. };
  69951. let onVolumeRemoved = (e) => {
  69952. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69953. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  69954. tree.jstree("delete_node", jsonNode.id);
  69955. };
  69956. let onPolygonClipVolumeRemoved = (e) => {
  69957. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69958. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  69959. tree.jstree("delete_node", jsonNode.id);
  69960. };
  69961. let onProfileRemoved = (e) => {
  69962. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69963. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.profile.uuid);
  69964. tree.jstree("delete_node", jsonNode.id);
  69965. };
  69966. this.viewer.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  69967. this.viewer.scene.addEventListener("volume_removed", onVolumeRemoved);
  69968. this.viewer.scene.addEventListener("polygon_clip_volume_removed", onPolygonClipVolumeRemoved);
  69969. this.viewer.scene.addEventListener("profile_removed", onProfileRemoved);
  69970. {
  69971. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  69972. this.annotationMapping = new Map();
  69973. this.annotationMapping.set(this.viewer.scene.annotations, annotationsID);
  69974. this.viewer.scene.annotations.traverseDescendants(annotation => {
  69975. let parentID = this.annotationMapping.get(annotation.parent);
  69976. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  69977. this.annotationMapping.set(annotation, annotationID);
  69978. });
  69979. }
  69980. const scene = this.viewer.scene;
  69981. for(let pointcloud of scene.pointclouds){
  69982. onPointCloudAdded({pointcloud: pointcloud});
  69983. }
  69984. for(let measurement of scene.measurements){
  69985. onMeasurementAdded({measurement: measurement});
  69986. }
  69987. for(let volume of [...scene.volumes, ...scene.polygonClipVolumes]){
  69988. onVolumeAdded({volume: volume});
  69989. }
  69990. for(let animation of scene.cameraAnimations){
  69991. onCameraAnimationAdded({animation: animation});
  69992. }
  69993. for(let images of scene.orientedImages){
  69994. onOrientedImagesAdded({images: images});
  69995. }
  69996. for(let images of scene.images360){
  69997. onImages360Added({images: images});
  69998. }
  69999. for(const geopackage of scene.geopackages){
  70000. onGeopackageAdded({geopackage: geopackage});
  70001. }
  70002. for(let profile of scene.profiles){
  70003. onProfileAdded({profile: profile});
  70004. }
  70005. {
  70006. createNode(otherID, "Camera", null, new Camera());
  70007. }
  70008. this.viewer.addEventListener("scene_changed", (e) => {
  70009. propertiesPanel.setScene(e.scene);
  70010. e.oldScene.removeEventListener("pointcloud_added", onPointCloudAdded);
  70011. e.oldScene.removeEventListener("measurement_added", onMeasurementAdded);
  70012. e.oldScene.removeEventListener("profile_added", onProfileAdded);
  70013. e.oldScene.removeEventListener("volume_added", onVolumeAdded);
  70014. e.oldScene.removeEventListener("polygon_clip_volume_added", onVolumeAdded);
  70015. e.oldScene.removeEventListener("measurement_removed", onMeasurementRemoved);
  70016. e.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  70017. e.scene.addEventListener("measurement_added", onMeasurementAdded);
  70018. e.scene.addEventListener("profile_added", onProfileAdded);
  70019. e.scene.addEventListener("volume_added", onVolumeAdded);
  70020. e.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  70021. e.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  70022. });
  70023. }
  70024. initClippingTool(){
  70025. this.viewer.addEventListener("cliptask_changed", (event) => {
  70026. console.log("TODO");
  70027. });
  70028. this.viewer.addEventListener("clipmethod_changed", (event) => {
  70029. console.log("TODO");
  70030. });
  70031. {
  70032. let elClipTask = $("#cliptask_options");
  70033. elClipTask.selectgroup({title: "Clip Task"});
  70034. elClipTask.find("input").click( (e) => {
  70035. this.viewer.setClipTask(ClipTask[e.target.value]);
  70036. });
  70037. let currentClipTask = Object.keys(ClipTask)
  70038. .filter(key => ClipTask[key] === this.viewer.clipTask);
  70039. elClipTask.find(`input[value=${currentClipTask}]`).trigger("click");
  70040. }
  70041. {
  70042. let elClipMethod = $("#clipmethod_options");
  70043. elClipMethod.selectgroup({title: "Clip Method"});
  70044. elClipMethod.find("input").click( (e) => {
  70045. this.viewer.setClipMethod(ClipMethod[e.target.value]);
  70046. });
  70047. let currentClipMethod = Object.keys(ClipMethod)
  70048. .filter(key => ClipMethod[key] === this.viewer.clipMethod);
  70049. elClipMethod.find(`input[value=${currentClipMethod}]`).trigger("click");
  70050. }
  70051. let clippingToolBar = $("#clipping_tools");
  70052. // CLIP VOLUME
  70053. clippingToolBar.append(this.createToolIcon(
  70054. Potree.resourcePath + '/icons/clip_volume.svg',
  70055. '[title]tt.clip_volume',
  70056. () => {
  70057. let item = this.volumeTool.startInsertion({clip: true});
  70058. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  70059. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  70060. $.jstree.reference(jsonNode.id).deselect_all();
  70061. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  70062. }
  70063. ));
  70064. // CLIP POLYGON
  70065. clippingToolBar.append(this.createToolIcon(
  70066. Potree.resourcePath + "/icons/clip-polygon.svg",
  70067. "[title]tt.clip_polygon",
  70068. () => {
  70069. let item = this.viewer.clippingTool.startInsertion({type: "polygon"});
  70070. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  70071. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  70072. $.jstree.reference(jsonNode.id).deselect_all();
  70073. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  70074. }
  70075. ));
  70076. {// SCREEN BOX SELECT
  70077. let boxSelectTool = new ScreenBoxSelectTool(this.viewer);
  70078. clippingToolBar.append(this.createToolIcon(
  70079. Potree.resourcePath + "/icons/clip-screen.svg",
  70080. "[title]tt.screen_clip_box",
  70081. () => {
  70082. if(!(this.viewer.scene.getActiveCamera() instanceof OrthographicCamera)){
  70083. this.viewer.postMessage(`Switch to Orthographic Camera Mode before using the Screen-Box-Select tool.`,
  70084. {duration: 2000});
  70085. return;
  70086. }
  70087. let item = boxSelectTool.startInsertion();
  70088. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  70089. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  70090. $.jstree.reference(jsonNode.id).deselect_all();
  70091. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  70092. }
  70093. ));
  70094. }
  70095. { // REMOVE CLIPPING TOOLS
  70096. clippingToolBar.append(this.createToolIcon(
  70097. Potree.resourcePath + "/icons/remove.svg",
  70098. "[title]tt.remove_all_clipping_volumes",
  70099. () => {
  70100. this.viewer.scene.removeAllClipVolumes();
  70101. }
  70102. ));
  70103. }
  70104. }
  70105. initFilters(){
  70106. this.initClassificationList();
  70107. this.initReturnFilters();
  70108. this.initGPSTimeFilters();
  70109. this.initPointSourceIDFilters();
  70110. }
  70111. initReturnFilters(){
  70112. let elReturnFilterPanel = $('#return_filter_panel');
  70113. { // RETURN NUMBER
  70114. let sldReturnNumber = elReturnFilterPanel.find('#sldReturnNumber');
  70115. let lblReturnNumber = elReturnFilterPanel.find('#lblReturnNumber');
  70116. sldReturnNumber.slider({
  70117. range: true,
  70118. min: 0, max: 7, step: 1,
  70119. values: [0, 7],
  70120. slide: (event, ui) => {
  70121. this.viewer.setFilterReturnNumberRange(ui.values[0], ui.values[1]);
  70122. }
  70123. });
  70124. let onReturnNumberChanged = (event) => {
  70125. let [from, to] = this.viewer.filterReturnNumberRange;
  70126. lblReturnNumber[0].innerHTML = `${from} to ${to}`;
  70127. sldReturnNumber.slider({values: [from, to]});
  70128. };
  70129. this.viewer.addEventListener('filter_return_number_range_changed', onReturnNumberChanged);
  70130. onReturnNumberChanged();
  70131. }
  70132. { // NUMBER OF RETURNS
  70133. let sldNumberOfReturns = elReturnFilterPanel.find('#sldNumberOfReturns');
  70134. let lblNumberOfReturns = elReturnFilterPanel.find('#lblNumberOfReturns');
  70135. sldNumberOfReturns.slider({
  70136. range: true,
  70137. min: 0, max: 7, step: 1,
  70138. values: [0, 7],
  70139. slide: (event, ui) => {
  70140. this.viewer.setFilterNumberOfReturnsRange(ui.values[0], ui.values[1]);
  70141. }
  70142. });
  70143. let onNumberOfReturnsChanged = (event) => {
  70144. let [from, to] = this.viewer.filterNumberOfReturnsRange;
  70145. lblNumberOfReturns[0].innerHTML = `${from} to ${to}`;
  70146. sldNumberOfReturns.slider({values: [from, to]});
  70147. };
  70148. this.viewer.addEventListener('filter_number_of_returns_range_changed', onNumberOfReturnsChanged);
  70149. onNumberOfReturnsChanged();
  70150. }
  70151. }
  70152. initGPSTimeFilters(){
  70153. let elGPSTimeFilterPanel = $('#gpstime_filter_panel');
  70154. {
  70155. let slider = new HierarchicalSlider({
  70156. levels: 4,
  70157. slide: (event) => {
  70158. this.viewer.setFilterGPSTimeRange(...event.values);
  70159. },
  70160. });
  70161. let initialized = false;
  70162. let initialize = () => {
  70163. let elRangeContainer = $("#gpstime_multilevel_range_container");
  70164. elRangeContainer[0].prepend(slider.element);
  70165. let extent = this.viewer.getGpsTimeExtent();
  70166. slider.setRange(extent);
  70167. slider.setValues(extent);
  70168. initialized = true;
  70169. };
  70170. this.viewer.addEventListener("update", (e) => {
  70171. let extent = this.viewer.getGpsTimeExtent();
  70172. let gpsTimeAvailable = extent[0] !== Infinity;
  70173. if(!initialized && gpsTimeAvailable){
  70174. initialize();
  70175. }
  70176. slider.setRange(extent);
  70177. });
  70178. }
  70179. {
  70180. const txtGpsTime = elGPSTimeFilterPanel.find("#txtGpsTime");
  70181. const btnFindGpsTime = elGPSTimeFilterPanel.find("#btnFindGpsTime");
  70182. let targetTime = null;
  70183. txtGpsTime.on("input", (e) => {
  70184. const str = txtGpsTime.val();
  70185. if(!isNaN(str)){
  70186. const value = parseFloat(str);
  70187. targetTime = value;
  70188. txtGpsTime.css("background-color", "");
  70189. }else {
  70190. targetTime = null;
  70191. txtGpsTime.css("background-color", "#ff9999");
  70192. }
  70193. });
  70194. btnFindGpsTime.click( () => {
  70195. if(targetTime !== null){
  70196. viewer.moveToGpsTimeVicinity(targetTime);
  70197. }
  70198. });
  70199. }
  70200. }
  70201. initPointSourceIDFilters() {
  70202. let elPointSourceIDFilterPanel = $('#pointsourceid_filter_panel');
  70203. {
  70204. let slider = new HierarchicalSlider({
  70205. levels: 4,
  70206. range: [0, 65535],
  70207. precision: 1,
  70208. slide: (event) => {
  70209. let values = event.values;
  70210. this.viewer.setFilterPointSourceIDRange(values[0], values[1]);
  70211. }
  70212. });
  70213. let initialized = false;
  70214. let initialize = () => {
  70215. elPointSourceIDFilterPanel[0].prepend(slider.element);
  70216. initialized = true;
  70217. };
  70218. this.viewer.addEventListener("update", (e) => {
  70219. let extent = this.viewer.filterPointSourceIDRange;
  70220. if(!initialized){
  70221. initialize();
  70222. slider.setValues(extent);
  70223. }
  70224. });
  70225. }
  70226. // let lblPointSourceID = elPointSourceIDFilterPanel.find("#lblPointSourceID");
  70227. // let elPointSourceID = elPointSourceIDFilterPanel.find("#spnPointSourceID");
  70228. // let slider = new ZoomableSlider();
  70229. // elPointSourceID[0].appendChild(slider.element);
  70230. // slider.update();
  70231. // slider.change( () => {
  70232. // let range = slider.chosenRange;
  70233. // this.viewer.setFilterPointSourceIDRange(range[0], range[1]);
  70234. // });
  70235. // let onPointSourceIDExtentChanged = (event) => {
  70236. // let range = this.viewer.filterPointSourceIDExtent;
  70237. // slider.setVisibleRange(range);
  70238. // };
  70239. // let onPointSourceIDChanged = (event) => {
  70240. // let range = this.viewer.filterPointSourceIDRange;
  70241. // let precision = 1;
  70242. // let from = `${Utils.addCommas(range[0].toFixed(precision))}`;
  70243. // let to = `${Utils.addCommas(range[1].toFixed(precision))}`;
  70244. // lblPointSourceID[0].innerHTML = `${from} to ${to}`;
  70245. // slider.setRange(range);
  70246. // };
  70247. // this.viewer.addEventListener('filter_point_source_id_range_changed', onPointSourceIDChanged);
  70248. // this.viewer.addEventListener('filter_point_source_id_extent_changed', onPointSourceIDExtentChanged);
  70249. }
  70250. initClassificationList(){
  70251. let elClassificationList = $('#classificationList');
  70252. let addClassificationItem = (code, name) => {
  70253. const classification = this.viewer.classifications[code];
  70254. const inputID = 'chkClassification_' + code;
  70255. const colorPickerID = 'colorPickerClassification_' + code;
  70256. const checked = classification.visible ? "checked" : "";
  70257. let element = $(`
  70258. <li>
  70259. <label style="whitespace: nowrap; display: flex">
  70260. <input id="${inputID}" type="checkbox" ${checked}/>
  70261. <span style="flex-grow: 1">${name}</span>
  70262. <input id="${colorPickerID}" style="zoom: 0.5" />
  70263. </label>
  70264. </li>
  70265. `);
  70266. const elInput = element.find('input');
  70267. const elColorPicker = element.find(`#${colorPickerID}`);
  70268. elInput.click(event => {
  70269. this.viewer.setClassificationVisibility(code, event.target.checked);
  70270. });
  70271. let defaultColor = classification.color.map(c => c * 255).join(", ");
  70272. defaultColor = `rgb(${defaultColor})`;
  70273. elColorPicker.spectrum({
  70274. // flat: true,
  70275. color: defaultColor,
  70276. showInput: true,
  70277. preferredFormat: 'rgb',
  70278. cancelText: '',
  70279. chooseText: 'Apply',
  70280. move: color => {
  70281. let rgb = color.toRgb();
  70282. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  70283. classification.color = c;
  70284. },
  70285. change: color => {
  70286. let rgb = color.toRgb();
  70287. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  70288. classification.color = c;
  70289. }
  70290. });
  70291. elClassificationList.append(element);
  70292. };
  70293. const addToggleAllButton = () => { // toggle all button
  70294. const element = $(`
  70295. <li>
  70296. <label style="whitespace: nowrap">
  70297. <input id="toggleClassificationFilters" type="checkbox" checked/>
  70298. <span>show/hide all</span>
  70299. </label>
  70300. </li>
  70301. `);
  70302. let elInput = element.find('input');
  70303. elInput.click(event => {
  70304. this.viewer.toggleAllClassificationsVisibility();
  70305. });
  70306. elClassificationList.append(element);
  70307. };
  70308. const addInvertButton = () => {
  70309. const element = $(`
  70310. <li>
  70311. <input type="button" value="invert" />
  70312. </li>
  70313. `);
  70314. let elInput = element.find('input');
  70315. elInput.click( () => {
  70316. const classifications = this.viewer.classifications;
  70317. for(let key of Object.keys(classifications)){
  70318. let value = classifications[key];
  70319. this.viewer.setClassificationVisibility(key, !value.visible);
  70320. }
  70321. });
  70322. elClassificationList.append(element);
  70323. };
  70324. const populate = () => {
  70325. addToggleAllButton();
  70326. for (let classID in this.viewer.classifications) {
  70327. addClassificationItem(classID, this.viewer.classifications[classID].name);
  70328. }
  70329. addInvertButton();
  70330. };
  70331. populate();
  70332. this.viewer.addEventListener("classifications_changed", () => {
  70333. elClassificationList.empty();
  70334. populate();
  70335. });
  70336. this.viewer.addEventListener("classification_visibility_changed", () => {
  70337. { // set checked state of classification buttons
  70338. for(const classID of Object.keys(this.viewer.classifications)){
  70339. const classValue = this.viewer.classifications[classID];
  70340. let elItem = elClassificationList.find(`#chkClassification_${classID}`);
  70341. elItem.prop("checked", classValue.visible);
  70342. }
  70343. }
  70344. { // set checked state of toggle button based on state of all other buttons
  70345. let numVisible = 0;
  70346. let numItems = 0;
  70347. for(const key of Object.keys(this.viewer.classifications)){
  70348. if(this.viewer.classifications[key].visible){
  70349. numVisible++;
  70350. }
  70351. numItems++;
  70352. }
  70353. const allVisible = numVisible === numItems;
  70354. let elToggle = elClassificationList.find("#toggleClassificationFilters");
  70355. elToggle.prop("checked", allVisible);
  70356. }
  70357. });
  70358. }
  70359. initAccordion(){
  70360. $('.accordion > h3').each(function(){
  70361. let header = $(this);
  70362. let content = $(this).next();
  70363. //header.addClass('accordion-header ui-widget');
  70364. //content.addClass('accordion-content ui-widget');
  70365. content.hide();
  70366. header.click(() => {
  70367. content.slideToggle();
  70368. });
  70369. });
  70370. let languages = [
  70371. ["EN", "en"],
  70372. ["FR", "fr"],
  70373. ["DE", "de"],
  70374. ["JP", "jp"],
  70375. ["ES", "es"],
  70376. ["SE", "se"],
  70377. ["ZH", "zh"]
  70378. ];
  70379. let elLanguages = $('#potree_languages');
  70380. for(let i = 0; i < languages.length; i++){
  70381. let [key, value] = languages[i];
  70382. let element = $(`<a>${key}</a>`);
  70383. element.click(() => this.viewer.setLanguage(value));
  70384. if(i === 0){
  70385. element.css("margin-left", "30px");
  70386. }
  70387. elLanguages.append(element);
  70388. if(i < languages.length - 1){
  70389. elLanguages.append($(document.createTextNode(' - ')));
  70390. }
  70391. }
  70392. // to close all, call
  70393. // $(".accordion > div").hide()
  70394. // to open the, for example, tool menu, call:
  70395. // $("#menu_tools").next().show()
  70396. }
  70397. initAppearance(){
  70398. const sldPointBudget = this.dom.find('#sldPointBudget');
  70399. sldPointBudget.slider({
  70400. value: this.viewer.getPointBudget(),
  70401. min: 100 * 1000,
  70402. max: 10 * 1000 * 1000,
  70403. step: 1000,
  70404. slide: (event, ui) => { this.viewer.setPointBudget(ui.value); }
  70405. });
  70406. this.dom.find('#sldFOV').slider({
  70407. value: this.viewer.getFOV(),
  70408. min: 20,
  70409. max: 100,
  70410. step: 1,
  70411. slide: (event, ui) => { this.viewer.setFOV(ui.value); }
  70412. });
  70413. $('#sldEDLRadius').slider({
  70414. value: this.viewer.getEDLRadius(),
  70415. min: 1,
  70416. max: 4,
  70417. step: 0.01,
  70418. slide: (event, ui) => { this.viewer.setEDLRadius(ui.value); }
  70419. });
  70420. $('#sldEDLStrength').slider({
  70421. value: this.viewer.getEDLStrength(),
  70422. min: 0,
  70423. max: 5,
  70424. step: 0.01,
  70425. slide: (event, ui) => { this.viewer.setEDLStrength(ui.value); }
  70426. });
  70427. $('#sldEDLOpacity').slider({
  70428. value: this.viewer.getEDLOpacity(),
  70429. min: 0,
  70430. max: 1,
  70431. step: 0.01,
  70432. slide: (event, ui) => { this.viewer.setEDLOpacity(ui.value); }
  70433. });
  70434. this.viewer.addEventListener('point_budget_changed', (event) => {
  70435. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  70436. sldPointBudget.slider({value: this.viewer.getPointBudget()});
  70437. });
  70438. this.viewer.addEventListener('fov_changed', (event) => {
  70439. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  70440. $('#sldFOV').slider({value: this.viewer.getFOV()});
  70441. });
  70442. this.viewer.addEventListener('use_edl_changed', (event) => {
  70443. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  70444. });
  70445. this.viewer.addEventListener('edl_radius_changed', (event) => {
  70446. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  70447. $('#sldEDLRadius').slider({value: this.viewer.getEDLRadius()});
  70448. });
  70449. this.viewer.addEventListener('edl_strength_changed', (event) => {
  70450. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  70451. $('#sldEDLStrength').slider({value: this.viewer.getEDLStrength()});
  70452. });
  70453. this.viewer.addEventListener('background_changed', (event) => {
  70454. $("input[name=background][value='" + this.viewer.getBackground() + "']").prop('checked', true);
  70455. });
  70456. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  70457. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  70458. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  70459. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  70460. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  70461. {
  70462. let elBackground = $(`#background_options`);
  70463. elBackground.selectgroup();
  70464. elBackground.find("input").click( (e) => {
  70465. this.viewer.setBackground(e.target.value);
  70466. });
  70467. let currentBackground = this.viewer.getBackground();
  70468. try{
  70469. $(`input[name=background_options][value=${currentBackground}]`).trigger("click");
  70470. }catch(e){}
  70471. }
  70472. $('#chkEDLEnabled').click( () => {
  70473. this.viewer.setEDLEnabled($('#chkEDLEnabled').prop("checked"));
  70474. });
  70475. }
  70476. initNavigation(){
  70477. let elNavigation = $('#navigation');
  70478. let sldMoveSpeed = $('#sldMoveSpeed');
  70479. let lblMoveSpeed = $('#lblMoveSpeed');
  70480. elNavigation.append(this.createToolIcon(
  70481. Potree.resourcePath + '/icons/earth_controls_1.png',
  70482. '[title]tt.earth_control',
  70483. () => { this.viewer.setControls(this.viewer.earthControls); }
  70484. ));
  70485. elNavigation.append(this.createToolIcon(
  70486. Potree.resourcePath + '/icons/fps_controls.svg',
  70487. '[title]tt.flight_control',
  70488. () => {
  70489. this.viewer.setControls(this.viewer.fpControls);
  70490. this.viewer.fpControls.lockElevation = false;
  70491. }
  70492. ));
  70493. elNavigation.append(this.createToolIcon(
  70494. Potree.resourcePath + '/icons/helicopter_controls.svg',
  70495. '[title]tt.heli_control',
  70496. () => {
  70497. this.viewer.setControls(this.viewer.fpControls);
  70498. this.viewer.fpControls.lockElevation = true;
  70499. }
  70500. ));
  70501. elNavigation.append(this.createToolIcon(
  70502. Potree.resourcePath + '/icons/orbit_controls.svg',
  70503. '[title]tt.orbit_control',
  70504. () => { this.viewer.setControls(this.viewer.orbitControls); }
  70505. ));
  70506. elNavigation.append(this.createToolIcon(
  70507. Potree.resourcePath + '/icons/focus.svg',
  70508. '[title]tt.focus_control',
  70509. () => { this.viewer.fitToScreen(); }
  70510. ));
  70511. elNavigation.append(this.createToolIcon(
  70512. Potree.resourcePath + "/icons/navigation_cube.svg",
  70513. "[title]tt.navigation_cube_control",
  70514. () => {this.viewer.toggleNavigationCube();}
  70515. ));
  70516. elNavigation.append(this.createToolIcon(
  70517. Potree.resourcePath + "/images/compas.svg",
  70518. "[title]tt.compass",
  70519. () => {
  70520. const visible = !this.viewer.compass.isVisible();
  70521. this.viewer.compass.setVisible(visible);
  70522. }
  70523. ));
  70524. elNavigation.append(this.createToolIcon(
  70525. Potree.resourcePath + "/icons/camera_animation.svg",
  70526. "[title]tt.camera_animation",
  70527. () => {
  70528. const animation = CameraAnimation.defaultFromView(this.viewer);
  70529. viewer.scene.addCameraAnimation(animation);
  70530. }
  70531. ));
  70532. elNavigation.append("<br>");
  70533. elNavigation.append(this.createToolIcon(
  70534. Potree.resourcePath + "/icons/left.svg",
  70535. "[title]tt.left_view_control",
  70536. () => {this.viewer.setLeftView();}
  70537. ));
  70538. elNavigation.append(this.createToolIcon(
  70539. Potree.resourcePath + "/icons/right.svg",
  70540. "[title]tt.right_view_control",
  70541. () => {this.viewer.setRightView();}
  70542. ));
  70543. elNavigation.append(this.createToolIcon(
  70544. Potree.resourcePath + "/icons/front.svg",
  70545. "[title]tt.front_view_control",
  70546. () => {this.viewer.setFrontView();}
  70547. ));
  70548. elNavigation.append(this.createToolIcon(
  70549. Potree.resourcePath + "/icons/back.svg",
  70550. "[title]tt.back_view_control",
  70551. () => {this.viewer.setBackView();}
  70552. ));
  70553. elNavigation.append(this.createToolIcon(
  70554. Potree.resourcePath + "/icons/top.svg",
  70555. "[title]tt.top_view_control",
  70556. () => {this.viewer.setTopView();}
  70557. ));
  70558. elNavigation.append(this.createToolIcon(
  70559. Potree.resourcePath + "/icons/bottom.svg",
  70560. "[title]tt.bottom_view_control",
  70561. () => {this.viewer.setBottomView();}
  70562. ));
  70563. let elCameraProjection = $(`
  70564. <selectgroup id="camera_projection_options">
  70565. <option id="camera_projection_options_perspective" value="PERSPECTIVE">Perspective</option>
  70566. <option id="camera_projection_options_orthigraphic" value="ORTHOGRAPHIC">Orthographic</option>
  70567. </selectgroup>
  70568. `);
  70569. elNavigation.append(elCameraProjection);
  70570. elCameraProjection.selectgroup({title: "Camera Projection"});
  70571. elCameraProjection.find("input").click( (e) => {
  70572. this.viewer.setCameraMode(CameraMode[e.target.value]);
  70573. });
  70574. let cameraMode = Object.keys(CameraMode)
  70575. .filter(key => CameraMode[key] === this.viewer.scene.cameraMode);
  70576. elCameraProjection.find(`input[value=${cameraMode}]`).trigger("click");
  70577. let speedRange = new Vector2$1(1, 10 * 1000);
  70578. let toLinearSpeed = (value) => {
  70579. return Math.pow(value, 4) * speedRange.y + speedRange.x;
  70580. };
  70581. let toExpSpeed = (value) => {
  70582. return Math.pow((value - speedRange.x) / speedRange.y, 1 / 4);
  70583. };
  70584. sldMoveSpeed.slider({
  70585. value: toExpSpeed(this.viewer.getMoveSpeed()),
  70586. min: 0,
  70587. max: 1,
  70588. step: 0.01,
  70589. slide: (event, ui) => { this.viewer.setMoveSpeed(toLinearSpeed(ui.value)); }
  70590. });
  70591. this.viewer.addEventListener('move_speed_changed', (event) => {
  70592. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  70593. sldMoveSpeed.slider({value: toExpSpeed(this.viewer.getMoveSpeed())});
  70594. });
  70595. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  70596. }
  70597. initSettings(){
  70598. {
  70599. $('#sldMinNodeSize').slider({
  70600. value: this.viewer.getMinNodeSize(),
  70601. min: 0,
  70602. max: 1000,
  70603. step: 0.01,
  70604. slide: (event, ui) => { this.viewer.setMinNodeSize(ui.value); }
  70605. });
  70606. this.viewer.addEventListener('minnodesize_changed', (event) => {
  70607. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  70608. $('#sldMinNodeSize').slider({value: this.viewer.getMinNodeSize()});
  70609. });
  70610. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  70611. }
  70612. {
  70613. let elSplatQuality = $("#splat_quality_options");
  70614. elSplatQuality.selectgroup({title: "Splat Quality"});
  70615. elSplatQuality.find("input").click( (e) => {
  70616. if(e.target.value === "standard"){
  70617. this.viewer.useHQ = false;
  70618. }else if(e.target.value === "hq"){
  70619. this.viewer.useHQ = true;
  70620. }
  70621. });
  70622. let currentQuality = this.viewer.useHQ ? "hq" : "standard";
  70623. elSplatQuality.find(`input[value=${currentQuality}]`).trigger("click");
  70624. }
  70625. $('#show_bounding_box').click(() => {
  70626. this.viewer.setShowBoundingBox($('#show_bounding_box').prop("checked"));
  70627. });
  70628. $('#set_freeze').click(() => {
  70629. this.viewer.setFreeze($('#set_freeze').prop("checked"));
  70630. });
  70631. }
  70632. }
  70633. class AnnotationTool extends EventDispatcher{
  70634. constructor (viewer) {
  70635. super();
  70636. this.viewer = viewer;
  70637. this.renderer = viewer.renderer;
  70638. this.sg = new SphereGeometry(0.1);
  70639. this.sm = new MeshNormalMaterial();
  70640. this.s = new Mesh(this.sg, this.sm);
  70641. }
  70642. startInsertion (args = {}) {
  70643. let domElement = this.viewer.renderer.domElement;
  70644. let annotation = new Annotation({
  70645. position: [589748.270, 231444.540, 753.675],
  70646. title: "Annotation Title",
  70647. description: `Annotation Description`,
  70648. radius: 1,//add
  70649. cameraPosition: [589748.270, 231444.540, 753.675],//add
  70650. });
  70651. this.dispatchEvent({type: 'start_inserting_annotation', annotation: annotation});
  70652. const annotations = this.viewer.scene.annotations;
  70653. annotations.add(annotation);
  70654. let callbacks = {
  70655. cancel: null,
  70656. finish: null,
  70657. };
  70658. let insertionCallback = (e) => {
  70659. if (e.button === MOUSE.LEFT) {
  70660. callbacks.finish();
  70661. } else if (e.button === MOUSE.RIGHT) {
  70662. callbacks.cancel();
  70663. }
  70664. };
  70665. callbacks.cancel = e => {
  70666. annotations.remove(annotation);
  70667. domElement.removeEventListener('mouseup', insertionCallback, true);
  70668. };
  70669. callbacks.finish = e => {
  70670. domElement.removeEventListener('mouseup', insertionCallback, true);
  70671. };
  70672. domElement.addEventListener('mouseup', insertionCallback, true);
  70673. let drag = (e) => {
  70674. let camera = e.viewer.scene.getActiveCamera();
  70675. /* let I = Utils.getMousePointCloudIntersection(
  70676. e.drag.end,
  70677. camera,
  70678. e.viewer,
  70679. e.viewer.scene.pointclouds,
  70680. {pickClipped: true}); */
  70681. let I = e.viewer.inputHandler.intersectPoint;
  70682. if (I) {
  70683. this.s.position.copy(I.location);
  70684. annotation.position.copy(I.location);
  70685. annotation.cameraTarget.copy(I.location);//add
  70686. annotation.cameraPosition.copy(camera.position);//add
  70687. }
  70688. };
  70689. let drop = (e) => {
  70690. viewer.scene.scene.remove(this.s);
  70691. this.s.removeEventListener("drag", drag);
  70692. this.s.removeEventListener("drop", drop);
  70693. };
  70694. this.s.addEventListener('drag', drag);
  70695. this.s.addEventListener('drop', drop);
  70696. this.viewer.scene.scene.add(this.s);
  70697. this.viewer.inputHandler.startDragging(this.s);
  70698. return annotation;
  70699. }
  70700. update(){
  70701. // let camera = this.viewer.scene.getActiveCamera();
  70702. // let domElement = this.renderer.domElement;
  70703. // let measurements = this.viewer.scene.measurements;
  70704. // const renderAreaSize = this.renderer.getSize(new THREE.Vector2());
  70705. // let clientWidth = renderAreaSize.width;
  70706. // let clientHeight = renderAreaSize.height;
  70707. }
  70708. render(){
  70709. //this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  70710. }
  70711. };
  70712. const renderOrders = {
  70713. line: 0 ,
  70714. spot: 15, //高过模型
  70715. };
  70716. const planeGeo$3 = new PlaneGeometry(1,1);
  70717. let texLoader$5 = new TextureLoader();
  70718. let lineMat = new LineBasicMaterial({
  70719. color: '#ffffff',
  70720. });
  70721. let spotMat;
  70722. const defaultLineLength = 0.6;
  70723. const defaultSpotScale = 0.4;
  70724. class Tag extends Object3D{
  70725. constructor(o){
  70726. super();
  70727. this.lineLength = o.lineLength != void 0 ? o.lineLength : defaultLineLength;
  70728. this.position.copy(o.position);
  70729. this.normal = o.normal != void 0 ? o.normal : new Vector3(0,0,-1);
  70730. this.root = o.root;
  70731. //this.matrixAutoUpdate = false
  70732. this.build();
  70733. /* this.spot.addEventListener('mouseover',()=>{
  70734. }) */
  70735. }
  70736. build(){
  70737. if(!spotMat){
  70738. spotMat = new MeshBasicMaterial({
  70739. transparent:true,
  70740. map: texLoader$5.load(Potree.resourcePath+'/textures/spot_default.png' ),
  70741. });
  70742. }
  70743. let endPos = this.normal.clone().multiplyScalar(this.lineLength);
  70744. this.line = LineDraw.createLine([
  70745. new Vector3(0,0,0),
  70746. endPos
  70747. ], {mat:lineMat});
  70748. let group = new Object3D();
  70749. this.spot = new Mesh(planeGeo$3, spotMat);
  70750. this.spot.scale.set(defaultSpotScale,defaultSpotScale,defaultSpotScale);
  70751. this.titleLabel = new TextSprite({root: group, text:'1', sizeInfo:{width2d:200},
  70752. textColor:{r:255,g:255,b:255,a:1.0},
  70753. backgroundColor:{r:0,g:0,b:0,a:0.8},
  70754. borderRadius: 6,
  70755. fontsize:13, fontWeight:'',//thick
  70756. renderOrder : renderOrders.spot, pickOrder:renderOrders.spot,
  70757. }); //更新sprite时,实际更新的是root: spot的矩阵
  70758. this.spot.renderOrder = renderOrders.spot;
  70759. /* const mainLabelProp = {
  70760. backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  70761. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  70762. fontsize:16,
  70763. useDepth : true ,
  70764. renderOrder : 5, pickOrder:5,
  70765. } */
  70766. this.titleLabel.position.set(0,0.4,0);
  70767. this.titleLabel.sprite.material.depthTest = this.titleLabel.sprite.material.depthWrite = true;
  70768. group.position.copy(endPos);
  70769. group.add(this.spot);
  70770. group.add(this.titleLabel);
  70771. this.add(group);
  70772. this.add(this.line);
  70773. viewer.scene.tags.add(this);
  70774. }
  70775. changeTitle(title){
  70776. this.titleLabel.changeText(title);
  70777. }
  70778. updateMatrixWorld(force){ //重写,只为了将root当做parent
  70779. this.updateMatrix();
  70780. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  70781. const children = this.children;
  70782. for ( let i = 0, l = children.length; i < l; i ++ ) {
  70783. children[ i ].updateMatrixWorld( force );
  70784. }
  70785. }
  70786. updateWorldMatrix( updateParents, updateChildren ) {//重写,只为了将root当做parent
  70787. if ( updateParents === true && this.root !== null ) {
  70788. this.root.updateWorldMatrix( true, false );
  70789. }
  70790. if ( this.matrixAutoUpdate ) this.updateMatrix();
  70791. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  70792. if ( updateChildren === true ) {
  70793. const children = this.children;
  70794. for ( let i = 0, l = children.length; i < l; i ++ ) {
  70795. children[ i ].updateWorldMatrix( false, true );
  70796. }
  70797. }
  70798. }
  70799. dispose(){
  70800. this.parent.remove(this);
  70801. this.titleLabel.dispatchEvent({type:'dispose'});
  70802. }
  70803. }
  70804. class TagTool extends EventDispatcher{
  70805. constructor (viewer) {
  70806. super();
  70807. this.viewer = viewer;
  70808. this.viewer.addEventListener('start_inserting_tag', e => {
  70809. this.viewer.dispatchEvent({
  70810. type: 'cancel_insertions'
  70811. });
  70812. });
  70813. }
  70814. createTagFromData(data){
  70815. let tag = new Tag({
  70816. title: data.title, position: data.position, normal: data.normal,
  70817. root: data.root //e.intersect.pointcloud || e.intersect.object
  70818. });
  70819. return tag
  70820. }
  70821. startInsertion (args = {}, callback, cancelFun) {
  70822. let deferred = $.Deferred();
  70823. this.viewer.dispatchEvent({
  70824. type: 'start_inserting_tag'
  70825. });
  70826. this.adding = true;
  70827. let cancel = ()=>{
  70828. end();
  70829. };
  70830. let end = ()=>{
  70831. this.adding = false;
  70832. viewer.dispatchEvent({type:"endTagMove"});
  70833. this.viewer.removeEventListener('global_click', click);
  70834. };
  70835. let click = (e)=>{
  70836. var worldPos = e.intersect && (/* e.intersect.orthoIntersect || */e.intersect.location);
  70837. if(!worldPos){
  70838. return
  70839. }
  70840. let localPos = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:e.intersect.pointcloud, object:e.intersect.object, position:worldPos });
  70841. let tag = new Tag({
  70842. title: '1', position: localPos, normal:e.intersect.normal,
  70843. root: e.intersect.pointcloud || e.intersect.object
  70844. });
  70845. //pointcloud里加一个normal 的非float32
  70846. end();
  70847. e.consume && e.consume();
  70848. deferred.resolve(tag);
  70849. return {stopContinue:true}
  70850. };
  70851. this.viewer.addEventListener('global_click', click, 10);
  70852. return deferred.promise()
  70853. }
  70854. }
  70855. class NavigationCube extends Object3D {
  70856. constructor(viewer){
  70857. super();
  70858. this.viewer = viewer;
  70859. let createPlaneMaterial = (img) => {
  70860. let material = new MeshBasicMaterial( {
  70861. depthTest: true,
  70862. depthWrite: true,
  70863. side: DoubleSide
  70864. });
  70865. new TextureLoader().load(
  70866. exports.resourcePath + '/textures/navigation/' + img,
  70867. function(texture) {
  70868. texture.anisotropy = viewer.renderer.capabilities.getMaxAnisotropy();
  70869. material.map = texture;
  70870. material.needsUpdate = true;
  70871. });
  70872. return material;
  70873. };
  70874. let planeGeometry = new PlaneGeometry(1, 1);
  70875. this.front = new Mesh(planeGeometry, createPlaneMaterial('F.png'));
  70876. this.front.position.y = -0.5;
  70877. this.front.rotation.x = Math.PI / 2.0;
  70878. this.front.updateMatrixWorld();
  70879. this.front.name = "F";
  70880. this.add(this.front);
  70881. this.back = new Mesh(planeGeometry, createPlaneMaterial('B.png'));
  70882. this.back.position.y = 0.5;
  70883. this.back.rotation.x = Math.PI / 2.0;
  70884. this.back.updateMatrixWorld();
  70885. this.back.name = "B";
  70886. this.add(this.back);
  70887. this.left = new Mesh(planeGeometry, createPlaneMaterial('L.png'));
  70888. this.left.position.x = -0.5;
  70889. this.left.rotation.y = Math.PI / 2.0;
  70890. this.left.updateMatrixWorld();
  70891. this.left.name = "L";
  70892. this.add(this.left);
  70893. this.right = new Mesh(planeGeometry, createPlaneMaterial('R.png'));
  70894. this.right.position.x = 0.5;
  70895. this.right.rotation.y = Math.PI / 2.0;
  70896. this.right.updateMatrixWorld();
  70897. this.right.name = "R";
  70898. this.add(this.right);
  70899. this.bottom = new Mesh(planeGeometry, createPlaneMaterial('D.png'));
  70900. this.bottom.position.z = -0.5;
  70901. this.bottom.updateMatrixWorld();
  70902. this.bottom.name = "D";
  70903. this.add(this.bottom);
  70904. this.top = new Mesh(planeGeometry, createPlaneMaterial('U.png'));
  70905. this.top.position.z = 0.5;
  70906. this.top.updateMatrixWorld();
  70907. this.top.name = "U";
  70908. this.add(this.top);
  70909. this.width = 150; // in px
  70910. this.camera = new OrthographicCamera(-1, 1, 1, -1, -1, 1);
  70911. this.camera.position.copy(new Vector3(0, 0, 0));
  70912. this.camera.lookAt(new Vector3(0, 1, 0));
  70913. this.camera.updateMatrixWorld();
  70914. this.camera.rotation.order = "ZXY";
  70915. let onMouseDown = (event) => {
  70916. if (!this.visible) {
  70917. return;
  70918. }
  70919. this.pickedFace = null;
  70920. let mouse = new Vector2$1();
  70921. mouse.x = event.clientX - (window.innerWidth - this.width);
  70922. mouse.y = event.clientY;
  70923. if(mouse.x < 0 || mouse.y > this.width) return;
  70924. mouse.x = (mouse.x / this.width) * 2 - 1;
  70925. mouse.y = -(mouse.y / this.width) * 2 + 1;
  70926. let raycaster = new Raycaster();
  70927. raycaster.setFromCamera(mouse, this.camera);
  70928. raycaster.ray.origin.sub(this.camera.getWorldDirection(new Vector3()));
  70929. let intersects = raycaster.intersectObjects(this.children);
  70930. let minDistance = 1000;
  70931. for (let i = 0; i < intersects.length; i++) {
  70932. if(intersects[i].distance < minDistance) {
  70933. this.pickedFace = intersects[i].object.name;
  70934. minDistance = intersects[i].distance;
  70935. }
  70936. }
  70937. if(this.pickedFace) {
  70938. this.viewer.setView(this.pickedFace);
  70939. }
  70940. };
  70941. this.viewer.renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  70942. }
  70943. update(rotation) {
  70944. this.camera.rotation.copy(rotation);
  70945. this.camera.updateMatrixWorld();
  70946. }
  70947. }
  70948. /**
  70949. * @author mschuetz / http://mschuetz.at
  70950. *
  70951. * adapted from THREE.OrbitControls by
  70952. *
  70953. * @author qiao / https://github.com/qiao
  70954. * @author mrdoob / http://mrdoob.com
  70955. * @author alteredq / http://alteredqualia.com/
  70956. * @author WestLangley / http://github.com/WestLangley
  70957. * @author erich666 / http://erichaines.com
  70958. *
  70959. *
  70960. *
  70961. */
  70962. let minRadius = 2;
  70963. class OrbitControls extends EventDispatcher{
  70964. constructor(viewer){
  70965. super();
  70966. this.viewer = viewer;
  70967. this.renderer = viewer.renderer;
  70968. this.scene = null;
  70969. this.sceneControls = new Scene();
  70970. this.rotationSpeed = 3; //旋转速度
  70971. this.fadeFactor = 100;
  70972. this.yawDelta = 0;
  70973. this.pitchDelta = 0;
  70974. this.panDelta = new Vector2$1(0, 0);
  70975. this.radiusDelta = 0;
  70976. this.doubleClockZoomEnabled = true;
  70977. this.tweens = [];
  70978. this.dollyStart = new Vector2$1;
  70979. this.dollyEnd = new Vector2$1;
  70980. this.keys = {
  70981. FORWARD: ['W'.charCodeAt(0), 38],
  70982. BACKWARD: ['S'.charCodeAt(0), 40],
  70983. LEFT: ['A'.charCodeAt(0), 37],
  70984. RIGHT: ['D'.charCodeAt(0), 39],
  70985. UP: ['Q'.charCodeAt(0)],
  70986. DOWN: ['E'.charCodeAt(0)],
  70987. };
  70988. let drag = (e) => {
  70989. if(!this.enabled)return
  70990. let viewport = e.dragViewport;
  70991. if(!viewport || viewport.camera.type == "OrthographicCamera" )return
  70992. //let camera = viewport.camera
  70993. if (e.drag.object !== null) {
  70994. return;
  70995. }
  70996. let mode;
  70997. if(e.isTouch){
  70998. if(e.touches.length == 1){
  70999. mode = 'rotate';
  71000. }else {
  71001. mode = 'scale-pan';
  71002. }
  71003. }else {
  71004. mode = e.buttons === Buttons.LEFT ? 'rotate' : 'pan';
  71005. }
  71006. if (e.drag.startHandled === undefined) {
  71007. e.drag.startHandled = true;
  71008. this.dispatchEvent({type: 'start'});
  71009. }
  71010. let ndrag = e.drag.pointerDelta.clone();//.add(new THREE.Vector2(1,1)).multiplyScalar(0.5)
  71011. ndrag.y *= -1;
  71012. if (mode == 'rotate') {
  71013. this.yawDelta += ndrag.x * this.rotationSpeed;
  71014. this.pitchDelta += ndrag.y * this.rotationSpeed;
  71015. } else if(mode == 'pan'){
  71016. this.panDelta.x += ndrag.x;
  71017. this.panDelta.y += ndrag.y;
  71018. }else if(mode == 'scale-pan'){ //add
  71019. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  71020. var scale = this.dollyEnd.length() / this.dollyStart.length();
  71021. this.dollyStart.copy(this.dollyEnd);
  71022. this.radiusDelta = (1-scale) * this.scene.view.radius;
  71023. //------------------------
  71024. //平移
  71025. let pointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  71026. let delta = new Vector2$1().subVectors(pointer, this.lastScalePointer);
  71027. delta.y *= -1;
  71028. this.panDelta.add(delta);
  71029. this.lastScalePointer = pointer.clone();
  71030. //console.log('scale ',scale, this.radiusDelta)
  71031. }
  71032. this.stopTweens();
  71033. };
  71034. let drop = e => {
  71035. if(!this.enabled)return
  71036. this.dispatchEvent({type: 'end'});
  71037. };
  71038. let scroll = (e) => {
  71039. if(!this.enabled)return
  71040. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  71041. if(resolvedRadius < 0.1 && e.delta>0)return; //防止缩放太小,导致很慢
  71042. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  71043. this.stopTweens();
  71044. };
  71045. let dblclick = (e) => {
  71046. if(!this.enabled)return
  71047. if(this.doubleClockZoomEnabled){
  71048. this.zoomToLocation(e.mouse);
  71049. }
  71050. };
  71051. let previousTouch = null;
  71052. let touchStart = e => {
  71053. previousTouch = e;
  71054. };
  71055. let touchEnd = e => {
  71056. previousTouch = e;
  71057. };
  71058. let touchMove = e => {
  71059. if(!this.enabled)return
  71060. if (e.touches.length === 2 && previousTouch.touches.length === 2){
  71061. let prev = previousTouch;
  71062. let curr = e;
  71063. let prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  71064. let prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  71065. let prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  71066. let currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  71067. let currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  71068. let currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  71069. let delta = currDist / prevDist;
  71070. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  71071. let newRadius = resolvedRadius / delta;
  71072. this.radiusDelta = newRadius - resolvedRadius;
  71073. this.stopTweens();
  71074. }else if(e.touches.length === 3 && previousTouch.touches.length === 3){
  71075. let prev = previousTouch;
  71076. let curr = e;
  71077. let prevMeanX = (prev.touches[0].pageX + prev.touches[1].pageX + prev.touches[2].pageX) / 3;
  71078. let prevMeanY = (prev.touches[0].pageY + prev.touches[1].pageY + prev.touches[2].pageY) / 3;
  71079. let currMeanX = (curr.touches[0].pageX + curr.touches[1].pageX + curr.touches[2].pageX) / 3;
  71080. let currMeanY = (curr.touches[0].pageY + curr.touches[1].pageY + curr.touches[2].pageY) / 3;
  71081. let delta = {
  71082. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  71083. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  71084. };
  71085. this.panDelta.x += delta.x;
  71086. this.panDelta.y += delta.y;
  71087. this.stopTweens();
  71088. }
  71089. previousTouch = e;
  71090. };
  71091. this.addEventListener('touchstart', touchStart);
  71092. this.addEventListener('touchend', touchEnd);
  71093. this.addEventListener('touchmove', touchMove);
  71094. this.viewer.addEventListener('global_drag', drag);
  71095. this.viewer.addEventListener('global_drop', drop);
  71096. this.viewer.addEventListener('global_mousewheel', scroll);
  71097. this.viewer.addEventListener('global_dblclick', dblclick);
  71098. this.viewer.addEventListener('global_touchmove', (e)=>{
  71099. if(e.touches.length>1){//单指的就触发上一句
  71100. //console.log('global_touchmove' )
  71101. drag(e);
  71102. }
  71103. });
  71104. let prepareScale = (e)=>{//触屏的scale
  71105. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  71106. this.lastScalePointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  71107. };
  71108. this.viewer.addEventListener('global_touchstart', (e)=>{
  71109. if(this.enabled && e.touches.length==2){//只监听开头两个指头
  71110. prepareScale(e);
  71111. }
  71112. });
  71113. /* this.viewer.addEventListener('global_touchend', (e)=>{
  71114. if(!this.enabled)return
  71115. if(e.touches.length==1){//停止scale,开始rotate
  71116. prepareRotate(e)
  71117. //this.pointerDragStart = null
  71118. //console.log('只剩一个', e.pointer.toArray())
  71119. }
  71120. }) */
  71121. this.viewer.addEventListener('focusOnObject',(o)=>{
  71122. if(o.position && o.CamTarget){
  71123. let distance = o.position.distanceTo(o.CamTarget);
  71124. if(distance < minRadius) minRadius = distance * 0.5; //融合页面当focus一个很小的物体时,需要将minRadius也调小
  71125. }
  71126. });
  71127. }
  71128. setScene (scene) {
  71129. this.scene = scene;
  71130. }
  71131. setEnable(enabled){
  71132. this.enabled = enabled;
  71133. }
  71134. stop(){
  71135. this.yawDelta = 0;
  71136. this.pitchDelta = 0;
  71137. this.radiusDelta = 0;
  71138. this.panDelta.set(0, 0);
  71139. }
  71140. /* zoomToLocation(mouse){
  71141. if(!this.enabled)return
  71142. let camera = this.scene.getActiveCamera();
  71143. let I = Utils.getMousePointCloudIntersection(
  71144. null, mouse, this.viewer.inputHandler.pointer,
  71145. camera,
  71146. this.viewer,
  71147. this.scene.pointclouds,
  71148. {pickClipped: true});
  71149. if (I === null) {
  71150. return;
  71151. }
  71152. let targetRadius = 0;
  71153. {
  71154. let minimumJumpDistance = 0.2;
  71155. let domElement = this.renderer.domElement;
  71156. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer , camera, domElement.clientWidth, domElement.clientHeight);
  71157. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  71158. let lastNode = nodes[nodes.length - 1];
  71159. let radius = lastNode.getBoundingSphere(new THREE.Sphere()).radius;
  71160. targetRadius = Math.min(this.scene.view.radius, radius);
  71161. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  71162. }
  71163. let d = this.scene.view.direction.multiplyScalar(-1);
  71164. let cameraTargetPosition = new THREE.Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  71165. // TODO Unused: let controlsTargetPosition = I.location;
  71166. let animationDuration = 600;
  71167. let easing = TWEEN.Easing.Quartic.Out;
  71168. { // animate
  71169. let value = {x: 0};
  71170. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  71171. tween.easing(easing);
  71172. this.tweens.push(tween);
  71173. let startPos = this.scene.view.position.clone();
  71174. let targetPos = cameraTargetPosition.clone();
  71175. let startRadius = this.scene.view.radius;
  71176. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  71177. tween.onUpdate(() => {
  71178. let t = value.x;
  71179. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  71180. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  71181. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  71182. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  71183. this.viewer.setMoveSpeed(this.scene.view.radius);
  71184. });
  71185. tween.onComplete(() => {
  71186. this.tweens = this.tweens.filter(e => e !== tween);
  71187. });
  71188. tween.start();
  71189. }
  71190. } */
  71191. zoomToLocation(mouse){
  71192. let I = viewer.inputHandler.intersect;
  71193. if(!I)return
  71194. let object = I.object || I.pointcloud;
  71195. I = I.location;
  71196. if(!I || !object)return;
  71197. let dis = this.scene.view.position.distanceTo(I);
  71198. let bound = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  71199. let size = bound.getSize(new Vector3);
  71200. let len = size.length();
  71201. let distance = MathUtils.clamp(dis, 0.1, Math.max(len * 0.1, 3) );
  71202. minRadius = distance;
  71203. viewer.focusOnObject({ position:I }, 'point', null, {distance});
  71204. }
  71205. stopTweens () {
  71206. this.tweens.forEach(e => e.stop());
  71207. this.tweens = [];
  71208. }
  71209. update (delta) {
  71210. if(!this.enabled)return
  71211. let view = this.scene.view;
  71212. { // accelerate while input is given
  71213. let ih = this.viewer.inputHandler;
  71214. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  71215. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  71216. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  71217. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  71218. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  71219. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  71220. let px = 0 , py = 0, pz = 0;
  71221. if(moveForward){
  71222. py = 1;
  71223. }else if(moveBackward){
  71224. py = -1;
  71225. }
  71226. if(moveLeft){
  71227. px = -1;
  71228. }else if(moveRight){
  71229. px = 1;
  71230. }
  71231. if(moveUp){
  71232. pz = 1;
  71233. }else if(moveDown){
  71234. pz = -1;
  71235. }
  71236. (px!=0 || py!=0 || pz!=0) && view.translate(px, py, pz, true);
  71237. }
  71238. { // apply rotation
  71239. let progression = Math.min(1, this.fadeFactor * delta);
  71240. let yaw = view.yaw;
  71241. let pitch = view.pitch;
  71242. let pivot = view.getPivot();
  71243. yaw -= progression * this.yawDelta;
  71244. pitch -= progression * this.pitchDelta;
  71245. view.yaw = yaw;
  71246. view.pitch = pitch;
  71247. let V = this.scene.view.direction.multiplyScalar(-view.radius);
  71248. let position = new Vector3().addVectors(pivot, V);
  71249. view.position.copy(position);
  71250. }
  71251. { // apply pan
  71252. /* let progression = Math.min(1, this.fadeFactor * delta);
  71253. let panDistance = progression * view.radius * 3; */
  71254. let camera = this.scene.getActiveCamera();
  71255. let panDistance = 2 * view.radius * Math.tan(MathUtils.degToRad(camera.fov / 2));//参照4dkk。 平移target(也就是平移镜头位置),但还是难以保证跟手(navvis也不一定跟手,但是很奇怪在居中时中心点居然是跟手的,可能计算方式不同)
  71256. //计算了下确实是这么算的。 平移pivot。
  71257. let px = -this.panDelta.x * panDistance;
  71258. let py = this.panDelta.y * panDistance;
  71259. view.pan(px, py);
  71260. }
  71261. { // apply zoom
  71262. let progression = 1;//Math.min(1, this.fadeFactor * delta);
  71263. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  71264. let radius = view.radius + progression * this.radiusDelta;
  71265. let V = view.direction.multiplyScalar(-radius);
  71266. let position = new Vector3().addVectors(view.getPivot(), V);
  71267. if(this.constantlyForward) {// 到达中心点后还能继续向前移动,也就是能推进中心点
  71268. if(radius < minRadius){
  71269. radius = minRadius;
  71270. }
  71271. }
  71272. view.radius = radius;
  71273. view.position.copy(position);
  71274. }
  71275. {
  71276. let speed = view.radius;
  71277. this.viewer.setMoveSpeed(speed);
  71278. }
  71279. { // decelerate over time
  71280. /* let progression = Math.min(1, this.fadeFactor * delta);
  71281. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  71282. this.yawDelta *= attenuation;
  71283. this.pitchDelta *= attenuation;
  71284. this.panDelta.multiplyScalar(attenuation);
  71285. // this.radiusDelta *= attenuation;
  71286. this.radiusDelta -= progression * this.radiusDelta; */
  71287. //取消衰减,直接stop
  71288. this.stop();
  71289. }
  71290. }
  71291. };
  71292. class EarthControls extends EventDispatcher {
  71293. constructor (viewer) {
  71294. super(viewer);
  71295. this.viewer = viewer;
  71296. this.renderer = viewer.renderer;
  71297. this.scene = null;
  71298. this.sceneControls = new Scene();
  71299. this.rotationSpeed = 10;
  71300. this.fadeFactor = 20;
  71301. this.wheelDelta = 0;
  71302. this.zoomDelta = new Vector3();
  71303. this.camStart = null;
  71304. this.tweens = [];
  71305. {
  71306. let sg = new SphereGeometry(1, 16, 16);
  71307. let sm = new MeshNormalMaterial();
  71308. this.pivotIndicator = new Mesh(sg, sm);
  71309. this.pivotIndicator.visible = false;
  71310. this.sceneControls.add(this.pivotIndicator);
  71311. }
  71312. let drag = (e) => {
  71313. if (e.drag.object !== null) {
  71314. return;
  71315. }
  71316. if (!this.pivot) {
  71317. return;
  71318. }
  71319. if (e.drag.startHandled === undefined) {
  71320. e.drag.startHandled = true;
  71321. this.dispatchEvent({type: 'start'});
  71322. }
  71323. let camStart = this.camStart;
  71324. let camera = this.scene.getActiveCamera();
  71325. let view = this.viewer.scene.view;
  71326. // let camera = this.viewer.scene.camera;
  71327. let Buttons = e.drag.end;
  71328. let domElement = this.viewer.renderer.domElement;
  71329. if (e.drag.Buttons === Buttons.LEFT) {
  71330. let ray = Utils.ButtonsToRay(this.viewer.inputHandler.pointer/* Buttons */, camera, domElement.clientWidth, domElement.clientHeight);
  71331. let plane = new Plane().setFromNormalAndCoplanarPoint(
  71332. new Vector3(0, 0, 1),
  71333. this.pivot);
  71334. let distanceToPlane = ray.distanceToPlane(plane);
  71335. if (distanceToPlane > 0) {
  71336. let I = new Vector3().addVectors(
  71337. camStart.position,
  71338. ray.direction.clone().multiplyScalar(distanceToPlane));
  71339. let movedBy = new Vector3().subVectors(
  71340. I, this.pivot);
  71341. let newCamPos = camStart.position.clone().sub(movedBy);
  71342. view.position.copy(newCamPos);
  71343. {
  71344. let distance = newCamPos.distanceTo(this.pivot);
  71345. view.radius = distance;
  71346. let speed = view.radius / 2.5;
  71347. this.viewer.setMoveSpeed(speed);
  71348. }
  71349. }
  71350. } else if (e.drag.Buttons === Buttons.RIGHT) {
  71351. let ndrag = {
  71352. x: e.drag.ButtonsDelta.x / this.renderer.domElement.clientWidth,
  71353. y: e.drag.ButtonsDelta.y / this.renderer.domElement.clientHeight
  71354. };
  71355. let yawDelta = -ndrag.x * this.rotationSpeed * 0.5;
  71356. let pitchDelta = -ndrag.y * this.rotationSpeed * 0.2;
  71357. let originalPitch = view.pitch;
  71358. let tmpView = view.clone();
  71359. tmpView.pitch = tmpView.pitch + pitchDelta;
  71360. pitchDelta = tmpView.pitch - originalPitch;
  71361. let pivotToCam = new Vector3().subVectors(view.position, this.pivot);
  71362. let pivotToCamTarget = new Vector3().subVectors(view.getPivot(), this.pivot);
  71363. let side = view.getSide();
  71364. pivotToCam.applyAxisAngle(side, pitchDelta);
  71365. pivotToCamTarget.applyAxisAngle(side, pitchDelta);
  71366. pivotToCam.applyAxisAngle(new Vector3(0, 0, 1), yawDelta);
  71367. pivotToCamTarget.applyAxisAngle(new Vector3(0, 0, 1), yawDelta);
  71368. let newCam = new Vector3().addVectors(this.pivot, pivotToCam);
  71369. // TODO: Unused: let newCamTarget = new THREE.Vector3().addVectors(this.pivot, pivotToCamTarget);
  71370. view.position.copy(newCam);
  71371. view.yaw += yawDelta;
  71372. view.pitch += pitchDelta;
  71373. }
  71374. };
  71375. let onButtonsDown = e => {
  71376. let I = Utils.getButtonsPointCloudIntersection(
  71377. e.Buttons,
  71378. this.scene.getActiveCamera(),
  71379. this.viewer,
  71380. this.scene.pointclouds,
  71381. {pickClipped: false});
  71382. if (I) {
  71383. this.pivot = I.location;
  71384. this.camStart = this.scene.getActiveCamera().clone();
  71385. this.pivotIndicator.visible = true;
  71386. this.pivotIndicator.position.copy(I.location);
  71387. }
  71388. };
  71389. let drop = e => {
  71390. this.dispatchEvent({type: 'end'});
  71391. };
  71392. let onButtonsUp = e => {
  71393. this.camStart = null;
  71394. this.pivot = null;
  71395. this.pivotIndicator.visible = false;
  71396. };
  71397. let scroll = (e) => {
  71398. this.wheelDelta += e.delta;
  71399. };
  71400. let dblclick = (e) => {
  71401. this.zoomToLocation(e.Buttons);
  71402. };
  71403. this.addEventListener('drag', drag);
  71404. this.addEventListener('drop', drop);
  71405. this.addEventListener('Buttonswheel', scroll);
  71406. this.addEventListener('Buttonsdown', onButtonsDown);
  71407. this.addEventListener('Buttonsup', onButtonsUp);
  71408. this.addEventListener('dblclick', dblclick);
  71409. }
  71410. setScene (scene) {
  71411. this.scene = scene;
  71412. }
  71413. stop(){
  71414. this.wheelDelta = 0;
  71415. this.zoomDelta.set(0, 0, 0);
  71416. }
  71417. zoomToLocation(Buttons){
  71418. let camera = this.scene.getActiveCamera();
  71419. let I = Utils.getButtonsPointCloudIntersection(
  71420. Buttons,
  71421. camera,
  71422. this.viewer,
  71423. this.scene.pointclouds);
  71424. if (I === null) {
  71425. return;
  71426. }
  71427. let targetRadius = 0;
  71428. {
  71429. let minimumJumpDistance = 0.2;
  71430. let domElement = this.renderer.domElement;
  71431. let ray = Utils.ButtonsToRay(this.viewer.inputHandler.pointer, camera, domElement.clientWidth, domElement.clientHeight);
  71432. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  71433. let lastNode = nodes[nodes.length - 1];
  71434. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  71435. targetRadius = Math.min(this.scene.view.radius, radius);
  71436. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  71437. }
  71438. let d = this.scene.view.direction.multiplyScalar(-1);
  71439. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  71440. // TODO Unused: let controlsTargetPosition = I.location;
  71441. let animationDuration = 600;
  71442. let easing = TWEEN.Easing.Quartic.Out;
  71443. { // animate
  71444. let value = {x: 0};
  71445. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  71446. tween.easing(easing);
  71447. this.tweens.push(tween);
  71448. let startPos = this.scene.view.position.clone();
  71449. let targetPos = cameraTargetPosition.clone();
  71450. let startRadius = this.scene.view.radius;
  71451. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  71452. tween.onUpdate(() => {
  71453. let t = value.x;
  71454. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  71455. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  71456. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  71457. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  71458. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  71459. });
  71460. tween.onComplete(() => {
  71461. this.tweens = this.tweens.filter(e => e !== tween);
  71462. });
  71463. tween.start();
  71464. }
  71465. }
  71466. update (delta) {
  71467. let view = this.scene.view;
  71468. let fade = Math.pow(0.5, this.fadeFactor * delta);
  71469. let progression = 1 - fade;
  71470. let camera = this.scene.getActiveCamera();
  71471. // compute zoom
  71472. if (this.wheelDelta !== 0) {
  71473. let I = Utils.getButtonsPointCloudIntersection(
  71474. this.viewer.inputHandler.Buttons,
  71475. this.scene.getActiveCamera(),
  71476. this.viewer,
  71477. this.scene.pointclouds);
  71478. if (I) {
  71479. let resolvedPos = new Vector3().addVectors(view.position, this.zoomDelta);
  71480. let distance = I.location.distanceTo(resolvedPos);
  71481. let jumpDistance = distance * 0.2 * this.wheelDelta;
  71482. let targetDir = new Vector3().subVectors(I.location, view.position);
  71483. targetDir.normalize();
  71484. resolvedPos.add(targetDir.multiplyScalar(jumpDistance));
  71485. this.zoomDelta.subVectors(resolvedPos, view.position);
  71486. {
  71487. let distance = resolvedPos.distanceTo(I.location);
  71488. view.radius = distance;
  71489. let speed = view.radius / 2.5;
  71490. this.viewer.setMoveSpeed(speed);
  71491. }
  71492. }
  71493. }
  71494. // apply zoom
  71495. if (this.zoomDelta.length() !== 0) {
  71496. let p = this.zoomDelta.clone().multiplyScalar(progression);
  71497. let newPos = new Vector3().addVectors(view.position, p);
  71498. view.position.copy(newPos);
  71499. }
  71500. if (this.pivotIndicator.visible) {
  71501. let distance = this.pivotIndicator.position.distanceTo(view.position);
  71502. let pixelwidth = this.renderer.domElement.clientwidth;
  71503. let pixelHeight = this.renderer.domElement.clientHeight;
  71504. let pr = Utils.projectedRadius(1, camera, distance, pixelwidth, pixelHeight);
  71505. let scale = (10 / pr);
  71506. this.pivotIndicator.scale.set(scale, scale, scale);
  71507. }
  71508. // decelerate over time
  71509. {
  71510. this.zoomDelta.multiplyScalar(fade);
  71511. this.wheelDelta = 0;
  71512. }
  71513. }
  71514. };
  71515. /**
  71516. * @author chrisl / Geodan
  71517. *
  71518. * adapted from Potree.FirstPersonControls by
  71519. *
  71520. * @author mschuetz / http://mschuetz.at
  71521. *
  71522. * and THREE.DeviceOrientationControls by
  71523. *
  71524. * @author richt / http://richt.me
  71525. * @author WestLangley / http://github.com/WestLangley
  71526. *
  71527. *
  71528. *
  71529. */
  71530. class DeviceOrientationControls extends EventDispatcher{
  71531. constructor(viewer){
  71532. super();
  71533. this.viewer = viewer;
  71534. this.renderer = viewer.renderer;
  71535. this.scene = null;
  71536. this.sceneControls = new Scene();
  71537. this.screenOrientation = window.orientation || 0;
  71538. let deviceOrientationChange = e => {
  71539. this.deviceOrientation = e;
  71540. };
  71541. let screenOrientationChange = e => {
  71542. this.screenOrientation = window.orientation || 0;
  71543. };
  71544. if ('ondeviceorientationabsolute' in window) {
  71545. window.addEventListener('deviceorientationabsolute', deviceOrientationChange);
  71546. } else if ('ondeviceorientation' in window) {
  71547. window.addEventListener('deviceorientation', deviceOrientationChange);
  71548. } else {
  71549. console.warn("No device orientation found.");
  71550. }
  71551. // window.addEventListener('deviceorientation', deviceOrientationChange);
  71552. window.addEventListener('orientationchange', screenOrientationChange);
  71553. }
  71554. setScene (scene) {
  71555. this.scene = scene;
  71556. }
  71557. update (delta) {
  71558. let computeQuaternion = function (alpha, beta, gamma, orient) {
  71559. let quaternion = new Quaternion();
  71560. let zee = new Vector3(0, 0, 1);
  71561. let euler = new Euler();
  71562. let q0 = new Quaternion();
  71563. euler.set(beta, gamma, alpha, 'ZXY');
  71564. quaternion.setFromEuler(euler);
  71565. quaternion.multiply(q0.setFromAxisAngle(zee, -orient));
  71566. return quaternion;
  71567. };
  71568. if (typeof this.deviceOrientation !== 'undefined') {
  71569. let alpha = this.deviceOrientation.alpha ? MathUtils.degToRad(this.deviceOrientation.alpha) : 0;
  71570. let beta = this.deviceOrientation.beta ? MathUtils.degToRad(this.deviceOrientation.beta) : 0;
  71571. let gamma = this.deviceOrientation.gamma ? MathUtils.degToRad(this.deviceOrientation.gamma) : 0;
  71572. let orient = this.screenOrientation ? MathUtils.degToRad(this.screenOrientation) : 0;
  71573. let quaternion = computeQuaternion(alpha, beta, gamma, orient);
  71574. viewer.scene.cameraP.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  71575. }
  71576. }
  71577. };
  71578. const _taskCache = new WeakMap();
  71579. class DRACOLoader extends Loader {
  71580. constructor( manager ) {
  71581. super( manager );
  71582. this.decoderPath = '';
  71583. this.decoderConfig = {};
  71584. this.decoderBinary = null;
  71585. this.decoderPending = null;
  71586. this.workerLimit = 4;
  71587. this.workerPool = [];
  71588. this.workerNextTaskID = 1;
  71589. this.workerSourceURL = '';
  71590. this.defaultAttributeIDs = {
  71591. position: 'POSITION',
  71592. normal: 'NORMAL',
  71593. color: 'COLOR',
  71594. uv: 'TEX_COORD'
  71595. };
  71596. this.defaultAttributeTypes = {
  71597. position: 'Float32Array',
  71598. normal: 'Float32Array',
  71599. color: 'Float32Array',
  71600. uv: 'Float32Array'
  71601. };
  71602. }
  71603. setDecoderPath( path ) {
  71604. this.decoderPath = path;
  71605. return this;
  71606. }
  71607. setDecoderConfig( config ) {
  71608. this.decoderConfig = config;
  71609. return this;
  71610. }
  71611. setWorkerLimit( workerLimit ) {
  71612. this.workerLimit = workerLimit;
  71613. return this;
  71614. }
  71615. load( url, onLoad, onProgress, onError ) {
  71616. const loader = new FileLoader( this.manager );
  71617. loader.setPath( this.path );
  71618. loader.setResponseType( 'arraybuffer' );
  71619. loader.setRequestHeader( this.requestHeader );
  71620. loader.setWithCredentials( this.withCredentials );
  71621. loader.load( url, ( buffer ) => {
  71622. const taskConfig = {
  71623. attributeIDs: this.defaultAttributeIDs,
  71624. attributeTypes: this.defaultAttributeTypes,
  71625. useUniqueIDs: false
  71626. };
  71627. this.decodeGeometry( buffer, taskConfig )
  71628. .then( onLoad )
  71629. .catch( onError );
  71630. }, onProgress, onError );
  71631. }
  71632. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  71633. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes ) {
  71634. const taskConfig = {
  71635. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  71636. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  71637. useUniqueIDs: !! attributeIDs
  71638. };
  71639. this.decodeGeometry( buffer, taskConfig ).then( callback );
  71640. }
  71641. decodeGeometry( buffer, taskConfig ) {
  71642. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  71643. // references (rather than names) to typed array constructors. These must be
  71644. // serialized before sending them to the worker.
  71645. for ( const attribute in taskConfig.attributeTypes ) {
  71646. const type = taskConfig.attributeTypes[ attribute ];
  71647. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  71648. taskConfig.attributeTypes[ attribute ] = type.name;
  71649. }
  71650. }
  71651. //
  71652. const taskKey = JSON.stringify( taskConfig );
  71653. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  71654. // again from this thread.
  71655. if ( _taskCache.has( buffer ) ) {
  71656. const cachedTask = _taskCache.get( buffer );
  71657. if ( cachedTask.key === taskKey ) {
  71658. return cachedTask.promise;
  71659. } else if ( buffer.byteLength === 0 ) {
  71660. // Technically, it would be possible to wait for the previous task to complete,
  71661. // transfer the buffer back, and decode again with the second configuration. That
  71662. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  71663. // different ways, so this is left unimplemented.
  71664. throw new Error(
  71665. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  71666. 'settings. Buffer has already been transferred.'
  71667. );
  71668. }
  71669. }
  71670. //
  71671. let worker;
  71672. const taskID = this.workerNextTaskID ++;
  71673. const taskCost = buffer.byteLength;
  71674. // Obtain a worker and assign a task, and construct a geometry instance
  71675. // when the task completes.
  71676. const geometryPending = this._getWorker( taskID, taskCost )
  71677. .then( ( _worker ) => {
  71678. worker = _worker;
  71679. return new Promise( ( resolve, reject ) => {
  71680. worker._callbacks[ taskID ] = { resolve, reject };
  71681. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  71682. // this.debug();
  71683. } );
  71684. } )
  71685. .then( ( message ) => this._createGeometry( message.geometry ) );
  71686. // Remove task from the task list.
  71687. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  71688. geometryPending
  71689. .catch( () => true )
  71690. .then( () => {
  71691. if ( worker && taskID ) {
  71692. this._releaseTask( worker, taskID );
  71693. // this.debug();
  71694. }
  71695. } );
  71696. // Cache the task result.
  71697. _taskCache.set( buffer, {
  71698. key: taskKey,
  71699. promise: geometryPending
  71700. } );
  71701. return geometryPending;
  71702. }
  71703. _createGeometry( geometryData ) {
  71704. const geometry = new BufferGeometry();
  71705. if ( geometryData.index ) {
  71706. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  71707. }
  71708. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  71709. const attribute = geometryData.attributes[ i ];
  71710. const name = attribute.name;
  71711. const array = attribute.array;
  71712. const itemSize = attribute.itemSize;
  71713. geometry.setAttribute( name, new BufferAttribute( array, itemSize ) );
  71714. }
  71715. return geometry;
  71716. }
  71717. _loadLibrary( url, responseType ) {
  71718. const loader = new FileLoader( this.manager );
  71719. loader.setPath( this.decoderPath );
  71720. loader.setResponseType( responseType );
  71721. loader.setWithCredentials( this.withCredentials );
  71722. return new Promise( ( resolve, reject ) => {
  71723. loader.load( url, resolve, undefined, reject );
  71724. } );
  71725. }
  71726. preload() {
  71727. this._initDecoder();
  71728. return this;
  71729. }
  71730. _initDecoder() {
  71731. if ( this.decoderPending ) return this.decoderPending;
  71732. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  71733. const librariesPending = [];
  71734. if ( useJS ) {
  71735. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  71736. } else {
  71737. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  71738. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  71739. }
  71740. this.decoderPending = Promise.all( librariesPending )
  71741. .then( ( libraries ) => {
  71742. const jsContent = libraries[ 0 ];
  71743. if ( ! useJS ) {
  71744. this.decoderConfig.wasmBinary = libraries[ 1 ];
  71745. }
  71746. const fn = DRACOWorker.toString();
  71747. const body = [
  71748. '/* draco decoder */',
  71749. jsContent,
  71750. '',
  71751. '/* worker */',
  71752. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  71753. ].join( '\n' );
  71754. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  71755. } );
  71756. return this.decoderPending;
  71757. }
  71758. _getWorker( taskID, taskCost ) {
  71759. return this._initDecoder().then( () => {
  71760. if ( this.workerPool.length < this.workerLimit ) {
  71761. const worker = new Worker( this.workerSourceURL );
  71762. worker._callbacks = {};
  71763. worker._taskCosts = {};
  71764. worker._taskLoad = 0;
  71765. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  71766. worker.onmessage = function ( e ) {
  71767. const message = e.data;
  71768. switch ( message.type ) {
  71769. case 'decode':
  71770. worker._callbacks[ message.id ].resolve( message );
  71771. break;
  71772. case 'error':
  71773. worker._callbacks[ message.id ].reject( message );
  71774. break;
  71775. default:
  71776. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  71777. }
  71778. };
  71779. this.workerPool.push( worker );
  71780. } else {
  71781. this.workerPool.sort( function ( a, b ) {
  71782. return a._taskLoad > b._taskLoad ? - 1 : 1;
  71783. } );
  71784. }
  71785. const worker = this.workerPool[ this.workerPool.length - 1 ];
  71786. worker._taskCosts[ taskID ] = taskCost;
  71787. worker._taskLoad += taskCost;
  71788. return worker;
  71789. } );
  71790. }
  71791. _releaseTask( worker, taskID ) {
  71792. worker._taskLoad -= worker._taskCosts[ taskID ];
  71793. delete worker._callbacks[ taskID ];
  71794. delete worker._taskCosts[ taskID ];
  71795. }
  71796. debug() {
  71797. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  71798. }
  71799. dispose() {
  71800. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  71801. this.workerPool[ i ].terminate();
  71802. }
  71803. this.workerPool.length = 0;
  71804. return this;
  71805. }
  71806. }
  71807. /* WEB WORKER */
  71808. function DRACOWorker() {
  71809. let decoderConfig;
  71810. let decoderPending;
  71811. onmessage = function ( e ) {
  71812. const message = e.data;
  71813. switch ( message.type ) {
  71814. case 'init':
  71815. decoderConfig = message.decoderConfig;
  71816. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  71817. decoderConfig.onModuleLoaded = function ( draco ) {
  71818. // Module is Promise-like. Wrap before resolving to avoid loop.
  71819. resolve( { draco: draco } );
  71820. };
  71821. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  71822. } );
  71823. break;
  71824. case 'decode':
  71825. const buffer = message.buffer;
  71826. const taskConfig = message.taskConfig;
  71827. decoderPending.then( ( module ) => {
  71828. const draco = module.draco;
  71829. const decoder = new draco.Decoder();
  71830. const decoderBuffer = new draco.DecoderBuffer();
  71831. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  71832. try {
  71833. const geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  71834. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  71835. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  71836. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  71837. } catch ( error ) {
  71838. console.error( error );
  71839. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  71840. } finally {
  71841. draco.destroy( decoderBuffer );
  71842. draco.destroy( decoder );
  71843. }
  71844. } );
  71845. break;
  71846. }
  71847. };
  71848. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  71849. const attributeIDs = taskConfig.attributeIDs;
  71850. const attributeTypes = taskConfig.attributeTypes;
  71851. let dracoGeometry;
  71852. let decodingStatus;
  71853. const geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  71854. if ( geometryType === draco.TRIANGULAR_MESH ) {
  71855. dracoGeometry = new draco.Mesh();
  71856. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  71857. } else if ( geometryType === draco.POINT_CLOUD ) {
  71858. dracoGeometry = new draco.PointCloud();
  71859. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  71860. } else {
  71861. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  71862. }
  71863. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  71864. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  71865. }
  71866. const geometry = { index: null, attributes: [] };
  71867. // Gather all vertex attributes.
  71868. for ( const attributeName in attributeIDs ) {
  71869. const attributeType = self[ attributeTypes[ attributeName ] ];
  71870. let attribute;
  71871. let attributeID;
  71872. // A Draco file may be created with default vertex attributes, whose attribute IDs
  71873. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  71874. // a Draco file may contain a custom set of attributes, identified by known unique
  71875. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  71876. if ( taskConfig.useUniqueIDs ) {
  71877. attributeID = attributeIDs[ attributeName ];
  71878. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  71879. } else {
  71880. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  71881. if ( attributeID === - 1 ) continue;
  71882. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  71883. }
  71884. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  71885. }
  71886. // Add index.
  71887. if ( geometryType === draco.TRIANGULAR_MESH ) {
  71888. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  71889. }
  71890. draco.destroy( dracoGeometry );
  71891. return geometry;
  71892. }
  71893. function decodeIndex( draco, decoder, dracoGeometry ) {
  71894. const numFaces = dracoGeometry.num_faces();
  71895. const numIndices = numFaces * 3;
  71896. const byteLength = numIndices * 4;
  71897. const ptr = draco._malloc( byteLength );
  71898. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  71899. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  71900. draco._free( ptr );
  71901. return { array: index, itemSize: 1 };
  71902. }
  71903. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  71904. const numComponents = attribute.num_components();
  71905. const numPoints = dracoGeometry.num_points();
  71906. const numValues = numPoints * numComponents;
  71907. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  71908. const dataType = getDracoDataType( draco, attributeType );
  71909. const ptr = draco._malloc( byteLength );
  71910. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  71911. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  71912. draco._free( ptr );
  71913. return {
  71914. name: attributeName,
  71915. array: array,
  71916. itemSize: numComponents
  71917. };
  71918. }
  71919. function getDracoDataType( draco, attributeType ) {
  71920. switch ( attributeType ) {
  71921. case Float32Array: return draco.DT_FLOAT32;
  71922. case Int8Array: return draco.DT_INT8;
  71923. case Int16Array: return draco.DT_INT16;
  71924. case Int32Array: return draco.DT_INT32;
  71925. case Uint8Array: return draco.DT_UINT8;
  71926. case Uint16Array: return draco.DT_UINT16;
  71927. case Uint32Array: return draco.DT_UINT32;
  71928. }
  71929. }
  71930. }
  71931. /**
  71932. * @author Deepkolos / https://github.com/deepkolos
  71933. */
  71934. class WorkerPool$1 {
  71935. constructor( pool = 4 ) {
  71936. this.pool = pool;
  71937. this.queue = [];
  71938. this.workers = [];
  71939. this.workersResolve = [];
  71940. this.workerStatus = 0;
  71941. }
  71942. _initWorker( workerId ) {
  71943. if ( ! this.workers[ workerId ] ) {
  71944. const worker = this.workerCreator();
  71945. worker.addEventListener( 'message', this._onMessage.bind( this, workerId ) );
  71946. this.workers[ workerId ] = worker;
  71947. }
  71948. }
  71949. _getIdleWorker() {
  71950. for ( let i = 0; i < this.pool; i ++ )
  71951. if ( ! ( this.workerStatus & ( 1 << i ) ) ) return i;
  71952. return - 1;
  71953. }
  71954. _onMessage( workerId, msg ) {
  71955. const resolve = this.workersResolve[ workerId ];
  71956. resolve && resolve( msg );
  71957. if ( this.queue.length ) {
  71958. const { resolve, msg, transfer } = this.queue.shift();
  71959. this.workersResolve[ workerId ] = resolve;
  71960. this.workers[ workerId ].postMessage( msg, transfer );
  71961. } else {
  71962. this.workerStatus ^= 1 << workerId;
  71963. }
  71964. }
  71965. setWorkerCreator( workerCreator ) {
  71966. this.workerCreator = workerCreator;
  71967. }
  71968. setWorkerLimit( pool ) {
  71969. this.pool = pool;
  71970. }
  71971. postMessage( msg, transfer ) {
  71972. return new Promise( ( resolve ) => {
  71973. const workerId = this._getIdleWorker();
  71974. if ( workerId !== - 1 ) {
  71975. this._initWorker( workerId );
  71976. this.workerStatus |= 1 << workerId;
  71977. this.workersResolve[ workerId ] = resolve;
  71978. this.workers[ workerId ].postMessage( msg, transfer );
  71979. } else {
  71980. this.queue.push( { resolve, msg, transfer } );
  71981. }
  71982. } );
  71983. }
  71984. dispose() {
  71985. this.workers.forEach( ( worker ) => worker.terminate() );
  71986. this.workersResolve.length = 0;
  71987. this.workers.length = 0;
  71988. this.queue.length = 0;
  71989. this.workerStatus = 0;
  71990. }
  71991. }
  71992. 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,..._]))}
  71993. var KTX = /*#__PURE__*/Object.freeze({
  71994. __proto__: null,
  71995. KHR_DF_CHANNEL_RGBSDA_ALPHA: Q,
  71996. KHR_DF_CHANNEL_RGBSDA_BLUE: q,
  71997. KHR_DF_CHANNEL_RGBSDA_DEPTH: J,
  71998. KHR_DF_CHANNEL_RGBSDA_GREEN: Y,
  71999. KHR_DF_CHANNEL_RGBSDA_RED: R,
  72000. KHR_DF_CHANNEL_RGBSDA_STENCIL: G,
  72001. KHR_DF_FLAG_ALPHA_PREMULTIPLIED: p,
  72002. KHR_DF_FLAG_ALPHA_STRAIGHT: _$1,
  72003. KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT: s,
  72004. KHR_DF_MODEL_ASTC: c$3,
  72005. KHR_DF_MODEL_ETC1: f,
  72006. KHR_DF_MODEL_ETC1S: h$2,
  72007. KHR_DF_MODEL_ETC2: U$1,
  72008. KHR_DF_MODEL_RGBSDA: l$1,
  72009. KHR_DF_MODEL_UNSPECIFIED: o$1,
  72010. KHR_DF_PRIMARIES_ACES: W,
  72011. KHR_DF_PRIMARIES_ACESCC: N,
  72012. KHR_DF_PRIMARIES_ADOBERGB: j,
  72013. KHR_DF_PRIMARIES_BT2020: z,
  72014. KHR_DF_PRIMARIES_BT601_EBU: P,
  72015. KHR_DF_PRIMARIES_BT601_SMPTE: C,
  72016. KHR_DF_PRIMARIES_BT709: F,
  72017. KHR_DF_PRIMARIES_CIEXYZ: M$1,
  72018. KHR_DF_PRIMARIES_DISPLAYP3: X,
  72019. KHR_DF_PRIMARIES_NTSC1953: H,
  72020. KHR_DF_PRIMARIES_PAL525: K,
  72021. KHR_DF_PRIMARIES_UNSPECIFIED: E,
  72022. KHR_DF_SAMPLE_DATATYPE_EXPONENT: tt,
  72023. KHR_DF_SAMPLE_DATATYPE_FLOAT: Z,
  72024. KHR_DF_SAMPLE_DATATYPE_LINEAR: et,
  72025. KHR_DF_SAMPLE_DATATYPE_SIGNED: $$1,
  72026. KHR_DF_TRANSFER_ACESCC: O,
  72027. KHR_DF_TRANSFER_ACESCCT: T$1,
  72028. KHR_DF_TRANSFER_ADOBERGB: V,
  72029. KHR_DF_TRANSFER_BT1886: w$1,
  72030. KHR_DF_TRANSFER_DCIP3: k,
  72031. KHR_DF_TRANSFER_HLG_EOTF: B,
  72032. KHR_DF_TRANSFER_HLG_OETF: D,
  72033. KHR_DF_TRANSFER_ITU: u$2,
  72034. KHR_DF_TRANSFER_LINEAR: y,
  72035. KHR_DF_TRANSFER_NTSC: b$1,
  72036. KHR_DF_TRANSFER_PAL625_EOTF: S$1,
  72037. KHR_DF_TRANSFER_PAL_OETF: v,
  72038. KHR_DF_TRANSFER_PQ_EOTF: L,
  72039. KHR_DF_TRANSFER_PQ_OETF: A,
  72040. KHR_DF_TRANSFER_SLOG: d,
  72041. KHR_DF_TRANSFER_SLOG2: m,
  72042. KHR_DF_TRANSFER_SRGB: x$2,
  72043. KHR_DF_TRANSFER_ST240: I,
  72044. KHR_DF_TRANSFER_UNSPECIFIED: g,
  72045. KHR_DF_VENDORID_KHRONOS: a$1,
  72046. KHR_DF_VERSION: r,
  72047. KHR_SUPERCOMPRESSION_BASISLZ: e$1,
  72048. KHR_SUPERCOMPRESSION_NONE: t,
  72049. KHR_SUPERCOMPRESSION_ZLIB: i$2,
  72050. KHR_SUPERCOMPRESSION_ZSTD: n$1,
  72051. KTX2Container: Si,
  72052. VK_FORMAT_A1R5G5B5_UNORM_PACK16: Ut,
  72053. VK_FORMAT_A2B10G10R10_SINT_PACK32: qt,
  72054. VK_FORMAT_A2B10G10R10_SNORM_PACK32: Rt,
  72055. VK_FORMAT_A2B10G10R10_UINT_PACK32: Yt,
  72056. VK_FORMAT_A2B10G10R10_UNORM_PACK32: jt,
  72057. VK_FORMAT_A2R10G10B10_SINT_PACK32: Xt,
  72058. VK_FORMAT_A2R10G10B10_SNORM_PACK32: Ht,
  72059. VK_FORMAT_A2R10G10B10_UINT_PACK32: Kt,
  72060. VK_FORMAT_A2R10G10B10_UNORM_PACK32: Nt,
  72061. VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT: vi,
  72062. VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT: ki,
  72063. VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT: Bi,
  72064. VK_FORMAT_ASTC_10x10_SRGB_BLOCK: Xn,
  72065. VK_FORMAT_ASTC_10x10_UNORM_BLOCK: Kn,
  72066. VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT: mi,
  72067. VK_FORMAT_ASTC_10x5_SRGB_BLOCK: zn,
  72068. VK_FORMAT_ASTC_10x5_UNORM_BLOCK: Cn,
  72069. VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT: wi,
  72070. VK_FORMAT_ASTC_10x6_SRGB_BLOCK: Wn,
  72071. VK_FORMAT_ASTC_10x6_UNORM_BLOCK: Mn,
  72072. VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT: Di,
  72073. VK_FORMAT_ASTC_10x8_SRGB_BLOCK: Hn,
  72074. VK_FORMAT_ASTC_10x8_UNORM_BLOCK: Nn,
  72075. VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT: Li,
  72076. VK_FORMAT_ASTC_12x10_SRGB_BLOCK: Rn,
  72077. VK_FORMAT_ASTC_12x10_UNORM_BLOCK: jn,
  72078. VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT: Ai,
  72079. VK_FORMAT_ASTC_12x12_SRGB_BLOCK: qn,
  72080. VK_FORMAT_ASTC_12x12_UNORM_BLOCK: Yn,
  72081. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT: _i,
  72082. VK_FORMAT_ASTC_4x4_SRGB_BLOCK: wn,
  72083. VK_FORMAT_ASTC_4x4_UNORM_BLOCK: mn,
  72084. VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT: pi,
  72085. VK_FORMAT_ASTC_5x4_SRGB_BLOCK: Bn,
  72086. VK_FORMAT_ASTC_5x4_UNORM_BLOCK: Dn,
  72087. VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT: gi,
  72088. VK_FORMAT_ASTC_5x5_SRGB_BLOCK: An,
  72089. VK_FORMAT_ASTC_5x5_UNORM_BLOCK: Ln,
  72090. VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT: yi,
  72091. VK_FORMAT_ASTC_6x5_SRGB_BLOCK: vn,
  72092. VK_FORMAT_ASTC_6x5_UNORM_BLOCK: kn,
  72093. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT: xi,
  72094. VK_FORMAT_ASTC_6x6_SRGB_BLOCK: In,
  72095. VK_FORMAT_ASTC_6x6_UNORM_BLOCK: Sn,
  72096. VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT: ui,
  72097. VK_FORMAT_ASTC_8x5_SRGB_BLOCK: Tn,
  72098. VK_FORMAT_ASTC_8x5_UNORM_BLOCK: On,
  72099. VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT: bi,
  72100. VK_FORMAT_ASTC_8x6_SRGB_BLOCK: En,
  72101. VK_FORMAT_ASTC_8x6_UNORM_BLOCK: Vn,
  72102. VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT: di,
  72103. VK_FORMAT_ASTC_8x8_SRGB_BLOCK: Pn,
  72104. VK_FORMAT_ASTC_8x8_UNORM_BLOCK: Fn,
  72105. VK_FORMAT_B10G11R11_UFLOAT_PACK32: Me,
  72106. VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: $n,
  72107. VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: si,
  72108. VK_FORMAT_B4G4R4A4_UNORM_PACK16: at,
  72109. VK_FORMAT_B5G5R5A1_UNORM_PACK16: ft,
  72110. VK_FORMAT_B5G6R5_UNORM_PACK16: ot,
  72111. VK_FORMAT_B8G8R8A8_SINT: Mt,
  72112. VK_FORMAT_B8G8R8A8_SNORM: Ct,
  72113. VK_FORMAT_B8G8R8A8_SRGB: Wt,
  72114. VK_FORMAT_B8G8R8A8_UINT: zt,
  72115. VK_FORMAT_B8G8R8A8_UNORM: Pt,
  72116. VK_FORMAT_B8G8R8_SINT: St,
  72117. VK_FORMAT_B8G8R8_SNORM: kt,
  72118. VK_FORMAT_B8G8R8_SRGB: It,
  72119. VK_FORMAT_B8G8R8_UINT: vt,
  72120. VK_FORMAT_B8G8R8_UNORM: At,
  72121. VK_FORMAT_BC1_RGBA_SRGB_BLOCK: Qe,
  72122. VK_FORMAT_BC1_RGBA_UNORM_BLOCK: Je,
  72123. VK_FORMAT_BC1_RGB_SRGB_BLOCK: Ge,
  72124. VK_FORMAT_BC1_RGB_UNORM_BLOCK: qe,
  72125. VK_FORMAT_BC2_SRGB_BLOCK: $e,
  72126. VK_FORMAT_BC2_UNORM_BLOCK: Ze,
  72127. VK_FORMAT_BC3_SRGB_BLOCK: en,
  72128. VK_FORMAT_BC3_UNORM_BLOCK: tn,
  72129. VK_FORMAT_BC4_SNORM_BLOCK: sn,
  72130. VK_FORMAT_BC4_UNORM_BLOCK: nn,
  72131. VK_FORMAT_BC5_SNORM_BLOCK: rn,
  72132. VK_FORMAT_BC5_UNORM_BLOCK: an,
  72133. VK_FORMAT_BC6H_SFLOAT_BLOCK: ln,
  72134. VK_FORMAT_BC6H_UFLOAT_BLOCK: on,
  72135. VK_FORMAT_BC7_SRGB_BLOCK: Un,
  72136. VK_FORMAT_BC7_UNORM_BLOCK: fn,
  72137. VK_FORMAT_D16_UNORM: Ne,
  72138. VK_FORMAT_D16_UNORM_S8_UINT: je,
  72139. VK_FORMAT_D24_UNORM_S8_UINT: Re,
  72140. VK_FORMAT_D32_SFLOAT: Ke,
  72141. VK_FORMAT_D32_SFLOAT_S8_UINT: Ye,
  72142. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: We,
  72143. VK_FORMAT_EAC_R11G11_SNORM_BLOCK: dn,
  72144. VK_FORMAT_EAC_R11G11_UNORM_BLOCK: bn,
  72145. VK_FORMAT_EAC_R11_SNORM_BLOCK: un,
  72146. VK_FORMAT_EAC_R11_UNORM_BLOCK: xn,
  72147. VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: pn,
  72148. VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: _n,
  72149. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: yn,
  72150. VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: gn,
  72151. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: hn,
  72152. VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: cn,
  72153. VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: Zn,
  72154. VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: ii,
  72155. VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG: fi,
  72156. VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG: ai,
  72157. VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG: Ui,
  72158. VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG: ri,
  72159. VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG: ci,
  72160. VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG: oi,
  72161. VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: hi,
  72162. VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG: li,
  72163. VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: Qn,
  72164. VK_FORMAT_R10X6G10X6_UNORM_2PACK16: Jn,
  72165. VK_FORMAT_R10X6_UNORM_PACK16: Gn,
  72166. VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: ni,
  72167. VK_FORMAT_R12X4G12X4_UNORM_2PACK16: ei,
  72168. VK_FORMAT_R12X4_UNORM_PACK16: ti,
  72169. VK_FORMAT_R16G16B16A16_SFLOAT: pe,
  72170. VK_FORMAT_R16G16B16A16_SINT: _e,
  72171. VK_FORMAT_R16G16B16A16_SNORM: ce,
  72172. VK_FORMAT_R16G16B16A16_UINT: he,
  72173. VK_FORMAT_R16G16B16A16_UNORM: Ue,
  72174. VK_FORMAT_R16G16B16_SFLOAT: fe,
  72175. VK_FORMAT_R16G16B16_SINT: le,
  72176. VK_FORMAT_R16G16B16_SNORM: re,
  72177. VK_FORMAT_R16G16B16_UINT: oe,
  72178. VK_FORMAT_R16G16B16_UNORM: ae,
  72179. VK_FORMAT_R16G16_SFLOAT: se,
  72180. VK_FORMAT_R16G16_SINT: ie,
  72181. VK_FORMAT_R16G16_SNORM: ee,
  72182. VK_FORMAT_R16G16_UINT: ne,
  72183. VK_FORMAT_R16G16_UNORM: te,
  72184. VK_FORMAT_R16_SFLOAT: $t,
  72185. VK_FORMAT_R16_SINT: Zt,
  72186. VK_FORMAT_R16_SNORM: Jt,
  72187. VK_FORMAT_R16_UINT: Qt,
  72188. VK_FORMAT_R16_UNORM: Gt,
  72189. VK_FORMAT_R32G32B32A32_SFLOAT: Ae,
  72190. VK_FORMAT_R32G32B32A32_SINT: Le,
  72191. VK_FORMAT_R32G32B32A32_UINT: Be,
  72192. VK_FORMAT_R32G32B32_SFLOAT: De,
  72193. VK_FORMAT_R32G32B32_SINT: we,
  72194. VK_FORMAT_R32G32B32_UINT: me,
  72195. VK_FORMAT_R32G32_SFLOAT: de,
  72196. VK_FORMAT_R32G32_SINT: be,
  72197. VK_FORMAT_R32G32_UINT: ue,
  72198. VK_FORMAT_R32_SFLOAT: xe,
  72199. VK_FORMAT_R32_SINT: ye,
  72200. VK_FORMAT_R32_UINT: ge,
  72201. VK_FORMAT_R4G4B4A4_UNORM_PACK16: st,
  72202. VK_FORMAT_R4G4_UNORM_PACK8: it,
  72203. VK_FORMAT_R5G5B5A1_UNORM_PACK16: lt,
  72204. VK_FORMAT_R5G6B5_UNORM_PACK16: rt,
  72205. VK_FORMAT_R64G64B64A64_SFLOAT: ze,
  72206. VK_FORMAT_R64G64B64A64_SINT: Ce,
  72207. VK_FORMAT_R64G64B64A64_UINT: Pe,
  72208. VK_FORMAT_R64G64B64_SFLOAT: Fe,
  72209. VK_FORMAT_R64G64B64_SINT: Ee,
  72210. VK_FORMAT_R64G64B64_UINT: Ve,
  72211. VK_FORMAT_R64G64_SFLOAT: Te,
  72212. VK_FORMAT_R64G64_SINT: Oe,
  72213. VK_FORMAT_R64G64_UINT: Ie,
  72214. VK_FORMAT_R64_SFLOAT: Se,
  72215. VK_FORMAT_R64_SINT: ve,
  72216. VK_FORMAT_R64_UINT: ke,
  72217. VK_FORMAT_R8G8B8A8_SINT: Et,
  72218. VK_FORMAT_R8G8B8A8_SNORM: Tt,
  72219. VK_FORMAT_R8G8B8A8_SRGB: Ft,
  72220. VK_FORMAT_R8G8B8A8_UINT: Vt,
  72221. VK_FORMAT_R8G8B8A8_UNORM: Ot,
  72222. VK_FORMAT_R8G8B8_SINT: Bt,
  72223. VK_FORMAT_R8G8B8_SNORM: wt,
  72224. VK_FORMAT_R8G8B8_SRGB: Lt,
  72225. VK_FORMAT_R8G8B8_UINT: Dt,
  72226. VK_FORMAT_R8G8B8_UNORM: mt,
  72227. VK_FORMAT_R8G8_SINT: bt,
  72228. VK_FORMAT_R8G8_SNORM: xt,
  72229. VK_FORMAT_R8G8_SRGB: dt,
  72230. VK_FORMAT_R8G8_UINT: ut,
  72231. VK_FORMAT_R8G8_UNORM: yt,
  72232. VK_FORMAT_R8_SINT: pt,
  72233. VK_FORMAT_R8_SNORM: ht,
  72234. VK_FORMAT_R8_SRGB: gt,
  72235. VK_FORMAT_R8_UINT: _t,
  72236. VK_FORMAT_R8_UNORM: ct,
  72237. VK_FORMAT_S8_UINT: Xe,
  72238. VK_FORMAT_UNDEFINED: nt,
  72239. VK_FORMAT_X8_D24_UNORM_PACK32: He,
  72240. read: Pi,
  72241. write: Mi
  72242. });
  72243. /**
  72244. * Loader for KTX 2.0 GPU Texture containers.
  72245. *
  72246. * KTX 2.0 is a container format for various GPU texture formats. The loader
  72247. * supports Basis Universal GPU textures, which can be quickly transcoded to
  72248. * a wide variety of GPU texture compression formats, as well as some
  72249. * uncompressed DataTexture and Data3DTexture formats.
  72250. *
  72251. * References:
  72252. * - KTX: http://github.khronos.org/KTX-Specification/
  72253. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  72254. */
  72255. const {
  72256. read: read$1,
  72257. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  72258. KHR_DF_TRANSFER_SRGB,
  72259. VK_FORMAT_UNDEFINED,
  72260. VK_FORMAT_R16_SFLOAT,
  72261. VK_FORMAT_R16G16_SFLOAT,
  72262. VK_FORMAT_R16G16B16A16_SFLOAT,
  72263. VK_FORMAT_R32_SFLOAT,
  72264. VK_FORMAT_R32G32_SFLOAT,
  72265. VK_FORMAT_R32G32B32A32_SFLOAT,
  72266. VK_FORMAT_R8_SRGB,
  72267. VK_FORMAT_R8_UNORM,
  72268. VK_FORMAT_R8G8_SRGB,
  72269. VK_FORMAT_R8G8_UNORM,
  72270. VK_FORMAT_R8G8B8A8_SRGB,
  72271. VK_FORMAT_R8G8B8A8_UNORM,
  72272. } = KTX; // eslint-disable-line no-undef
  72273. const _taskCache$1 = new WeakMap();
  72274. let _activeLoaders = 0;
  72275. class KTX2Loader extends Loader {
  72276. constructor( manager ) {
  72277. super( manager );
  72278. this.transcoderPath = '';
  72279. this.transcoderBinary = null;
  72280. this.transcoderPending = null;
  72281. this.workerPool = new WorkerPool$1();
  72282. this.workerSourceURL = '';
  72283. this.workerConfig = null;
  72284. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  72285. console.warn(
  72286. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  72287. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  72288. );
  72289. }
  72290. }
  72291. setTranscoderPath( path ) {
  72292. this.transcoderPath = path;
  72293. return this;
  72294. }
  72295. setWorkerLimit( num ) {
  72296. this.workerPool.setWorkerLimit( num );
  72297. return this;
  72298. }
  72299. detectSupport( renderer ) {
  72300. this.workerConfig = {
  72301. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  72302. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  72303. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  72304. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  72305. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  72306. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  72307. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  72308. };
  72309. if ( renderer.capabilities.isWebGL2 ) {
  72310. // https://github.com/mrdoob/three.js/pull/22928
  72311. this.workerConfig.etc1Supported = false;
  72312. }
  72313. return this;
  72314. }
  72315. init() {
  72316. if ( ! this.transcoderPending ) {
  72317. // Load transcoder wrapper.
  72318. const jsLoader = new FileLoader( this.manager );
  72319. jsLoader.setPath( this.transcoderPath );
  72320. jsLoader.setWithCredentials( this.withCredentials );
  72321. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  72322. // Load transcoder WASM binary.
  72323. const binaryLoader = new FileLoader( this.manager );
  72324. binaryLoader.setPath( this.transcoderPath );
  72325. binaryLoader.setResponseType( 'arraybuffer' );
  72326. binaryLoader.setWithCredentials( this.withCredentials );
  72327. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  72328. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  72329. .then( ( [ jsContent, binaryContent ] ) => {
  72330. const fn = KTX2Loader.BasisWorker.toString();
  72331. const body = [
  72332. '/* constants */',
  72333. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  72334. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  72335. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  72336. '/* basis_transcoder.js */',
  72337. jsContent,
  72338. '/* worker */',
  72339. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  72340. ].join( '\n' );
  72341. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  72342. this.transcoderBinary = binaryContent;
  72343. this.workerPool.setWorkerCreator( () => {
  72344. const worker = new Worker( this.workerSourceURL );
  72345. const transcoderBinary = this.transcoderBinary.slice( 0 );
  72346. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  72347. return worker;
  72348. } );
  72349. } );
  72350. if ( _activeLoaders > 0 ) {
  72351. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  72352. console.warn(
  72353. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  72354. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  72355. );
  72356. }
  72357. _activeLoaders ++;
  72358. }
  72359. return this.transcoderPending;
  72360. }
  72361. load( url, onLoad, onProgress, onError ) {
  72362. if ( this.workerConfig === null ) {
  72363. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  72364. }
  72365. const loader = new FileLoader( this.manager );
  72366. loader.setResponseType( 'arraybuffer' );
  72367. loader.setWithCredentials( this.withCredentials );
  72368. loader.load( url, ( buffer ) => {
  72369. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  72370. // again from this thread.
  72371. if ( _taskCache$1.has( buffer ) ) {
  72372. const cachedTask = _taskCache$1.get( buffer );
  72373. return cachedTask.promise.then( onLoad ).catch( onError );
  72374. }
  72375. this._createTexture( buffer )
  72376. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  72377. .catch( onError );
  72378. }, onProgress, onError );
  72379. }
  72380. _createTextureFrom( transcodeResult ) {
  72381. const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult;
  72382. if ( type === 'error' ) return Promise.reject( error );
  72383. const texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  72384. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  72385. texture.magFilter = LinearFilter;
  72386. texture.generateMipmaps = false;
  72387. texture.needsUpdate = true;
  72388. texture.encoding = dfdTransferFn === KHR_DF_TRANSFER_SRGB ? sRGBEncoding : LinearEncoding;
  72389. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  72390. return texture;
  72391. }
  72392. /**
  72393. * @param {ArrayBuffer} buffer
  72394. * @param {object?} config
  72395. * @return {Promise<CompressedTexture|DataTexture|Data3DTexture>}
  72396. */
  72397. _createTexture( buffer, config = {} ) {
  72398. const container = read$1( new Uint8Array( buffer ) );
  72399. if ( container.vkFormat !== VK_FORMAT_UNDEFINED ) {
  72400. return createDataTexture( container );
  72401. }
  72402. //
  72403. const taskConfig = config;
  72404. const texturePending = this.init().then( () => {
  72405. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  72406. } ).then( ( e ) => this._createTextureFrom( e.data ) );
  72407. // Cache the task result.
  72408. _taskCache$1.set( buffer, { promise: texturePending } );
  72409. return texturePending;
  72410. }
  72411. dispose() {
  72412. this.workerPool.dispose();
  72413. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  72414. _activeLoaders --;
  72415. return this;
  72416. }
  72417. }
  72418. /* CONSTANTS */
  72419. KTX2Loader.BasisFormat = {
  72420. ETC1S: 0,
  72421. UASTC_4x4: 1,
  72422. };
  72423. KTX2Loader.TranscoderFormat = {
  72424. ETC1: 0,
  72425. ETC2: 1,
  72426. BC1: 2,
  72427. BC3: 3,
  72428. BC4: 4,
  72429. BC5: 5,
  72430. BC7_M6_OPAQUE_ONLY: 6,
  72431. BC7_M5: 7,
  72432. PVRTC1_4_RGB: 8,
  72433. PVRTC1_4_RGBA: 9,
  72434. ASTC_4x4: 10,
  72435. ATC_RGB: 11,
  72436. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  72437. RGBA32: 13,
  72438. RGB565: 14,
  72439. BGR565: 15,
  72440. RGBA4444: 16,
  72441. };
  72442. KTX2Loader.EngineFormat = {
  72443. RGBAFormat: RGBAFormat,
  72444. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  72445. RGBA_BPTC_Format: RGBA_BPTC_Format,
  72446. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  72447. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  72448. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  72449. RGB_ETC1_Format: RGB_ETC1_Format,
  72450. RGB_ETC2_Format: RGB_ETC2_Format,
  72451. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  72452. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  72453. };
  72454. /* WEB WORKER */
  72455. KTX2Loader.BasisWorker = function () {
  72456. let config;
  72457. let transcoderPending;
  72458. let BasisModule;
  72459. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  72460. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  72461. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  72462. self.addEventListener( 'message', function ( e ) {
  72463. const message = e.data;
  72464. switch ( message.type ) {
  72465. case 'init':
  72466. config = message.config;
  72467. init( message.transcoderBinary );
  72468. break;
  72469. case 'transcode':
  72470. transcoderPending.then( () => {
  72471. try {
  72472. const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode( message.buffer );
  72473. const buffers = [];
  72474. for ( let i = 0; i < mipmaps.length; ++ i ) {
  72475. buffers.push( mipmaps[ i ].data.buffer );
  72476. }
  72477. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers );
  72478. } catch ( error ) {
  72479. console.error( error );
  72480. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  72481. }
  72482. } );
  72483. break;
  72484. }
  72485. } );
  72486. function init( wasmBinary ) {
  72487. transcoderPending = new Promise( ( resolve ) => {
  72488. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  72489. BASIS( BasisModule ); // eslint-disable-line no-undef
  72490. } ).then( () => {
  72491. BasisModule.initializeBasis();
  72492. if ( BasisModule.KTX2File === undefined ) {
  72493. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  72494. }
  72495. } );
  72496. }
  72497. function transcode( buffer ) {
  72498. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  72499. function cleanup() {
  72500. ktx2File.close();
  72501. ktx2File.delete();
  72502. }
  72503. if ( ! ktx2File.isValid() ) {
  72504. cleanup();
  72505. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  72506. }
  72507. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  72508. const width = ktx2File.getWidth();
  72509. const height = ktx2File.getHeight();
  72510. const levels = ktx2File.getLevels();
  72511. const hasAlpha = ktx2File.getHasAlpha();
  72512. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  72513. const dfdFlags = ktx2File.getDFDFlags();
  72514. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  72515. if ( ! width || ! height || ! levels ) {
  72516. cleanup();
  72517. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  72518. }
  72519. if ( ! ktx2File.startTranscoding() ) {
  72520. cleanup();
  72521. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  72522. }
  72523. const mipmaps = [];
  72524. for ( let mip = 0; mip < levels; mip ++ ) {
  72525. const levelInfo = ktx2File.getImageLevelInfo( mip, 0, 0 );
  72526. const mipWidth = levelInfo.origWidth;
  72527. const mipHeight = levelInfo.origHeight;
  72528. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, 0, 0, transcoderFormat ) );
  72529. const status = ktx2File.transcodeImage(
  72530. dst,
  72531. mip,
  72532. 0,
  72533. 0,
  72534. transcoderFormat,
  72535. 0,
  72536. - 1,
  72537. - 1,
  72538. );
  72539. if ( ! status ) {
  72540. cleanup();
  72541. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  72542. }
  72543. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  72544. }
  72545. cleanup();
  72546. return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags };
  72547. }
  72548. //
  72549. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  72550. // device capabilities, and texture dimensions. The list below ranks the formats separately
  72551. // for ETC1S and UASTC.
  72552. //
  72553. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  72554. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  72555. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  72556. const FORMAT_OPTIONS = [
  72557. {
  72558. if: 'astcSupported',
  72559. basisFormat: [ BasisFormat.UASTC_4x4 ],
  72560. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  72561. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  72562. priorityETC1S: Infinity,
  72563. priorityUASTC: 1,
  72564. needsPowerOfTwo: false,
  72565. },
  72566. {
  72567. if: 'bptcSupported',
  72568. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72569. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  72570. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  72571. priorityETC1S: 3,
  72572. priorityUASTC: 2,
  72573. needsPowerOfTwo: false,
  72574. },
  72575. {
  72576. if: 'dxtSupported',
  72577. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72578. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  72579. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  72580. priorityETC1S: 4,
  72581. priorityUASTC: 5,
  72582. needsPowerOfTwo: false,
  72583. },
  72584. {
  72585. if: 'etc2Supported',
  72586. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72587. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  72588. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  72589. priorityETC1S: 1,
  72590. priorityUASTC: 3,
  72591. needsPowerOfTwo: false,
  72592. },
  72593. {
  72594. if: 'etc1Supported',
  72595. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72596. transcoderFormat: [ TranscoderFormat.ETC1 ],
  72597. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  72598. priorityETC1S: 2,
  72599. priorityUASTC: 4,
  72600. needsPowerOfTwo: false,
  72601. },
  72602. {
  72603. if: 'pvrtcSupported',
  72604. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72605. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  72606. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  72607. priorityETC1S: 5,
  72608. priorityUASTC: 6,
  72609. needsPowerOfTwo: true,
  72610. },
  72611. ];
  72612. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  72613. return a.priorityETC1S - b.priorityETC1S;
  72614. } );
  72615. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  72616. return a.priorityUASTC - b.priorityUASTC;
  72617. } );
  72618. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  72619. let transcoderFormat;
  72620. let engineFormat;
  72621. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  72622. for ( let i = 0; i < options.length; i ++ ) {
  72623. const opt = options[ i ];
  72624. if ( ! config[ opt.if ] ) continue;
  72625. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  72626. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  72627. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  72628. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  72629. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  72630. return { transcoderFormat, engineFormat };
  72631. }
  72632. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  72633. transcoderFormat = TranscoderFormat.RGBA32;
  72634. engineFormat = EngineFormat.RGBAFormat;
  72635. return { transcoderFormat, engineFormat };
  72636. }
  72637. function isPowerOfTwo( value ) {
  72638. if ( value <= 2 ) return true;
  72639. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  72640. }
  72641. };
  72642. //
  72643. // DataTexture and Data3DTexture parsing.
  72644. const FORMAT_MAP = {
  72645. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  72646. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  72647. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  72648. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  72649. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  72650. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  72651. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  72652. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  72653. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  72654. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  72655. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  72656. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  72657. };
  72658. const TYPE_MAP = {
  72659. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  72660. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  72661. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  72662. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  72663. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  72664. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  72665. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  72666. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  72667. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  72668. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  72669. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  72670. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  72671. };
  72672. const ENCODING_MAP = {
  72673. [ VK_FORMAT_R8G8B8A8_SRGB ]: sRGBEncoding,
  72674. [ VK_FORMAT_R8G8_SRGB ]: sRGBEncoding,
  72675. [ VK_FORMAT_R8_SRGB ]: sRGBEncoding,
  72676. };
  72677. function createDataTexture( container ) {
  72678. const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container;
  72679. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  72680. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  72681. }
  72682. //
  72683. let view;
  72684. const levelData = container.levels[ 0 ].levelData;
  72685. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  72686. view = new Float32Array(
  72687. levelData.buffer,
  72688. levelData.byteOffset,
  72689. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  72690. );
  72691. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  72692. view = new Uint16Array(
  72693. levelData.buffer,
  72694. levelData.byteOffset,
  72695. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  72696. );
  72697. } else {
  72698. view = levelData;
  72699. }
  72700. //
  72701. const texture = pixelDepth === 0
  72702. ? new DataTexture( view, pixelWidth, pixelHeight )
  72703. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  72704. texture.type = TYPE_MAP[ vkFormat ];
  72705. texture.format = FORMAT_MAP[ vkFormat ];
  72706. texture.encoding = ENCODING_MAP[ vkFormat ] || LinearEncoding;
  72707. texture.needsUpdate = true;
  72708. //
  72709. return Promise.resolve( texture );
  72710. }
  72711. // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  72712. // Copyright (C) 2016-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  72713. var MeshoptDecoder = (function() {
  72714. "use strict";
  72715. // Built with clang version 11.0.0 (https://github.com/llvm/llvm-project.git 0160ad802e899c2922bc9b29564080c22eb0908c)
  72716. // Built from meshoptimizer 0.14
  72717. 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";
  72718. 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";
  72719. // Uses bulk-memory and simd extensions
  72720. 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]);
  72721. // Used to unpack wasm
  72722. 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]);
  72723. if (typeof WebAssembly !== 'object') {
  72724. // This module requires WebAssembly to function
  72725. return {
  72726. supported: false,
  72727. };
  72728. }
  72729. var wasm = wasm_base;
  72730. if (WebAssembly.validate(detector)) {
  72731. wasm = wasm_simd;
  72732. console.log("Warning: meshopt_decoder is using experimental SIMD support");
  72733. }
  72734. var instance;
  72735. var promise =
  72736. WebAssembly.instantiate(unpack(wasm), {})
  72737. .then(function(result) {
  72738. instance = result.instance;
  72739. instance.exports.__wasm_call_ctors();
  72740. });
  72741. function unpack(data) {
  72742. var result = new Uint8Array(data.length);
  72743. for (var i = 0; i < data.length; ++i) {
  72744. var ch = data.charCodeAt(i);
  72745. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  72746. }
  72747. var write = 0;
  72748. for (var i = 0; i < data.length; ++i) {
  72749. result[write++] = (result[i] < 60) ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  72750. }
  72751. return result.buffer.slice(0, write);
  72752. }
  72753. function decode(fun, target, count, size, source, filter) {
  72754. var sbrk = instance.exports.sbrk;
  72755. var count4 = (count + 3) & ~3; // pad for SIMD filter
  72756. var tp = sbrk(count4 * size);
  72757. var sp = sbrk(source.length);
  72758. var heap = new Uint8Array(instance.exports.memory.buffer);
  72759. heap.set(source, sp);
  72760. var res = fun(tp, count, size, sp, source.length);
  72761. if (res == 0 && filter) {
  72762. filter(tp, count4, size);
  72763. }
  72764. target.set(heap.subarray(tp, tp + count * size));
  72765. sbrk(tp - sbrk(0));
  72766. if (res != 0) {
  72767. throw new Error("Malformed buffer data: " + res);
  72768. }
  72769. };
  72770. var filters = {
  72771. // legacy index-based enums for glTF
  72772. 0: "",
  72773. 1: "meshopt_decodeFilterOct",
  72774. 2: "meshopt_decodeFilterQuat",
  72775. 3: "meshopt_decodeFilterExp",
  72776. // string-based enums for glTF
  72777. NONE: "",
  72778. OCTAHEDRAL: "meshopt_decodeFilterOct",
  72779. QUATERNION: "meshopt_decodeFilterQuat",
  72780. EXPONENTIAL: "meshopt_decodeFilterExp",
  72781. };
  72782. var decoders = {
  72783. // legacy index-based enums for glTF
  72784. 0: "meshopt_decodeVertexBuffer",
  72785. 1: "meshopt_decodeIndexBuffer",
  72786. 2: "meshopt_decodeIndexSequence",
  72787. // string-based enums for glTF
  72788. ATTRIBUTES: "meshopt_decodeVertexBuffer",
  72789. TRIANGLES: "meshopt_decodeIndexBuffer",
  72790. INDICES: "meshopt_decodeIndexSequence",
  72791. };
  72792. return {
  72793. ready: promise,
  72794. supported: true,
  72795. decodeVertexBuffer: function(target, count, size, source, filter) {
  72796. decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
  72797. },
  72798. decodeIndexBuffer: function(target, count, size, source) {
  72799. decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
  72800. },
  72801. decodeIndexSequence: function(target, count, size, source) {
  72802. decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
  72803. },
  72804. decodeGltfBuffer: function(target, count, size, source, mode, filter) {
  72805. decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
  72806. }
  72807. };
  72808. })();
  72809. var DDSLoader = function ( manager ) {
  72810. CompressedTextureLoader.call( this, manager );
  72811. };
  72812. DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prototype ), {
  72813. constructor: DDSLoader,
  72814. parse: function ( buffer, loadMipmaps ) {
  72815. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  72816. // Adapted from @toji's DDS utils
  72817. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  72818. // All values and structures referenced from:
  72819. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72820. var DDS_MAGIC = 0x20534444;
  72821. // var DDSD_CAPS = 0x1;
  72822. // var DDSD_HEIGHT = 0x2;
  72823. // var DDSD_WIDTH = 0x4;
  72824. // var DDSD_PITCH = 0x8;
  72825. // var DDSD_PIXELFORMAT = 0x1000;
  72826. var DDSD_MIPMAPCOUNT = 0x20000;
  72827. // var DDSD_LINEARSIZE = 0x80000;
  72828. // var DDSD_DEPTH = 0x800000;
  72829. // var DDSCAPS_COMPLEX = 0x8;
  72830. // var DDSCAPS_MIPMAP = 0x400000;
  72831. // var DDSCAPS_TEXTURE = 0x1000;
  72832. var DDSCAPS2_CUBEMAP = 0x200;
  72833. var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400;
  72834. var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800;
  72835. var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000;
  72836. var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000;
  72837. var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000;
  72838. var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000;
  72839. // var DDSCAPS2_VOLUME = 0x200000;
  72840. // var DDPF_ALPHAPIXELS = 0x1;
  72841. // var DDPF_ALPHA = 0x2;
  72842. var DDPF_FOURCC = 0x4;
  72843. // var DDPF_RGB = 0x40;
  72844. // var DDPF_YUV = 0x200;
  72845. // var DDPF_LUMINANCE = 0x20000;
  72846. function fourCCToInt32( value ) {
  72847. return value.charCodeAt( 0 ) +
  72848. ( value.charCodeAt( 1 ) << 8 ) +
  72849. ( value.charCodeAt( 2 ) << 16 ) +
  72850. ( value.charCodeAt( 3 ) << 24 );
  72851. }
  72852. function int32ToFourCC( value ) {
  72853. return String.fromCharCode(
  72854. value & 0xff,
  72855. ( value >> 8 ) & 0xff,
  72856. ( value >> 16 ) & 0xff,
  72857. ( value >> 24 ) & 0xff
  72858. );
  72859. }
  72860. function loadARGBMip( buffer, dataOffset, width, height ) {
  72861. var dataLength = width * height * 4;
  72862. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  72863. var byteArray = new Uint8Array( dataLength );
  72864. var dst = 0;
  72865. var src = 0;
  72866. for ( var y = 0; y < height; y ++ ) {
  72867. for ( var x = 0; x < width; x ++ ) {
  72868. var b = srcBuffer[ src ]; src ++;
  72869. var g = srcBuffer[ src ]; src ++;
  72870. var r = srcBuffer[ src ]; src ++;
  72871. var a = srcBuffer[ src ]; src ++;
  72872. byteArray[ dst ] = r; dst ++; //r
  72873. byteArray[ dst ] = g; dst ++; //g
  72874. byteArray[ dst ] = b; dst ++; //b
  72875. byteArray[ dst ] = a; dst ++; //a
  72876. }
  72877. }
  72878. return byteArray;
  72879. }
  72880. var FOURCC_DXT1 = fourCCToInt32( 'DXT1' );
  72881. var FOURCC_DXT3 = fourCCToInt32( 'DXT3' );
  72882. var FOURCC_DXT5 = fourCCToInt32( 'DXT5' );
  72883. var FOURCC_ETC1 = fourCCToInt32( 'ETC1' );
  72884. var headerLengthInt = 31; // The header length in 32 bit ints
  72885. // Offsets into the header array
  72886. var off_magic = 0;
  72887. var off_size = 1;
  72888. var off_flags = 2;
  72889. var off_height = 3;
  72890. var off_width = 4;
  72891. var off_mipmapCount = 7;
  72892. var off_pfFlags = 20;
  72893. var off_pfFourCC = 21;
  72894. var off_RGBBitCount = 22;
  72895. var off_RBitMask = 23;
  72896. var off_GBitMask = 24;
  72897. var off_BBitMask = 25;
  72898. var off_ABitMask = 26;
  72899. // var off_caps = 27;
  72900. var off_caps2 = 28;
  72901. // var off_caps3 = 29;
  72902. // var off_caps4 = 30;
  72903. // Parse header
  72904. var header = new Int32Array( buffer, 0, headerLengthInt );
  72905. if ( header[ off_magic ] !== DDS_MAGIC ) {
  72906. console.error( 'THREE.DDSLoader.parse: Invalid magic number in DDS header.' );
  72907. return dds;
  72908. }
  72909. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  72910. console.error( 'THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code.' );
  72911. return dds;
  72912. }
  72913. var blockBytes;
  72914. var fourCC = header[ off_pfFourCC ];
  72915. var isRGBAUncompressed = false;
  72916. switch ( fourCC ) {
  72917. case FOURCC_DXT1:
  72918. blockBytes = 8;
  72919. dds.format = RGB_S3TC_DXT1_Format;
  72920. break;
  72921. case FOURCC_DXT3:
  72922. blockBytes = 16;
  72923. dds.format = RGBA_S3TC_DXT3_Format;
  72924. break;
  72925. case FOURCC_DXT5:
  72926. blockBytes = 16;
  72927. dds.format = RGBA_S3TC_DXT5_Format$1;
  72928. break;
  72929. case FOURCC_ETC1:
  72930. blockBytes = 8;
  72931. dds.format = RGB_ETC1_Format;
  72932. break;
  72933. default:
  72934. if ( header[ off_RGBBitCount ] === 32
  72935. && header[ off_RBitMask ] & 0xff0000
  72936. && header[ off_GBitMask ] & 0xff00
  72937. && header[ off_BBitMask ] & 0xff
  72938. && header[ off_ABitMask ] & 0xff000000 ) {
  72939. isRGBAUncompressed = true;
  72940. blockBytes = 64;
  72941. dds.format = RGBAFormat;
  72942. } else {
  72943. console.error( 'THREE.DDSLoader.parse: Unsupported FourCC code ', int32ToFourCC( fourCC ) );
  72944. return dds;
  72945. }
  72946. }
  72947. dds.mipmapCount = 1;
  72948. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  72949. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  72950. }
  72951. var caps2 = header[ off_caps2 ];
  72952. dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false;
  72953. if ( dds.isCubemap && (
  72954. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEX ) ||
  72955. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX ) ||
  72956. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEY ) ||
  72957. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY ) ||
  72958. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ ) ||
  72959. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ )
  72960. ) ) {
  72961. console.error( 'THREE.DDSLoader.parse: Incomplete cubemap faces' );
  72962. return dds;
  72963. }
  72964. dds.width = header[ off_width ];
  72965. dds.height = header[ off_height ];
  72966. var dataOffset = header[ off_size ] + 4;
  72967. // Extract mipmaps buffers
  72968. var faces = dds.isCubemap ? 6 : 1;
  72969. for ( var face = 0; face < faces; face ++ ) {
  72970. var width = dds.width;
  72971. var height = dds.height;
  72972. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  72973. if ( isRGBAUncompressed ) {
  72974. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  72975. var dataLength = byteArray.length;
  72976. } else {
  72977. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  72978. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  72979. }
  72980. var mipmap = { 'data': byteArray, 'width': width, 'height': height };
  72981. dds.mipmaps.push( mipmap );
  72982. dataOffset += dataLength;
  72983. width = Math.max( width >> 1, 1 );
  72984. height = Math.max( height >> 1, 1 );
  72985. }
  72986. }
  72987. return dds;
  72988. }
  72989. } );
  72990. var GLTFLoader = ( function () {
  72991. function GLTFLoader( manager, renderer, urlPrefix) {
  72992. Loader.call( this, manager );
  72993. /* this.dracoLoader = null;
  72994. this.ddsLoader = null;
  72995. this.ktx2Loader = null;
  72996. this.meshoptDecoder = null; */
  72997. //xzw add:
  72998. this.dracoLoader = new DRACOLoader;
  72999. this.ktx2Loader = new KTX2Loader;
  73000. this.meshoptDecoder = MeshoptDecoder;
  73001. this.ddsLoader = new DDSLoader; //这个没测过
  73002. //路径相对于index.html
  73003. this.dracoLoader.setDecoderPath( urlPrefix + 'three.js/loaders/draco/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/draco/gltf/' 版本可升级 */); //这两个路径可以自己改。在laser的环境也要放一份这个路径
  73004. this.ktx2Loader.setTranscoderPath(urlPrefix + 'three.js/loaders/ktx/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/basis/' 版本可升级 */).detectSupport( renderer );
  73005. //------------
  73006. this.pluginCallbacks = [];
  73007. this.register( function ( parser ) {
  73008. return new GLTFMaterialsClearcoatExtension( parser );
  73009. } );
  73010. this.register( function ( parser ) {
  73011. return new GLTFTextureBasisUExtension( parser );
  73012. } );
  73013. this.register( function ( parser ) {
  73014. return new GLTFTextureWebPExtension( parser );
  73015. } );
  73016. this.register( function ( parser ) {
  73017. return new GLTFMaterialsTransmissionExtension( parser );
  73018. } );
  73019. this.register( function ( parser ) {
  73020. return new GLTFLightsExtension( parser );
  73021. } );
  73022. this.register( function ( parser ) {
  73023. return new GLTFMeshoptCompression( parser );
  73024. } );
  73025. }
  73026. GLTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  73027. constructor: GLTFLoader,
  73028. load: function ( url, onLoad, onProgress, onError ) {
  73029. var scope = this;
  73030. var resourcePath;
  73031. if ( this.resourcePath !== '' ) {
  73032. resourcePath = this.resourcePath;
  73033. } else if ( this.path !== '' ) {
  73034. resourcePath = this.path;
  73035. } else {
  73036. resourcePath = LoaderUtils.extractUrlBase( url );
  73037. }
  73038. // Tells the LoadingManager to track an extra item, which resolves after
  73039. // the model is fully loaded. This means the count of items loaded will
  73040. // be incorrect, but ensures manager.onLoad() does not fire early.
  73041. this.manager.itemStart( url );
  73042. var _onError = function ( e ) {
  73043. if ( onError ) {
  73044. onError( e );
  73045. } else {
  73046. console.error( e );
  73047. }
  73048. scope.manager.itemError( url );
  73049. scope.manager.itemEnd( url );
  73050. };
  73051. var loader = new FileLoader( this.manager );
  73052. loader.setPath( this.path );
  73053. loader.setResponseType( 'arraybuffer' );
  73054. loader.setRequestHeader( this.requestHeader );
  73055. loader.setWithCredentials( this.withCredentials );
  73056. loader.load( url, function ( data, total ) {// xzw add total
  73057. console.log('数据加载成功', url.split('/').pop(), ' ,total: '+total);
  73058. let f = ()=>{
  73059. try {
  73060. scope.parse( data, resourcePath, function ( gltf ) {
  73061. onLoad( gltf, total );
  73062. scope.manager.itemEnd( url );
  73063. }, _onError );
  73064. } catch ( e ) {
  73065. _onError( e );
  73066. }
  73067. };
  73068. f();
  73069. //setTimeout(f,5000)/////////////////test
  73070. }, onProgress, _onError );
  73071. },
  73072. setDRACOLoader: function ( dracoLoader ) {
  73073. this.dracoLoader = dracoLoader;
  73074. return this;
  73075. },
  73076. setDDSLoader: function ( ddsLoader ) {
  73077. this.ddsLoader = ddsLoader;
  73078. return this;
  73079. },
  73080. setKTX2Loader: function ( ktx2Loader ) {
  73081. this.ktx2Loader = ktx2Loader;
  73082. return this;
  73083. },
  73084. setMeshoptDecoder: function ( meshoptDecoder ) {
  73085. this.meshoptDecoder = meshoptDecoder;
  73086. return this;
  73087. },
  73088. register: function ( callback ) {
  73089. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  73090. this.pluginCallbacks.push( callback );
  73091. }
  73092. return this;
  73093. },
  73094. unregister: function ( callback ) {
  73095. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  73096. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  73097. }
  73098. return this;
  73099. },
  73100. parse: function ( data, path, onLoad, onError ) {
  73101. var content;
  73102. var extensions = {};
  73103. var plugins = {};
  73104. if ( typeof data === 'string' ) {
  73105. content = data;
  73106. } else {
  73107. var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  73108. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  73109. try {
  73110. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  73111. } catch ( error ) {
  73112. if ( onError ) onError( error );
  73113. return;
  73114. }
  73115. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  73116. } else {
  73117. content = LoaderUtils.decodeText( new Uint8Array( data ) );
  73118. }
  73119. }
  73120. var json = JSON.parse( content );
  73121. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  73122. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  73123. return;
  73124. }
  73125. var parser = new GLTFParser( json, {
  73126. path: path || this.resourcePath || '',
  73127. crossOrigin: this.crossOrigin,
  73128. manager: this.manager,
  73129. ktx2Loader: this.ktx2Loader,
  73130. meshoptDecoder: this.meshoptDecoder,
  73131. } );
  73132. parser.unlitMat = this.unlitMat;//add
  73133. parser.fileLoader.setRequestHeader( this.requestHeader );
  73134. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  73135. var plugin = this.pluginCallbacks[ i ]( parser );
  73136. plugins[ plugin.name ] = plugin;
  73137. // Workaround to avoid determining as unknown extension
  73138. // in addUnknownExtensionsToUserData().
  73139. // Remove this workaround if we move all the existing
  73140. // extension handlers to plugin system
  73141. extensions[ plugin.name ] = true;
  73142. }
  73143. if ( json.extensionsUsed ) {
  73144. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  73145. var extensionName = json.extensionsUsed[ i ];
  73146. var extensionsRequired = json.extensionsRequired || [];
  73147. switch ( extensionName ) {
  73148. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  73149. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  73150. break;
  73151. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  73152. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  73153. break;
  73154. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  73155. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  73156. break;
  73157. case EXTENSIONS.MSFT_TEXTURE_DDS:
  73158. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  73159. break;
  73160. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  73161. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  73162. break;
  73163. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  73164. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  73165. break;
  73166. default:
  73167. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  73168. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  73169. }
  73170. }
  73171. }
  73172. }
  73173. parser.setExtensions( extensions );
  73174. parser.setPlugins( plugins );
  73175. parser.parse( onLoad, onError );
  73176. }
  73177. } );
  73178. /* GLTFREGISTRY */
  73179. function GLTFRegistry() {
  73180. var objects = {};
  73181. return {
  73182. get: function ( key ) {
  73183. return objects[ key ];
  73184. },
  73185. add: function ( key, object ) {
  73186. objects[ key ] = object;
  73187. },
  73188. remove: function ( key ) {
  73189. delete objects[ key ];
  73190. },
  73191. removeAll: function () {
  73192. objects = {};
  73193. }
  73194. };
  73195. }
  73196. /*********************************/
  73197. /********** EXTENSIONS ***********/
  73198. /*********************************/
  73199. var EXTENSIONS = {
  73200. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  73201. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  73202. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  73203. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  73204. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  73205. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  73206. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  73207. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  73208. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  73209. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  73210. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  73211. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  73212. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  73213. };
  73214. /**
  73215. * DDS Texture Extension
  73216. *
  73217. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  73218. *
  73219. */
  73220. function GLTFTextureDDSExtension( ddsLoader ) {
  73221. if ( ! ddsLoader ) {
  73222. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader' );
  73223. }
  73224. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  73225. this.ddsLoader = ddsLoader;
  73226. }
  73227. /**
  73228. * Punctual Lights Extension
  73229. *
  73230. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  73231. */
  73232. function GLTFLightsExtension( parser ) {
  73233. this.parser = parser;
  73234. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  73235. // Object3D instance caches
  73236. this.cache = { refs: {}, uses: {} };
  73237. }
  73238. GLTFLightsExtension.prototype._markDefs = function () {
  73239. var parser = this.parser;
  73240. var nodeDefs = this.parser.json.nodes || [];
  73241. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  73242. var nodeDef = nodeDefs[ nodeIndex ];
  73243. if ( nodeDef.extensions
  73244. && nodeDef.extensions[ this.name ]
  73245. && nodeDef.extensions[ this.name ].light !== undefined ) {
  73246. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  73247. }
  73248. }
  73249. };
  73250. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  73251. var parser = this.parser;
  73252. var cacheKey = 'light:' + lightIndex;
  73253. var dependency = parser.cache.get( cacheKey );
  73254. if ( dependency ) return dependency;
  73255. var json = parser.json;
  73256. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  73257. var lightDefs = extensions.lights || [];
  73258. var lightDef = lightDefs[ lightIndex ];
  73259. var lightNode;
  73260. var color = new Color( 0xffffff );
  73261. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  73262. var range = lightDef.range !== undefined ? lightDef.range : 0;
  73263. switch ( lightDef.type ) {
  73264. case 'directional':
  73265. lightNode = new DirectionalLight( color );
  73266. lightNode.target.position.set( 0, 0, - 1 );
  73267. lightNode.add( lightNode.target );
  73268. break;
  73269. case 'point':
  73270. lightNode = new PointLight( color );
  73271. lightNode.distance = range;
  73272. break;
  73273. case 'spot':
  73274. lightNode = new SpotLight( color );
  73275. lightNode.distance = range;
  73276. // Handle spotlight properties.
  73277. lightDef.spot = lightDef.spot || {};
  73278. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  73279. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  73280. lightNode.angle = lightDef.spot.outerConeAngle;
  73281. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  73282. lightNode.target.position.set( 0, 0, - 1 );
  73283. lightNode.add( lightNode.target );
  73284. break;
  73285. default:
  73286. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  73287. }
  73288. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  73289. // here, because node-level parsing will only override position if explicitly specified.
  73290. lightNode.position.set( 0, 0, 0 );
  73291. lightNode.decay = 2;
  73292. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  73293. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  73294. dependency = Promise.resolve( lightNode );
  73295. parser.cache.add( cacheKey, dependency );
  73296. return dependency;
  73297. };
  73298. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  73299. var self = this;
  73300. var parser = this.parser;
  73301. var json = parser.json;
  73302. var nodeDef = json.nodes[ nodeIndex ];
  73303. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  73304. var lightIndex = lightDef.light;
  73305. if ( lightIndex === undefined ) return null;
  73306. return this._loadLight( lightIndex ).then( function ( light ) {
  73307. return parser._getNodeRef( self.cache, lightIndex, light );
  73308. } );
  73309. };
  73310. /**
  73311. * Unlit Materials Extension
  73312. *
  73313. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  73314. */
  73315. function GLTFMaterialsUnlitExtension() {
  73316. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  73317. }
  73318. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  73319. return MeshBasicMaterial;
  73320. };
  73321. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  73322. var pending = [];
  73323. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  73324. materialParams.opacity = 1.0;
  73325. var metallicRoughness = materialDef.pbrMetallicRoughness;
  73326. if ( metallicRoughness ) {
  73327. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  73328. var array = metallicRoughness.baseColorFactor;
  73329. materialParams.color.fromArray( array );
  73330. materialParams.opacity = array[ 3 ];
  73331. }
  73332. if ( metallicRoughness.baseColorTexture !== undefined ) {
  73333. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  73334. }
  73335. }
  73336. return Promise.all( pending );
  73337. };
  73338. /**
  73339. * Clearcoat Materials Extension
  73340. *
  73341. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  73342. */
  73343. function GLTFMaterialsClearcoatExtension( parser ) {
  73344. this.parser = parser;
  73345. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  73346. }
  73347. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  73348. var parser = this.parser;
  73349. var materialDef = parser.json.materials[ materialIndex ];
  73350. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  73351. return MeshPhysicalMaterial;
  73352. };
  73353. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  73354. var parser = this.parser;
  73355. var materialDef = parser.json.materials[ materialIndex ];
  73356. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  73357. return Promise.resolve();
  73358. }
  73359. var pending = [];
  73360. var extension = materialDef.extensions[ this.name ];
  73361. if ( extension.clearcoatFactor !== undefined ) {
  73362. materialParams.clearcoat = extension.clearcoatFactor;
  73363. }
  73364. if ( extension.clearcoatTexture !== undefined ) {
  73365. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  73366. }
  73367. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  73368. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  73369. }
  73370. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  73371. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  73372. }
  73373. if ( extension.clearcoatNormalTexture !== undefined ) {
  73374. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  73375. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  73376. var scale = extension.clearcoatNormalTexture.scale;
  73377. materialParams.clearcoatNormalScale = new Vector2$1( scale, scale );
  73378. }
  73379. }
  73380. return Promise.all( pending );
  73381. };
  73382. /**
  73383. * Transmission Materials Extension
  73384. *
  73385. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  73386. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  73387. */
  73388. function GLTFMaterialsTransmissionExtension( parser ) {
  73389. this.parser = parser;
  73390. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  73391. }
  73392. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  73393. var parser = this.parser;
  73394. var materialDef = parser.json.materials[ materialIndex ];
  73395. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  73396. return MeshPhysicalMaterial;
  73397. };
  73398. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  73399. var parser = this.parser;
  73400. var materialDef = parser.json.materials[ materialIndex ];
  73401. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  73402. return Promise.resolve();
  73403. }
  73404. var pending = [];
  73405. var extension = materialDef.extensions[ this.name ];
  73406. if ( extension.transmissionFactor !== undefined ) {
  73407. materialParams.transmission = extension.transmissionFactor;
  73408. }
  73409. if ( extension.transmissionTexture !== undefined ) {
  73410. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  73411. }
  73412. return Promise.all( pending );
  73413. };
  73414. /**
  73415. * BasisU Texture Extension
  73416. *
  73417. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  73418. */
  73419. function GLTFTextureBasisUExtension( parser ) {
  73420. this.parser = parser;
  73421. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  73422. }
  73423. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  73424. var parser = this.parser;
  73425. var json = parser.json;
  73426. var textureDef = json.textures[ textureIndex ];
  73427. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  73428. return null;
  73429. }
  73430. var extension = textureDef.extensions[ this.name ];
  73431. var source = json.images[ extension.source ];
  73432. var loader = parser.options.ktx2Loader;
  73433. if ( ! loader ) {
  73434. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  73435. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  73436. } else {
  73437. // Assumes that the extension is optional and that a fallback texture is present
  73438. return null;
  73439. }
  73440. }
  73441. return parser.loadTextureImage( textureIndex, source, loader );
  73442. };
  73443. /**
  73444. * WebP Texture Extension
  73445. *
  73446. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  73447. */
  73448. function GLTFTextureWebPExtension( parser ) {
  73449. this.parser = parser;
  73450. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  73451. this.isSupported = null;
  73452. }
  73453. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  73454. var name = this.name;
  73455. var parser = this.parser;
  73456. var json = parser.json;
  73457. var textureDef = json.textures[ textureIndex ];
  73458. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  73459. return null;
  73460. }
  73461. var extension = textureDef.extensions[ name ];
  73462. var source = json.images[ extension.source ];
  73463. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  73464. return this.detectSupport().then( function ( isSupported ) {
  73465. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  73466. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  73467. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  73468. }
  73469. // Fall back to PNG or JPEG.
  73470. return parser.loadTexture( textureIndex );
  73471. } );
  73472. };
  73473. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  73474. if ( ! this.isSupported ) {
  73475. this.isSupported = new Promise( function ( resolve ) {
  73476. var image = new Image();
  73477. // Lossy test image. Support for lossy images doesn't guarantee support for all
  73478. // WebP images, unfortunately.
  73479. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  73480. image.onload = image.onerror = function () {
  73481. resolve( image.height === 1 );
  73482. };
  73483. } );
  73484. }
  73485. return this.isSupported;
  73486. };
  73487. /**
  73488. * meshopt BufferView Compression Extension
  73489. *
  73490. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  73491. */
  73492. function GLTFMeshoptCompression( parser ) {
  73493. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  73494. this.parser = parser;
  73495. }
  73496. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  73497. var json = this.parser.json;
  73498. var bufferView = json.bufferViews[ index ];
  73499. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  73500. var extensionDef = bufferView.extensions[ this.name ];
  73501. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  73502. var decoder = this.parser.options.meshoptDecoder;
  73503. if ( ! decoder || ! decoder.supported ) {
  73504. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  73505. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  73506. } else {
  73507. // Assumes that the extension is optional and that fallback buffer data is present
  73508. return null;
  73509. }
  73510. }
  73511. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  73512. var byteOffset = extensionDef.byteOffset || 0;
  73513. var byteLength = extensionDef.byteLength || 0;
  73514. var count = extensionDef.count;
  73515. var stride = extensionDef.byteStride;
  73516. var result = new ArrayBuffer( count * stride );
  73517. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  73518. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  73519. return result;
  73520. } );
  73521. } else {
  73522. return null;
  73523. }
  73524. };
  73525. /* BINARY EXTENSION */
  73526. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  73527. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  73528. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  73529. function GLTFBinaryExtension( data ) {
  73530. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  73531. this.content = null;
  73532. this.body = null;
  73533. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  73534. this.header = {
  73535. magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  73536. version: headerView.getUint32( 4, true ),
  73537. length: headerView.getUint32( 8, true )
  73538. };
  73539. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  73540. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  73541. } else if ( this.header.version < 2.0 ) {
  73542. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  73543. }
  73544. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  73545. var chunkIndex = 0;
  73546. while ( chunkIndex < chunkView.byteLength ) {
  73547. var chunkLength = chunkView.getUint32( chunkIndex, true );
  73548. chunkIndex += 4;
  73549. var chunkType = chunkView.getUint32( chunkIndex, true );
  73550. chunkIndex += 4;
  73551. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  73552. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  73553. this.content = LoaderUtils.decodeText( contentArray );
  73554. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  73555. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  73556. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  73557. }
  73558. // Clients must ignore chunks with unknown types.
  73559. chunkIndex += chunkLength;
  73560. }
  73561. if ( this.content === null ) {
  73562. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  73563. }
  73564. }
  73565. /**
  73566. * DRACO Mesh Compression Extension
  73567. *
  73568. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  73569. */
  73570. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  73571. if ( ! dracoLoader ) {
  73572. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  73573. }
  73574. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  73575. this.json = json;
  73576. this.dracoLoader = dracoLoader;
  73577. this.dracoLoader.preload();
  73578. }
  73579. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  73580. var json = this.json;
  73581. var dracoLoader = this.dracoLoader;
  73582. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  73583. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  73584. var threeAttributeMap = {};
  73585. var attributeNormalizedMap = {};
  73586. var attributeTypeMap = {};
  73587. for ( var attributeName in gltfAttributeMap ) {
  73588. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  73589. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  73590. }
  73591. for ( attributeName in primitive.attributes ) {
  73592. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  73593. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  73594. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  73595. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  73596. attributeTypeMap[ threeAttributeName ] = componentType;
  73597. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  73598. }
  73599. }
  73600. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  73601. return new Promise( function ( resolve ) {
  73602. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  73603. for ( var attributeName in geometry.attributes ) {
  73604. var attribute = geometry.attributes[ attributeName ];
  73605. var normalized = attributeNormalizedMap[ attributeName ];
  73606. if ( normalized !== undefined ) attribute.normalized = normalized;
  73607. }
  73608. resolve( geometry );
  73609. }, threeAttributeMap, attributeTypeMap );
  73610. } );
  73611. } );
  73612. };
  73613. /**
  73614. * Texture Transform Extension
  73615. *
  73616. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  73617. */
  73618. function GLTFTextureTransformExtension() {
  73619. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  73620. }
  73621. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  73622. texture = texture.clone();
  73623. if ( transform.offset !== undefined ) {
  73624. texture.offset.fromArray( transform.offset );
  73625. }
  73626. if ( transform.rotation !== undefined ) {
  73627. texture.rotation = transform.rotation;
  73628. }
  73629. if ( transform.scale !== undefined ) {
  73630. texture.repeat.fromArray( transform.scale );
  73631. }
  73632. if ( transform.texCoord !== undefined ) {
  73633. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  73634. }
  73635. texture.needsUpdate = true;
  73636. return texture;
  73637. };
  73638. /**
  73639. * Specular-Glossiness Extension
  73640. *
  73641. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  73642. */
  73643. /**
  73644. * A sub class of StandardMaterial with some of the functionality
  73645. * changed via the `onBeforeCompile` callback
  73646. * @pailhead
  73647. */
  73648. function GLTFMeshStandardSGMaterial( params ) {
  73649. MeshStandardMaterial.call( this );
  73650. this.isGLTFSpecularGlossinessMaterial = true;
  73651. //various chunks that need replacing
  73652. var specularMapParsFragmentChunk = [
  73653. '#ifdef USE_SPECULARMAP',
  73654. ' uniform sampler2D specularMap;',
  73655. '#endif'
  73656. ].join( '\n' );
  73657. var glossinessMapParsFragmentChunk = [
  73658. '#ifdef USE_GLOSSINESSMAP',
  73659. ' uniform sampler2D glossinessMap;',
  73660. '#endif'
  73661. ].join( '\n' );
  73662. var specularMapFragmentChunk = [
  73663. 'vec3 specularFactor = specular;',
  73664. '#ifdef USE_SPECULARMAP',
  73665. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  73666. ' texelSpecular = sRGBToLinear( texelSpecular );',
  73667. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  73668. ' specularFactor *= texelSpecular.rgb;',
  73669. '#endif'
  73670. ].join( '\n' );
  73671. var glossinessMapFragmentChunk = [
  73672. 'float glossinessFactor = glossiness;',
  73673. '#ifdef USE_GLOSSINESSMAP',
  73674. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  73675. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  73676. ' glossinessFactor *= texelGlossiness.a;',
  73677. '#endif'
  73678. ].join( '\n' );
  73679. var lightPhysicalFragmentChunk = [
  73680. 'PhysicalMaterial material;',
  73681. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  73682. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  73683. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  73684. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  73685. 'material.specularRoughness += geometryRoughness;',
  73686. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  73687. 'material.specularColor = specularFactor;',
  73688. ].join( '\n' );
  73689. var uniforms = {
  73690. specular: { value: new Color().setHex( 0xffffff ) },
  73691. glossiness: { value: 1 },
  73692. specularMap: { value: null },
  73693. glossinessMap: { value: null }
  73694. };
  73695. this._extraUniforms = uniforms;
  73696. this.onBeforeCompile = function ( shader ) {
  73697. for ( var uniformName in uniforms ) {
  73698. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  73699. }
  73700. shader.fragmentShader = shader.fragmentShader
  73701. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  73702. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  73703. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  73704. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  73705. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  73706. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  73707. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  73708. };
  73709. Object.defineProperties( this, {
  73710. specular: {
  73711. get: function () {
  73712. return uniforms.specular.value;
  73713. },
  73714. set: function ( v ) {
  73715. uniforms.specular.value = v;
  73716. }
  73717. },
  73718. specularMap: {
  73719. get: function () {
  73720. return uniforms.specularMap.value;
  73721. },
  73722. set: function ( v ) {
  73723. uniforms.specularMap.value = v;
  73724. if ( v ) {
  73725. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  73726. } else {
  73727. delete this.defines.USE_SPECULARMAP;
  73728. }
  73729. }
  73730. },
  73731. glossiness: {
  73732. get: function () {
  73733. return uniforms.glossiness.value;
  73734. },
  73735. set: function ( v ) {
  73736. uniforms.glossiness.value = v;
  73737. }
  73738. },
  73739. glossinessMap: {
  73740. get: function () {
  73741. return uniforms.glossinessMap.value;
  73742. },
  73743. set: function ( v ) {
  73744. uniforms.glossinessMap.value = v;
  73745. if ( v ) {
  73746. this.defines.USE_GLOSSINESSMAP = '';
  73747. this.defines.USE_UV = '';
  73748. } else {
  73749. delete this.defines.USE_GLOSSINESSMAP;
  73750. delete this.defines.USE_UV;
  73751. }
  73752. }
  73753. }
  73754. } );
  73755. delete this.metalness;
  73756. delete this.roughness;
  73757. delete this.metalnessMap;
  73758. delete this.roughnessMap;
  73759. this.setValues( params );
  73760. }
  73761. GLTFMeshStandardSGMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  73762. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  73763. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  73764. MeshStandardMaterial.prototype.copy.call( this, source );
  73765. this.specularMap = source.specularMap;
  73766. this.specular.copy( source.specular );
  73767. this.glossinessMap = source.glossinessMap;
  73768. this.glossiness = source.glossiness;
  73769. delete this.metalness;
  73770. delete this.roughness;
  73771. delete this.metalnessMap;
  73772. delete this.roughnessMap;
  73773. return this;
  73774. };
  73775. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  73776. return {
  73777. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  73778. specularGlossinessParams: [
  73779. 'color',
  73780. 'map',
  73781. 'lightMap',
  73782. 'lightMapIntensity',
  73783. 'aoMap',
  73784. 'aoMapIntensity',
  73785. 'emissive',
  73786. 'emissiveIntensity',
  73787. 'emissiveMap',
  73788. 'bumpMap',
  73789. 'bumpScale',
  73790. 'normalMap',
  73791. 'normalMapType',
  73792. 'displacementMap',
  73793. 'displacementScale',
  73794. 'displacementBias',
  73795. 'specularMap',
  73796. 'specular',
  73797. 'glossinessMap',
  73798. 'glossiness',
  73799. 'alphaMap',
  73800. 'envMap',
  73801. 'envMapIntensity',
  73802. 'refractionRatio',
  73803. ],
  73804. getMaterialType: function () {
  73805. return GLTFMeshStandardSGMaterial;
  73806. },
  73807. extendParams: function ( materialParams, materialDef, parser ) {
  73808. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  73809. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  73810. materialParams.opacity = 1.0;
  73811. var pending = [];
  73812. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  73813. var array = pbrSpecularGlossiness.diffuseFactor;
  73814. materialParams.color.fromArray( array );
  73815. materialParams.opacity = array[ 3 ];
  73816. }
  73817. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  73818. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  73819. }
  73820. materialParams.emissive = new Color( 0.0, 0.0, 0.0 );
  73821. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  73822. materialParams.specular = new Color( 1.0, 1.0, 1.0 );
  73823. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  73824. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  73825. }
  73826. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  73827. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  73828. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  73829. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  73830. }
  73831. return Promise.all( pending );
  73832. },
  73833. createMaterial: function ( materialParams ) {
  73834. var material = new GLTFMeshStandardSGMaterial( materialParams );
  73835. material.fog = true;
  73836. material.color = materialParams.color;
  73837. material.map = materialParams.map === undefined ? null : materialParams.map;
  73838. material.lightMap = null;
  73839. material.lightMapIntensity = 1.0;
  73840. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  73841. material.aoMapIntensity = 1.0;
  73842. material.emissive = materialParams.emissive;
  73843. material.emissiveIntensity = 1.0;
  73844. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  73845. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  73846. material.bumpScale = 1;
  73847. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  73848. material.normalMapType = TangentSpaceNormalMap;
  73849. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  73850. material.displacementMap = null;
  73851. material.displacementScale = 1;
  73852. material.displacementBias = 0;
  73853. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  73854. material.specular = materialParams.specular;
  73855. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  73856. material.glossiness = materialParams.glossiness;
  73857. material.alphaMap = null;
  73858. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  73859. material.envMapIntensity = 1.0;
  73860. material.refractionRatio = 0.98;
  73861. return material;
  73862. },
  73863. };
  73864. }
  73865. /**
  73866. * Mesh Quantization Extension
  73867. *
  73868. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  73869. */
  73870. function GLTFMeshQuantizationExtension() {
  73871. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  73872. }
  73873. /*********************************/
  73874. /********** INTERPOLATION ********/
  73875. /*********************************/
  73876. // Spline Interpolation
  73877. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  73878. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  73879. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  73880. }
  73881. GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype );
  73882. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  73883. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  73884. // Copies a sample value to the result buffer. See description of glTF
  73885. // CUBICSPLINE values layout in interpolate_() function below.
  73886. var result = this.resultBuffer,
  73887. values = this.sampleValues,
  73888. valueSize = this.valueSize,
  73889. offset = index * valueSize * 3 + valueSize;
  73890. for ( var i = 0; i !== valueSize; i ++ ) {
  73891. result[ i ] = values[ offset + i ];
  73892. }
  73893. return result;
  73894. };
  73895. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  73896. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  73897. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  73898. var result = this.resultBuffer;
  73899. var values = this.sampleValues;
  73900. var stride = this.valueSize;
  73901. var stride2 = stride * 2;
  73902. var stride3 = stride * 3;
  73903. var td = t1 - t0;
  73904. var p = ( t - t0 ) / td;
  73905. var pp = p * p;
  73906. var ppp = pp * p;
  73907. var offset1 = i1 * stride3;
  73908. var offset0 = offset1 - stride3;
  73909. var s2 = - 2 * ppp + 3 * pp;
  73910. var s3 = ppp - pp;
  73911. var s0 = 1 - s2;
  73912. var s1 = s3 - pp + p;
  73913. // Layout of keyframe output values for CUBICSPLINE animations:
  73914. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  73915. for ( var i = 0; i !== stride; i ++ ) {
  73916. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  73917. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  73918. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  73919. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  73920. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  73921. }
  73922. return result;
  73923. };
  73924. /*********************************/
  73925. /********** INTERNALS ************/
  73926. /*********************************/
  73927. /* CONSTANTS */
  73928. var WEBGL_CONSTANTS = {
  73929. FLOAT: 5126,
  73930. //FLOAT_MAT2: 35674,
  73931. FLOAT_MAT3: 35675,
  73932. FLOAT_MAT4: 35676,
  73933. FLOAT_VEC2: 35664,
  73934. FLOAT_VEC3: 35665,
  73935. FLOAT_VEC4: 35666,
  73936. LINEAR: 9729,
  73937. REPEAT: 10497,
  73938. SAMPLER_2D: 35678,
  73939. POINTS: 0,
  73940. LINES: 1,
  73941. LINE_LOOP: 2,
  73942. LINE_STRIP: 3,
  73943. TRIANGLES: 4,
  73944. TRIANGLE_STRIP: 5,
  73945. TRIANGLE_FAN: 6,
  73946. UNSIGNED_BYTE: 5121,
  73947. UNSIGNED_SHORT: 5123
  73948. };
  73949. var WEBGL_COMPONENT_TYPES = {
  73950. 5120: Int8Array,
  73951. 5121: Uint8Array,
  73952. 5122: Int16Array,
  73953. 5123: Uint16Array,
  73954. 5125: Uint32Array,
  73955. 5126: Float32Array
  73956. };
  73957. var WEBGL_FILTERS = {
  73958. 9728: NearestFilter,
  73959. 9729: LinearFilter,
  73960. 9984: NearestMipmapNearestFilter,
  73961. 9985: LinearMipmapNearestFilter,
  73962. 9986: NearestMipmapLinearFilter,
  73963. 9987: LinearMipmapLinearFilter
  73964. };
  73965. var WEBGL_WRAPPINGS = {
  73966. 33071: ClampToEdgeWrapping,
  73967. 33648: MirroredRepeatWrapping,
  73968. 10497: RepeatWrapping
  73969. };
  73970. var WEBGL_TYPE_SIZES = {
  73971. 'SCALAR': 1,
  73972. 'VEC2': 2,
  73973. 'VEC3': 3,
  73974. 'VEC4': 4,
  73975. 'MAT2': 4,
  73976. 'MAT3': 9,
  73977. 'MAT4': 16
  73978. };
  73979. var ATTRIBUTES = {
  73980. POSITION: 'position',
  73981. NORMAL: 'normal',
  73982. TANGENT: 'tangent',
  73983. TEXCOORD_0: 'uv',
  73984. TEXCOORD_1: 'uv2',
  73985. COLOR_0: 'color',
  73986. WEIGHTS_0: 'skinWeight',
  73987. JOINTS_0: 'skinIndex',
  73988. };
  73989. var PATH_PROPERTIES = {
  73990. scale: 'scale',
  73991. translation: 'position',
  73992. rotation: 'quaternion',
  73993. weights: 'morphTargetInfluences'
  73994. };
  73995. var INTERPOLATION = {
  73996. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  73997. // keyframe track will be initialized with a default interpolation type, then modified.
  73998. LINEAR: InterpolateLinear,
  73999. STEP: InterpolateDiscrete
  74000. };
  74001. var ALPHA_MODES = {
  74002. OPAQUE: 'OPAQUE',
  74003. MASK: 'MASK',
  74004. BLEND: 'BLEND'
  74005. };
  74006. /* UTILITY FUNCTIONS */
  74007. function resolveURL( url, path ) {
  74008. // Invalid URL
  74009. if ( typeof url !== 'string' || url === '' ) return '';
  74010. // Host Relative URL
  74011. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  74012. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  74013. }
  74014. // Absolute URL http://,https://,//
  74015. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  74016. // Data URI
  74017. if ( /^data:.*,.*$/i.test( url ) ) return url;
  74018. // Blob URL
  74019. if ( /^blob:.*$/i.test( url ) ) return url;
  74020. // Relative URL
  74021. return path + url;
  74022. }
  74023. /**
  74024. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  74025. */
  74026. function createDefaultMaterial( cache ) {
  74027. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  74028. cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {
  74029. color: 0xFFFFFF,
  74030. emissive: 0x000000,
  74031. metalness: 1,
  74032. roughness: 1,
  74033. transparent: false,
  74034. depthTest: true,
  74035. side: FrontSide
  74036. } );
  74037. }
  74038. return cache[ 'DefaultMaterial' ];
  74039. }
  74040. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  74041. // Add unknown glTF extensions to an object's userData.
  74042. for ( var name in objectDef.extensions ) {
  74043. if ( knownExtensions[ name ] === undefined ) {
  74044. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  74045. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  74046. }
  74047. }
  74048. }
  74049. /**
  74050. * @param {Object3D|Material|BufferGeometry} object
  74051. * @param {GLTF.definition} gltfDef
  74052. */
  74053. function assignExtrasToUserData( object, gltfDef ) {
  74054. if ( gltfDef.extras !== undefined ) {
  74055. if ( typeof gltfDef.extras === 'object' ) {
  74056. Object.assign( object.userData, gltfDef.extras );
  74057. } else {
  74058. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  74059. }
  74060. }
  74061. }
  74062. /**
  74063. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  74064. *
  74065. * @param {BufferGeometry} geometry
  74066. * @param {Array<GLTF.Target>} targets
  74067. * @param {GLTFParser} parser
  74068. * @return {Promise<BufferGeometry>}
  74069. */
  74070. function addMorphTargets( geometry, targets, parser ) {
  74071. var hasMorphPosition = false;
  74072. var hasMorphNormal = false;
  74073. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74074. var target = targets[ i ];
  74075. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  74076. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  74077. if ( hasMorphPosition && hasMorphNormal ) break;
  74078. }
  74079. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  74080. var pendingPositionAccessors = [];
  74081. var pendingNormalAccessors = [];
  74082. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74083. var target = targets[ i ];
  74084. if ( hasMorphPosition ) {
  74085. var pendingAccessor = target.POSITION !== undefined
  74086. ? parser.getDependency( 'accessor', target.POSITION )
  74087. : geometry.attributes.position;
  74088. pendingPositionAccessors.push( pendingAccessor );
  74089. }
  74090. if ( hasMorphNormal ) {
  74091. var pendingAccessor = target.NORMAL !== undefined
  74092. ? parser.getDependency( 'accessor', target.NORMAL )
  74093. : geometry.attributes.normal;
  74094. pendingNormalAccessors.push( pendingAccessor );
  74095. }
  74096. }
  74097. return Promise.all( [
  74098. Promise.all( pendingPositionAccessors ),
  74099. Promise.all( pendingNormalAccessors )
  74100. ] ).then( function ( accessors ) {
  74101. var morphPositions = accessors[ 0 ];
  74102. var morphNormals = accessors[ 1 ];
  74103. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  74104. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  74105. geometry.morphTargetsRelative = true;
  74106. return geometry;
  74107. } );
  74108. }
  74109. /**
  74110. * @param {Mesh} mesh
  74111. * @param {GLTF.Mesh} meshDef
  74112. */
  74113. function updateMorphTargets( mesh, meshDef ) {
  74114. mesh.updateMorphTargets();
  74115. if ( meshDef.weights !== undefined ) {
  74116. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  74117. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  74118. }
  74119. }
  74120. // .extras has user-defined data, so check that .extras.targetNames is an array.
  74121. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  74122. var targetNames = meshDef.extras.targetNames;
  74123. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  74124. mesh.morphTargetDictionary = {};
  74125. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  74126. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  74127. }
  74128. } else {
  74129. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  74130. }
  74131. }
  74132. }
  74133. function createPrimitiveKey( primitiveDef ) {
  74134. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  74135. var geometryKey;
  74136. if ( dracoExtension ) {
  74137. geometryKey = 'draco:' + dracoExtension.bufferView
  74138. + ':' + dracoExtension.indices
  74139. + ':' + createAttributesKey( dracoExtension.attributes );
  74140. } else {
  74141. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  74142. }
  74143. return geometryKey;
  74144. }
  74145. function createAttributesKey( attributes ) {
  74146. var attributesKey = '';
  74147. var keys = Object.keys( attributes ).sort();
  74148. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  74149. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  74150. }
  74151. return attributesKey;
  74152. }
  74153. /* GLTF PARSER */
  74154. function GLTFParser( json, options ) {
  74155. this.json = json || {};
  74156. this.extensions = {};
  74157. this.plugins = {};
  74158. this.options = options || {};
  74159. // loader object cache
  74160. this.cache = new GLTFRegistry();
  74161. // associations between Three.js objects and glTF elements
  74162. this.associations = new Map();
  74163. // BufferGeometry caching
  74164. this.primitiveCache = {};
  74165. // Object3D instance caches
  74166. this.meshCache = { refs: {}, uses: {} };
  74167. this.cameraCache = { refs: {}, uses: {} };
  74168. this.lightCache = { refs: {}, uses: {} };
  74169. // Track node names, to ensure no duplicates
  74170. this.nodeNamesUsed = {};
  74171. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  74172. // expensive work of uploading a texture to the GPU off the main thread.
  74173. /* if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  74174. this.textureLoader = new ImageBitmapLoader( this.options.manager );
  74175. } else { */
  74176. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,改用TextureLoader by xzw
  74177. this.textureLoader = new TextureLoader( this.options.manager );
  74178. //}
  74179. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  74180. this.fileLoader = new FileLoader( this.options.manager );
  74181. this.fileLoader.setResponseType( 'arraybuffer' );
  74182. if ( this.options.crossOrigin === 'use-credentials' ) {
  74183. this.fileLoader.setWithCredentials( true );
  74184. }
  74185. }
  74186. GLTFParser.prototype.setExtensions = function ( extensions ) {
  74187. this.extensions = extensions;
  74188. };
  74189. GLTFParser.prototype.setPlugins = function ( plugins ) {
  74190. this.plugins = plugins;
  74191. };
  74192. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  74193. var parser = this;
  74194. var json = this.json;
  74195. var extensions = this.extensions;
  74196. // Clear the loader cache
  74197. this.cache.removeAll();
  74198. // Mark the special nodes/meshes in json for efficient parse
  74199. this._invokeAll( function ( ext ) {
  74200. return ext._markDefs && ext._markDefs();
  74201. } );
  74202. Promise.all( [
  74203. this.getDependencies( 'scene' ),
  74204. this.getDependencies( 'animation' ),
  74205. this.getDependencies( 'camera' ),
  74206. ] ).then( function ( dependencies ) {
  74207. var result = {
  74208. scene: dependencies[ 0 ][ json.scene || 0 ],
  74209. scenes: dependencies[ 0 ],
  74210. animations: dependencies[ 1 ],
  74211. cameras: dependencies[ 2 ],
  74212. asset: json.asset,
  74213. parser: parser,
  74214. userData: {}
  74215. };
  74216. addUnknownExtensionsToUserData( extensions, result, json );
  74217. assignExtrasToUserData( result, json );
  74218. onLoad( result );
  74219. } ).catch( onError );
  74220. };
  74221. /**
  74222. * Marks the special nodes/meshes in json for efficient parse.
  74223. */
  74224. GLTFParser.prototype._markDefs = function () {
  74225. var nodeDefs = this.json.nodes || [];
  74226. var skinDefs = this.json.skins || [];
  74227. var meshDefs = this.json.meshes || [];
  74228. // Nothing in the node definition indicates whether it is a Bone or an
  74229. // Object3D. Use the skins' joint references to mark bones.
  74230. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  74231. var joints = skinDefs[ skinIndex ].joints;
  74232. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  74233. nodeDefs[ joints[ i ] ].isBone = true;
  74234. }
  74235. }
  74236. // Iterate over all nodes, marking references to shared resources,
  74237. // as well as skeleton joints.
  74238. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  74239. var nodeDef = nodeDefs[ nodeIndex ];
  74240. if ( nodeDef.mesh !== undefined ) {
  74241. this._addNodeRef( this.meshCache, nodeDef.mesh );
  74242. // Nothing in the mesh definition indicates whether it is
  74243. // a SkinnedMesh or Mesh. Use the node's mesh reference
  74244. // to mark SkinnedMesh if node has skin.
  74245. if ( nodeDef.skin !== undefined ) {
  74246. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  74247. }
  74248. }
  74249. if ( nodeDef.camera !== undefined ) {
  74250. this._addNodeRef( this.cameraCache, nodeDef.camera );
  74251. }
  74252. }
  74253. };
  74254. /**
  74255. * Counts references to shared node / Object3D resources. These resources
  74256. * can be reused, or "instantiated", at multiple nodes in the scene
  74257. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  74258. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  74259. * Textures) can be reused directly and are not marked here.
  74260. *
  74261. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  74262. */
  74263. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  74264. if ( index === undefined ) return;
  74265. if ( cache.refs[ index ] === undefined ) {
  74266. cache.refs[ index ] = cache.uses[ index ] = 0;
  74267. }
  74268. cache.refs[ index ] ++;
  74269. };
  74270. /** Returns a reference to a shared resource, cloning it if necessary. */
  74271. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  74272. if ( cache.refs[ index ] <= 1 ) return object;
  74273. var ref = object.clone();
  74274. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  74275. return ref;
  74276. };
  74277. GLTFParser.prototype._invokeOne = function ( func ) {
  74278. var extensions = Object.values( this.plugins );
  74279. extensions.push( this );
  74280. for ( var i = 0; i < extensions.length; i ++ ) {
  74281. var result = func( extensions[ i ] );
  74282. if ( result ) return result;
  74283. }
  74284. };
  74285. GLTFParser.prototype._invokeAll = function ( func ) {
  74286. var extensions = Object.values( this.plugins );
  74287. extensions.unshift( this );
  74288. var pending = [];
  74289. for ( var i = 0; i < extensions.length; i ++ ) {
  74290. var result = func( extensions[ i ] );
  74291. if ( result ) pending.push( result );
  74292. }
  74293. return pending;
  74294. };
  74295. /**
  74296. * Requests the specified dependency asynchronously, with caching.
  74297. * @param {string} type
  74298. * @param {number} index
  74299. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  74300. */
  74301. GLTFParser.prototype.getDependency = function ( type, index ) {
  74302. var cacheKey = type + ':' + index;
  74303. var dependency = this.cache.get( cacheKey );
  74304. if ( ! dependency ) {
  74305. switch ( type ) {
  74306. case 'scene':
  74307. dependency = this.loadScene( index );
  74308. break;
  74309. case 'node':
  74310. dependency = this.loadNode( index );
  74311. break;
  74312. case 'mesh':
  74313. dependency = this._invokeOne( function ( ext ) {
  74314. return ext.loadMesh && ext.loadMesh( index );
  74315. } );
  74316. break;
  74317. case 'accessor':
  74318. dependency = this.loadAccessor( index );
  74319. break;
  74320. case 'bufferView':
  74321. dependency = this._invokeOne( function ( ext ) {
  74322. return ext.loadBufferView && ext.loadBufferView( index );
  74323. } );
  74324. break;
  74325. case 'buffer':
  74326. dependency = this.loadBuffer( index );
  74327. break;
  74328. case 'material':
  74329. dependency = this._invokeOne( function ( ext ) {
  74330. return ext.loadMaterial && ext.loadMaterial( index );
  74331. } );
  74332. break;
  74333. case 'texture':
  74334. dependency = this._invokeOne( function ( ext ) {
  74335. return ext.loadTexture && ext.loadTexture( index );
  74336. } );
  74337. break;
  74338. case 'skin':
  74339. dependency = this.loadSkin( index );
  74340. break;
  74341. case 'animation':
  74342. dependency = this.loadAnimation( index );
  74343. break;
  74344. case 'camera':
  74345. dependency = this.loadCamera( index );
  74346. break;
  74347. default:
  74348. throw new Error( 'Unknown type: ' + type );
  74349. }
  74350. this.cache.add( cacheKey, dependency );
  74351. }
  74352. return dependency;
  74353. };
  74354. /**
  74355. * Requests all dependencies of the specified type asynchronously, with caching.
  74356. * @param {string} type
  74357. * @return {Promise<Array<Object>>}
  74358. */
  74359. GLTFParser.prototype.getDependencies = function ( type ) {
  74360. var dependencies = this.cache.get( type );
  74361. if ( ! dependencies ) {
  74362. var parser = this;
  74363. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  74364. dependencies = Promise.all( defs.map( function ( def, index ) {
  74365. return parser.getDependency( type, index );
  74366. } ) );
  74367. this.cache.add( type, dependencies );
  74368. }
  74369. return dependencies;
  74370. };
  74371. /**
  74372. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  74373. * @param {number} bufferIndex
  74374. * @return {Promise<ArrayBuffer>}
  74375. */
  74376. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  74377. var bufferDef = this.json.buffers[ bufferIndex ];
  74378. var loader = this.fileLoader;
  74379. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  74380. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  74381. }
  74382. // If present, GLB container is required to be the first buffer.
  74383. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  74384. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  74385. }
  74386. var options = this.options;
  74387. return new Promise( function ( resolve, reject ) {
  74388. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  74389. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  74390. } );
  74391. } );
  74392. };
  74393. /**
  74394. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  74395. * @param {number} bufferViewIndex
  74396. * @return {Promise<ArrayBuffer>}
  74397. */
  74398. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  74399. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  74400. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  74401. var byteLength = bufferViewDef.byteLength || 0;
  74402. var byteOffset = bufferViewDef.byteOffset || 0;
  74403. return buffer.slice( byteOffset, byteOffset + byteLength );
  74404. } );
  74405. };
  74406. /**
  74407. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  74408. * @param {number} accessorIndex
  74409. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  74410. */
  74411. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  74412. var parser = this;
  74413. var json = this.json;
  74414. var accessorDef = this.json.accessors[ accessorIndex ];
  74415. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  74416. // Ignore empty accessors, which may be used to declare runtime
  74417. // information about attributes coming from another source (e.g. Draco
  74418. // compression extension).
  74419. return Promise.resolve( null );
  74420. }
  74421. var pendingBufferViews = [];
  74422. if ( accessorDef.bufferView !== undefined ) {
  74423. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  74424. } else {
  74425. pendingBufferViews.push( null );
  74426. }
  74427. if ( accessorDef.sparse !== undefined ) {
  74428. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  74429. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  74430. }
  74431. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  74432. var bufferView = bufferViews[ 0 ];
  74433. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  74434. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  74435. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  74436. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  74437. var itemBytes = elementBytes * itemSize;
  74438. var byteOffset = accessorDef.byteOffset || 0;
  74439. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  74440. var normalized = accessorDef.normalized === true;
  74441. var array, bufferAttribute;
  74442. // The buffer is not interleaved if the stride is the item size in bytes.
  74443. if ( byteStride && byteStride !== itemBytes ) {
  74444. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  74445. // This makes sure that IBA.count reflects accessor.count properly
  74446. var ibSlice = Math.floor( byteOffset / byteStride );
  74447. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  74448. var ib = parser.cache.get( ibCacheKey );
  74449. if ( ! ib ) {
  74450. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  74451. // Integer parameters to IB/IBA are in array elements, not bytes.
  74452. ib = new InterleavedBuffer( array, byteStride / elementBytes );
  74453. parser.cache.add( ibCacheKey, ib );
  74454. }
  74455. bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  74456. } else {
  74457. if ( bufferView === null ) {
  74458. array = new TypedArray( accessorDef.count * itemSize );
  74459. } else {
  74460. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  74461. }
  74462. bufferAttribute = new BufferAttribute( array, itemSize, normalized );
  74463. }
  74464. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  74465. if ( accessorDef.sparse !== undefined ) {
  74466. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  74467. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  74468. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  74469. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  74470. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  74471. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  74472. if ( bufferView !== null ) {
  74473. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  74474. bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  74475. }
  74476. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  74477. var index = sparseIndices[ i ];
  74478. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  74479. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  74480. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  74481. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  74482. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  74483. }
  74484. }
  74485. return bufferAttribute;
  74486. } );
  74487. };
  74488. /**
  74489. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  74490. * @param {number} textureIndex
  74491. * @return {Promise<THREE.Texture>}
  74492. */
  74493. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  74494. var parser = this;
  74495. var json = this.json;
  74496. var options = this.options;
  74497. var textureDef = json.textures[ textureIndex ];
  74498. var textureExtensions = textureDef.extensions || {};
  74499. var source;
  74500. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  74501. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  74502. } else {
  74503. source = json.images[ textureDef.source ];
  74504. }
  74505. var loader;
  74506. if ( source.uri ) {
  74507. loader = options.manager.getHandler( source.uri );
  74508. }
  74509. if ( ! loader ) {
  74510. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  74511. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  74512. : this.textureLoader;
  74513. }
  74514. return this.loadTextureImage( textureIndex, source, loader );
  74515. };
  74516. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  74517. var parser = this;
  74518. var json = this.json;
  74519. var options = this.options;
  74520. var textureDef = json.textures[ textureIndex ];
  74521. var URL = self.URL || self.webkitURL;
  74522. var sourceURI = source.uri;
  74523. var isObjectURL = false;
  74524. var hasAlpha = true;
  74525. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  74526. if ( source.bufferView !== undefined ) {
  74527. // Load binary image data from bufferView, if provided.
  74528. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  74529. if ( source.mimeType === 'image/png' ) {
  74530. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  74531. // alpha channel. This check is conservative — the image could have an alpha
  74532. // channel with all values == 1, and the indexed type (colorType == 3) only
  74533. // sometimes contains alpha.
  74534. //
  74535. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  74536. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  74537. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  74538. }
  74539. isObjectURL = true;
  74540. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  74541. sourceURI = URL.createObjectURL( blob );
  74542. return sourceURI;
  74543. } );
  74544. }
  74545. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  74546. return new Promise( function ( resolve, reject ) {
  74547. /* var onLoad = resolve;
  74548. if ( loader.isImageBitmapLoader === true ) {
  74549. onLoad = function ( imageBitmap ) {
  74550. //console.log('resolveURL onLoad',textureIndex )
  74551. resolve( new CanvasTexture( imageBitmap ) );
  74552. };
  74553. }
  74554. */
  74555. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,重新写贴图加载方式:
  74556. parser.textureLoader.load(sourceURI, (tex)=>{
  74557. tex.minFilter = THREE.LinearMipmapLinearFilter; //原本:NearestMipMapNearestFilter 闪烁
  74558. //tex.needsUpdate
  74559. resolve(tex);
  74560. });
  74561. return;
  74562. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, (e,url)=>{
  74563. console.log('reject',textureIndex, arguments);
  74564. if ( loader.isImageBitmapLoader === true ) {
  74565. let img = new Image;
  74566. img.setAttribute('crossOrigin', 'Anonymous');
  74567. img.src = url;
  74568. resolve(new THREE.Texture(img));
  74569. /* img.onload = ()=>{
  74570. let canvas = document.createElement('canvas')
  74571. let context = canvas.getContext('2d')
  74572. context.canvas.width = img.width
  74573. context.canvas.height = img.height
  74574. context.drawImage(img, 0, 0, img.width, img.height)
  74575. resolve( new CanvasTexture( canvas ) );
  74576. console.log('自己绘制 onload', textureIndex)
  74577. } */
  74578. }else {
  74579. reject.apply(this,arguments);
  74580. }
  74581. } /* , reject */ );
  74582. } );
  74583. } ).then( function ( texture ) {
  74584. // Clean up resources and configure Texture.
  74585. //console.log('texture', textureIndex, texture.image)
  74586. if ( isObjectURL === true ) {
  74587. URL.revokeObjectURL( sourceURI );
  74588. }
  74589. texture.flipY = false;
  74590. if ( textureDef.name ) texture.name = textureDef.name;
  74591. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  74592. if ( ! hasAlpha ) texture.format = RGBFormat;
  74593. var samplers = json.samplers || {};
  74594. var sampler = samplers[ textureDef.sampler ] || {};
  74595. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  74596. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
  74597. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  74598. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  74599. parser.associations.set( texture, {
  74600. type: 'textures',
  74601. index: textureIndex
  74602. } );
  74603. return texture;
  74604. } );
  74605. };
  74606. /**
  74607. * Asynchronously assigns a texture to the given material parameters.
  74608. * @param {Object} materialParams
  74609. * @param {string} mapName
  74610. * @param {Object} mapDef
  74611. * @return {Promise}
  74612. */
  74613. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  74614. var parser = this;
  74615. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  74616. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  74617. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  74618. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  74619. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  74620. }
  74621. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  74622. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  74623. if ( transform ) {
  74624. var gltfReference = parser.associations.get( texture );
  74625. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  74626. parser.associations.set( texture, gltfReference );
  74627. }
  74628. }
  74629. materialParams[ mapName ] = texture;
  74630. } );
  74631. };
  74632. /**
  74633. * Assigns final material to a Mesh, Line, or Points instance. The instance
  74634. * already has a material (generated from the glTF material options alone)
  74635. * but reuse of the same glTF material may require multiple threejs materials
  74636. * to accomodate different primitive types, defines, etc. New materials will
  74637. * be created if necessary, and reused from a cache.
  74638. * @param {Object3D} mesh Mesh, Line, or Points instance.
  74639. */
  74640. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  74641. var geometry = mesh.geometry;
  74642. var material = mesh.material;
  74643. var useVertexTangents = geometry.attributes.tangent !== undefined;
  74644. var useVertexColors = geometry.attributes.color !== undefined;
  74645. var useFlatShading = geometry.attributes.normal === undefined;
  74646. var useSkinning = mesh.isSkinnedMesh === true;
  74647. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  74648. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  74649. if ( mesh.isPoints ) {
  74650. var cacheKey = 'PointsMaterial:' + material.uuid;
  74651. var pointsMaterial = this.cache.get( cacheKey );
  74652. if ( ! pointsMaterial ) {
  74653. pointsMaterial = new PointsMaterial();
  74654. Material.prototype.copy.call( pointsMaterial, material );
  74655. pointsMaterial.color.copy( material.color );
  74656. pointsMaterial.map = material.map;
  74657. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  74658. this.cache.add( cacheKey, pointsMaterial );
  74659. }
  74660. material = pointsMaterial;
  74661. } else if ( mesh.isLine ) {
  74662. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  74663. var lineMaterial = this.cache.get( cacheKey );
  74664. if ( ! lineMaterial ) {
  74665. lineMaterial = new LineBasicMaterial();
  74666. Material.prototype.copy.call( lineMaterial, material );
  74667. lineMaterial.color.copy( material.color );
  74668. this.cache.add( cacheKey, lineMaterial );
  74669. }
  74670. material = lineMaterial;
  74671. }
  74672. // Clone the material if it will be modified
  74673. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  74674. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  74675. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  74676. if ( useSkinning ) cacheKey += 'skinning:';
  74677. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  74678. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  74679. if ( useFlatShading ) cacheKey += 'flat-shading:';
  74680. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  74681. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  74682. var cachedMaterial = this.cache.get( cacheKey );
  74683. if ( ! cachedMaterial ) {
  74684. cachedMaterial = material.clone();
  74685. if ( useSkinning ) cachedMaterial.skinning = true;
  74686. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  74687. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  74688. if ( useFlatShading ) cachedMaterial.flatShading = true;
  74689. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  74690. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  74691. this.cache.add( cacheKey, cachedMaterial );
  74692. this.associations.set( cachedMaterial, this.associations.get( material ) );
  74693. }
  74694. material = cachedMaterial;
  74695. }
  74696. // workarounds for mesh and geometry
  74697. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  74698. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  74699. }
  74700. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  74701. if ( material.normalScale && ! useVertexTangents ) {
  74702. material.normalScale.y = - material.normalScale.y;
  74703. }
  74704. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  74705. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  74706. }
  74707. mesh.material = material;
  74708. };
  74709. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  74710. return this.unlitMat ? MeshBasicMaterial : MeshStandardMaterial; //xzw add unlitMat
  74711. };
  74712. /**
  74713. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  74714. * @param {number} materialIndex
  74715. * @return {Promise<Material>}
  74716. */
  74717. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  74718. var parser = this;
  74719. var json = this.json;
  74720. var extensions = this.extensions;
  74721. var materialDef = json.materials[ materialIndex ];
  74722. var materialType;
  74723. var materialParams = {};
  74724. var materialExtensions = materialDef.extensions || {};
  74725. var pending = [];
  74726. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  74727. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  74728. materialType = sgExtension.getMaterialType();
  74729. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  74730. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  74731. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  74732. materialType = kmuExtension.getMaterialType();
  74733. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  74734. } else {
  74735. // Specification:
  74736. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  74737. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  74738. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  74739. materialParams.opacity = 1.0;
  74740. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  74741. var array = metallicRoughness.baseColorFactor;
  74742. materialParams.color.fromArray( array );
  74743. materialParams.opacity = array[ 3 ];
  74744. }
  74745. if ( metallicRoughness.baseColorTexture !== undefined ) {
  74746. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  74747. }
  74748. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  74749. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  74750. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  74751. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  74752. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  74753. }
  74754. materialType = this._invokeOne( function ( ext ) {
  74755. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  74756. } );
  74757. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  74758. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  74759. } ) ) );
  74760. }
  74761. if ( materialDef.doubleSided === true ) {
  74762. materialParams.side = DoubleSide;
  74763. }
  74764. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  74765. if ( alphaMode === ALPHA_MODES.BLEND ) {
  74766. materialParams.transparent = true;
  74767. // See: https://github.com/mrdoob/three.js/issues/17706
  74768. materialParams.depthWrite = false;
  74769. } else {
  74770. materialParams.transparent = false;
  74771. if ( alphaMode === ALPHA_MODES.MASK ) {
  74772. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  74773. }
  74774. }
  74775. if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74776. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  74777. materialParams.normalScale = new Vector2$1( 1, 1 );
  74778. if ( materialDef.normalTexture.scale !== undefined ) {
  74779. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  74780. }
  74781. }
  74782. if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74783. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  74784. if ( materialDef.occlusionTexture.strength !== undefined ) {
  74785. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  74786. }
  74787. }
  74788. if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
  74789. materialParams.emissive = new Color().fromArray( materialDef.emissiveFactor );
  74790. }
  74791. if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74792. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  74793. }
  74794. return Promise.all( pending ).then( function () {
  74795. var material;
  74796. if ( materialType === GLTFMeshStandardSGMaterial ) {
  74797. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  74798. } else {
  74799. material = new materialType( materialParams );
  74800. }
  74801. if ( materialDef.name ) material.name = materialDef.name;
  74802. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  74803. if ( material.map ) material.map.encoding = sRGBEncoding;
  74804. if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding;
  74805. assignExtrasToUserData( material, materialDef );
  74806. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  74807. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  74808. return material;
  74809. } );
  74810. };
  74811. /** When Object3D instances are targeted by animation, they need unique names. */
  74812. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  74813. var sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );
  74814. var name = sanitizedName;
  74815. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  74816. name = sanitizedName + '_' + i;
  74817. }
  74818. this.nodeNamesUsed[ name ] = true;
  74819. return name;
  74820. };
  74821. /**
  74822. * @param {BufferGeometry} geometry
  74823. * @param {GLTF.Primitive} primitiveDef
  74824. * @param {GLTFParser} parser
  74825. */
  74826. function computeBounds( geometry, primitiveDef, parser ) {
  74827. var attributes = primitiveDef.attributes;
  74828. var box = new Box3();
  74829. if ( attributes.POSITION !== undefined ) {
  74830. var accessor = parser.json.accessors[ attributes.POSITION ];
  74831. var min = accessor.min;
  74832. var max = accessor.max;
  74833. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  74834. if ( min !== undefined && max !== undefined ) {
  74835. box.set(
  74836. new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  74837. new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  74838. } else {
  74839. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  74840. return;
  74841. }
  74842. } else {
  74843. return;
  74844. }
  74845. var targets = primitiveDef.targets;
  74846. if ( targets !== undefined ) {
  74847. var maxDisplacement = new Vector3();
  74848. var vector = new Vector3();
  74849. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74850. var target = targets[ i ];
  74851. if ( target.POSITION !== undefined ) {
  74852. var accessor = parser.json.accessors[ target.POSITION ];
  74853. var min = accessor.min;
  74854. var max = accessor.max;
  74855. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  74856. if ( min !== undefined && max !== undefined ) {
  74857. // we need to get max of absolute components because target weight is [-1,1]
  74858. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  74859. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  74860. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  74861. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  74862. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  74863. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  74864. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  74865. maxDisplacement.max( vector );
  74866. } else {
  74867. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  74868. }
  74869. }
  74870. }
  74871. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  74872. box.expandByVector( maxDisplacement );
  74873. }
  74874. geometry.boundingBox = box;
  74875. var sphere = new Sphere();
  74876. box.getCenter( sphere.center );
  74877. sphere.radius = box.min.distanceTo( box.max ) / 2;
  74878. geometry.boundingSphere = sphere;
  74879. }
  74880. /**
  74881. * @param {BufferGeometry} geometry
  74882. * @param {GLTF.Primitive} primitiveDef
  74883. * @param {GLTFParser} parser
  74884. * @return {Promise<BufferGeometry>}
  74885. */
  74886. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  74887. var attributes = primitiveDef.attributes;
  74888. var pending = [];
  74889. function assignAttributeAccessor( accessorIndex, attributeName ) {
  74890. return parser.getDependency( 'accessor', accessorIndex )
  74891. .then( function ( accessor ) {
  74892. geometry.setAttribute( attributeName, accessor );
  74893. } );
  74894. }
  74895. for ( var gltfAttributeName in attributes ) {
  74896. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  74897. // Skip attributes already provided by e.g. Draco extension.
  74898. if ( threeAttributeName in geometry.attributes ) continue;
  74899. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  74900. }
  74901. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  74902. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  74903. geometry.setIndex( accessor );
  74904. } );
  74905. pending.push( accessor );
  74906. }
  74907. assignExtrasToUserData( geometry, primitiveDef );
  74908. computeBounds( geometry, primitiveDef, parser );
  74909. return Promise.all( pending ).then( function () {
  74910. return primitiveDef.targets !== undefined
  74911. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  74912. : geometry;
  74913. } );
  74914. }
  74915. /**
  74916. * @param {BufferGeometry} geometry
  74917. * @param {Number} drawMode
  74918. * @return {BufferGeometry}
  74919. */
  74920. function toTrianglesDrawMode( geometry, drawMode ) {
  74921. var index = geometry.getIndex();
  74922. // generate index if not present
  74923. if ( index === null ) {
  74924. var indices = [];
  74925. var position = geometry.getAttribute( 'position' );
  74926. if ( position !== undefined ) {
  74927. for ( var i = 0; i < position.count; i ++ ) {
  74928. indices.push( i );
  74929. }
  74930. geometry.setIndex( indices );
  74931. index = geometry.getIndex();
  74932. } else {
  74933. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  74934. return geometry;
  74935. }
  74936. }
  74937. //
  74938. var numberOfTriangles = index.count - 2;
  74939. var newIndices = [];
  74940. if ( drawMode === TriangleFanDrawMode ) {
  74941. // gl.TRIANGLE_FAN
  74942. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  74943. newIndices.push( index.getX( 0 ) );
  74944. newIndices.push( index.getX( i ) );
  74945. newIndices.push( index.getX( i + 1 ) );
  74946. }
  74947. } else {
  74948. // gl.TRIANGLE_STRIP
  74949. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  74950. if ( i % 2 === 0 ) {
  74951. newIndices.push( index.getX( i ) );
  74952. newIndices.push( index.getX( i + 1 ) );
  74953. newIndices.push( index.getX( i + 2 ) );
  74954. } else {
  74955. newIndices.push( index.getX( i + 2 ) );
  74956. newIndices.push( index.getX( i + 1 ) );
  74957. newIndices.push( index.getX( i ) );
  74958. }
  74959. }
  74960. }
  74961. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  74962. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  74963. }
  74964. // build final geometry
  74965. var newGeometry = geometry.clone();
  74966. newGeometry.setIndex( newIndices );
  74967. return newGeometry;
  74968. }
  74969. /**
  74970. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  74971. *
  74972. * Creates BufferGeometries from primitives.
  74973. *
  74974. * @param {Array<GLTF.Primitive>} primitives
  74975. * @return {Promise<Array<BufferGeometry>>}
  74976. */
  74977. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  74978. var parser = this;
  74979. var extensions = this.extensions;
  74980. var cache = this.primitiveCache;
  74981. function createDracoPrimitive( primitive ) {
  74982. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  74983. .decodePrimitive( primitive, parser )
  74984. .then( function ( geometry ) {
  74985. return addPrimitiveAttributes( geometry, primitive, parser );
  74986. } );
  74987. }
  74988. var pending = [];
  74989. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  74990. var primitive = primitives[ i ];
  74991. var cacheKey = createPrimitiveKey( primitive );
  74992. // See if we've already created this geometry
  74993. var cached = cache[ cacheKey ];
  74994. if ( cached ) {
  74995. // Use the cached geometry if it exists
  74996. pending.push( cached.promise );
  74997. } else {
  74998. var geometryPromise;
  74999. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  75000. // Use DRACO geometry if available
  75001. geometryPromise = createDracoPrimitive( primitive );
  75002. } else {
  75003. // Otherwise create a new geometry
  75004. geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
  75005. }
  75006. // Cache this geometry
  75007. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  75008. pending.push( geometryPromise );
  75009. }
  75010. }
  75011. return Promise.all( pending );
  75012. };
  75013. /**
  75014. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  75015. * @param {number} meshIndex
  75016. * @return {Promise<Group|Mesh|SkinnedMesh>}
  75017. */
  75018. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  75019. var parser = this;
  75020. var json = this.json;
  75021. var extensions = this.extensions;
  75022. var meshDef = json.meshes[ meshIndex ];
  75023. var primitives = meshDef.primitives;
  75024. var pending = [];
  75025. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  75026. var material = primitives[ i ].material === undefined
  75027. ? createDefaultMaterial( this.cache )
  75028. : this.getDependency( 'material', primitives[ i ].material );
  75029. pending.push( material );
  75030. }
  75031. pending.push( parser.loadGeometries( primitives ) );
  75032. return Promise.all( pending ).then( function ( results ) {
  75033. var materials = results.slice( 0, results.length - 1 );
  75034. var geometries = results[ results.length - 1 ];
  75035. var meshes = [];
  75036. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  75037. var geometry = geometries[ i ];
  75038. var primitive = primitives[ i ];
  75039. // 1. create Mesh
  75040. var mesh;
  75041. var material = materials[ i ];
  75042. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  75043. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  75044. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  75045. primitive.mode === undefined ) {
  75046. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  75047. mesh = meshDef.isSkinnedMesh === true
  75048. ? new SkinnedMesh( geometry, material )
  75049. : new Mesh( geometry, material );
  75050. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  75051. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  75052. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  75053. mesh.normalizeSkinWeights();
  75054. }
  75055. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  75056. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode );
  75057. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  75058. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode );
  75059. }
  75060. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  75061. mesh = new LineSegments( geometry, material );
  75062. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  75063. mesh = new Line( geometry, material );
  75064. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  75065. mesh = new LineLoop( geometry, material );
  75066. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  75067. mesh = new Points( geometry, material );
  75068. } else {
  75069. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  75070. }
  75071. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  75072. updateMorphTargets( mesh, meshDef );
  75073. }
  75074. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  75075. assignExtrasToUserData( mesh, meshDef );
  75076. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  75077. parser.assignFinalMaterial( mesh );
  75078. meshes.push( mesh );
  75079. }
  75080. if ( meshes.length === 1 ) {
  75081. return meshes[ 0 ];
  75082. }
  75083. var group = new Group();
  75084. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  75085. group.add( meshes[ i ] );
  75086. }
  75087. return group;
  75088. } );
  75089. };
  75090. /**
  75091. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  75092. * @param {number} cameraIndex
  75093. * @return {Promise<THREE.Camera>}
  75094. */
  75095. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  75096. var camera;
  75097. var cameraDef = this.json.cameras[ cameraIndex ];
  75098. var params = cameraDef[ cameraDef.type ];
  75099. if ( ! params ) {
  75100. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  75101. return;
  75102. }
  75103. if ( cameraDef.type === 'perspective' ) {
  75104. camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  75105. } else if ( cameraDef.type === 'orthographic' ) {
  75106. camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  75107. }
  75108. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  75109. assignExtrasToUserData( camera, cameraDef );
  75110. return Promise.resolve( camera );
  75111. };
  75112. /**
  75113. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  75114. * @param {number} skinIndex
  75115. * @return {Promise<Object>}
  75116. */
  75117. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  75118. var skinDef = this.json.skins[ skinIndex ];
  75119. var skinEntry = { joints: skinDef.joints };
  75120. if ( skinDef.inverseBindMatrices === undefined ) {
  75121. return Promise.resolve( skinEntry );
  75122. }
  75123. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  75124. skinEntry.inverseBindMatrices = accessor;
  75125. return skinEntry;
  75126. } );
  75127. };
  75128. /**
  75129. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  75130. * @param {number} animationIndex
  75131. * @return {Promise<AnimationClip>}
  75132. */
  75133. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  75134. var json = this.json;
  75135. var animationDef = json.animations[ animationIndex ];
  75136. var pendingNodes = [];
  75137. var pendingInputAccessors = [];
  75138. var pendingOutputAccessors = [];
  75139. var pendingSamplers = [];
  75140. var pendingTargets = [];
  75141. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  75142. var channel = animationDef.channels[ i ];
  75143. var sampler = animationDef.samplers[ channel.sampler ];
  75144. var target = channel.target;
  75145. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  75146. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  75147. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  75148. pendingNodes.push( this.getDependency( 'node', name ) );
  75149. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  75150. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  75151. pendingSamplers.push( sampler );
  75152. pendingTargets.push( target );
  75153. }
  75154. return Promise.all( [
  75155. Promise.all( pendingNodes ),
  75156. Promise.all( pendingInputAccessors ),
  75157. Promise.all( pendingOutputAccessors ),
  75158. Promise.all( pendingSamplers ),
  75159. Promise.all( pendingTargets )
  75160. ] ).then( function ( dependencies ) {
  75161. var nodes = dependencies[ 0 ];
  75162. var inputAccessors = dependencies[ 1 ];
  75163. var outputAccessors = dependencies[ 2 ];
  75164. var samplers = dependencies[ 3 ];
  75165. var targets = dependencies[ 4 ];
  75166. var tracks = [];
  75167. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  75168. var node = nodes[ i ];
  75169. var inputAccessor = inputAccessors[ i ];
  75170. var outputAccessor = outputAccessors[ i ];
  75171. var sampler = samplers[ i ];
  75172. var target = targets[ i ];
  75173. if ( node === undefined ) continue;
  75174. node.updateMatrix();
  75175. node.matrixAutoUpdate = true;
  75176. var TypedKeyframeTrack;
  75177. switch ( PATH_PROPERTIES[ target.path ] ) {
  75178. case PATH_PROPERTIES.weights:
  75179. TypedKeyframeTrack = NumberKeyframeTrack;
  75180. break;
  75181. case PATH_PROPERTIES.rotation:
  75182. TypedKeyframeTrack = QuaternionKeyframeTrack;
  75183. break;
  75184. case PATH_PROPERTIES.position:
  75185. case PATH_PROPERTIES.scale:
  75186. default:
  75187. TypedKeyframeTrack = VectorKeyframeTrack;
  75188. break;
  75189. }
  75190. var targetName = node.name ? node.name : node.uuid;
  75191. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  75192. var targetNames = [];
  75193. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  75194. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  75195. node.traverse( function ( object ) {
  75196. if ( object.isMesh === true && object.morphTargetInfluences ) {
  75197. targetNames.push( object.name ? object.name : object.uuid );
  75198. }
  75199. } );
  75200. } else {
  75201. targetNames.push( targetName );
  75202. }
  75203. var outputArray = outputAccessor.array;
  75204. if ( outputAccessor.normalized ) {
  75205. var scale;
  75206. if ( outputArray.constructor === Int8Array ) {
  75207. scale = 1 / 127;
  75208. } else if ( outputArray.constructor === Uint8Array ) {
  75209. scale = 1 / 255;
  75210. } else if ( outputArray.constructor == Int16Array ) {
  75211. scale = 1 / 32767;
  75212. } else if ( outputArray.constructor === Uint16Array ) {
  75213. scale = 1 / 65535;
  75214. } else {
  75215. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  75216. }
  75217. var scaled = new Float32Array( outputArray.length );
  75218. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  75219. scaled[ j ] = outputArray[ j ] * scale;
  75220. }
  75221. outputArray = scaled;
  75222. }
  75223. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  75224. var track = new TypedKeyframeTrack(
  75225. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  75226. inputAccessor.array,
  75227. outputArray,
  75228. interpolation
  75229. );
  75230. // Override interpolation with custom factory method.
  75231. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  75232. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  75233. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  75234. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  75235. // must be divided by three to get the interpolant's sampleSize argument.
  75236. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  75237. };
  75238. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  75239. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  75240. }
  75241. tracks.push( track );
  75242. }
  75243. }
  75244. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  75245. return new AnimationClip( name, undefined, tracks );
  75246. } );
  75247. };
  75248. /**
  75249. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  75250. * @param {number} nodeIndex
  75251. * @return {Promise<Object3D>}
  75252. */
  75253. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  75254. var json = this.json;
  75255. var extensions = this.extensions;
  75256. var parser = this;
  75257. var nodeDef = json.nodes[ nodeIndex ];
  75258. // reserve node's name before its dependencies, so the root has the intended name.
  75259. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  75260. return ( function () {
  75261. var pending = [];
  75262. if ( nodeDef.mesh !== undefined ) {
  75263. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  75264. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  75265. // if weights are provided on the node, override weights on the mesh.
  75266. if ( nodeDef.weights !== undefined ) {
  75267. node.traverse( function ( o ) {
  75268. if ( ! o.isMesh ) return;
  75269. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  75270. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  75271. }
  75272. } );
  75273. }
  75274. return node;
  75275. } ) );
  75276. }
  75277. if ( nodeDef.camera !== undefined ) {
  75278. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  75279. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  75280. } ) );
  75281. }
  75282. parser._invokeAll( function ( ext ) {
  75283. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  75284. } ).forEach( function ( promise ) {
  75285. pending.push( promise );
  75286. } );
  75287. return Promise.all( pending );
  75288. }() ).then( function ( objects ) {
  75289. var node;
  75290. // .isBone isn't in glTF spec. See ._markDefs
  75291. if ( nodeDef.isBone === true ) {
  75292. node = new Bone();
  75293. } else if ( objects.length > 1 ) {
  75294. node = new Group();
  75295. } else if ( objects.length === 1 ) {
  75296. node = objects[ 0 ];
  75297. } else {
  75298. node = new Object3D();
  75299. }
  75300. if ( node !== objects[ 0 ] ) {
  75301. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  75302. node.add( objects[ i ] );
  75303. }
  75304. }
  75305. if ( nodeDef.name ) {
  75306. node.userData.name = nodeDef.name;
  75307. node.name = nodeName;
  75308. }
  75309. assignExtrasToUserData( node, nodeDef );
  75310. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  75311. if ( nodeDef.matrix !== undefined ) {
  75312. var matrix = new Matrix4();
  75313. matrix.fromArray( nodeDef.matrix );
  75314. node.applyMatrix4( matrix );
  75315. } else {
  75316. if ( nodeDef.translation !== undefined ) {
  75317. node.position.fromArray( nodeDef.translation );
  75318. }
  75319. if ( nodeDef.rotation !== undefined ) {
  75320. node.quaternion.fromArray( nodeDef.rotation );
  75321. }
  75322. if ( nodeDef.scale !== undefined ) {
  75323. node.scale.fromArray( nodeDef.scale );
  75324. }
  75325. }
  75326. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  75327. return node;
  75328. } );
  75329. };
  75330. /**
  75331. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  75332. * @param {number} sceneIndex
  75333. * @return {Promise<Group>}
  75334. */
  75335. GLTFParser.prototype.loadScene = function () {
  75336. // scene node hierachy builder
  75337. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  75338. var nodeDef = json.nodes[ nodeId ];
  75339. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  75340. if ( nodeDef.skin === undefined ) return node;
  75341. // build skeleton here as well
  75342. var skinEntry;
  75343. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  75344. skinEntry = skin;
  75345. var pendingJoints = [];
  75346. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  75347. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  75348. }
  75349. return Promise.all( pendingJoints );
  75350. } ).then( function ( jointNodes ) {
  75351. node.traverse( function ( mesh ) {
  75352. if ( ! mesh.isMesh ) return;
  75353. var bones = [];
  75354. var boneInverses = [];
  75355. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  75356. var jointNode = jointNodes[ j ];
  75357. if ( jointNode ) {
  75358. bones.push( jointNode );
  75359. var mat = new Matrix4();
  75360. if ( skinEntry.inverseBindMatrices !== undefined ) {
  75361. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  75362. }
  75363. boneInverses.push( mat );
  75364. } else {
  75365. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  75366. }
  75367. }
  75368. mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld );
  75369. } );
  75370. return node;
  75371. } );
  75372. } ).then( function ( node ) {
  75373. // build node hierachy
  75374. parentObject.add( node );
  75375. var pending = [];
  75376. if ( nodeDef.children ) {
  75377. var children = nodeDef.children;
  75378. for ( var i = 0, il = children.length; i < il; i ++ ) {
  75379. var child = children[ i ];
  75380. pending.push( buildNodeHierachy( child, node, json, parser ) );
  75381. }
  75382. }
  75383. return Promise.all( pending );
  75384. } );
  75385. }
  75386. return function loadScene( sceneIndex ) {
  75387. var json = this.json;
  75388. var extensions = this.extensions;
  75389. var sceneDef = this.json.scenes[ sceneIndex ];
  75390. var parser = this;
  75391. // Loader returns Group, not Scene.
  75392. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  75393. var scene = new Group();
  75394. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  75395. assignExtrasToUserData( scene, sceneDef );
  75396. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  75397. var nodeIds = sceneDef.nodes || [];
  75398. var pending = [];
  75399. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  75400. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  75401. }
  75402. return Promise.all( pending ).then( function () {
  75403. return scene;
  75404. } );
  75405. };
  75406. }();
  75407. return GLTFLoader;
  75408. } )();
  75409. /**
  75410. * @webxr-input-profiles/motion-controllers 1.0.0 https://github.com/immersive-web/webxr-input-profiles
  75411. */
  75412. const Constants = {
  75413. Handedness: Object.freeze({
  75414. NONE: 'none',
  75415. LEFT: 'left',
  75416. RIGHT: 'right'
  75417. }),
  75418. ComponentState: Object.freeze({
  75419. DEFAULT: 'default',
  75420. TOUCHED: 'touched',
  75421. PRESSED: 'pressed'
  75422. }),
  75423. ComponentProperty: Object.freeze({
  75424. BUTTON: 'button',
  75425. X_AXIS: 'xAxis',
  75426. Y_AXIS: 'yAxis',
  75427. STATE: 'state'
  75428. }),
  75429. ComponentType: Object.freeze({
  75430. TRIGGER: 'trigger',
  75431. SQUEEZE: 'squeeze',
  75432. TOUCHPAD: 'touchpad',
  75433. THUMBSTICK: 'thumbstick',
  75434. BUTTON: 'button'
  75435. }),
  75436. ButtonTouchThreshold: 0.05,
  75437. AxisTouchThreshold: 0.1,
  75438. VisualResponseProperty: Object.freeze({
  75439. TRANSFORM: 'transform',
  75440. VISIBILITY: 'visibility'
  75441. })
  75442. };
  75443. /**
  75444. * @description Static helper function to fetch a JSON file and turn it into a JS object
  75445. * @param {string} path - Path to JSON file to be fetched
  75446. */
  75447. async function fetchJsonFile(path) {
  75448. const response = await fetch(path);
  75449. if (!response.ok) {
  75450. throw new Error(response.statusText);
  75451. } else {
  75452. return response.json();
  75453. }
  75454. }
  75455. async function fetchProfilesList(basePath) {
  75456. if (!basePath) {
  75457. throw new Error('No basePath supplied');
  75458. }
  75459. const profileListFileName = 'profilesList.json';
  75460. const profilesList = await fetchJsonFile(`${basePath}/${profileListFileName}`);
  75461. return profilesList;
  75462. }
  75463. async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) {
  75464. if (!xrInputSource) {
  75465. throw new Error('No xrInputSource supplied');
  75466. }
  75467. if (!basePath) {
  75468. throw new Error('No basePath supplied');
  75469. }
  75470. // Get the list of profiles
  75471. const supportedProfilesList = await fetchProfilesList(basePath);
  75472. // Find the relative path to the first requested profile that is recognized
  75473. let match;
  75474. xrInputSource.profiles.some((profileId) => {
  75475. const supportedProfile = supportedProfilesList[profileId];
  75476. if (supportedProfile) {
  75477. match = {
  75478. profileId,
  75479. profilePath: `${basePath}/${supportedProfile.path}`,
  75480. deprecated: !!supportedProfile.deprecated
  75481. };
  75482. }
  75483. return !!match;
  75484. });
  75485. if (!match) {
  75486. if (!defaultProfile) {
  75487. throw new Error('No matching profile name found');
  75488. }
  75489. const supportedProfile = supportedProfilesList[defaultProfile];
  75490. if (!supportedProfile) {
  75491. throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`);
  75492. }
  75493. match = {
  75494. profileId: defaultProfile,
  75495. profilePath: `${basePath}/${supportedProfile.path}`,
  75496. deprecated: !!supportedProfile.deprecated
  75497. };
  75498. }
  75499. const profile = await fetchJsonFile(match.profilePath);
  75500. let assetPath;
  75501. if (getAssetPath) {
  75502. let layout;
  75503. if (xrInputSource.handedness === 'any') {
  75504. layout = profile.layouts[Object.keys(profile.layouts)[0]];
  75505. } else {
  75506. layout = profile.layouts[xrInputSource.handedness];
  75507. }
  75508. if (!layout) {
  75509. throw new Error(
  75510. `No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}`
  75511. );
  75512. }
  75513. if (layout.assetPath) {
  75514. assetPath = match.profilePath.replace('profile.json', layout.assetPath);
  75515. }
  75516. }
  75517. return { profile, assetPath };
  75518. }
  75519. /** @constant {Object} */
  75520. const defaultComponentValues = {
  75521. xAxis: 0,
  75522. yAxis: 0,
  75523. button: 0,
  75524. state: Constants.ComponentState.DEFAULT
  75525. };
  75526. /**
  75527. * @description Converts an X, Y coordinate from the range -1 to 1 (as reported by the Gamepad
  75528. * API) to the range 0 to 1 (for interpolation). Also caps the X, Y values to be bounded within
  75529. * a circle. This ensures that thumbsticks are not animated outside the bounds of their physical
  75530. * range of motion and touchpads do not report touch locations off their physical bounds.
  75531. * @param {number} x The original x coordinate in the range -1 to 1
  75532. * @param {number} y The original y coordinate in the range -1 to 1
  75533. */
  75534. function normalizeAxes(x = 0, y = 0) {
  75535. let xAxis = x;
  75536. let yAxis = y;
  75537. // Determine if the point is outside the bounds of the circle
  75538. // and, if so, place it on the edge of the circle
  75539. const hypotenuse = Math.sqrt((x * x) + (y * y));
  75540. if (hypotenuse > 1) {
  75541. const theta = Math.atan2(y, x);
  75542. xAxis = Math.cos(theta);
  75543. yAxis = Math.sin(theta);
  75544. }
  75545. // Scale and move the circle so values are in the interpolation range. The circle's origin moves
  75546. // from (0, 0) to (0.5, 0.5). The circle's radius scales from 1 to be 0.5.
  75547. const result = {
  75548. normalizedXAxis: (xAxis * 0.5) + 0.5,
  75549. normalizedYAxis: (yAxis * 0.5) + 0.5
  75550. };
  75551. return result;
  75552. }
  75553. /**
  75554. * Contains the description of how the 3D model should visually respond to a specific user input.
  75555. * This is accomplished by initializing the object with the name of a node in the 3D model and
  75556. * property that need to be modified in response to user input, the name of the nodes representing
  75557. * the allowable range of motion, and the name of the input which triggers the change. In response
  75558. * to the named input changing, this object computes the appropriate weighting to use for
  75559. * interpolating between the range of motion nodes.
  75560. */
  75561. class VisualResponse {
  75562. constructor(visualResponseDescription) {
  75563. this.componentProperty = visualResponseDescription.componentProperty;
  75564. this.states = visualResponseDescription.states;
  75565. this.valueNodeName = visualResponseDescription.valueNodeName;
  75566. this.valueNodeProperty = visualResponseDescription.valueNodeProperty;
  75567. if (this.valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
  75568. this.minNodeName = visualResponseDescription.minNodeName;
  75569. this.maxNodeName = visualResponseDescription.maxNodeName;
  75570. }
  75571. // Initializes the response's current value based on default data
  75572. this.value = 0;
  75573. this.updateFromComponent(defaultComponentValues);
  75574. }
  75575. /**
  75576. * Computes the visual response's interpolation weight based on component state
  75577. * @param {Object} componentValues - The component from which to update
  75578. * @param {number} xAxis - The reported X axis value of the component
  75579. * @param {number} yAxis - The reported Y axis value of the component
  75580. * @param {number} button - The reported value of the component's button
  75581. * @param {string} state - The component's active state
  75582. */
  75583. updateFromComponent({
  75584. xAxis, yAxis, button, state
  75585. }) {
  75586. const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis, yAxis);
  75587. switch (this.componentProperty) {
  75588. case Constants.ComponentProperty.X_AXIS:
  75589. this.value = (this.states.includes(state)) ? normalizedXAxis : 0.5;
  75590. break;
  75591. case Constants.ComponentProperty.Y_AXIS:
  75592. this.value = (this.states.includes(state)) ? normalizedYAxis : 0.5;
  75593. break;
  75594. case Constants.ComponentProperty.BUTTON:
  75595. this.value = (this.states.includes(state)) ? button : 0;
  75596. break;
  75597. case Constants.ComponentProperty.STATE:
  75598. if (this.valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) {
  75599. this.value = (this.states.includes(state));
  75600. } else {
  75601. this.value = this.states.includes(state) ? 1.0 : 0.0;
  75602. }
  75603. break;
  75604. default:
  75605. throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`);
  75606. }
  75607. }
  75608. }
  75609. class Component {
  75610. /**
  75611. * @param {Object} componentId - Id of the component
  75612. * @param {Object} componentDescription - Description of the component to be created
  75613. */
  75614. constructor(componentId, componentDescription) {
  75615. if (!componentId
  75616. || !componentDescription
  75617. || !componentDescription.visualResponses
  75618. || !componentDescription.gamepadIndices
  75619. || Object.keys(componentDescription.gamepadIndices).length === 0) {
  75620. throw new Error('Invalid arguments supplied');
  75621. }
  75622. this.id = componentId;
  75623. this.type = componentDescription.type;
  75624. this.rootNodeName = componentDescription.rootNodeName;
  75625. this.touchPointNodeName = componentDescription.touchPointNodeName;
  75626. // Build all the visual responses for this component
  75627. this.visualResponses = {};
  75628. Object.keys(componentDescription.visualResponses).forEach((responseName) => {
  75629. const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]);
  75630. this.visualResponses[responseName] = visualResponse;
  75631. });
  75632. // Set default values
  75633. this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices);
  75634. this.values = {
  75635. state: Constants.ComponentState.DEFAULT,
  75636. button: (this.gamepadIndices.button !== undefined) ? 0 : undefined,
  75637. xAxis: (this.gamepadIndices.xAxis !== undefined) ? 0 : undefined,
  75638. yAxis: (this.gamepadIndices.yAxis !== undefined) ? 0 : undefined
  75639. };
  75640. }
  75641. get data() {
  75642. const data = { id: this.id, ...this.values };
  75643. return data;
  75644. }
  75645. /**
  75646. * @description Poll for updated data based on current gamepad state
  75647. * @param {Object} gamepad - The gamepad object from which the component data should be polled
  75648. */
  75649. updateFromGamepad(gamepad) {
  75650. // Set the state to default before processing other data sources
  75651. this.values.state = Constants.ComponentState.DEFAULT;
  75652. // Get and normalize button
  75653. if (this.gamepadIndices.button !== undefined
  75654. && gamepad.buttons.length > this.gamepadIndices.button) {
  75655. const gamepadButton = gamepad.buttons[this.gamepadIndices.button];
  75656. this.values.button = gamepadButton.value;
  75657. this.values.button = (this.values.button < 0) ? 0 : this.values.button;
  75658. this.values.button = (this.values.button > 1) ? 1 : this.values.button;
  75659. // Set the state based on the button
  75660. if (gamepadButton.pressed || this.values.button === 1) {
  75661. this.values.state = Constants.ComponentState.PRESSED;
  75662. } else if (gamepadButton.touched || this.values.button > Constants.ButtonTouchThreshold) {
  75663. this.values.state = Constants.ComponentState.TOUCHED;
  75664. }
  75665. }
  75666. // Get and normalize x axis value
  75667. if (this.gamepadIndices.xAxis !== undefined
  75668. && gamepad.axes.length > this.gamepadIndices.xAxis) {
  75669. this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis];
  75670. this.values.xAxis = (this.values.xAxis < -1) ? -1 : this.values.xAxis;
  75671. this.values.xAxis = (this.values.xAxis > 1) ? 1 : this.values.xAxis;
  75672. // If the state is still default, check if the xAxis makes it touched
  75673. if (this.values.state === Constants.ComponentState.DEFAULT
  75674. && Math.abs(this.values.xAxis) > Constants.AxisTouchThreshold) {
  75675. this.values.state = Constants.ComponentState.TOUCHED;
  75676. }
  75677. }
  75678. // Get and normalize Y axis value
  75679. if (this.gamepadIndices.yAxis !== undefined
  75680. && gamepad.axes.length > this.gamepadIndices.yAxis) {
  75681. this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis];
  75682. this.values.yAxis = (this.values.yAxis < -1) ? -1 : this.values.yAxis;
  75683. this.values.yAxis = (this.values.yAxis > 1) ? 1 : this.values.yAxis;
  75684. // If the state is still default, check if the yAxis makes it touched
  75685. if (this.values.state === Constants.ComponentState.DEFAULT
  75686. && Math.abs(this.values.yAxis) > Constants.AxisTouchThreshold) {
  75687. this.values.state = Constants.ComponentState.TOUCHED;
  75688. }
  75689. }
  75690. // Update the visual response weights based on the current component data
  75691. Object.values(this.visualResponses).forEach((visualResponse) => {
  75692. visualResponse.updateFromComponent(this.values);
  75693. });
  75694. }
  75695. }
  75696. /**
  75697. * @description Builds a motion controller with components and visual responses based on the
  75698. * supplied profile description. Data is polled from the xrInputSource's gamepad.
  75699. * @author Nell Waliczek / https://github.com/NellWaliczek
  75700. */
  75701. class MotionController {
  75702. /**
  75703. * @param {Object} xrInputSource - The XRInputSource to build the MotionController around
  75704. * @param {Object} profile - The best matched profile description for the supplied xrInputSource
  75705. * @param {Object} assetUrl
  75706. */
  75707. constructor(xrInputSource, profile, assetUrl) {
  75708. if (!xrInputSource) {
  75709. throw new Error('No xrInputSource supplied');
  75710. }
  75711. if (!profile) {
  75712. throw new Error('No profile supplied');
  75713. }
  75714. this.xrInputSource = xrInputSource;
  75715. this.assetUrl = assetUrl;
  75716. this.id = profile.profileId;
  75717. // Build child components as described in the profile description
  75718. this.layoutDescription = profile.layouts[xrInputSource.handedness];
  75719. this.components = {};
  75720. Object.keys(this.layoutDescription.components).forEach((componentId) => {
  75721. const componentDescription = this.layoutDescription.components[componentId];
  75722. this.components[componentId] = new Component(componentId, componentDescription);
  75723. });
  75724. // Initialize components based on current gamepad state
  75725. this.updateFromGamepad();
  75726. }
  75727. get gripSpace() {
  75728. return this.xrInputSource.gripSpace;
  75729. }
  75730. get targetRaySpace() {
  75731. return this.xrInputSource.targetRaySpace;
  75732. }
  75733. /**
  75734. * @description Returns a subset of component data for simplified debugging
  75735. */
  75736. get data() {
  75737. const data = [];
  75738. Object.values(this.components).forEach((component) => {
  75739. data.push(component.data);
  75740. });
  75741. return data;
  75742. }
  75743. /**
  75744. * @description Poll for updated data based on current gamepad state
  75745. */
  75746. updateFromGamepad() {
  75747. Object.values(this.components).forEach((component) => {
  75748. component.updateFromGamepad(this.xrInputSource.gamepad);
  75749. });
  75750. }
  75751. }
  75752. const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles';
  75753. const DEFAULT_PROFILE = 'generic-trigger';
  75754. function XRControllerModel( ) {
  75755. Object3D.call( this );
  75756. this.motionController = null;
  75757. this.envMap = null;
  75758. }
  75759. XRControllerModel.prototype = Object.assign( Object.create( Object3D.prototype ), {
  75760. constructor: XRControllerModel,
  75761. setEnvironmentMap: function ( envMap ) {
  75762. if ( this.envMap == envMap ) {
  75763. return this;
  75764. }
  75765. this.envMap = envMap;
  75766. this.traverse( ( child ) => {
  75767. if ( child.isMesh ) {
  75768. child.material.envMap = this.envMap;
  75769. child.material.needsUpdate = true;
  75770. }
  75771. } );
  75772. return this;
  75773. },
  75774. /**
  75775. * Polls data from the XRInputSource and updates the model's components to match
  75776. * the real world data
  75777. */
  75778. updateMatrixWorld: function ( force ) {
  75779. Object3D.prototype.updateMatrixWorld.call( this, force );
  75780. if ( ! this.motionController ) return;
  75781. // Cause the MotionController to poll the Gamepad for data
  75782. this.motionController.updateFromGamepad();
  75783. // Update the 3D model to reflect the button, thumbstick, and touchpad state
  75784. Object.values( this.motionController.components ).forEach( ( component ) => {
  75785. // Update node data based on the visual responses' current states
  75786. Object.values( component.visualResponses ).forEach( ( visualResponse ) => {
  75787. const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse;
  75788. // Skip if the visual response node is not found. No error is needed,
  75789. // because it will have been reported at load time.
  75790. if ( ! valueNode ) return;
  75791. // Calculate the new properties based on the weight supplied
  75792. if ( valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY ) {
  75793. valueNode.visible = value;
  75794. } else if ( valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM ) {
  75795. Quaternion.slerp(
  75796. minNode.quaternion,
  75797. maxNode.quaternion,
  75798. valueNode.quaternion,
  75799. value
  75800. );
  75801. valueNode.position.lerpVectors(
  75802. minNode.position,
  75803. maxNode.position,
  75804. value
  75805. );
  75806. }
  75807. } );
  75808. } );
  75809. }
  75810. } );
  75811. /**
  75812. * Walks the model's tree to find the nodes needed to animate the components and
  75813. * saves them to the motionContoller components for use in the frame loop. When
  75814. * touchpads are found, attaches a touch dot to them.
  75815. */
  75816. function findNodes( motionController, scene ) {
  75817. // Loop through the components and find the nodes needed for each components' visual responses
  75818. Object.values( motionController.components ).forEach( ( component ) => {
  75819. const { type, touchPointNodeName, visualResponses } = component;
  75820. if ( type === Constants.ComponentType.TOUCHPAD ) {
  75821. component.touchPointNode = scene.getObjectByName( touchPointNodeName );
  75822. if ( component.touchPointNode ) {
  75823. // Attach a touch dot to the touchpad.
  75824. const sphereGeometry = new SphereBufferGeometry( 0.001 );
  75825. const material = new MeshBasicMaterial( { color: 0x0000FF } );
  75826. const sphere = new Mesh( sphereGeometry, material );
  75827. component.touchPointNode.add( sphere );
  75828. } else {
  75829. console.warn( `Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${component.id}` );
  75830. }
  75831. }
  75832. // Loop through all the visual responses to be applied to this component
  75833. Object.values( visualResponses ).forEach( ( visualResponse ) => {
  75834. const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;
  75835. // If animating a transform, find the two nodes to be interpolated between.
  75836. if ( valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM ) {
  75837. visualResponse.minNode = scene.getObjectByName( minNodeName );
  75838. visualResponse.maxNode = scene.getObjectByName( maxNodeName );
  75839. // If the extents cannot be found, skip this animation
  75840. if ( ! visualResponse.minNode ) {
  75841. console.warn( `Could not find ${minNodeName} in the model` );
  75842. return;
  75843. }
  75844. if ( ! visualResponse.maxNode ) {
  75845. console.warn( `Could not find ${maxNodeName} in the model` );
  75846. return;
  75847. }
  75848. }
  75849. // If the target node cannot be found, skip this animation
  75850. visualResponse.valueNode = scene.getObjectByName( valueNodeName );
  75851. if ( ! visualResponse.valueNode ) {
  75852. console.warn( `Could not find ${valueNodeName} in the model` );
  75853. }
  75854. } );
  75855. } );
  75856. }
  75857. function addAssetSceneToControllerModel( controllerModel, scene ) {
  75858. // Find the nodes needed for animation and cache them on the motionController.
  75859. findNodes( controllerModel.motionController, scene );
  75860. // Apply any environment map that the mesh already has set.
  75861. if ( controllerModel.envMap ) {
  75862. scene.traverse( ( child ) => {
  75863. if ( child.isMesh ) {
  75864. child.material.envMap = controllerModel.envMap;
  75865. child.material.needsUpdate = true;
  75866. }
  75867. } );
  75868. }
  75869. // Add the glTF scene to the controllerModel.
  75870. controllerModel.add( scene );
  75871. }
  75872. var XRControllerModelFactory = ( function () {
  75873. function XRControllerModelFactory( gltfLoader = null ) {
  75874. this.gltfLoader = gltfLoader;
  75875. this.path = DEFAULT_PROFILES_PATH;
  75876. this._assetCache = {};
  75877. // If a GLTFLoader wasn't supplied to the constructor create a new one.
  75878. if ( ! this.gltfLoader ) {
  75879. this.gltfLoader = new GLTFLoader();
  75880. }
  75881. }
  75882. XRControllerModelFactory.prototype = {
  75883. constructor: XRControllerModelFactory,
  75884. createControllerModel: function ( controller ) {
  75885. const controllerModel = new XRControllerModel();
  75886. let scene = null;
  75887. controller.addEventListener( 'connected', ( event ) => {
  75888. const xrInputSource = event.data;
  75889. if ( xrInputSource.targetRayMode !== 'tracked-pointer' || ! xrInputSource.gamepad ) return;
  75890. fetchProfile( xrInputSource, this.path, DEFAULT_PROFILE ).then( ( { profile, assetPath } ) => {
  75891. controllerModel.motionController = new MotionController(
  75892. xrInputSource,
  75893. profile,
  75894. assetPath
  75895. );
  75896. const cachedAsset = this._assetCache[ controllerModel.motionController.assetUrl ];
  75897. if ( cachedAsset ) {
  75898. scene = cachedAsset.scene.clone();
  75899. addAssetSceneToControllerModel( controllerModel, scene );
  75900. } else {
  75901. if ( ! this.gltfLoader ) {
  75902. throw new Error( 'GLTFLoader not set.' );
  75903. }
  75904. this.gltfLoader.setPath( '' );
  75905. this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => {
  75906. this._assetCache[ controllerModel.motionController.assetUrl ] = asset;
  75907. scene = asset.scene.clone();
  75908. addAssetSceneToControllerModel( controllerModel, scene );
  75909. },
  75910. null,
  75911. () => {
  75912. throw new Error( `Asset ${controllerModel.motionController.assetUrl} missing or malformed.` );
  75913. } );
  75914. }
  75915. } ).catch( ( err ) => {
  75916. console.warn( err );
  75917. } );
  75918. } );
  75919. controller.addEventListener( 'disconnected', () => {
  75920. controllerModel.motionController = null;
  75921. controllerModel.remove( scene );
  75922. scene = null;
  75923. } );
  75924. return controllerModel;
  75925. }
  75926. };
  75927. return XRControllerModelFactory;
  75928. } )();
  75929. let fakeCam = new PerspectiveCamera();
  75930. function toScene(vec, ref){
  75931. let node = ref.clone();
  75932. node.updateMatrix();
  75933. node.updateMatrixWorld();
  75934. let result = vec.clone().applyMatrix4(node.matrix);
  75935. result.z -= 0.8 * node.scale.x;
  75936. return result;
  75937. };
  75938. function computeMove(vrControls, controller){
  75939. if(!controller || !controller.inputSource || !controller.inputSource.gamepad){
  75940. return null;
  75941. }
  75942. let pad = controller.inputSource.gamepad;
  75943. let axes = pad.axes;
  75944. // [0,1] are for touchpad, [2,3] for thumbsticks?
  75945. let y = 0;
  75946. if(axes.length === 2){
  75947. y = axes[1];
  75948. }else if(axes.length === 4){
  75949. y = axes[3];
  75950. }
  75951. y = Math.sign(y) * (2 * y) ** 2;
  75952. let maxSize = 0;
  75953. for(let pc of viewer.scene.pointclouds){
  75954. let size = pc.boundingBox.min.distanceTo(pc.boundingBox.max);
  75955. maxSize = Math.max(maxSize, size);
  75956. }
  75957. let multiplicator = Math.pow(maxSize, 0.5) / 2;
  75958. let scale = vrControls.node.scale.x;
  75959. let moveSpeed = viewer.getMoveSpeed();
  75960. let amount = multiplicator * y * (moveSpeed ** 0.5) / scale;
  75961. let rotation = new Quaternion().setFromEuler(controller.rotation);
  75962. let dir = new Vector3(0, 0, -1);
  75963. dir.applyQuaternion(rotation);
  75964. let move = dir.clone().multiplyScalar(amount);
  75965. let p1 = vrControls.toScene(controller.position);
  75966. let p2 = vrControls.toScene(controller.position.clone().add(move));
  75967. move = p2.clone().sub(p1);
  75968. return move;
  75969. };
  75970. class FlyMode{
  75971. constructor(vrControls){
  75972. this.moveFactor = 1;
  75973. this.dbgLabel = null;
  75974. }
  75975. start(vrControls){
  75976. if(!this.dbgLabel){
  75977. /* this.dbgLabel = new Potree.TextSprite("abc");
  75978. this.dbgLabel.name = "debug label";
  75979. vrControls.viewer.sceneVR.add(this.dbgLabel);
  75980. this.dbgLabel.visible = false; */
  75981. }
  75982. }
  75983. end(){
  75984. }
  75985. update(vrControls, delta){
  75986. let primary = vrControls.cPrimary;
  75987. let secondary = vrControls.cSecondary;
  75988. let move1 = computeMove(vrControls, primary);
  75989. let move2 = computeMove(vrControls, secondary);
  75990. if(!move1){
  75991. move1 = new Vector3();
  75992. }
  75993. if(!move2){
  75994. move2 = new Vector3();
  75995. }
  75996. let move = move1.clone().add(move2);
  75997. move.multiplyScalar(-delta * this.moveFactor);
  75998. vrControls.node.position.add(move);
  75999. let scale = vrControls.node.scale.x;
  76000. let camVR = vrControls.viewer.renderer.xr.getCamera(fakeCam);
  76001. let vrPos = camVR.getWorldPosition(new Vector3());
  76002. let vrDir = camVR.getWorldDirection(new Vector3());
  76003. let vrTarget = vrPos.clone().add(vrDir.multiplyScalar(scale));
  76004. let scenePos = toScene(vrPos, vrControls.node);
  76005. let sceneDir = toScene(vrPos.clone().add(vrDir), vrControls.node).sub(scenePos);
  76006. sceneDir.normalize().multiplyScalar(scale);
  76007. let sceneTarget = scenePos.clone().add(sceneDir);
  76008. vrControls.viewer.scene.view.setView(scenePos, sceneTarget);
  76009. if(Potree.debug.message){
  76010. this.dbgLabel.visible = true;
  76011. this.dbgLabel.setText(Potree.debug.message);
  76012. this.dbgLabel.scale.set(0.1, 0.1, 0.1);
  76013. this.dbgLabel.position.copy(primary.position);
  76014. }
  76015. }
  76016. };
  76017. class TranslationMode{
  76018. constructor(){
  76019. this.controller = null;
  76020. this.startPos = null;
  76021. this.debugLine = null;
  76022. }
  76023. start(vrControls){
  76024. this.controller = vrControls.triggered.values().next().value;
  76025. this.startPos = vrControls.node.position.clone();
  76026. }
  76027. end(vrControls){
  76028. }
  76029. update(vrControls, delta){
  76030. let start = this.controller.start.position;
  76031. let end = this.controller.position;
  76032. start = vrControls.toScene(start);
  76033. end = vrControls.toScene(end);
  76034. let diff = end.clone().sub(start);
  76035. diff.set(-diff.x, -diff.y, -diff.z);
  76036. let pos = new Vector3().addVectors(this.startPos, diff);
  76037. vrControls.node.position.copy(pos);
  76038. }
  76039. };
  76040. class RotScaleMode{
  76041. constructor(){
  76042. this.line = null;
  76043. this.startState = null;
  76044. }
  76045. start(vrControls){
  76046. if(!this.line){
  76047. this.line = Potree.Utils.debugLine(
  76048. vrControls.viewer.sceneVR,
  76049. new Vector3(0, 0, 0),
  76050. new Vector3(0, 0, 0),
  76051. 0xffff00,
  76052. );
  76053. this.dbgLabel = new Potree.TextSprite("abc");
  76054. this.dbgLabel.scale.set(0.1, 0.1, 0.1);
  76055. vrControls.viewer.sceneVR.add(this.dbgLabel);
  76056. }
  76057. this.line.node.visible = true;
  76058. this.startState = vrControls.node.clone();
  76059. }
  76060. end(vrControls){
  76061. this.line.node.visible = false;
  76062. this.dbgLabel.visible = false;
  76063. }
  76064. update(vrControls, delta){
  76065. let start_c1 = vrControls.cPrimary.start.position.clone();
  76066. let start_c2 = vrControls.cSecondary.start.position.clone();
  76067. let start_center = start_c1.clone().add(start_c2).multiplyScalar(0.5);
  76068. let start_c1_c2 = start_c2.clone().sub(start_c1);
  76069. let end_c1 = vrControls.cPrimary.position.clone();
  76070. let end_c2 = vrControls.cSecondary.position.clone();
  76071. let end_center = end_c1.clone().add(end_c2).multiplyScalar(0.5);
  76072. let end_c1_c2 = end_c2.clone().sub(end_c1);
  76073. let d1 = start_c1_c2.length();
  76074. let d2 = end_c1_c2.length();
  76075. let angleStart = new Vector2$1(start_c1_c2.x, start_c1_c2.z).angle();
  76076. let angleEnd = new Vector2$1(end_c1_c2.x, end_c1_c2.z).angle();
  76077. let angleDiff = angleEnd - angleStart;
  76078. let scale = d2 / d1;
  76079. let node = this.startState.clone();
  76080. node.updateMatrix();
  76081. node.matrixAutoUpdate = false;
  76082. let mToOrigin = new Matrix4().makeTranslation(...toScene(start_center, this.startState).multiplyScalar(-1).toArray());
  76083. let mToStart = new Matrix4().makeTranslation(...toScene(start_center, this.startState).toArray());
  76084. let mRotate = new Matrix4().makeRotationZ(angleDiff);
  76085. let mScale = new Matrix4().makeScale(1 / scale, 1 / scale, 1 / scale);
  76086. node.applyMatrix4(mToOrigin);
  76087. node.applyMatrix4(mRotate);
  76088. node.applyMatrix4(mScale);
  76089. node.applyMatrix4(mToStart);
  76090. let oldScenePos = toScene(start_center, this.startState);
  76091. let newScenePos = toScene(end_center, node);
  76092. let toNew = oldScenePos.clone().sub(newScenePos);
  76093. let mToNew = new Matrix4().makeTranslation(...toNew.toArray());
  76094. node.applyMatrix4(mToNew);
  76095. node.matrix.decompose(node.position, node.quaternion, node.scale );
  76096. vrControls.node.position.copy(node.position);
  76097. vrControls.node.quaternion.copy(node.quaternion);
  76098. vrControls.node.scale.copy(node.scale);
  76099. vrControls.node.updateMatrix();
  76100. {
  76101. let scale = vrControls.node.scale.x;
  76102. let camVR = vrControls.viewer.renderer.xr.getCamera(fakeCam);
  76103. let vrPos = camVR.getWorldPosition(new Vector3());
  76104. let vrDir = camVR.getWorldDirection(new Vector3());
  76105. let vrTarget = vrPos.clone().add(vrDir.multiplyScalar(scale));
  76106. let scenePos = toScene(vrPos, this.startState);
  76107. let sceneDir = toScene(vrPos.clone().add(vrDir), this.startState).sub(scenePos);
  76108. sceneDir.normalize().multiplyScalar(scale);
  76109. let sceneTarget = scenePos.clone().add(sceneDir);
  76110. vrControls.viewer.scene.view.setView(scenePos, sceneTarget);
  76111. vrControls.viewer.setMoveSpeed(scale);
  76112. }
  76113. { // update "GUI"
  76114. this.line.set(end_c1, end_c2);
  76115. let scale = vrControls.node.scale.x;
  76116. this.dbgLabel.visible = true;
  76117. this.dbgLabel.position.copy(end_center);
  76118. this.dbgLabel.setText(`scale: 1 : ${scale.toFixed(2)}`);
  76119. this.dbgLabel.scale.set(0.05, 0.05, 0.05);
  76120. }
  76121. }
  76122. };
  76123. class VRControls extends EventDispatcher{
  76124. constructor(viewer){
  76125. super(viewer);
  76126. this.viewer = viewer;
  76127. viewer.addEventListener("vr_start", this.onStart.bind(this));
  76128. viewer.addEventListener("vr_end", this.onEnd.bind(this));
  76129. this.node = new Object3D();
  76130. this.node.up.set(0, 0, 1);
  76131. this.triggered = new Set();
  76132. let xr = viewer.renderer.xr;
  76133. { // lights
  76134. const light = new PointLight( 0xffffff, 5, 0, 1 );
  76135. light.position.set(0, 2, 0);
  76136. this.viewer.sceneVR.add(light);
  76137. }
  76138. this.menu = null;
  76139. const controllerModelFactory = new XRControllerModelFactory();
  76140. let sg = new SphereGeometry(1, 32, 32);
  76141. let sm = new MeshNormalMaterial();
  76142. { // setup primary controller
  76143. let controller = xr.getController(0);
  76144. let grip = xr.getControllerGrip(0);
  76145. grip.name = "grip(0)";
  76146. // ADD CONTROLLERMODEL
  76147. grip.add( controllerModelFactory.createControllerModel( grip ) );
  76148. this.viewer.sceneVR.add(grip);
  76149. // ADD SPHERE
  76150. let sphere = new Mesh(sg, sm);
  76151. sphere.scale.set(0.005, 0.005, 0.005);
  76152. controller.add(sphere);
  76153. controller.visible = true;
  76154. this.viewer.sceneVR.add(controller);
  76155. { // ADD LINE
  76156. let lineGeometry = new LineGeometry();
  76157. lineGeometry.setPositions([
  76158. 0, 0, -0.15,
  76159. 0, 0, 0.05,
  76160. ]);
  76161. let lineMaterial = new LineMaterial({
  76162. color: 0xff0000,
  76163. lineWidth: 2,
  76164. resolution: new Vector2$1(1000, 1000),
  76165. });
  76166. const line = new Line2(lineGeometry, lineMaterial);
  76167. controller.add(line);
  76168. }
  76169. controller.addEventListener( 'connected', function ( event ) {
  76170. const xrInputSource = event.data;
  76171. controller.inputSource = xrInputSource;
  76172. // initInfo(controller);
  76173. });
  76174. controller.addEventListener( 'selectstart', () => {this.onTriggerStart(controller);});
  76175. controller.addEventListener( 'selectend', () => {this.onTriggerEnd(controller);});
  76176. this.cPrimary = controller;
  76177. }
  76178. { // setup secondary controller
  76179. let controller = xr.getController(1);
  76180. let grip = xr.getControllerGrip(1);
  76181. // ADD CONTROLLER MODEL
  76182. let model = controllerModelFactory.createControllerModel( grip );
  76183. grip.add(model);
  76184. this.viewer.sceneVR.add( grip );
  76185. // ADD SPHERE
  76186. let sphere = new Mesh(sg, sm);
  76187. sphere.scale.set(0.005, 0.005, 0.005);
  76188. controller.add(sphere);
  76189. controller.visible = true;
  76190. this.viewer.sceneVR.add(controller);
  76191. { // ADD LINE
  76192. let lineGeometry = new LineGeometry();
  76193. lineGeometry.setPositions([
  76194. 0, 0, -0.15,
  76195. 0, 0, 0.05,
  76196. ]);
  76197. let lineMaterial = new LineMaterial({
  76198. color: 0xff0000,
  76199. lineWidth: 2,
  76200. resolution: new Vector2$1(1000, 1000),
  76201. });
  76202. const line = new Line2(lineGeometry, lineMaterial);
  76203. controller.add(line);
  76204. }
  76205. controller.addEventListener( 'connected', (event) => {
  76206. const xrInputSource = event.data;
  76207. controller.inputSource = xrInputSource;
  76208. this.initMenu(controller);
  76209. });
  76210. controller.addEventListener( 'selectstart', () => {this.onTriggerStart(controller);});
  76211. controller.addEventListener( 'selectend', () => {this.onTriggerEnd(controller);});
  76212. this.cSecondary = controller;
  76213. }
  76214. this.mode_fly = new FlyMode();
  76215. this.mode_translate = new TranslationMode();
  76216. this.mode_rotScale = new RotScaleMode();
  76217. this.setMode(this.mode_fly);
  76218. }
  76219. createSlider(label, min, max){
  76220. let sg = new SphereGeometry(1, 8, 8);
  76221. let cg = new CylinderGeometry(1, 1, 1, 8);
  76222. let matHandle = new MeshBasicMaterial({color: 0xff0000});
  76223. let matScale = new MeshBasicMaterial({color: 0xff4444});
  76224. let matValue = new MeshNormalMaterial();
  76225. let node = new Object3D("slider");
  76226. let nLabel = new Potree.TextSprite(`${label}: 0`);
  76227. let nMax = new Mesh(sg, matHandle);
  76228. let nMin = new Mesh(sg, matHandle);
  76229. let nValue = new Mesh(sg, matValue);
  76230. let nScale = new Mesh(cg, matScale);
  76231. nLabel.scale.set(0.2, 0.2, 0.2);
  76232. nLabel.position.set(0, 0.35, 0);
  76233. nMax.scale.set(0.02, 0.02, 0.02);
  76234. nMax.position.set(0, 0.25, 0);
  76235. nMin.scale.set(0.02, 0.02, 0.02);
  76236. nMin.position.set(0, -0.25, 0);
  76237. nValue.scale.set(0.02, 0.02, 0.02);
  76238. nValue.position.set(0, 0, 0);
  76239. nScale.scale.set(0.005, 0.5, 0.005);
  76240. node.add(nLabel);
  76241. node.add(nMax);
  76242. node.add(nMin);
  76243. node.add(nValue);
  76244. node.add(nScale);
  76245. return node;
  76246. }
  76247. createInfo(){
  76248. let texture = new TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  76249. let plane = new PlaneBufferGeometry(1, 1, 1, 1);
  76250. let infoMaterial = new MeshBasicMaterial({map: texture});
  76251. let infoNode = new Mesh(plane, infoMaterial);
  76252. return infoNode;
  76253. }
  76254. initMenu(controller){
  76255. if(this.menu){
  76256. return;
  76257. }
  76258. let node = new Object3D("vr menu");
  76259. // let nSlider = this.createSlider("speed", 0, 1);
  76260. // let nInfo = this.createInfo();
  76261. // // node.add(nSlider);
  76262. // node.add(nInfo);
  76263. // {
  76264. // node.rotation.set(-1.5, 0, 0)
  76265. // node.scale.set(0.3, 0.3, 0.3);
  76266. // node.position.set(-0.2, -0.002, -0.1)
  76267. // // nInfo.position.set(0.5, 0, 0);
  76268. // nInfo.scale.set(0.8, 0.6, 0);
  76269. // // controller.add(node);
  76270. // }
  76271. // node.position.set(-0.3, 1.2, 0.2);
  76272. // node.scale.set(0.3, 0.2, 0.3);
  76273. // node.lookAt(new THREE.Vector3(0, 1.5, 0.1));
  76274. // this.viewer.sceneVR.add(node);
  76275. this.menu = node;
  76276. // window.vrSlider = nSlider;
  76277. window.vrMenu = node;
  76278. }
  76279. toScene(vec){
  76280. let camVR = this.getCamera();
  76281. let mat = camVR.matrixWorld;
  76282. let result = vec.clone().applyMatrix4(mat);
  76283. return result;
  76284. }
  76285. toVR(vec){
  76286. let camVR = this.getCamera();
  76287. let mat = camVR.matrixWorld.clone();
  76288. mat.invert();
  76289. let result = vec.clone().applyMatrix4(mat);
  76290. return result;
  76291. }
  76292. setMode(mode){
  76293. if(this.mode === mode){
  76294. return;
  76295. }
  76296. if(this.mode){
  76297. this.mode.end(this);
  76298. }
  76299. for(let controller of [this.cPrimary, this.cSecondary]){
  76300. let start = {
  76301. position: controller.position.clone(),
  76302. rotation: controller.rotation.clone(),
  76303. };
  76304. controller.start = start;
  76305. }
  76306. this.mode = mode;
  76307. this.mode.start(this);
  76308. }
  76309. onTriggerStart(controller){
  76310. this.triggered.add(controller);
  76311. if(this.triggered.size === 0){
  76312. this.setMode(this.mode_fly);
  76313. }else if(this.triggered.size === 1){
  76314. this.setMode(this.mode_translate);
  76315. }else if(this.triggered.size === 2){
  76316. this.setMode(this.mode_rotScale);
  76317. }
  76318. }
  76319. onTriggerEnd(controller){
  76320. this.triggered.delete(controller);
  76321. if(this.triggered.size === 0){
  76322. this.setMode(this.mode_fly);
  76323. }else if(this.triggered.size === 1){
  76324. this.setMode(this.mode_translate);
  76325. }else if(this.triggered.size === 2){
  76326. this.setMode(this.mode_rotScale);
  76327. }
  76328. }
  76329. onStart(){
  76330. let position = this.viewer.scene.view.position.clone();
  76331. let direction = this.viewer.scene.view.direction;
  76332. direction.multiplyScalar(-1);
  76333. let target = position.clone().add(direction);
  76334. target.z = position.z;
  76335. let scale = this.viewer.getMoveSpeed();
  76336. this.node.position.copy(position);
  76337. this.node.lookAt(target);
  76338. this.node.scale.set(scale, scale, scale);
  76339. this.node.updateMatrix();
  76340. this.node.updateMatrixWorld();
  76341. }
  76342. onEnd(){
  76343. }
  76344. setScene(scene){
  76345. this.scene = scene;
  76346. }
  76347. getCamera(){
  76348. let reference = this.viewer.scene.getActiveCamera();
  76349. let camera = new PerspectiveCamera();
  76350. // let scale = this.node.scale.x;
  76351. let scale = this.viewer.getMoveSpeed();
  76352. //camera.near = 0.01 / scale;
  76353. camera.near = 0.1;
  76354. camera.far = 1000;
  76355. // camera.near = reference.near / scale;
  76356. // camera.far = reference.far / scale;
  76357. camera.up.set(0, 0, 1);
  76358. camera.lookAt(new Vector3(0, -1, 0));
  76359. camera.updateMatrix();
  76360. camera.updateMatrixWorld();
  76361. camera.position.copy(this.node.position);
  76362. camera.rotation.copy(this.node.rotation);
  76363. camera.scale.set(scale, scale, scale);
  76364. camera.updateMatrix();
  76365. camera.updateMatrixWorld();
  76366. camera.matrixAutoUpdate = false;
  76367. camera.parent = camera;
  76368. return camera;
  76369. }
  76370. update(delta){
  76371. // if(this.mode === this.mode_fly){
  76372. // let ray = new THREE.Ray(origin, direction);
  76373. // for(let object of this.selectables){
  76374. // if(object.intersectsRay(ray)){
  76375. // object.onHit(ray);
  76376. // }
  76377. // }
  76378. // }
  76379. this.mode.update(this, delta);
  76380. }
  76381. };
  76382. // Adapted from three.js VRButton
  76383. class VRButton {
  76384. constructor(){
  76385. this.onStartListeners = [];
  76386. this.onEndListeners = [];
  76387. this.element = null;
  76388. }
  76389. onStart(callback){
  76390. this.onStartListeners.push(callback);
  76391. }
  76392. onEnd(callback){
  76393. this.onEndListeners.push(callback);
  76394. }
  76395. static async createButton( renderer, options ) {
  76396. if ( options ) {
  76397. console.error( 'THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.' );
  76398. }
  76399. const button = new VRButton();
  76400. const element = document.createElement( 'button' );
  76401. button.element = element;
  76402. function setEnter(){
  76403. button.element.innerHTML = `
  76404. <div style="font-size: 0.5em;">ENTER</div>
  76405. <div style="font-weight: bold;">VR</div>
  76406. `;
  76407. }
  76408. function setExit(){
  76409. button.element.innerHTML = `
  76410. <div style="font-size: 0.5em;">EXIT</div>
  76411. <div style="font-weight: bold;">VR</div>
  76412. `;
  76413. }
  76414. function showEnterVR( /*device*/ ) {
  76415. let currentSession = null;
  76416. function onSessionStarted( session ) {
  76417. session.addEventListener( 'end', onSessionEnded );
  76418. for(let listener of button.onStartListeners){
  76419. listener();
  76420. }
  76421. renderer.xr.setSession( session );
  76422. setExit();
  76423. currentSession = session;
  76424. }
  76425. function onSessionEnded( /*event*/ ) {
  76426. currentSession.removeEventListener( 'end', onSessionEnded );
  76427. for(let listener of button.onEndListeners){
  76428. listener();
  76429. }
  76430. setEnter();
  76431. currentSession = null;
  76432. }
  76433. //
  76434. button.element.style.display = '';
  76435. button.element.style.cursor = 'pointer';
  76436. setEnter();
  76437. button.element.onmouseenter = function () {
  76438. button.element.style.opacity = '1.0';
  76439. };
  76440. button.element.onmouseleave = function () {
  76441. button.element.style.opacity = '0.7';
  76442. };
  76443. button.element.onclick = function () {
  76444. if ( currentSession === null ) {
  76445. // WebXR's requestReferenceSpace only works if the corresponding feature
  76446. // was requested at session creation time. For simplicity, just ask for
  76447. // the interesting ones as optional features, but be aware that the
  76448. // requestReferenceSpace call will fail if it turns out to be unavailable.
  76449. // ('local' is always available for immersive sessions and doesn't need to
  76450. // be requested separately.)
  76451. const sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor', 'hand-tracking' ] };
  76452. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  76453. } else {
  76454. currentSession.end();
  76455. }
  76456. };
  76457. }
  76458. function stylizeElement( element ) {
  76459. element.style.position = 'absolute';
  76460. element.style.bottom = '20px';
  76461. element.style.padding = '12px 6px';
  76462. element.style.border = '1px solid #fff';
  76463. element.style.borderRadius = '4px';
  76464. element.style.background = 'rgba(0,0,0,0.1)';
  76465. element.style.color = '#fff';
  76466. element.style.font = 'normal 13px sans-serif';
  76467. element.style.textAlign = 'center';
  76468. element.style.opacity = '0.7';
  76469. element.style.outline = 'none';
  76470. element.style.zIndex = '999';
  76471. }
  76472. if ( 'xr' in navigator ) {
  76473. button.element.id = 'VRButton';
  76474. button.element.style.display = 'none';
  76475. stylizeElement( button.element );
  76476. let supported = await navigator.xr.isSessionSupported( 'immersive-vr' );
  76477. if(supported){
  76478. showEnterVR();
  76479. return button;
  76480. }else {
  76481. return null;
  76482. }
  76483. } else {
  76484. if ( window.isSecureContext === false ) {
  76485. console.log("WEBXR NEEDS HTTPS");
  76486. } else {
  76487. console.log("WEBXR not available");
  76488. }
  76489. return null;
  76490. }
  76491. }
  76492. }
  76493. //处理cursor优先级
  76494. var CursorDeal = {
  76495. priorityEvent : [//在前面的优先级高
  76496. {'zoomInCloud':'zoom-in'},
  76497. {'hoverPano':'pointer'},
  76498. {'connectPano':`url({Potree.resourcePath}/images/connect.png),auto`},
  76499. {'disconnectPano':`url({Potree.resourcePath}/images/connect-dis.png),auto`},
  76500. {'hoverLine':'pointer'},
  76501. {"movePointcloud":'move'},
  76502. {"polygon_isIntersectSelf":'not-allowed'},
  76503. {"polygon_AtWrongPlace":'not-allowed'},
  76504. {"markerMove":'grab'},
  76505. {'mapClipMove':'move'},
  76506. {'mapClipRotate':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76507. {'rotatePointcloud':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76508. {'siteModelFloorDrag':'row-resize'},
  76509. {'addSth':'cell'},//or crosshair
  76510. ],
  76511. list:[], //当前存在的cursor状态
  76512. currentCursorIndex:null,
  76513. init : function(viewer, viewers){
  76514. this.priorityEvent.forEach(e=>{//刚开始Potree.resourcePath没值,现在换
  76515. for(let i in e){
  76516. e[i] = Common.replaceAll(e[i],'{Potree.resourcePath}',Potree.resourcePath);
  76517. }
  76518. });
  76519. this.domElements = viewers.map(e=>e.renderArea);
  76520. viewer.addEventListener("CursorChange",(e)=>{
  76521. if(e.action == 'add'){
  76522. this.add(e.name);
  76523. }else {
  76524. this.remove(e.name);
  76525. }
  76526. });
  76527. },
  76528. add : function(name){
  76529. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76530. if(!priorityItem){
  76531. console.error('CursorDeal 未定义优先级 name:'+ name);
  76532. return
  76533. }
  76534. if(!this.list.includes(name)){
  76535. this.judge({addItem: priorityItem, name});
  76536. this.list.push(name);
  76537. }
  76538. },
  76539. remove : function(name){
  76540. var index = this.list.indexOf(name);
  76541. if(index > -1){
  76542. this.list.splice(index, 1);
  76543. this.judge();
  76544. }
  76545. },
  76546. judge:function(o={}){
  76547. //console.log(o,this.list)
  76548. if(o.addItem){
  76549. var addIndex = this.priorityEvent.indexOf(o.addItem);
  76550. if(addIndex < this.currentCursorIndex || this.currentCursorIndex == void 0){
  76551. this.domElements.forEach(e=>e.style.cursor = o.addItem[o.name] );
  76552. this.currentCursorIndex = addIndex;
  76553. }
  76554. }else {
  76555. var levelMax = {index:Infinity, cursor:null };
  76556. this.list.forEach(name=>{
  76557. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76558. var index = this.priorityEvent.indexOf(priorityItem);
  76559. if(index < levelMax.index){
  76560. levelMax.index = index;
  76561. levelMax.cursor = priorityItem[name];
  76562. }
  76563. });
  76564. this.currentCursorIndex = levelMax.index;
  76565. this.domElements.forEach(e=>e.style.cursor = levelMax.cursor || '');
  76566. }
  76567. }
  76568. };
  76569. let texLoader$6 = new TextureLoader();
  76570. let color$1 = new Color(config$1.clip.color);
  76571. let markerMats$1;
  76572. let markerSizeInfo$1 = {width2d:30};
  76573. class mapClipBox extends ctrlPolygon {
  76574. constructor (center, scale) {
  76575. center = center.clone().setZ(0);//所有Z都为0
  76576. let prop = {
  76577. points : getPoints(center, scale, 0),
  76578. closed : true,
  76579. isRect : true,
  76580. dimension : '2d'
  76581. };
  76582. super('mapClipBox', prop);
  76583. this.angle = 0;
  76584. this.createRotateBar();
  76585. this.edgeMarkers = [];
  76586. //addMarkers:
  76587. this.initData(prop);
  76588. {//areaPlane event 能拖动
  76589. this.areaPlane.addEventListener('mouseover',()=>{
  76590. viewer.dispatchEvent({
  76591. type : "CursorChange", action : "add", name:"mapClipMove"
  76592. });
  76593. });
  76594. this.areaPlane.addEventListener('mouseleave',()=>{
  76595. viewer.dispatchEvent({
  76596. type : "CursorChange", action : "remove", name:"mapClipMove"
  76597. });
  76598. });
  76599. let lastPos;
  76600. let drag = (e)=>{
  76601. let intersect = e.intersect.orthoIntersect;
  76602. if(lastPos){
  76603. let moveVec = new Vector3().subVectors(intersect, lastPos).setZ(0);
  76604. this.center.add(moveVec);
  76605. this.updatePoints();
  76606. this.dispatchEvent({type:'repos'});
  76607. }
  76608. lastPos = intersect.clone();
  76609. };
  76610. let drop = (e)=>{
  76611. lastPos = null;
  76612. };
  76613. this.areaPlane.addEventListener('drag', drag);
  76614. this.areaPlane.addEventListener('drop', drop);
  76615. }
  76616. /* this.addEventListener('dragChange',()=>{
  76617. this.updateTwoMidMarker(index+1)
  76618. }) */
  76619. viewer.setObjectLayers(this, 'mapObjects' );
  76620. }
  76621. getScale(){
  76622. return new Vector3(this.points[0].distanceTo(this.points[1]), this.points[1].distanceTo(this.points[2]) ,1)
  76623. }
  76624. addMarker(o={} ){
  76625. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_marker", } );
  76626. marker.renderOrder = 3;
  76627. //marker.markerSelectStates = {}
  76628. let edge = LineDraw.createLine([new Vector3,new Vector3],{color: color$1 });
  76629. let edgeMarker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_edgePoint"} );
  76630. let mouseover = (e) => {
  76631. this.setMarkerSelected(e.object, true, 'single');
  76632. viewer.dispatchEvent({
  76633. type : "CursorChange", action : "add", name:"markerMove"
  76634. });
  76635. };
  76636. let mouseleave = (e) => {
  76637. this.setMarkerSelected(e.object, false, 'single');
  76638. viewer.dispatchEvent({
  76639. type : "CursorChange", action : "remove", name:"markerMove"
  76640. });
  76641. };
  76642. edgeMarker.addEventListener('mouseover', mouseover);
  76643. edgeMarker.addEventListener('mouseleave', mouseleave);
  76644. let dragInfo = {lastPos:null};
  76645. edgeMarker.addEventListener('drag', this.dragEdge.bind(this,dragInfo));
  76646. edgeMarker.addEventListener('drop', this.dropEdge.bind(this,dragInfo));
  76647. this.edgeMarkers.push(edgeMarker);
  76648. this.add(edgeMarker);
  76649. marker.dispatchEvent('addHoverEvent');
  76650. super.addMarker({point:o.point, marker:marker, edge});
  76651. }
  76652. dragEdge(dragInfo, e){//拖拽一个边(或一个边类型的marker),带动它的两个端点。 可以转化为拖拽marker往法线方向
  76653. var I, atMap;
  76654. atMap = e.dragViewport.name == 'mapViewport';
  76655. I = e.intersect.orthoIntersect;
  76656. if (I && dragInfo.lastPos) {
  76657. let i = this.edgeMarkers.indexOf(e.drag.object);
  76658. if (i !== -1) {
  76659. let lineNormal = math.getNormal2d({p1:this.points[i], p2:this.points[(i+1)%4]});
  76660. let moveVec = new Vector3().subVectors(I, dragInfo.lastPos).setZ(0);//移动的向量
  76661. let dragVec = moveVec.projectOnVector(lineNormal).setZ(0);//在法线上移动的向量
  76662. let newPos = new Vector3().addVectors(this.points[i], dragVec); //marker应到的位置
  76663. this.dragChange(newPos, i, atMap); //转化为这个marker的拖拽
  76664. }
  76665. }
  76666. dragInfo.lastPos = I.clone();
  76667. }
  76668. dropEdge(dragInfo, e){
  76669. dragInfo.lastPos = null;
  76670. this.setMarkerSelected(e.drag.object, false, 'single'); //拖拽时似乎没有触发mouseout
  76671. }
  76672. createAreaPlane(){
  76673. var planeMat = new MeshBasicMaterial({
  76674. color: color$1,//"#00eeff",
  76675. side:DoubleSide,
  76676. opacity:0.3,
  76677. transparent:true,
  76678. depthTest:false
  76679. });
  76680. return super.createAreaPlane(planeMat)
  76681. }
  76682. getMarkerMaterial(type) {
  76683. if(!markerMats$1){
  76684. markerMats$1 = {
  76685. default: new MeshBasicMaterial({
  76686. transparent: !0,
  76687. color: color$1,
  76688. opacity: 0.8,
  76689. map: texLoader$6.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76690. }),
  76691. select: new MeshBasicMaterial({
  76692. transparent: !0,
  76693. color: color$1,
  76694. opacity: 1,
  76695. map: texLoader$6.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76696. }),
  76697. };
  76698. mapClipBox.markerMats = markerMats$1;
  76699. }
  76700. return markerMats$1[type]
  76701. }
  76702. setMarkerSelected(marker, state, hoverObject){
  76703. //console.warn(marker.id , state, hoverObject)
  76704. if(state == 'hover'){
  76705. marker.material = this.getMarkerMaterial('select');
  76706. }else {
  76707. marker.material = this.getMarkerMaterial('default');
  76708. }
  76709. /* marker.markerSelectStates[hoverObject] = state
  76710. let absoluteState = false
  76711. for(var i in marker.markerSelectStates){
  76712. if(marker.markerSelectStates[i]){
  76713. absoluteState = true; break;
  76714. }
  76715. }
  76716. if(absoluteState){
  76717. marker.material = this.getMarkerMaterial('select')
  76718. }else{
  76719. marker.material = this.getMarkerMaterial('default')
  76720. }
  76721. marker.selected = absoluteState */
  76722. viewer.mapViewer.dispatchEvent('content_changed');
  76723. }
  76724. createRotateBar(){
  76725. //中心点在线的一端,整体初始在box上方
  76726. const lineLen = 1.5, circleWidth = 2, barOpacity = 0.7;
  76727. let object = new Object3D;
  76728. let bar = new Sprite$1({mat:new MeshBasicMaterial({
  76729. side:DoubleSide,
  76730. opacity: barOpacity,
  76731. transparent:true,
  76732. depthTest:false,
  76733. map: texLoader$6.load(Potree.resourcePath+'/textures/rotation_circle.png' ),
  76734. }) ,
  76735. root:object,
  76736. sizeInfo: markerSizeInfo$1,
  76737. dontFixOrient: true,
  76738. viewports:viewer.mapViewer.viewports,
  76739. name:"mapClipRotateBar"
  76740. });
  76741. bar.position.set(0,lineLen+circleWidth/2,0);
  76742. bar.scale.set(circleWidth,circleWidth,circleWidth);
  76743. bar.addEventListener('mouseover',()=>{
  76744. bar.material.opacity = 1;
  76745. viewer.dispatchEvent({
  76746. type : "CursorChange", action : "add", name:"mapClipRotate"
  76747. });
  76748. viewer.mapViewer.dispatchEvent('content_changed');
  76749. });
  76750. let leave = ()=>{
  76751. bar.material.opacity = barOpacity;
  76752. viewer.dispatchEvent({
  76753. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76754. });
  76755. viewer.mapViewer.dispatchEvent('content_changed');
  76756. };
  76757. bar.addEventListener('mouseleave',leave);
  76758. this.addEventListener('dispose', leave);
  76759. let lastPos;
  76760. bar.addEventListener('drag',(e)=>{
  76761. var intersect = e.intersect.orthoIntersect;
  76762. if(lastPos){
  76763. let vec1 = new Vector3().subVectors(lastPos, this.center).setZ(0);
  76764. let vec2 = new Vector3().subVectors(intersect, this.center).setZ(0);
  76765. let angle = math.getAngle(vec1,vec2,'z');
  76766. this.angle += angle;
  76767. this.rotateBar.rotation.z = this.angle;
  76768. this.updatePoints();
  76769. this.dispatchEvent({type:'rotate', angle: this.angle});
  76770. }
  76771. lastPos = intersect.clone();
  76772. });
  76773. bar.addEventListener('drop',()=>{
  76774. lastPos = null;
  76775. viewer.dispatchEvent({
  76776. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76777. });
  76778. });
  76779. let line = LineDraw.createLine([new Vector3, new Vector3(0,lineLen,0)],{color: color$1});
  76780. object.add(bar);
  76781. object.add(line);
  76782. this.add(object);
  76783. this.rotateBar = object;
  76784. this.rotateBar.bar = bar;
  76785. }
  76786. updatePoints(scale){
  76787. this.points = getPoints(this.center, scale || this.getScale(), this.angle);
  76788. this.getPoint2dInfo(this.points);
  76789. this.update({ifUpdateMarkers:true});
  76790. }
  76791. update(options={}){
  76792. super.update(options);
  76793. {//update rotateBar
  76794. let center = new Vector3().addVectors(this.points[0], this.points[1]).multiplyScalar(0.5);
  76795. this.rotateBar.position.copy(center);
  76796. this.rotateBar.bar.update();//更新sprite matrix
  76797. }
  76798. {
  76799. for(let i=0;i<4;i++){
  76800. let current = this.points[i];
  76801. let next = this.points[(i+1)%4];
  76802. let mid = new Vector3().addVectors(current, next).multiplyScalar(0.5);
  76803. this.updateMarker(this.edgeMarkers[i], mid);
  76804. }
  76805. }
  76806. }
  76807. dispose(){
  76808. super.dispose();
  76809. this.dispatchEvent('dispose');
  76810. }
  76811. }
  76812. function getPoints(center, scale, angle=0){
  76813. let points = [
  76814. new Vector3(-scale.x/2, +scale.y/2, 0),
  76815. new Vector3(+scale.x/2, +scale.y/2, 0),
  76816. new Vector3(+scale.x/2, -scale.y/2, 0),
  76817. new Vector3(-scale.x/2, -scale.y/2, 0),
  76818. ];
  76819. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  76820. points.forEach(e=>{
  76821. e.applyMatrix4(rotMatrix);
  76822. e.add(center);
  76823. });
  76824. return points
  76825. }
  76826. const defaultBoxWidth = 6; //navvis: 10
  76827. //navvis position: si {x: 0, y: 0, z: 0}
  76828. var Clip = {
  76829. bus : new EventDispatcher,
  76830. selectedDatasets : [],
  76831. changeCallback(force){
  76832. if(Potree.settings.isOfficial){
  76833. Common.intervalTool.isWaiting('clipSelectedDatasets', ()=>{ //延时update,防止卡顿
  76834. let pointclouds = this.getIntersectPointcloud();
  76835. if(force || Common.getDifferenceSet(pointclouds,this.selectedDatasets).length){
  76836. this.selectedDatasets = pointclouds;
  76837. //console.error('clipSelectedDatasets',selectedDatasets)
  76838. this.bus.dispatchEvent({type:'updateSelectedDatasets', selectedDatasets:pointclouds.map(e=>e.dataset_id) });
  76839. force = false;
  76840. return true
  76841. }
  76842. }, 300);
  76843. }
  76844. },
  76845. enter:function(){
  76846. this.previousView = {
  76847. position: viewer.images360.position,
  76848. target: viewer.scene.view.getPivot(),
  76849. displayMode : Potree.settings.displayMode,
  76850. //---
  76851. ifShowMarker : Potree.settings.ifShowMarker,
  76852. };
  76853. let pointcloud = this.getPointcloud();
  76854. let bound = pointcloud.bound; //只选取其中一个数据集的bound,而非整体,是因为担心两个数据集中间有空隙,于是刚好落在没有点云的地方。
  76855. let boundSize = bound.getSize(new Vector3());
  76856. let target = this.getTarget(bound.getCenter(new Vector3())); //navvis的位置xy是用相机位置 this.ViewService.mainView.getCamera().position 我觉得也可以用第一个漫游点的,或者最接近bound中心的漫游点
  76857. let scale = new Vector3(defaultBoxWidth,defaultBoxWidth, boundSize.z);//z和navvis一样
  76858. let eyeDir = viewer.scene.view.direction.clone().setZ(0/* -boundSize.z/3 */).multiplyScalar(-defaultBoxWidth); //为了使所在楼层不变,不修改z
  76859. //let eyeDir = scale.clone().setZ(boundSize.z/3).multiplyScalar(1.3)
  76860. let position = new Vector3().addVectors(target, eyeDir);
  76861. Potree.settings.displayMode = 'showPointCloud';
  76862. viewer.setView({
  76863. position ,
  76864. target,
  76865. duration:300,
  76866. callback:function(){
  76867. }
  76868. });
  76869. viewer.setControls(viewer.orbitControls);
  76870. viewer.setLimitFar(false);
  76871. {
  76872. this.box = new BoxVolume({
  76873. clip:true
  76874. });
  76875. this.box.name = "ClipBox";
  76876. this.box.position.copy(target);
  76877. this.box.scale.copy(scale);
  76878. //带动mapBox
  76879. this.box.addEventListener('position_changed',e=>{
  76880. this.mapBox.center.setX(this.box.position.x);
  76881. this.mapBox.center.setY(this.box.position.y);
  76882. this.mapBox.updatePoints();
  76883. this.changeCallback();
  76884. });
  76885. this.box.addEventListener('scale_changed',e=>{
  76886. var scale = this.box.scale;
  76887. this.mapBox.updatePoints(scale);
  76888. this.changeCallback();
  76889. });
  76890. this.box.addEventListener('orientation_changed',e=>{
  76891. this.mapBox.angle = this.box.rotation.z;
  76892. this.mapBox.rotateBar.rotation.z = this.mapBox.angle;
  76893. this.mapBox.updatePoints();
  76894. this.changeCallback();
  76895. });
  76896. viewer.scene.addVolume(this.box);
  76897. }
  76898. {//map
  76899. let boxRotateBack = ()=>{//不知道是不是这么写。 因为可能z的旋转不一定都在z
  76900. this.box.rotation.x = 0;
  76901. this.box.rotation.y = 0;
  76902. };
  76903. this.mapBox = new mapClipBox(target, scale);
  76904. viewer.mapViewer.scene.add(this.mapBox);
  76905. //带动box
  76906. this.mapBox.addEventListener('repos',e=>{
  76907. this.box.position.setX(this.mapBox.center.x);
  76908. this.box.position.setY(this.mapBox.center.y);
  76909. boxRotateBack();
  76910. this.changeCallback();
  76911. });
  76912. this.mapBox.addEventListener('dragChange',e=>{
  76913. var scale = this.mapBox.getScale();
  76914. this.box.scale.setX(scale.x);
  76915. this.box.scale.setY(scale.y);
  76916. this.box.position.setX(this.mapBox.center.x);
  76917. this.box.position.setY(this.mapBox.center.y);
  76918. boxRotateBack();
  76919. this.changeCallback();
  76920. });
  76921. this.mapBox.addEventListener('rotate',e=>{
  76922. this.box.rotation.z = this.mapBox.angle;
  76923. boxRotateBack();
  76924. this.changeCallback();
  76925. });
  76926. }
  76927. {
  76928. viewer.setClipTask(ClipTask["SHOW_INSIDE"]);
  76929. //viewer.setClipMethod(ClipMethod["INSIDE_ANY"])
  76930. }
  76931. Potree.settings.unableNavigate = true;
  76932. Potree.settings.ifShowMarker = false;
  76933. viewer.updateVisible(viewer.measuringTool.scene, 'clipModel', false);
  76934. //viewer.updateVisible(viewer.mapViewer.cursor, 'clipModel', false)//隐藏地图游标
  76935. viewer.inputHandler.toggleSelection(this.box);
  76936. viewer.inputHandler.fixSelection = true;
  76937. viewer.transformationTool.frame.material.color.set(Potree.config.clip.color);//navvis 15899953
  76938. viewer.setPointStandardMat(true);
  76939. {
  76940. this.events = {
  76941. flyToPos : (e)=>{
  76942. let dis = 2;
  76943. let target = e.position;
  76944. //position = new THREE.Vector3().subVectors(target, this.scene.view.direction)
  76945. //永远朝向框的中心
  76946. /* let dir = new THREE.Vector3().subVectors(this.box.position, e.position).normalize()
  76947. position = new THREE.Vector3().subVectors(target, dir) */
  76948. target = this.box.position;
  76949. position = e.position;
  76950. //为了方便缩放操作,直接使用box中心作为target
  76951. let duration = 1000;
  76952. viewer.scene.view.setView({position, duration, target});
  76953. }
  76954. };
  76955. this.bus.addEventListener('flyToPos',this.events.flyToPos);
  76956. }
  76957. this.editing = true;
  76958. setTimeout(()=>{this.changeCallback(true);},1);
  76959. },
  76960. leave:function(){
  76961. viewer.inputHandler.fixSelection = false;
  76962. viewer.scene.removeVolume(this.box);
  76963. this.mapBox.dispose();
  76964. viewer.setControls(viewer.fpControls);
  76965. Potree.settings.unableNavigate = false;
  76966. Potree.settings.ifShowMarker = this.previousView.ifShowMarker;
  76967. viewer.updateVisible(viewer.measuringTool.scene, 'clipModel', true);
  76968. //viewer.updateVisible(viewer.mapViewer.cursor, 'clipModel', true)
  76969. viewer.setView(this.previousView);
  76970. viewer.setLimitFar(true);
  76971. viewer.setPointStandardMat(false);
  76972. {
  76973. this.bus.removeEventListener('flyToPos',this.events.flyToPos);
  76974. this.events = null;
  76975. }
  76976. this.editing = false;
  76977. },
  76978. getPointcloud:function(){ //找一个离当前最近的点云,且最好有漫游点
  76979. let pointclouds = viewer.scene.pointclouds.filter(e=>e.panos.length>0);
  76980. if(pointclouds.length == 0)pointclouds = viewer.scene.pointclouds;
  76981. let result = Common.sortByScore(pointclouds,[],[e=>{
  76982. let center = e.bound.getCenter(new Vector3);
  76983. let size = e.bound.getSize(new Vector3).length() / 2;
  76984. let posToCenter = viewer.images360.position.distanceTo(center);
  76985. return size / posToCenter
  76986. }]);
  76987. return result[0].item
  76988. },
  76989. getTarget:function(boundCenter){//box位置。要找一个有点云的地方。方案1相机位置, 方案2接近相机的漫游点, 方案3接近中心的漫游点。选择方案2,因最大概率有点云
  76990. var target = new Vector3();
  76991. var cameraPos = viewer.images360.position;
  76992. var pano = Common.find(viewer.images360.panos , [], [Images360.sortFunctions.floorDisSquaredToPoint(cameraPos)]);
  76993. if(pano){
  76994. target.copy(pano.position);
  76995. target.setZ(boundCenter.z);
  76996. }else {
  76997. target.copy(boundCenter);
  76998. }
  76999. return target
  77000. },
  77001. /* switchMap:function(state){
  77002. }, */
  77003. download:function( ){
  77004. if(this.getIntersectPointcloud().length == 0){
  77005. return null
  77006. }
  77007. var visiPointclouds = viewer.scene.pointclouds.filter(e=> viewer.getObjVisiByReason(e, 'datasetSelection'));
  77008. let data = {
  77009. transformation_matrix: visiPointclouds.map((cloud)=>{
  77010. let data = {
  77011. id: cloud.dataset_id,
  77012. matrix : this.getTransformationMatrix(cloud).elements,
  77013. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  77014. };
  77015. return data
  77016. }) ,
  77017. aabb: "b-0.5 -0.5 -0.5 0.5 0.5 0.5" //剪裁空间( 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的
  77018. };
  77019. return data
  77020. //https://testlaser.4dkankan.com/indoor/t-ia44BhY/api/pointcloud/crop
  77021. },
  77022. downloadNoCrop(){//不剪裁 下载整个点云
  77023. var visiPointclouds = viewer.scene.pointclouds.filter(e=> viewer.getObjVisiByReason(e, 'datasetSelection'));
  77024. let data = {
  77025. transformation_matrix: visiPointclouds.map((cloud)=>{
  77026. let data = {
  77027. id: cloud.dataset_id,
  77028. matrix : new Matrix4().elements, //固定值
  77029. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  77030. };
  77031. return data
  77032. }) ,
  77033. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //固定剪裁空间
  77034. };
  77035. console.log(data);
  77036. return data
  77037. },
  77038. getTransformationMatrix:function(pointcloud) {//剪裁矩阵
  77039. var invMatrix = new Matrix4().getInverse(this.box.matrixWorld);
  77040. return (new Matrix4).multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose()
  77041. },
  77042. getIntersectPointcloud(){
  77043. var boxBound = new Box3(
  77044. new Vector3(-0.5,-0.5,-0.5), new Vector3(0.5,0.5,0.5),
  77045. ).applyMatrix4(this.box.matrixWorld); //large boundingbox
  77046. /* var boxTightPoints = this.box.children[0].geometry.vertices.map(e=>e.clone().applyMatrix4(this.matrixWorld))
  77047. console.log(boxTightPoints)
  77048. */
  77049. let boxMatrixInverse = new Matrix4().copy(this.box.matrixWorld).invert();
  77050. let boxPoints = [
  77051. new Vector3(boxBound.min.x, boxBound.min.y,0),
  77052. new Vector3(boxBound.max.x, boxBound.min.y,0),
  77053. new Vector3(boxBound.max.x, boxBound.max.y,0),
  77054. new Vector3(boxBound.min.x, boxBound.max.y,0)
  77055. ];
  77056. var intersect = (pointcloud)=>{
  77057. if(!pointcloud.bound.intersectsBox(boxBound))return false
  77058. //判断box和点云的tight bound是否相交(因为box可以任意旋转,且实在找不到三维中的立方体相交的函数,所以直接用boxBound)
  77059. var points = pointcloud.getUnrotBoundPoint('all');
  77060. let rings = math.getPolygonsMixedRings([points.slice(0,4), boxPoints] , true);
  77061. //console.log(pointcloud.dataset_id, pointcloud.name, rings.length)
  77062. if(rings.length > 1 )return false
  77063. {//再用frustum和数据集的sphere相交试试,能排除一些错误
  77064. let a = Potree.Utils.isInsideBox(points, boxMatrixInverse);
  77065. if(!a){
  77066. console.log('没能经过isInsideBox测试');
  77067. }
  77068. return a
  77069. }
  77070. return true
  77071. };
  77072. return viewer.scene.pointclouds.filter(e=>intersect(e))
  77073. }
  77074. /*
  77075. 裁剪点云时,2D界面显示全部平面图,按楼层切换显示。
  77076. */
  77077. };
  77078. class SplitScreen extends EventDispatcher{
  77079. constructor (args = {}) {
  77080. super();
  77081. }
  77082. splitStart(cameraProps){
  77083. let viewports = [];
  77084. let subViewports = [viewer.mainViewport];
  77085. if(viewer.mapViewer){
  77086. subViewports.push(viewer.mapViewer.viewports[0]);
  77087. }
  77088. let length = cameraProps.length;
  77089. for(let i=0;i<length;i++){
  77090. let prop = cameraProps[i];
  77091. let viewport;
  77092. let v = subViewports.find(e=>e.name == (prop.name2||prop.name));
  77093. if(v){
  77094. viewport = v;
  77095. viewport.left = prop.left; viewport.bottom = prop.bottom; viewport.width = prop.width; viewport.height = prop.height;
  77096. }
  77097. if(!viewport){
  77098. let view = new View();
  77099. if(prop.limitBound)view.limitBound = prop.limitBound;
  77100. prop.direction && (view.direction = prop.direction);
  77101. viewport = new Viewport(view , this.getOrthoCamera(), prop );
  77102. if(prop.viewContainsPoints)viewport.viewContainsPoints = prop.viewContainsPoints;
  77103. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  77104. }
  77105. if(viewport.camera.type == 'OrthographicCamera' ){
  77106. viewport.targetPlane = new Plane();
  77107. viewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  77108. }
  77109. viewport.fitMargin = prop.margin;
  77110. viewports.push(viewport);
  77111. }
  77112. viewer.viewports = viewports;
  77113. viewer.updateScreenSize({forceUpdateSize:true});
  77114. viewports.forEach(viewport=>{
  77115. if(viewport.name == 'MainView')return
  77116. this.viewportFitBound(viewport, viewer.bound.boundingBox , viewer.bound.center , 0, viewport.fitMargin);
  77117. });
  77118. return viewports
  77119. }
  77120. unSplit(){
  77121. this.unfocusViewport();
  77122. viewer.viewports = [viewer.mainViewport];
  77123. viewer.mainViewport.width = 1;
  77124. viewer.mainViewport.height = 1;
  77125. viewer.mainViewport.left = 0;
  77126. viewer.mainViewport.bottom = 0;
  77127. viewer.updateScreenSize({forceUpdateSize:true});
  77128. }
  77129. viewportFitBound(viewport, bound, center, duration=0, margin){
  77130. let view = viewport.view;
  77131. let info = {bound};
  77132. let {boundSize, boundCenter} = this.getViewBound(viewport);
  77133. viewport.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), boundCenter );
  77134. viewport.targetPlane.projectPoint(center, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  77135. info.endPosition = this.getPosOutOfModel(viewport, boundSize);
  77136. //if(viewport.name == 'mapViewport')info.endPosition.z = Math.max(Potree.config.map.cameraHeight, info.endPosition.z)
  77137. info.margin = margin || {x:30, y:30};
  77138. view.moveOrthoCamera(viewport, info , duration );
  77139. }
  77140. getViewBound(viewport){
  77141. let {boundSize, center} = viewer.bound;
  77142. if(viewport.viewContainsPoints){//视野范围内必须要包含的点,直接算入模型区域。这时候得到的boundCenter和模型中心不重合
  77143. let boundingBox = viewer.bound.boundingBox.clone();
  77144. viewport.viewContainsPoints.forEach(point=>{
  77145. boundingBox.expandByPoint(point);
  77146. });
  77147. boundSize = boundingBox.getSize(new Vector3);
  77148. center = boundingBox.getCenter(new Vector3);
  77149. }
  77150. return {boundSize, boundCenter:center }
  77151. }
  77152. getPosOutOfModel(viewport, boundSize){
  77153. //let {boundSize, center} = viewer.bound
  77154. boundSize = boundSize || this.getViewBound(viewport).boundSize;
  77155. let expand = 10;
  77156. let radius = boundSize.length(); // / 2
  77157. let position = viewport.shiftTarget.clone().sub(viewport.view.direction.clone().multiplyScalar(radius + expand));
  77158. return position
  77159. }
  77160. updateCameraOutOfModel(){//因为移动模型导致模型超出相机外,所以更新位置
  77161. viewer.viewports.forEach((viewport, i )=>{
  77162. if(viewport != viewer.mainViewport){
  77163. let {boundSize, boundCenter} = this.getViewBound(viewport);
  77164. viewport.targetPlane.setFromNormalAndCoplanarPoint( viewport.view.direction.clone(), boundCenter);
  77165. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  77166. let endPosition = this.getPosOutOfModel(viewport, boundSize);
  77167. //if(viewport.name == 'mapViewport')endPosition.z = Math.max(Potree.config.map.cameraHeight, endPosition.z)
  77168. viewport.view.position.copy(endPosition);
  77169. }
  77170. });
  77171. }
  77172. rotateSideCamera(viewport, angle){//侧视图绕模型中心水平旋转
  77173. //let {boundSize, center} = viewer.bound
  77174. let {boundSize, boundCenter } = this.getViewBound(viewport);
  77175. let center = this.focusCenter || boundCenter; //旋转中心,一般是所有模型的中心,除非想指定中心点
  77176. //找到平移向量
  77177. viewport.targetPlane.setFromNormalAndCoplanarPoint(viewport.view.direction , center );
  77178. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  77179. let vec = new Vector3().subVectors(center, viewport.shiftTarget);//相对于中心的偏移值,旋转后偏移值也旋转
  77180. //旋转
  77181. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  77182. viewport.view.direction = viewport.view.direction.applyMatrix4(rotMatrix);
  77183. vec.applyMatrix4(rotMatrix);
  77184. viewport.shiftTarget.subVectors(center,vec); //新的
  77185. viewport.view.position = this.getPosOutOfModel(viewport, boundSize);
  77186. }
  77187. getOrthoCamera(){
  77188. return new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000)
  77189. }
  77190. focusOnViewport(name){//全屏
  77191. viewer.viewports.forEach((viewport, i )=>{
  77192. if(viewport.name == name){
  77193. this.focusInfo = {
  77194. name,
  77195. left : viewport.left, bottom : viewport.bottom, height : viewport.height, width : viewport.width
  77196. };
  77197. viewport.left = 0; viewport.bottom = 0; viewport.height = 1; viewport.width = 1;
  77198. }else {
  77199. viewport.active = false;
  77200. }
  77201. });
  77202. viewer.updateScreenSize({forceUpdateSize:true});
  77203. }
  77204. unfocusViewport(){
  77205. if(!this.focusInfo)return
  77206. viewer.viewports.forEach((viewport, i )=>{
  77207. if(this.focusInfo.name == viewport.name){//全屏的恢复
  77208. viewport.left = this.focusInfo.left;
  77209. viewport.bottom = this.focusInfo.bottom;
  77210. viewport.height = this.focusInfo.height;
  77211. viewport.width = this.focusInfo.width;
  77212. }
  77213. viewport.active = true;
  77214. });
  77215. viewer.updateScreenSize({forceUpdateSize:true});
  77216. this.focusInfo = null;
  77217. }
  77218. }
  77219. const viewportProps = [
  77220. {
  77221. left:0.5,
  77222. bottom:0.5,
  77223. width: 0.5,height:0.5,
  77224. name : 'MainView',
  77225. //view: viewer.scene.view,
  77226. active: true,
  77227. },
  77228. {
  77229. left:0,
  77230. bottom:0.5,
  77231. width: 0.5,height:0.5,
  77232. name : 'top',
  77233. name2 : 'mapViewport',
  77234. axis:["x","y"],
  77235. direction : new Vector3(0,0,-1), //镜头朝向
  77236. //axisSign:[1,1],
  77237. active: true,
  77238. //相机位置在z轴正向
  77239. },
  77240. {
  77241. left:0.5,
  77242. bottom:0,
  77243. width: 0.5,height:0.5,
  77244. name : 'right',
  77245. axis:["y","z"],
  77246. direction : new Vector3(1,0,0),
  77247. //axisSign:[1,1],
  77248. active: true,
  77249. //相机位置在x轴负向 右下角屏
  77250. },
  77251. {
  77252. left:0,
  77253. bottom:0,
  77254. width: 0.5,height:0.5,
  77255. name : 'back',
  77256. axis:["x","z"],
  77257. direction : new Vector3(0,-1,0),
  77258. //axisSign:[-1,1], // 从镜头方向看 x向左 所以取负
  77259. active: true,
  77260. //相机位置在y轴正向 左下角屏
  77261. },
  77262. ];
  77263. var SplitScreen4Views = new SplitScreen();
  77264. SplitScreen4Views.split = function(o={}){
  77265. var defaultCamera = viewer.scene.getActiveCamera();
  77266. let {boundSize, center} = viewer.bound;
  77267. viewer.setLimitFar(false);
  77268. viewer.mapViewer.attachToMainViewer(true,'split4Screens','dontSet');
  77269. let viewports = this.splitStart(viewportProps);
  77270. //覆盖在map上、点云等其他物体之下的一层背景
  77271. let mapViewport = viewer.mapViewer.viewports[0];
  77272. mapViewport.noPointcloud = false;
  77273. //隐藏地图游标
  77274. //viewer.updateVisible(viewer.mapViewer.cursor, 'split4Screens', false)
  77275. /* viewer.images360.panos.forEach(pano=>{
  77276. viewer.updateVisible(pano.mapMarker, 'split4Screens', false) //希望这时候mapMarker已经建好了吧
  77277. }) */
  77278. //材质
  77279. this.statesBefore = {
  77280. pointDensity : Potree.settings.pointDensity,
  77281. displayMode : Potree.settings.displayMode,
  77282. position: viewer.images360.position,
  77283. target: viewer.scene.view.getPivot(),
  77284. //---
  77285. //ifShowMarker : Potree.settings.ifShowMarker,
  77286. };
  77287. viewer.setPointStandardMat(true,null,true); //切换到标准模式(主要为了mainViewport) 点云使用标准大小
  77288. var matBefore = {
  77289. opacity : new Map()
  77290. };
  77291. var newOpacityMap = new Map();
  77292. viewer.scene.pointclouds.forEach(e=>{
  77293. matBefore.opacity.set(e, e.temp.pointOpacity);
  77294. matBefore.colorType = e.material.activeAttributeName;
  77295. /* {
  77296. var map = new Map()
  77297. newOpacityMap.set(e, map )
  77298. var size = e.bound.getSize()
  77299. viewports.forEach(viewport=>{//根据bound设置opacity,越小的要靠越近,需要大的opacity。但似乎影响太大了
  77300. if(viewport.name == 'MainView')return;
  77301. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77302. let axis = prop.axis
  77303. var width = size[axis[0]]
  77304. var height = size[axis[1]]
  77305. var area = width * height
  77306. map.set(viewport, 5000/area);
  77307. })
  77308. } */
  77309. });
  77310. let beforeRender = function(){
  77311. viewer.scene.pointclouds.forEach(e=>{
  77312. if(this.name == "MainView"){
  77313. e.material.activeAttributeName = matBefore.colorType; // 'rgba'
  77314. e.material.useFilterByNormal = false;
  77315. e.changePointOpacity(matBefore.opacity.get(e)); //1 //恢复下 e.temp.pointOpacity 其实就是1
  77316. Potree.settings.pointDensity = 'fourViewportsMain';/* 'fourViewports' */ //本来想比另外三屏高一点质量,结果发现会闪烁,因为点云加载需要时间 (navvis仿版也是一样,以后看看能否优化)
  77317. }else {
  77318. e.material.activeAttributeName = "color";
  77319. e.material.useFilterByNormal = true;
  77320. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  77321. e.changePointOpacity(0.6/* newOpacityMap.get(e).get(viewport), true */); //多数据集有的数据集很小,放大后显示特别淡
  77322. //console.log(e.name, viewport.name, e.temp.pointOpacity, e.material.opacity)
  77323. }
  77324. });
  77325. };
  77326. viewports.forEach(viewport=>{viewport.beforeRender = beforeRender;});
  77327. this.enableMap(false);
  77328. this.enableFloorplan(false);
  77329. viewer.mapViewer.setViewLimit('expand'); //多数据集距离远时可以任意远,所以不限制了。但是这样就会看到地图边界了怎么办?
  77330. //viewer.dispatchEvent({'type': 'beginSplitView' })
  77331. //viewer.updateScreenSize({forceUpdateSize:true})
  77332. //this.viewportFitBound(mapViewport, boundSize, center)
  77333. //Potree.settings.ifShowMarker = false
  77334. Potree.settings.displayMode = 'showPointCloud';
  77335. };
  77336. SplitScreen4Views.recover = function(){
  77337. this.unSplit();
  77338. /* const {width, height} = viewer.renderer.getSize(new THREE.Vector2());
  77339. viewer.renderer.setViewport(0,0,width,height)
  77340. viewer.renderer.setScissorTest( false ); */
  77341. viewer.setView({
  77342. position: this.statesBefore.position,
  77343. target: this.statesBefore.target,
  77344. duration:300,
  77345. callback:function(){
  77346. }
  77347. });
  77348. viewer.mainViewport.beforeRender = null;
  77349. viewer.setLimitFar(true);
  77350. let mapViewport = viewer.mapViewer.viewports[0];
  77351. viewer.mapViewer.attachToMainViewer(false);
  77352. //viewer.updateVisible(viewer.mapViewer.cursor, 'split4Screens', true)
  77353. /* viewer.images360.panos.forEach(pano=>{
  77354. viewer.updateVisible(pano.mapMarker, 'split4Screens', true)
  77355. }) */
  77356. mapViewport.noPointcloud = true;
  77357. {
  77358. this.enableMap(Potree.settings.mapEnable);
  77359. this.enableFloorplan(Potree.settings.floorplanEnable);
  77360. if(this.floorplanListener){
  77361. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77362. this.floorplanListener = null;
  77363. }
  77364. }
  77365. Potree.settings.pointDensity = this.statesBefore.pointDensity;
  77366. if(!Potree.settings.isOfficial){
  77367. Potree.settings.displayMode = this.statesBefore.displayMode;
  77368. }
  77369. viewer.scene.pointclouds.forEach(e=>{
  77370. //e.material.color.set(this.statesBefore.mat.color)
  77371. //e.material.activeAttributeName = this.statesBefore.mat.colorType
  77372. e.material.useFilterByNormal = false;
  77373. //e.material.opacity = this.statesBefore.mat.opacity
  77374. });
  77375. viewer.setPointStandardMat(false);
  77376. viewer.mapViewer.setViewLimit('standard');
  77377. //Potree.settings.ifShowMarker = this.statesBefore.ifShowMarker
  77378. //viewer.dispatchEvent({'type': 'finishSplitView' })
  77379. //viewer.updateScreenSize({forceUpdateSize:true})
  77380. };
  77381. SplitScreen4Views.updateMapViewerBG = function(){
  77382. let mapViewport = viewer.mapViewer.viewports[0];
  77383. if(this.floorplanEnabled || this.mapEnabled){
  77384. mapViewport.background = 'overlayColor';
  77385. mapViewport.backgroundColor = new Color(0,0,0);
  77386. mapViewport.backgroundOpacity = 0.5;
  77387. }else {
  77388. mapViewport.background = null;
  77389. mapViewport.backgroundColor = null;
  77390. mapViewport.backgroundOpacity = null;
  77391. }
  77392. };
  77393. SplitScreen4Views.setFloorplanDisplay = function(e, show=false){
  77394. //viewer.updateVisible(e.floorplan.objectGroup, 'splitScreen', !!show)
  77395. //e.floorplan.objectGroup.visible = !!show
  77396. //viewer.mapViewer.mapLayer.needUpdate = true
  77397. e.floorplan.setEnable(show);
  77398. };
  77399. SplitScreen4Views.enableMap = function(enable){
  77400. let map = viewer.mapViewer.mapLayer.maps.find(e=>e.name == 'map');
  77401. //viewer.updateVisible(map.objectGroup, 'splitScreen', !!enable)
  77402. //map.objectGroup.visible = !!enable
  77403. //if(enable)viewer.mapViewer.mapLayer.needUpdate = true //加载地图
  77404. map.setEnable(!!enable);
  77405. //viewer.mapViewer.mapGradientBG = viewer.background == 'gradient' && !enable
  77406. this.mapEnabled = enable;
  77407. this.updateMapViewerBG();
  77408. },
  77409. //直接覆盖原设置
  77410. SplitScreen4Views.enableFloorplan = function(enable){ //是否让自定义的平面图显示
  77411. let floorplans = viewer.mapViewer.mapLayer.maps.filter(e=>e.name.includes('floorplan'));
  77412. if(this.floorplanListener){
  77413. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77414. }
  77415. this.floorplanListener = (e)=>{
  77416. this.setFloorplanDisplay(e, enable);
  77417. };
  77418. viewer.mapViewer.mapLayer.addEventListener( 'floorplanLoaded', this.floorplanListener ); //万一之后才加载
  77419. if(!enable){
  77420. //隐藏平面图
  77421. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},false));
  77422. }else {
  77423. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},true));
  77424. }
  77425. if (enable && floorplans.length == 0) Potree.loadMapEntity('all',true);
  77426. this.floorplanEnabled = enable;
  77427. this.updateMapViewerBG();
  77428. },
  77429. /* viewportFitBound:function(viewport, boundSize, center){ //使一个viewport聚焦在某个范围
  77430. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77431. let axis = prop.axis
  77432. let expand = 10;
  77433. let position = center.clone()
  77434. var moveAtAxis = ['x','y','z'].find(e=>!(axis.includes(e)))
  77435. if(viewport.name == 'mapViewport'){
  77436. let ori = viewport.view.position[moveAtAxis]
  77437. position[moveAtAxis] = ori //不改变这个值,尤其是mapViewer中的z
  77438. }else{
  77439. position[moveAtAxis] += boundSize[moveAtAxis]/2+expand//移动到bounding边缘外
  77440. }
  77441. viewport.view.position.copy(position)
  77442. var width = Math.max(boundSize[axis[0]], boundSize[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  77443. var margin = 50 //px
  77444. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  77445. viewport.camera.updateProjectionMatrix()
  77446. },
  77447. */
  77448. SplitScreen4Views.focusOnPointCloud = function(pointcloud){//三个屏都聚焦在这个点云
  77449. var boundSize = pointcloud.bound.getSize(new Vector3);
  77450. var center = pointcloud.bound.getCenter(new Vector3);
  77451. let target = pointcloud.panosBound && pointcloud.panosBound.center; //看向pano集中的地方,也就是真正有点云的地方。(因为需要展示所有点云,所以没办法用这个做为center)
  77452. this.focusOnObject(pointcloud.bound, center,target);
  77453. viewer.flyToDataset({pointcloud, dontMoveMap:true, duration:0});
  77454. };
  77455. SplitScreen4Views.focusOnObject = function(bound, center, target, duration=0){
  77456. viewer.viewports.forEach(e=>{
  77457. if(e.name == 'MainView'){
  77458. /* let len = boundSize.length()
  77459. let distance = THREE.Math.clamp(e.view.position.distanceTo(center), len * 0.01, len*0.3 ) //距离限制
  77460. //viewer.focusOnObject({position:center}, 'point', duration, {distance, direction: e.view.direction,dontMoveMap:true} )//平移镜头
  77461. //为了方便定位,直接飞到中心位置:
  77462. e.view.setView({
  77463. position:center, duration, target
  77464. }) */
  77465. }else {
  77466. this.viewportFitBound(e, bound, center);
  77467. }
  77468. });
  77469. };
  77470. class History extends EventDispatcher{
  77471. constructor(o){
  77472. super();
  77473. this.list = [];
  77474. this.callback = o.callback;
  77475. }
  77476. undo(){
  77477. let last = this.list.pop();
  77478. last && this.callback && this.callback(last);
  77479. }
  77480. redo(){//暂时不写
  77481. }
  77482. writeIn(item){
  77483. this.list.push(item);
  77484. }
  77485. clear(){
  77486. this.list.length = 0;
  77487. }
  77488. }
  77489. var Alignment = {
  77490. SplitScreen: SplitScreen4Views,
  77491. handleState:null, //操作状态 'translate'|'rotate'
  77492. bus: new EventDispatcher(),
  77493. prepareRecord : true,
  77494. writeToHistory(content){
  77495. if(!this.prepareRecord)return;
  77496. this.prepareRecord = false;
  77497. this.history.writeIn(content);
  77498. },
  77499. /* undo(){//撤销一步
  77500. let last = this.history.pop();
  77501. last && last.forEach(item=>{
  77502. this.applyTemp(item)
  77503. })
  77504. }, */
  77505. applyTemp(item){
  77506. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id+p.name == item.sid);
  77507. pointcloud.orientationUser = item.orientationUser;
  77508. pointcloud.translateUser = item.translateUser;
  77509. this.setMatrix( pointcloud );
  77510. },
  77511. getTemp(pointclouds){//记录最近一次保存后的状态,便于恢复
  77512. pointclouds = pointclouds || viewer.scene.pointclouds;
  77513. return pointclouds.map(e=>{
  77514. return {
  77515. sid : e.dataset_id+e.name,
  77516. orientationUser : e.orientationUser,
  77517. translateUser : e.translateUser.clone(),
  77518. }
  77519. } )
  77520. },
  77521. init:function(){
  77522. let rotateInfo;
  77523. viewer.fpControls.addEventListener("transformPointcloud",(e)=>{
  77524. if(e.pointclouds[0].dataset_id == Potree.settings.originDatasetId){//禁止手动移动初始数据集
  77525. return this.bus.dispatchEvent('forbitMoveOriginDataset')
  77526. }
  77527. this.writeToHistory(this.getTemp(e.pointclouds) );
  77528. if(this.handleState == 'translate'){
  77529. e.pointclouds.forEach(cloud=>Alignment.translate(cloud, e.moveVec));
  77530. }else if(this.handleState == 'rotate'){
  77531. if(Potree.settings.editType == 'pano'){
  77532. let center = e.intersectStart; //旋转中心是mousedown的位置
  77533. if(e.intersect.equals(center))return
  77534. if(!rotateInfo){
  77535. rotateInfo = {
  77536. orientationUser : e.pointclouds[0].orientationUser,
  77537. //vecStart : e.moveVec, // 首次移动向量 只有八个方向,精度太小,所以延迟
  77538. pointclouds: e.pointclouds
  77539. };
  77540. this.bus.dispatchEvent({type:'rotateStart', startPoint:center});
  77541. return
  77542. }else if(!rotateInfo.vecStart){
  77543. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77544. if(vec.length() * e.camera.zoom > 30){ //在屏幕上距离初始点有一定距离后开始算
  77545. //console.log('moveVec',vec)
  77546. rotateInfo.vecStart = vec;
  77547. }
  77548. }else {
  77549. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77550. let angle = math.getAngle(rotateInfo.vecStart,vec,'z');
  77551. let diffAngle = rotateInfo.orientationUser + angle - rotateInfo.pointclouds[0].orientationUser;
  77552. rotateInfo.pointclouds.forEach(cloud=>{
  77553. /* let centerNoTranfrom = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:cloud, position: center }) //中心点在数据集中的位置
  77554. Alignment.rotate(cloud, null, diffAngle)
  77555. let centerNow = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:cloud, position: centerNoTranfrom }) //中心点的现在位置
  77556. let shift = new THREE.Vector3().subVectors( center, centerNow); //偏移量
  77557. Alignment.translate(cloud,shift) //使center还保留在原位
  77558. //let centerNow1 = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:rotateInfo.pointcloud, position: centerNoTranfrom }) //中心点的现在位置
  77559. */
  77560. Alignment.rotateAround(center, cloud, null, diffAngle);
  77561. });
  77562. }
  77563. this.bus.dispatchEvent({type:'rotate', endPoint: e.intersect});
  77564. }else {
  77565. let center = e.pointclouds[0].translateUser; //移动到的位置就是中心
  77566. if(e.intersect.equals(center))return
  77567. if(!rotateInfo){
  77568. rotateInfo = {
  77569. orientationUser : e.pointclouds[0].orientationUser,
  77570. vecStart : new Vector3().subVectors(e.intersectStart, center).setZ(0),
  77571. //pointclouds: e.pointclouds
  77572. pointcloud: e.pointclouds[0]
  77573. };
  77574. }else {
  77575. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77576. let angle = math.getAngle(rotateInfo.vecStart,vec,'z');
  77577. let diffAngle = rotateInfo.orientationUser + angle - rotateInfo.pointcloud.orientationUser;
  77578. Alignment.rotate(rotateInfo.pointcloud, null, diffAngle);
  77579. }
  77580. }
  77581. }
  77582. });
  77583. viewer.fpControls.addEventListener("end",(e)=>{
  77584. rotateInfo = null;
  77585. this.prepareRecord = true;
  77586. });
  77587. viewer.inputHandler.addEventListener('keydown',e=>{
  77588. if(e.keyCode == 90 && e.event.ctrlKey){//Z
  77589. this.history.undo();
  77590. }
  77591. });
  77592. // cursor:
  77593. let updateCursor = (e)=>{
  77594. if(e.drag || !this.editing)return //仅在鼠标不按下时更新:
  77595. let handleState = Alignment.handleState;
  77596. if(e.hoverViewport.alignment && handleState && e.hoverViewport.alignment[handleState]){
  77597. if(handleState == 'translate'){
  77598. if( e.intersect && e.intersect.location ){
  77599. viewer.dispatchEvent({
  77600. type : "CursorChange", action : "add", name:"movePointcloud"
  77601. });
  77602. }else {
  77603. viewer.dispatchEvent({
  77604. type : "CursorChange", action : "remove", name:"movePointcloud"
  77605. });
  77606. }
  77607. }else if(handleState == 'rotate'){
  77608. if( e.intersect && e.intersect.location ){
  77609. viewer.dispatchEvent({
  77610. type : "CursorChange", action : "add", name:"rotatePointcloud"
  77611. });
  77612. }else {
  77613. viewer.dispatchEvent({
  77614. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77615. });
  77616. }
  77617. }
  77618. }else {
  77619. //清空:
  77620. viewer.dispatchEvent({
  77621. type : "CursorChange", action : "remove", name:"movePointcloud"
  77622. });
  77623. viewer.dispatchEvent({
  77624. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77625. });
  77626. }
  77627. };
  77628. viewer.addEventListener('global_mousemove',updateCursor);
  77629. viewer.addEventListener('global_drop',updateCursor);//拖拽结束
  77630. viewer.addEventListener('updateModelBound', (e)=>{
  77631. if(this.editing){
  77632. this.SplitScreen.updateCameraOutOfModel();
  77633. }
  77634. });
  77635. },
  77636. setMatrix : function(pointcloud){
  77637. var vec1 = pointcloud.position; //position为数据集内部的偏移,在navvis中对应的是dataset.pointCloudSceneNode的children[0].position
  77638. var vec2 = pointcloud.translateUser;
  77639. var angle = pointcloud.orientationUser;
  77640. var pos1Matrix = new Matrix4().setPosition(vec1);//先移动到点云本身应该在的初始位置(在4dkk里和其他应用中都是在这个位置的,也能和漫游点对应上)
  77641. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  77642. var pos2Matrix = new Matrix4().setPosition(vec2);//最后是平移
  77643. var matrix = new Matrix4().multiplyMatrices(pos2Matrix, rotMatrix);
  77644. pointcloud.transformMatrix = matrix.clone();//为该数据集的变化矩阵。 对应navvis的m2w_
  77645. pointcloud.transformInvMatrix.copy(matrix).invert();
  77646. pointcloud.rotateMatrix = rotMatrix;
  77647. pointcloud.rotateInvMatrix.copy(rotMatrix).invert();
  77648. pointcloud.panos.forEach(e=>e.transformByPointcloud());
  77649. matrix = new Matrix4().multiplyMatrices(matrix, pos1Matrix);
  77650. pointcloud.matrix = matrix;
  77651. //pointcloud.matrixWorldNeedsUpdate = true //更新matrixWorld (非计算,直接赋值)
  77652. pointcloud.updateMatrixWorld(true);
  77653. if(this.editing){
  77654. Alignment.changeCallBack && Alignment.changeCallBack();
  77655. }
  77656. if(pointcloud.spriteNodeRoot){
  77657. pointcloud.spriteNodeRoot.matrixWorld.copy(pointcloud.matrixWorld);//.multiplyMatrices(pointcloud.matrixWorld, pointcloud.matrixWorld);
  77658. }
  77659. viewer.updateModelBound();
  77660. //pointcloud.updateBound()
  77661. pointcloud.getPanosBound();
  77662. },
  77663. rotateAround(center, pointcloud, deg, angle){//绕center点转动
  77664. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg);
  77665. let vec1 = new Vector3().subVectors(pointcloud.translateUser, center);
  77666. let rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  77667. let vec2 = vec1.clone().applyMatrix4(rotMatrix); //将到旋转中心的偏差也转动
  77668. let vec3 = new Vector3().subVectors(vec2,vec1); //这个就是多出来的一步translateUser
  77669. this.rotate(pointcloud, deg, angle);
  77670. this.translate(pointcloud, vec3);
  77671. //绕点转动就是比普通转动多一步移动到相对center的某个位置。 1 初始点云移动到自己的position; 2 移动一个vec1 3绕原点旋转 4再移动一个原本的translateUser。 绘制出来后发现移动量就是第二步vec旋转后的偏移
  77672. },
  77673. rotate:function(pointcloud, deg, angle){//绕各自中心转动(各自的position) 假设点云位移position后0,0,0就是它的中心了(根据navvis观察这样做是绕同一个点旋转的)
  77674. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); //正逆负顺
  77675. pointcloud.orientationUser += angle;
  77676. Alignment.setMatrix(pointcloud);
  77677. },
  77678. translate:function(pointcloud, vec){
  77679. pointcloud.translateUser.add(vec);
  77680. Alignment.setMatrix(pointcloud);
  77681. },
  77682. enter:function(){
  77683. //this.saveTemp()
  77684. this.originData = this.getTemp();
  77685. this.SplitScreen.split({alignment:true});
  77686. viewer.images360.panos.forEach(pano=>{
  77687. viewer.updateVisible(pano.mapMarker, 'split4Screens', false);
  77688. });
  77689. viewer.viewports.find(e=>e.name == 'mapViewport').alignment = {rotate:true,translate:true};
  77690. viewer.viewports.find(e=>e.name == 'right').alignment = {translate:true};
  77691. viewer.viewports.find(e=>e.name == 'back').alignment = {translate:true};
  77692. this.editing = true;
  77693. viewer.updateFpVisiDatasets();
  77694. },
  77695. leave:function(){
  77696. this.switchHandle(null);
  77697. /* this.originData.forEach(e=>{//恢复
  77698. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.id)
  77699. this.translate(pointcloud, new THREE.Vector3().subVectors(e.translateUser , pointcloud.translateUser))
  77700. this.rotate(pointcloud, null, e.orientationUser - pointcloud.orientationUser)
  77701. }) */
  77702. this.originData.forEach(e=>{//恢复
  77703. this.applyTemp(e);
  77704. });
  77705. this.SplitScreen.recover();
  77706. viewer.images360.panos.forEach(pano=>{
  77707. viewer.updateVisible(pano.mapMarker, 'split4Screens', true);
  77708. });
  77709. this.editing = false;
  77710. this.history.clear();
  77711. viewer.updateFpVisiDatasets();
  77712. viewer.dispatchEvent({
  77713. type : "CursorChange", action : "remove", name:"movePointcloud"
  77714. });
  77715. viewer.dispatchEvent({
  77716. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77717. });
  77718. }
  77719. ,
  77720. switchHandle:function(state){
  77721. this.handleState = state;
  77722. //清空:
  77723. viewer.dispatchEvent({
  77724. type : "CursorChange", action : "remove", name:"movePointcloud"
  77725. });
  77726. viewer.dispatchEvent({
  77727. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77728. });
  77729. this.bus.dispatchEvent({type:'switchHandle' , state });
  77730. },
  77731. save: function(){//保存所有数据集的位置和旋转
  77732. let callback = ()=>{//保存成功后
  77733. this.originData = this.getTemp(); //this.saveTemp();
  77734. //需要修改 测量线的position。漫游点已经实时修改了
  77735. viewer.scene.measurements.forEach(e=>e.transformByPointcloud());
  77736. viewer.images360.updateCube(viewer.bound);
  77737. };
  77738. var data = viewer.scene.pointclouds.map(e=>{
  77739. let pos = viewer.transform.lonlatToLocal.inverse(e.translateUser.clone());
  77740. return {
  77741. id: e.dataset_id,
  77742. orientation : e.orientationUser,
  77743. location:[pos.x, pos.y, pos.z],
  77744. //transformMatrix: e.transformMatrix.elements,
  77745. }
  77746. });
  77747. //data = JSON.stringify(data)
  77748. //test: 退出后保留结果
  77749. if(!Potree.settings.isOfficial){
  77750. callback();
  77751. }
  77752. return {data, callback}
  77753. }
  77754. };
  77755. Alignment.history = new History({
  77756. callback: (data)=>{
  77757. data.forEach(item=>{
  77758. Alignment.applyTemp(item);
  77759. });
  77760. }
  77761. });
  77762. let texLoader$7 = new TextureLoader();
  77763. let markerMats$2;
  77764. let markerSizeInfo$2 = {width2d:35};
  77765. let color$2 = new Color('#FFF');
  77766. let faceMats;
  77767. let getFaceMat = (name)=>{
  77768. if(!faceMats){ //navvis材质可以搜gridTexture
  77769. let gridTex = texLoader$7.load( Potree.resourcePath+'/textures/gridmap.png' );
  77770. gridTex.wrapS = gridTex.wrapT = RepeatWrapping;
  77771. //gridTex.repeat.set(0.5,0.5)//放大一些
  77772. faceMats = {
  77773. dataset: new MeshStandardMaterial({
  77774. color:812922,
  77775. side:DoubleSide,
  77776. opacity:0.2,
  77777. transparent:true,
  77778. depthTest:false,
  77779. wireframe:true
  77780. }),
  77781. building: new MeshStandardMaterial({
  77782. color:812922, metalness: 0.2, roughness:0.8,
  77783. side:DoubleSide,
  77784. opacity:0.1,
  77785. transparent:true,
  77786. depthTest:true
  77787. }),
  77788. buildingSelect: new MeshStandardMaterial({
  77789. color:36582, metalness: 0, roughness:1,
  77790. side:DoubleSide,
  77791. opacity:0.1,
  77792. transparent:true,
  77793. depthTest:true
  77794. }),
  77795. floor: new MeshStandardMaterial({
  77796. color:11708469, metalness: 0.1, roughness:1,
  77797. side:DoubleSide,//BackSide,
  77798. opacity:0.05,
  77799. transparent:true,
  77800. depthTest:true,
  77801. }),
  77802. /* floorSelect: new THREE.MeshStandardMaterial({
  77803. color:16707151, metalness: 0, roughness:1,
  77804. side:THREE.DoubleSide,
  77805. opacity:1,
  77806. transparent:true,
  77807. depthTest:true,
  77808. polygonOffset : true,//是否开启多边形偏移
  77809. polygonOffsetFactor : -0.75,//多边形偏移因子
  77810. polygonOffsetUnits : -4.0,//多边形偏移单位
  77811. map: gridTex,
  77812. }), */
  77813. floorSelect: new DepthBasicMaterial({
  77814. map: gridTex,
  77815. color:16707151,
  77816. side:DoubleSide,//BackSide,
  77817. opacity:1,
  77818. transparent:true,
  77819. useDepth : true,
  77820. /* polygonOffset : true,//是否开启多边形偏移
  77821. polygonOffsetFactor : -0.75,//多边形偏移因子
  77822. polygonOffsetUnits : -4.0,//多边形偏移单位 */
  77823. clipDistance : 1, occlusionDistance:1, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77824. maxClipFactor:0.4, backColor:'#efe' //backColor:"#669988" ,
  77825. }),
  77826. room: new MeshStandardMaterial({
  77827. color:"#ff44ee", metalness: 0, roughness:1,
  77828. side:DoubleSide,//BackSide,
  77829. opacity:0.08,
  77830. transparent:true,
  77831. depthTest:false,
  77832. }),
  77833. /* roomSelect: new THREE.MeshStandardMaterial({
  77834. color:"#ff44ee", metalness: 0.3, roughness:1,
  77835. side:THREE.DoubleSide,//BackSide,
  77836. opacity:1,
  77837. transparent:true,
  77838. depthTest:true,
  77839. polygonOffset : true,//是否开启多边形偏移.(开启是因为和floor重叠了会闪烁)
  77840. polygonOffsetFactor : -0.75,//多边形偏移因子
  77841. polygonOffsetUnits : -4.0,//多边形偏移单位
  77842. map: gridTex,
  77843. }), */
  77844. roomSelect: new DepthBasicMaterial({
  77845. map: gridTex,
  77846. color:"#ff44ee",
  77847. side:DoubleSide,//BackSide,
  77848. opacity:1,
  77849. transparent:true,
  77850. useDepth : true,
  77851. /* polygonOffset : true,//是否开启多边形偏移
  77852. polygonOffsetFactor : -0.75,//多边形偏移因子
  77853. polygonOffsetUnits : -4.0,//多边形偏移单位 */
  77854. clipDistance : 1, occlusionDistance:0.5, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77855. maxClipFactor:0.6, backColor:'#ff88dd'//"#cc99c2" ,
  77856. })
  77857. };
  77858. }
  77859. return faceMats[name]
  77860. };
  77861. class BuildingBox extends ctrlPolygon{//建筑实体,包括building, floor, room
  77862. constructor(prop) {
  77863. prop.dimension = '3d';
  77864. //prop.name = Potree.config.siteModel.names[prop.buildType] +
  77865. super('siteModel_'+prop.buildType, prop);
  77866. this.midMarkers = [];
  77867. this.buildChildren = [];//子实体
  77868. this.holes = []; //在这创建的hole
  77869. this.parentHoles = [];//floor从building那得到的当层holes
  77870. this.mats = {}; //材质
  77871. this.panos = this.panos || [];
  77872. this.center; //中心点
  77873. if(this.buildType=='floor'){
  77874. this.points = prop.points = this.buildParent.points;//完全等于建筑的点
  77875. this.buildParent.holes.forEach(hole=>{//从building获取holes
  77876. let floorHole = new BuildingBox({
  77877. buildType : 'hole',
  77878. buildParent:this,
  77879. originHole : hole, //整栋大楼在当层的hole
  77880. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77881. });
  77882. this.parentHoles.push(floorHole);
  77883. this.add(floorHole);
  77884. floorHole.points = hole.points;//完全等于建筑的点
  77885. });
  77886. }
  77887. if(this.buildType == 'room' || this.buildType == 'hole'){
  77888. this.restrictArea = this.buildParent; //不能超出的区域
  77889. }
  77890. if(this.ifDraw){ //只存储空间模型信息,不绘制
  77891. if(this.buildType != 'hole'){
  77892. this.box = this.createBox();
  77893. this.add(this.box);
  77894. }
  77895. {
  77896. this.lineMesh = LineDraw.createLine([],{color: color$2});
  77897. this.lineMesh.name = 'buildingLines';
  77898. this.lineMesh.visible = false;
  77899. this.add(this.lineMesh);
  77900. viewer.setObjectLayers(this.lineMesh, 'bothMapAndScene' );
  77901. }
  77902. this.addEventListener('dragChange',(e)=>{ //修改中点
  77903. this.updateTwoMidMarker(e.index);
  77904. });
  77905. }
  77906. this.initData(prop);
  77907. }
  77908. initData(prop){
  77909. if(prop.ifDraw){
  77910. super.initData(prop);
  77911. }else {
  77912. if(prop.points){
  77913. this.points = prop.points;
  77914. }
  77915. }
  77916. }
  77917. intersectPointcloudVolume(pointcloud){//和pointcloud的重叠体积
  77918. var bound = this.getBound();
  77919. let bound2 = pointcloud.bound;
  77920. if(!bound.intersectsBox(bound2)) return 0;
  77921. let {zMin , zMax} = this.getRealZ();
  77922. let min = Math.min(zMin, bound2.min.z);
  77923. let max = Math.max(zMax, bound2.max.z);
  77924. let height1 = zMax - zMin;
  77925. let height2 = bound2.max.z-bound2.min.z;
  77926. let coverHeight = height1 + height2 - (max-min);//重叠高度 <=0是没重叠
  77927. let boxPoints = pointcloud.getUnrotBoundPoint(); //获取tightBound的四个点。 如果是有旋转角度的点云,这个和pointcloud.bound的四个点是不一致的,覆盖面积小于pointcloud.bound
  77928. let areaWhole = 0;
  77929. let area1 = this.getArea();
  77930. let area2 = Math.abs(math.getArea(boxPoints));
  77931. {//计算points与点云总面积 (但是把hole也加入了面积)(并集,重叠部分只算一次)
  77932. let rings = math.getPolygonsMixedRings([this.points, boxPoints] );
  77933. rings.forEach(e=>{
  77934. areaWhole+=e.area;
  77935. });
  77936. }
  77937. let coverHoleArea = 0; //holes与数据集重叠的部分
  77938. let holes = this.holes.concat(this.parentHoles);
  77939. let holesArea = 0; //所有holes面积相加
  77940. let areaHoleWithPointcloud = 0; //hole和点云的面积并集
  77941. if(holes.length>0){//还要再扣除holes与数据集重叠的部分。其中holes为mix轮廓
  77942. let outHoles = [];//没有重合的holes的外轮廓
  77943. /* if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  77944. let holes_ = holes.map(e=>e.points)
  77945. outHoles = math.getPolygonsMixedRings(holes_, true )
  77946. outHoles.forEach(e=>{
  77947. holesArea+=e.area
  77948. })
  77949. outHoles = outHoles.map(e=>e.points)
  77950. }else{
  77951. outHoles = holes.map(e=>e.points)
  77952. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)))
  77953. } */
  77954. holesArea = this.getHolesArea();
  77955. //holes与数据集重叠的部分
  77956. {
  77957. let polygons = outHoles.concat([boxPoints]);
  77958. let rings = math.getPolygonsMixedRings(polygons);
  77959. rings.forEach(e=>{
  77960. areaHoleWithPointcloud+=e.area;
  77961. });
  77962. coverHoleArea = holesArea + area2 - areaHoleWithPointcloud;//hole和点云的交集
  77963. }
  77964. }
  77965. let coverArea = area1 + area2 - areaWhole - coverHoleArea; //重叠面积
  77966. return coverArea * coverHeight
  77967. }
  77968. addHole(points=[]){
  77969. let prop = {
  77970. buildType : 'hole',
  77971. zMin : this.zMin,
  77972. zMax : this.zMax,
  77973. points,
  77974. buildParent:this,
  77975. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77976. };
  77977. //hole的zMin zMax跟随buildParent
  77978. var hole = new BuildingBox(prop);
  77979. this.holes.push(hole);
  77980. if(this.buildType == 'building'){//为每一层添加对应的hole
  77981. this.buildChildren.forEach(floor=>{
  77982. let floorHole = new BuildingBox({
  77983. buildType : 'hole',
  77984. zMin : this.zMin,
  77985. zMax : this.zMax,
  77986. buildParent:floor,
  77987. originHole : hole, //整栋大楼在当层的hole
  77988. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77989. });
  77990. floor.parentHoles.push(floorHole);
  77991. floor.add(floorHole);
  77992. floorHole.points = hole.points;//完全等于建筑的点
  77993. });
  77994. }
  77995. this.add(hole);//直接加在这,不加meshGroup了
  77996. this.update(); //update box mesh
  77997. return hole
  77998. //hole不创建box,只有它的buildParent需要更新box。 但有线条和marker. hole不在buildChildren里,但有buildParent
  77999. }
  78000. removeHole(hole){// 这个hole不会是parentHoles里的。
  78001. hole.dispose();
  78002. if(this.buildType == 'building'){ //若是整栋大楼的hole,在每层去除它的对应hole
  78003. this.buildChildren.forEach(floor=>{
  78004. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  78005. let index = floor.parentHoles.indexOf(holeAtFloor);
  78006. index > -1 && floor.parentHoles.splice(index, 1);
  78007. holeAtFloor.dispose();
  78008. });
  78009. }
  78010. let index = this.holes.indexOf(hole);
  78011. if(index>-1){
  78012. this.holes.splice(index, 1);
  78013. }
  78014. this.remove(hole);
  78015. this.update();
  78016. }
  78017. createBox(){
  78018. var geometry = new Geometry();
  78019. this.mats.boxDefault = getFaceMat(this.buildType);
  78020. this.mats.boxSelected = getFaceMat(this.buildType+'Select');
  78021. var mesh = new Mesh(geometry, this.mats.boxDefault);
  78022. mesh.name = 'buildingBox';
  78023. if(this.buildType == 'floor'){
  78024. viewer.setObjectLayers(mesh, 'siteModelMapUnvisi' ); //楼层默认在地图不显示,为了不会叠加透明度
  78025. }else {
  78026. viewer.setObjectLayers(mesh, 'bothMapAndScene' );
  78027. }
  78028. //mesh.frustumCulled = false;
  78029. return mesh
  78030. }
  78031. addMarker(o={} ){
  78032. if(this.buildType=='floor')return; //楼层不需要marker
  78033. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), renderOrder : 3, sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_marker"} );
  78034. viewer.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  78035. o.marker = marker;
  78036. super.addMarker(o);
  78037. if(!this.selected)viewer.updateVisible(marker,'select',false);
  78038. let addClickEvent = (e)=>{
  78039. let click = (e) => {
  78040. this.dispatchEvent({type:'clickMarker', marker } ); //由entity发送给sitemodel统一处理
  78041. };
  78042. marker.addEventListener('click', click);
  78043. marker.addEventListener('clickSelect', (e)=>{
  78044. this.setMarkerSelected(marker, e.state ? 'select' : 'unselect' );
  78045. });
  78046. marker.removeEventListener('addHoverEvent',addClickEvent);
  78047. };
  78048. marker.addEventListener('addHoverEvent',addClickEvent);//当非isNew时才添加事件
  78049. if(!this.isNew){
  78050. marker.dispatchEvent('addHoverEvent');
  78051. }
  78052. return marker
  78053. }
  78054. removeMarker(index){
  78055. super.removeMarker(index);
  78056. if(!this.isNew){
  78057. //重新添加midMarkers
  78058. this.midMarkers.forEach(e=>this.remove(e));
  78059. this.midMarkers = [];
  78060. this.addMidMarkers();
  78061. }
  78062. this.update();
  78063. if(this.points.length == 2 && this.box){//清除原先length>=3时候的
  78064. this.box.geometry = new Geometry();
  78065. }
  78066. }
  78067. addMidMarker(index, point){
  78068. if(this.buildType=='floor')return; //楼层不需要marker
  78069. let marker = new Sprite$1({mat:this.getMarkerMaterial('midPrepare'), sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_midMarker"} );
  78070. this.midMarkers = [...this.midMarkers.slice(0,index), marker, ...this.midMarkers.slice(index,this.midMarkers.length)];
  78071. marker.renderOrder = 3;
  78072. viewer.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  78073. { // Event Listeners
  78074. let mouseover = (e) => {
  78075. this.setMarkerSelected(e.object, 'hover', 'single');
  78076. viewer.dispatchEvent({
  78077. type : "CursorChange", action : "add", name:"markerMove"
  78078. });
  78079. };
  78080. let mouseleave = (e) => {
  78081. this.setMarkerSelected(e.object, 'unhover', 'single');
  78082. viewer.dispatchEvent({
  78083. type : "CursorChange", action : "remove", name:"markerMove"
  78084. });
  78085. };
  78086. let drag = (e) => {
  78087. let index = this.midMarkers.indexOf(marker);
  78088. let newMarker = this.addMarker({index:(index+1), point:marker.position.clone() });
  78089. this.addMidMarker(index+1, new Vector3 );
  78090. this.updateTwoMidMarker(index+1);
  78091. this.setMarkerSelected(marker, 'unhover');
  78092. viewer.inputHandler.startDragging(newMarker , {/* dragViewport:viewer.mapViewer.viewports[0], */ } ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78093. };
  78094. marker.addEventListener('drag', drag );
  78095. //marker.addEventListener('drop', drop);
  78096. marker.addEventListener('mouseover', mouseover);
  78097. marker.addEventListener('mouseleave', mouseleave);
  78098. }
  78099. this.add(marker);
  78100. this.updateMarker(marker, point);
  78101. if(!this.selected)viewer.updateVisible(marker,'select',false);
  78102. return marker
  78103. }
  78104. addMidMarkers(){//第一次画好所有marker后,一次性为线段增加中点marker
  78105. let length = this.points.length;
  78106. this.points.forEach((point,index)=>{
  78107. let nextPoint = this.points[(index+1)%length];
  78108. let midPoint = new Vector3().addVectors(point, nextPoint).multiplyScalar(0.5);
  78109. this.addMidMarker(index, midPoint );
  78110. });
  78111. }
  78112. updateTwoMidMarker(index){//更新第index个marker两边的midMarker
  78113. if(!this.midMarkers.length)return
  78114. let length = this.points.length;
  78115. let last = this.points[(index-1+length)%length]; //它之前的marker位置
  78116. let next = this.points[(index+1)%length];//它之后的marker位置
  78117. let current = this.points[index];//当前位置
  78118. let lastMid = new Vector3().addVectors(last, current).multiplyScalar(0.5);//上一个中点
  78119. let nextMid = new Vector3().addVectors(next, current).multiplyScalar(0.5);//下一个中点
  78120. let lastMidMarker = this.midMarkers[(index-1+length)%length];
  78121. let nextMidMarker = this.midMarkers[index];
  78122. this.updateMarker(lastMidMarker, lastMid);
  78123. this.updateMarker(nextMidMarker, nextMid);
  78124. }
  78125. dispose(){//销毁geo、remove from parent
  78126. super.dispose();
  78127. this.box && this.box.geometry.dispose();
  78128. this.lineMesh && this.lineMesh.geometry.dispose();
  78129. this.holes.forEach(e=>e.dispose());
  78130. this.parentHoles.forEach(e=>e.dispose());
  78131. //this.buildChildren.forEach(e=>e.dispose())
  78132. this.dispatchEvent('dispose');
  78133. }
  78134. updateBox(){
  78135. if(!this.box)return
  78136. this.box.geometry.dispose();
  78137. var shrink = this.buildType == 'room' ? 0.11 : this.buildType == 'floor' ? 0.082 : 0.2 ;//防止mesh重叠冲突(给一个不寻常的数字) 但离远了还是会有点闪烁
  78138. if(this.points.length >= 3){
  78139. let holes = this.holes.concat(this.parentHoles);
  78140. let holesPoints = holes.filter(e=>e.points.length>2).map(e=>e.points);
  78141. this.box.geometry = MeshDraw.getExtrudeGeo(this.points, holesPoints, {
  78142. depth:this.zMax-this.zMin-shrink,
  78143. UVGenerator: new MetricUVGenerator()
  78144. });
  78145. if(this.buildType == 'building' ){
  78146. this.box.position.z = this.zMin - shrink / 2;
  78147. }else {
  78148. this.box.position.z = this.zMin + shrink / 2;
  78149. }
  78150. }
  78151. }
  78152. update(options={}){
  78153. super.update(this.buildType != 'floor' && options.ifUpdateMarkers);
  78154. let length = this.points.length;
  78155. {//确保一下一样
  78156. if(this.originHole){
  78157. this.points = this.originHole.points; //完全等于building的hole
  78158. }
  78159. if(this.buildType == 'hole'){
  78160. this.zMin = this.buildParent.zMin;
  78161. this.zMax = this.buildParent.zMax;
  78162. }
  78163. }
  78164. if(!options.dontUpdateBox){
  78165. let boxOwner;
  78166. if(this.buildType == 'hole'){
  78167. if(this.buildParent.buildType == 'building'){ //若是整栋大楼的hole,在每层都要更新下它的对应hole
  78168. this.buildParent.buildChildren.forEach(floor=>{
  78169. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  78170. holeAtFloor && holeAtFloor.update(); //刚开始创建时还没创建对应的 holeAtFloor会为null
  78171. });
  78172. }
  78173. boxOwner = this.buildParent;
  78174. }else {
  78175. boxOwner = this;
  78176. }
  78177. boxOwner.updateBox();
  78178. }
  78179. {//update lines
  78180. let positions = [];
  78181. this.points.forEach((point, index)=>{
  78182. //竖线:
  78183. positions.push(point.clone().setZ(this.zMin), point.clone().setZ(this.zMax));
  78184. //横线
  78185. let nextPoint = this.points[(index+1)%length];
  78186. if(!nextPoint)return;//when length==1
  78187. positions.push(point.clone().setZ(this.zMax), nextPoint.clone().setZ(this.zMax));//上横线
  78188. positions.push(point.clone().setZ(this.zMin), nextPoint.clone().setZ(this.zMin));//下横线
  78189. });
  78190. LineDraw.moveLine(this.lineMesh,positions);
  78191. }
  78192. if(!options.dontUpdateChildren){
  78193. if(this.buildType == 'building' ){
  78194. this.buildChildren.forEach(floor=>{
  78195. floor.points = this.points;
  78196. floor.update();
  78197. });
  78198. }
  78199. {
  78200. let holes = this.holes.concat(this.parentHoles);
  78201. holes.forEach(hole=> {
  78202. hole.update({dontUpdateBox:true});//父级更新了box,hole就不需要更新box了
  78203. });
  78204. }
  78205. }
  78206. }
  78207. getHolesArea(){
  78208. let holes = this.holes.concat(this.parentHoles);
  78209. let outHoles, holesArea = 0;
  78210. if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  78211. let holes_ = holes.map(e=>e.points);
  78212. outHoles = math.getPolygonsMixedRings(holes_, true );
  78213. outHoles.forEach(e=>{
  78214. holesArea+=e.area;
  78215. });
  78216. outHoles = outHoles.map(e=>e.points);
  78217. }else {
  78218. outHoles = holes.map(e=>e.points);
  78219. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)));
  78220. }
  78221. return holesArea
  78222. }
  78223. getArea(ifRidOfHoles){//面积
  78224. //不排除hole
  78225. return Math.abs(math.getArea(this.points)) - (ifRidOfHoles ? this.getHolesArea() : 0)
  78226. }
  78227. getVolume(ifRidOfHoles){//体积
  78228. let {zMin , zMax} = this.getRealZ();
  78229. let height = zMax - zMin;
  78230. if(isNaN(height))height = 0;
  78231. return this.getArea(ifRidOfHoles) * height
  78232. }
  78233. getRealZ(){//求真实高度时用到的
  78234. let zMin , zMax;
  78235. if (this.buildType == 'building') {
  78236. //building的zMax和zMin一样的所以要算
  78237. let top = this.buildChildren[this.buildChildren.length - 1];
  78238. let btm = this.buildChildren[0];
  78239. zMin = btm ? btm.zMin : 0; //建好的建筑不加楼的话是0
  78240. zMax = top ? top.zMax : 0;
  78241. }else if(this.buildType == 'hole'){
  78242. return this.buildParent.getRealZ()
  78243. }else {
  78244. zMin = this.zMin, zMax = this.zMax;
  78245. }
  78246. return {zMin,zMax}
  78247. }
  78248. /* getDrawZ(){ //画线和box时用到的z
  78249. let zMin , zMax
  78250. if(this.buildType == 'hole'){
  78251. if(this.buildParent.buildType == 'building' && atFloor){
  78252. zMin = atFloor.zMin, zMax = atFloor.zMax
  78253. }else{
  78254. zMin = this.buildParent.zMin, zMax = this.buildParent.zMax
  78255. }
  78256. }else{
  78257. zMin = this.zMin, zMax = this.zMax
  78258. }
  78259. return {zMin, zMax}
  78260. } */
  78261. getBound(){
  78262. let bound = new Box3;
  78263. let {zMin , zMax} = this.getRealZ();
  78264. let points = this.buildType == 'floor' ? this.buildParent.points : this.points;
  78265. points.forEach(p=>{
  78266. bound.expandByPoint(p.clone().setZ(zMin));
  78267. bound.expandByPoint(p.clone().setZ(zMax));
  78268. });
  78269. return bound
  78270. }
  78271. getMarkerMaterial(type) {
  78272. if(!markerMats$2){
  78273. markerMats$2 = {
  78274. default: new MeshBasicMaterial({
  78275. transparent: !0,
  78276. color: color$2,
  78277. opacity: 0.8,
  78278. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78279. depthTest:false,
  78280. }),
  78281. midPrepare: new MeshBasicMaterial({ //线中心的半透明点
  78282. transparent: !0,
  78283. color: color$2,
  78284. opacity: 0.4,
  78285. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78286. depthTest:false,
  78287. }),
  78288. hover: new MeshBasicMaterial({
  78289. transparent: !0,
  78290. color: color$2,
  78291. opacity: 1,
  78292. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78293. depthTest:false,
  78294. }),
  78295. select: new MeshBasicMaterial({
  78296. transparent: !0,
  78297. color:new Color('#00C8AF'),
  78298. opacity: 1,
  78299. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78300. depthTest:false,
  78301. }),
  78302. };
  78303. }
  78304. return markerMats$2[type]
  78305. }
  78306. setMarkerSelected(marker, state, hoverObject){
  78307. //console.warn(marker.id , state, hoverObject)
  78308. if(state == 'select'){
  78309. marker.selected = true;
  78310. marker.material = this.getMarkerMaterial('select');
  78311. }else if(state == 'unselect'){
  78312. marker.selected = false;
  78313. marker.material = this.getMarkerMaterial('default');
  78314. }else {
  78315. if(marker.selected)return //选中时不允许修改为除了'unselect'以外的状态
  78316. if(state == 'hover'){
  78317. marker.material = this.getMarkerMaterial('hover');
  78318. }else if(state == 'unhover'){
  78319. if(marker.name.includes('mid')){
  78320. marker.material = this.getMarkerMaterial('midPrepare');
  78321. }else {
  78322. marker.material = this.getMarkerMaterial('default');
  78323. }
  78324. }
  78325. }
  78326. }
  78327. select(){
  78328. //最多再显示一层子级的线,如building不会显示room中的hole的线
  78329. //box是一直显示的,但会切换材质
  78330. /*
  78331. 选中 box 线
  78332. building 自己(底盘)选中 自己, floor不带hole
  78333. floor 自己选中 自己, room不带hole
  78334. room 自己选中 自己
  78335. */ //注:自己的就代表定包括hole,如果有parentHoles的也(building上的hole的对应)
  78336. //console.log('select '+this.name, this.selected)
  78337. if(this.selected)return
  78338. if(this.box){
  78339. this.box.material = this.mats.boxSelected;
  78340. }
  78341. if(this.buildType == 'building'|| this.buildType == 'floor'){
  78342. this.buildChildren.forEach(e=>{
  78343. e.lineMesh.visible = true;
  78344. });
  78345. if(this.buildType == 'floor'){
  78346. viewer.setObjectLayers(this.box, 'bothMapAndScene' );
  78347. viewer.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' ); //当选中floor或room时,building在地图不可见
  78348. }
  78349. }else if(this.buildType == 'room'){
  78350. viewer.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78351. viewer.setObjectLayers(this.buildParent.buildParent.box, 'siteModelMapUnvisi' );
  78352. }
  78353. this.lineMesh.visible = true;
  78354. this.markers && this.markers.forEach(e=>viewer.updateVisible(e,'select',true) );
  78355. this.midMarkers && this.midMarkers.forEach(e=>e.visible = true);
  78356. let holes = this.holes.concat(this.parentHoles);
  78357. holes.forEach(e=>e.select());
  78358. this.selected = true;
  78359. this.dispatchEvent({type:'select'});
  78360. }
  78361. unselect(){
  78362. if(!this.selected)return
  78363. //console.log('unselect '+this.name )
  78364. if(this.box){
  78365. this.box.material = this.mats.boxDefault;
  78366. }
  78367. if(this.buildType == 'building' || this.buildType == 'floor'){
  78368. this.buildChildren.forEach(e=>{ //(这里要保证选中前要先取消选中,否则如选中房间后取消了楼层,房间线就隐藏了)
  78369. e.lineMesh.visible = false;
  78370. });
  78371. if(this.buildType == 'floor'){
  78372. viewer.setObjectLayers(this.box, 'siteModelMapUnvisi' );
  78373. viewer.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78374. }
  78375. }else if(this.buildType == 'room'){
  78376. viewer.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' );
  78377. viewer.setObjectLayers(this.buildParent.buildParent.box, 'bothMapAndScene' );
  78378. }
  78379. this.lineMesh.visible = false;
  78380. this.markers && this.markers.forEach(e=>viewer.updateVisible(e,'select',false) );
  78381. this.midMarkers && this.midMarkers.forEach(e=>e.visible = false);
  78382. let holes = this.holes.concat(this.parentHoles);
  78383. holes.forEach(e=>e.unselect());
  78384. this.selected = false;
  78385. this.dispatchEvent({type:'unselect'});
  78386. }
  78387. ifContainsPoint(position){//看它所定义的空间是否包含某个坐标(要排除hole)
  78388. let {zMin , zMax} = this.getRealZ();
  78389. if(position.z < zMin || position.z > zMax ) return
  78390. let holes = this.holes.concat(this.parentHoles);
  78391. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  78392. let inShape = math.isPointInArea(this.points, holesPoints, position);
  78393. return !!inShape
  78394. }
  78395. }
  78396. class MetricUVGenerator{
  78397. constructor(){
  78398. this.a = new Vector3,
  78399. this.b = new Vector3,
  78400. this.c = new Vector3,
  78401. this.d = new Vector3;
  78402. }
  78403. generateTopUV(t, e, n, r, o) {
  78404. 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])]
  78405. }
  78406. generateSideWallUV(t, e, n, r, o, a) {
  78407. var s = e;
  78408. this.a.set(s[3 * n], s[3 * n + 1], s[3 * n + 2]),
  78409. this.b.set(s[3 * r], s[3 * r + 1], s[3 * r + 2]),
  78410. this.c.set(s[3 * o], s[3 * o + 1], s[3 * o + 2]),
  78411. this.d.set(s[3 * a], s[3 * a + 1], s[3 * a + 2]);
  78412. var c = this.a.x !== this.b.x
  78413. , l = c ? this.b : this.d
  78414. , u = this.a.distanceTo(l)
  78415. , d = l.distanceTo(this.c);
  78416. 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)]
  78417. }
  78418. }
  78419. const minFloorHeight = 0.5;
  78420. const ifDrawDatasetBound = true; //显示一下数据集的tightBound线框
  78421. const minMarkers = 3;
  78422. const Limit = {zMin:-config$1.map.cameraHeight, zMax:config$1.map.cameraHeight,}; //不能超过camera的高度,为了对称所以也限制了最低
  78423. var SiteModel = {
  78424. bus: new EventDispatcher(),
  78425. entities:[], //所有实体
  78426. buildings:[], //所有建筑父集
  78427. meshGroup: new Object3D,
  78428. inEntity : null,
  78429. lastPos: new Vector3(Infinity,Infinity,Infinity),
  78430. init: function(){
  78431. viewer.scene.scene.add(this.meshGroup);
  78432. this.meshGroup.name = 'siteModel';
  78433. this.SplitScreen = SplitScreen4Views;
  78434. if(Potree.settings.editType == 'pano'){
  78435. return
  78436. }
  78437. this.createHeightPull();
  78438. if(Potree.settings.isTest && ifDrawDatasetBound){
  78439. viewer.addEventListener('allLoaded',()=>{
  78440. viewer.scene.pointclouds.forEach(pointcloud=>{
  78441. let boxPoints = pointcloud.getUnrotBoundPoint();
  78442. let boundingBox = new BuildingBox({
  78443. name: '数据集tightBound_'+pointcloud.dataset_id,
  78444. points: boxPoints,
  78445. buildType : 'dataset',
  78446. zMax: pointcloud.bound.max.z,
  78447. zMin: pointcloud.bound.min.z,
  78448. ifDraw:true
  78449. });
  78450. this.meshGroup.add(boundingBox);
  78451. //boundingBox.markers.forEach(e=>e.visible = false)
  78452. });
  78453. });
  78454. }
  78455. if(Potree.settings.isOfficial){
  78456. viewer.addEventListener('camera_changed', e => {
  78457. if(e.changeInfo.positionChanged){
  78458. this.updateEntityAt();
  78459. }
  78460. });
  78461. }
  78462. {
  78463. let pressDelete = (e)=>{
  78464. if(e.keyCode == KeyCodes.BACKSPACE || e.keyCode == KeyCodes.DELETE){
  78465. if(this.selectedMarker){
  78466. let entity = this.selectedMarker.parent;
  78467. let index = entity.markers.indexOf(this.selectedMarker);
  78468. entity.removeMarker(index);
  78469. if(entity.points.length<2){//删到只剩一个点时重新画(如果是hole的点,直接删除hole吧?)
  78470. this.startInsertion('resume',entity);
  78471. }
  78472. }
  78473. }
  78474. };
  78475. viewer.inputHandler.addEventListener('keydown', pressDelete);
  78476. }
  78477. },
  78478. updateEntityAt(force){
  78479. //if(!this.entities.length || this.editing) return //编辑时也要根据位置显示不同楼层的漫游点与cad
  78480. let fun = ()=>{ //延时update,防止卡顿
  78481. let currPos = viewer.mainViewport.view.position;
  78482. //if(force || !currPos.equals(this.lastPos) ){
  78483. //console.log('currPos ', currPos.toArray())
  78484. this.lastPos.copy(currPos);
  78485. let entity;
  78486. let searchPos = Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : currPos;
  78487. entity = this.pointInWhichEntity(searchPos, 'room');
  78488. if(force || this.inEntity != entity ){
  78489. let oldEntity = this.inEntity;
  78490. this.inEntity = entity;
  78491. //console.log('buildingChange', entity)
  78492. this.bus.dispatchEvent({type:'buildingChange',entity});
  78493. //this.updatePanosVisible(oldEntity, this.inEntity)
  78494. let lastFloor = this.currentFloor; //oldEntity ? oldEntity.buildType == 'floor' ? oldEntity : oldEntity.buildType == 'room' ? oldEntity.buildParent : null : null; //基本只会是floor或room
  78495. let currentFloor = entity ? entity.buildType == 'floor' ? entity : entity.buildType == 'room' ? entity.buildParent : null : null; //基本只会是floor或room
  78496. if(force || currentFloor != lastFloor){
  78497. //console.log('改变了floor',lastFloor,currentFloor)
  78498. this.currentFloor = currentFloor;
  78499. this.bus.dispatchEvent({type:'FloorChange',currentFloor});
  78500. }
  78501. }
  78502. force = false;
  78503. return true
  78504. //}
  78505. };
  78506. if(force)fun();
  78507. else Common.intervalTool.isWaiting('sitemodelCameraInterval', fun , 500);
  78508. },
  78509. enter:function(){
  78510. Potree.Log('sitemodel enter');
  78511. this.clear(); //确保全部清空
  78512. this.editing = true;
  78513. //this.updatePanosVisible(null, null, true)//show all
  78514. viewer.updateFpVisiDatasets();
  78515. let mapViewport = viewer.mapViewer.viewports[0];
  78516. this.SplitScreen.split({siteModel:true/* , viewports:[{name:'Top',viewport : mapViewport }] */});
  78517. viewer.viewports.forEach(e=>{
  78518. if(e.name != 'mapViewport'){
  78519. e.layersAdd('siteModelMapUnvisi');
  78520. }
  78521. if(e.name == 'right' || e.name == 'back'){
  78522. e.layersAdd('siteModeSideVisi');
  78523. }
  78524. });
  78525. viewer.images360.panos.forEach(pano=>{
  78526. viewer.setObjectLayers(pano.marker, 'siteModelMapUnvisi' );
  78527. });
  78528. mapViewport.layersAdd('siteModeOnlyMapVisi'); //只有mapViewport能看到marker
  78529. },
  78530. leave:function(){
  78531. Potree.Log('sitemodel leave');
  78532. let mapViewport = viewer.mapViewer.viewports[0];
  78533. this.SplitScreen.recover();
  78534. viewer.viewports.forEach(e=>{
  78535. if(e.name != 'mapViewport'){
  78536. e.layersRemove('siteModelMapUnvisi');
  78537. }
  78538. if(e.name == 'right' || e.name == 'back'){
  78539. e.layersRemove('siteModeSideVisi');
  78540. }
  78541. });
  78542. viewer.images360.panos.forEach(pano=>{
  78543. viewer.setObjectLayers(pano.marker, 'sceneObjects' );
  78544. });
  78545. mapViewport.layersRemove('siteModeOnlyMapVisi');
  78546. this.clear();
  78547. this.editing = false;
  78548. this.updateEntityAt(true);
  78549. viewer.updateFpVisiDatasets();
  78550. } ,
  78551. addFloor:function(parent, dirType, sid, name){//dirType:'top'|'bottom'在上方建还是下方。如果建筑中没有楼层,默认在基底建一个
  78552. let buildType = 'floor';
  78553. let zMin, zMax;
  78554. if(parent.buildChildren.length == 0){
  78555. zMin = parent.zMin;
  78556. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78557. }else {
  78558. if(dirType == 'bottom'){
  78559. //var btm = Common.find(parent.buildChildren,null,[e=>e.zMin])
  78560. var btm = parent.buildChildren[0];
  78561. zMax = btm.zMin;
  78562. zMin = zMax - Potree.config.siteModel.floorHeightDefault;
  78563. }else {
  78564. //var top = Common.find(parent.buildChildren,null,[e=>e.zMax])
  78565. var top = parent.buildChildren[parent.buildChildren.length - 1];
  78566. zMin = top.zMax;
  78567. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78568. }
  78569. }
  78570. let prop = {
  78571. buildType,
  78572. //name : Potree.config.siteModel.names[buildType],
  78573. zMin,
  78574. zMax,
  78575. buildParent:parent,
  78576. sid, name,
  78577. ifDraw:true
  78578. };
  78579. var floor = new BuildingBox(prop);
  78580. /* parent.buildChildren.push(floor)
  78581. this.meshGroup.add(floor);
  78582. this.entities.push(floor) */
  78583. floor.update();
  78584. this.addEntity(floor,parent);
  78585. //this.selectEntity(floor)
  78586. if(this.selected == parent){//重新选择下,为了显示新楼层线框
  78587. parent.unselect();
  78588. parent.select();
  78589. }
  78590. return floor
  78591. },
  78592. startInsertion:function(buildType, parent, sid, name, callback, cancelFun){
  78593. let zMin, zMax, entity, resume;
  78594. let mapViewport = viewer.mapViewer.viewports[0];
  78595. if(buildType == 'resume'){//继续画(使用最后一个点或者新加的点)
  78596. resume = true;
  78597. entity = parent;
  78598. buildType = parent.buildType;
  78599. //删除原先所有的点,因为它们已经添加了事件,会很麻烦:
  78600. entity.reDraw(0);
  78601. entity.isNew = true; //当作新的来画
  78602. }
  78603. if(!resume){
  78604. if(buildType == 'hole' || buildType == 'room'){
  78605. zMin = parent.zMin;
  78606. zMax = parent.zMax;
  78607. }else if(buildType == 'building'){
  78608. parent = null;
  78609. zMin = viewer.bound.boundingBox.min.z;
  78610. zMax = viewer.bound.boundingBox.min.z;
  78611. }
  78612. if(buildType == 'hole'){
  78613. entity = parent.addHole();
  78614. entity.isNew = true;
  78615. this.selectEntity(parent);
  78616. entity.select();
  78617. console.log('挖洞 ',entity.uuid);
  78618. }else {
  78619. let prop = {
  78620. buildType,
  78621. //name : Potree.config.siteModel.names[buildType],//'building',
  78622. zMin,
  78623. zMax,
  78624. buildParent:parent,
  78625. sid, name,
  78626. ifDraw:true
  78627. };
  78628. entity = new BuildingBox(prop);
  78629. entity.isNew = true;
  78630. this.selectEntity(entity);
  78631. }
  78632. this.addEntity(entity, parent);
  78633. }
  78634. let timer;
  78635. let endDragFun = (e) => {
  78636. if (e.button == MOUSE.LEFT ) {
  78637. var marker = entity.addMarker({point:entity.points[entity.points.length - 1].clone()});
  78638. //entity.editStateChange(true) //重新激活reticule状态
  78639. entity.continueDrag(marker, e);
  78640. } else if (e.button === MOUSE.RIGHT ) {
  78641. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  78642. else entity.continueDrag(null, e/* .drag.object */);
  78643. }
  78644. };
  78645. let finish = ()=>{//结束绘画
  78646. viewer.removeEventListener('cancel_insertions', Exit);
  78647. entity.removeEventListener('unselect', Exit);
  78648. clearTimeout(timer);
  78649. entity.editStateChange(false);
  78650. //pressExit && viewer.inputHandler.removeEventListener('keydown', pressExit);
  78651. callback && callback(entity);
  78652. };
  78653. let end = (e={}) => {//尝试结束
  78654. /* 退出的三种形式:
  78655. 1 普通:如果大于三个marker,结束且保留;否则重新画。()
  78656. 2 删除:直接结束且删除。(remove)
  78657. 3 结束:如果大于三个marker,结束且保留;否则结束且删除。 (finish)
  78658. 4 保留:无论几个marker,都保留着,结束。(remain)
  78659. */
  78660. if(e.remove){
  78661. finish();
  78662. return this.removeEntity(entity)
  78663. }
  78664. if(!e.remain && !e.finish && !e.remove && entity.markers.length<=minMarkers){//右键 当个数不够时取消
  78665. //重新开始画
  78666. entity.reDraw(1);
  78667. viewer.updateVisible(entity.markers[0],'unMove',false);
  78668. var f = ()=>{
  78669. viewer.updateVisible(entity.markers[0],'unMove',true);
  78670. entity.removeEventListener('dragChange',f);
  78671. };
  78672. entity.addEventListener('dragChange',f);
  78673. //console.log('waitcontinue')
  78674. entity.continueDrag(entity.markers[0], e);
  78675. return
  78676. }
  78677. finish();
  78678. if (e.remain || !e.remove && entity.markers.length > 3) {//保留
  78679. entity.removeMarker(entity.points.length - 1);
  78680. entity.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  78681. if(buildType == 'room'){
  78682. this.fitPullBox();
  78683. }
  78684. entity.isNew = false;
  78685. entity.addMidMarkers();
  78686. }else {
  78687. this.removeEntity(entity); //直接删除没画好的,比较简单。这样就不用担心旧的continueDrag仍旧触发了
  78688. }
  78689. return entity
  78690. };
  78691. let Exit = (e)=>{ //强制结束
  78692. entity.removeEventListener('unselect', Exit);
  78693. if(viewer.inputHandler.drag){//还未触发drop的话
  78694. viewer.inputHandler.drag.object.dispatchEvent({
  78695. type: 'drop',
  78696. drag: viewer.inputHandler.drag,
  78697. viewer: viewer,
  78698. pressDistance:0,
  78699. button : MOUSE.RIGHT
  78700. });
  78701. viewer.inputHandler.drag = null;
  78702. }else {
  78703. end({remain:true});
  78704. }
  78705. viewer.inputHandler.drag = null;
  78706. };
  78707. viewer.dispatchEvent( 'cancel_insertions' );//取消之前的
  78708. viewer.addEventListener('cancel_insertions', Exit);
  78709. entity.addEventListener('unselect', Exit);
  78710. var marker = entity.addMarker({point:new Vector3(0, 0, 0)});
  78711. viewer.updateVisible(marker,'unMove',false);//这时候的位置是假的(0,0,0)所以先不可见
  78712. var f = ()=>{
  78713. viewer.updateVisible(marker,'unMove',true);
  78714. entity.removeEventListener('dragChange',f);
  78715. };
  78716. entity.addEventListener('dragChange',f);
  78717. marker.isDragging = true;
  78718. viewer.inputHandler.startDragging(marker , {dragViewport:mapViewport, endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78719. return entity;
  78720. },
  78721. getPreDealData(points, zMin, zMax, initial, buildType, parent){
  78722. /* if( buildType == 'building' ){
  78723. zMax = zMin //强制变得一样,作为基底。如果有必要,保存时再算真实的zMax。目前zMin没有保存所以数据是错的,会直接根据floor计算
  78724. } */
  78725. var bound = viewer.bound.boundingBox;
  78726. if(buildType == 'building' && initial){//初始数据错的,要自己建(只有一个building和floor) 原posIsLonlat
  78727. console.log('空间模型未编辑过, 初始化了一个');
  78728. points = [
  78729. new Vector3(bound.min.x, bound.min.y,0),
  78730. new Vector3(bound.max.x, bound.min.y,0),
  78731. new Vector3(bound.max.x, bound.max.y,0),
  78732. new Vector3(bound.min.x, bound.max.y,0),
  78733. ];
  78734. zMin = bound.min.z;
  78735. zMax = bound.max.z;
  78736. /* points = points.map(e=>{
  78737. return viewer.transform.lonlatToLocal.forward(e)
  78738. }) */
  78739. }else {//相对于初始数据集的模型内坐标
  78740. points = points.map(e=> this.transform(e, 'fromDataset'));
  78741. if(buildType == 'floor' && initial){
  78742. zMin = bound.min.z;
  78743. zMax = bound.max.z;
  78744. }
  78745. }
  78746. return {points, zMax, zMin }
  78747. },
  78748. resetFromData:function(entity, points=[], holes=[], zMin, zMax ){
  78749. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , this.autoBuild , entity.buildType, entity.buildParent );
  78750. if(entity.buildType != 'floor' )entity.points = points;
  78751. if(entity.buildType == 'room'){
  78752. entity.zMin = zMin;
  78753. entity.zMax = zMax;
  78754. }else if(entity.buildType == 'floor'){//改楼高
  78755. let height = zMax - zMin;
  78756. let zMax2 = entity.zMin + height;
  78757. SiteModel.changeZ(entity, 'zMax', zMax2);
  78758. }
  78759. {
  78760. //删除旧的holes重新添加
  78761. let holesOld = entity.holes;
  78762. holesOld.forEach(e=>{
  78763. entity.removeHole(e);
  78764. });
  78765. holes.forEach(points =>{
  78766. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78767. let hole = entity.addHole(ps);
  78768. hole.addMidMarkers();
  78769. });
  78770. }
  78771. entity.update();
  78772. return entity
  78773. }
  78774. ,
  78775. createFromData:function( buildType, parent ,sid, name, points=[], holes=[], zMin, zMax, initial,panos_,flagPano){
  78776. if(buildType != 'building' && buildType != 'floor' && buildType != 'room' ) return
  78777. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , initial, buildType, parent );
  78778. let panos = [];
  78779. {
  78780. if(panos_){
  78781. panos_.forEach(sid=>{
  78782. let pano = viewer.images360.getPano(sid,'sid');
  78783. if(pano)panos.push(pano);
  78784. });
  78785. }
  78786. flagPano = flagPano != void 0 ? viewer.images360.getPano(flagPano,'sid') : null ; //最中心的pano 或者 最靠近该实体的pano(当panos为空时)
  78787. if(!this.editing && buildType == 'floor' && !flagPano){//没有的话可能是自动添加的floor,直接用parent的吧
  78788. panos = parent.panos;
  78789. flagPano = parent.flagPano;
  78790. }
  78791. }
  78792. let prop = {
  78793. buildType,
  78794. points,
  78795. name,
  78796. sid,
  78797. zMin,
  78798. zMax,
  78799. buildParent:parent,
  78800. ifDraw:this.editing || Potree.settings.drawEntityData,
  78801. panos, flagPano,
  78802. autoBuild : initial
  78803. };
  78804. let entity = new BuildingBox(prop);
  78805. SiteModel.addEntity(entity, parent );
  78806. if(this.editing){
  78807. if(buildType == 'building'|| buildType == 'room'){
  78808. entity.addMidMarkers();
  78809. }
  78810. }
  78811. holes.forEach(points =>{
  78812. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78813. let hole = entity.addHole(ps);
  78814. this.editing && hole.addMidMarkers();
  78815. });
  78816. /* if(buildType == 'floor'){
  78817. this.updateBuildingZ(parent)
  78818. } */
  78819. return entity
  78820. },
  78821. transform:function(pos, type){
  78822. if(Potree.settings.editType == 'pano'){ // 模型不经转换
  78823. return new Vector3().copy(pos).setZ(0);
  78824. }
  78825. if(type == 'toDataset'){
  78826. let point = Potree.Utils.datasetPosTransform({ toDataset: true, position: pos.clone(), datasetId: Potree.settings.originDatasetId });
  78827. return new Vector2$1().copy(point)
  78828. }else {
  78829. let position = new Vector3().copy(pos).setZ(0);
  78830. return Potree.Utils.datasetPosTransform({ fromDataset: true, position, datasetId: Potree.settings.originDatasetId })
  78831. }
  78832. },
  78833. addEntity:function(entity, parent){
  78834. this.meshGroup.add(entity);
  78835. this.entities.push(entity);
  78836. if(entity.buildType == 'building'){
  78837. this.buildings.push(entity);
  78838. }else {
  78839. parent.buildChildren.push(entity);
  78840. }
  78841. if(entity.buildType == 'room'){
  78842. entity.addEventListener('marker_dropped',()=>{
  78843. this.fitPullBox();
  78844. });
  78845. }else if(entity.buildType == 'floor'){
  78846. this.updateBuildingZ(parent);
  78847. parent.dispatchEvent({type:'addFloor'});
  78848. }
  78849. {//仅能存在一个marker被选中。选中的点可以被删除
  78850. entity.addEventListener('clickMarker', (e)=>{
  78851. if(this.selectedMarker == e.marker){
  78852. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78853. this.selectedMarker = null;
  78854. }else {
  78855. if(this.selectedMarker){
  78856. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78857. }
  78858. this.selectedMarker = e.marker;
  78859. this.selectedMarker.dispatchEvent({type:'clickSelect',state:true});
  78860. }
  78861. });
  78862. entity.addEventListener('removeMarker', (e)=>{
  78863. if(this.selectedMarker == e.marker){
  78864. this.selectedMarker = null;
  78865. }
  78866. });
  78867. let unselect = (e)=>{//取消选中实体或删除后
  78868. if(this.selectedMarker && entity.markers.includes(this.selectedMarker)){
  78869. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78870. this.selectedMarker = null;
  78871. }
  78872. };
  78873. entity.addEventListener('dispose', unselect);
  78874. entity.addEventListener('unselect', unselect);
  78875. }
  78876. //console.log('添加实体:', entity.buildType, entity.sid, entity.uuid)
  78877. },
  78878. removeEntity : function(entity){
  78879. if(!this.entities.includes(entity))return
  78880. console.log('删除实体:', entity.buildType, entity.sid);
  78881. if(this.selected == entity){
  78882. this.height_pull_box.visible = false;
  78883. this.selectEntity(null);
  78884. }
  78885. if(entity.buildType == 'building'){
  78886. var index = this.buildings.indexOf(entity);
  78887. if(index>-1){
  78888. this.buildings.splice(index,1);
  78889. }
  78890. }else {
  78891. var index = entity.buildParent.buildChildren.indexOf(entity);
  78892. if(index>-1){
  78893. entity.buildParent.buildChildren.splice(index,1);
  78894. }
  78895. }
  78896. var index = this.entities.indexOf(entity);
  78897. if(index>-1){
  78898. this.entities.splice(index,1);
  78899. }
  78900. entity.dispose();
  78901. let buildChildren = entity.buildChildren.slice();
  78902. buildChildren.forEach(e=>this.removeEntity(e));
  78903. },
  78904. updateBuildingZ:function(building){
  78905. building.buildChildren = building.buildChildren.sort((e,a)=>e.zMin-a.zMin);//从低到高排序
  78906. building.zMin = building.zMax = building.buildChildren[0].zMin; //基底高度
  78907. //building.zMax = building.buildChildren[building.buildChildren.length-1].zMax
  78908. if(this.editing) building.update({dontUpdateChildren:true});
  78909. building.dispatchEvent('updateBuildingZ');
  78910. },
  78911. selectEntity : function(entity, state=true){
  78912. if(state === false){
  78913. entity.unselect();
  78914. if(this.selected == entity)this.selected = null;
  78915. return
  78916. }
  78917. if(this.selected == entity || entity && entity.buildType == 'hole')return
  78918. //this.buildings.forEach(e=>e.unselect())
  78919. this.selected && this.selected.unselect();
  78920. this.height_pull_box.visible = false;
  78921. if(entity){
  78922. entity.select();
  78923. }
  78924. this.selected = entity;
  78925. if(entity && (entity.buildType == 'floor' || entity.buildType == 'room' )){
  78926. this.height_pull_box.visible = true;
  78927. this.fitPullBox();
  78928. }
  78929. if(entity && !entity.isNew && (entity.buildType == 'building' || entity.buildType == 'room' ) && entity.points.length<2){
  78930. this.startInsertion('resume',entity); //继续画
  78931. }
  78932. },
  78933. fitPullBox: function(){ //自适应拖拽楼层的pullMesh
  78934. if(!this.selected || this.selected.buildType!= 'floor' && this.selected.buildType!= 'room')return
  78935. let bound = new Box3();
  78936. bound.expandByObject(this.selected.box);
  78937. let center = bound.getCenter(new Vector3() );
  78938. let size = bound.getSize(new Vector3() );
  78939. this.height_pull_box.scale.copy(size);
  78940. this.height_pull_box.position.copy(center);
  78941. },
  78942. changeZ:function(entity, dirType, value){ // floor or room 修改zMin or zMax
  78943. let max, min; //limit
  78944. if(entity.buildType == 'floor'){//楼层
  78945. let index = entity.buildParent.buildChildren.indexOf(entity);
  78946. if(dirType == 'zMax'){
  78947. let upper = entity.buildParent.buildChildren[index+1];
  78948. entity.zMax = Math.min(Limit.zMax, value);
  78949. min = entity.zMin + minFloorHeight;
  78950. if(entity.zMax < min){
  78951. entity.zMax = min;
  78952. }else {
  78953. if(upper){
  78954. max = upper.zMax - minFloorHeight;
  78955. if(entity.zMax > max){
  78956. entity.zMax = max;
  78957. }
  78958. }
  78959. }
  78960. if(upper){
  78961. upper.zMin = entity.zMax;
  78962. upper.update();
  78963. upper.dispatchEvent({type:'changeHeight'});
  78964. }
  78965. }else {
  78966. let lower = entity.buildParent.buildChildren[index-1];
  78967. entity.zMin = Math.max(Limit.zMin, value);
  78968. max = entity.zMax - minFloorHeight;
  78969. if(entity.zMin > max){
  78970. entity.zMin = max;
  78971. }else {
  78972. if(lower){
  78973. min = lower.zMin + minFloorHeight;
  78974. if(entity.zMin < min){
  78975. entity.zMin = min;
  78976. }
  78977. }
  78978. }
  78979. if(lower){
  78980. lower.zMax = entity.zMin;
  78981. lower.update();
  78982. lower.dispatchEvent({type:'changeHeight'});
  78983. }
  78984. if(index == 0)this.updateBuildingZ(entity.buildParent);
  78985. }
  78986. }else if(entity.buildType == 'room'){//房间
  78987. //按照navvis的是不一定限制在当前楼层,只要高度不超过当前楼层即可。
  78988. let maxHeight = entity.buildParent.zMax - entity.buildParent.zMin;
  78989. if(dirType == 'zMax'){
  78990. min = entity.zMin + minFloorHeight;
  78991. max = entity.zMin + maxHeight;
  78992. entity.zMax = MathUtils.clamp(value, min, max);
  78993. }else {
  78994. min = entity.zMax - maxHeight;
  78995. max = entity.zMax - minFloorHeight;
  78996. entity.zMin = MathUtils.clamp(value, min, max);
  78997. }
  78998. }
  78999. entity.update();
  79000. entity.dispatchEvent({type:'changeHeight'});
  79001. //this.selected.emit('update')
  79002. this.fitPullBox();
  79003. },
  79004. createHeightPull:function(){ //拖拽楼层的bounding box
  79005. let boxGeo = new BoxBufferGeometry( 1, 1, 1/4 );
  79006. let boxMat = new MeshBasicMaterial({
  79007. color:"#F00",
  79008. opacity:0,
  79009. transparent:true,
  79010. depthTest:false,
  79011. side:2
  79012. });
  79013. let height_pull_box_up = new Mesh(boxGeo,boxMat);
  79014. let height_pull_box_down = new Mesh(boxGeo,boxMat);
  79015. height_pull_box_up.name = 'height_pull_box_up';
  79016. height_pull_box_down.name = 'height_pull_box_down';
  79017. this.height_pull_box = new Object3D();
  79018. this.height_pull_box.name = 'height_pull_box';
  79019. this.height_pull_box.add(height_pull_box_up);
  79020. this.height_pull_box.add(height_pull_box_down);
  79021. this.height_pull_box.visible = false;
  79022. this.meshGroup.add(this.height_pull_box);
  79023. height_pull_box_up.position.set(0,0,1/2/* 3/8 */);
  79024. height_pull_box_down.position.set(0,0,-1/2/* -3/8 */);
  79025. viewer.setObjectLayers(this.height_pull_box, 'siteModeSideVisi' );
  79026. let mouseover = (e)=>{
  79027. viewer.dispatchEvent({
  79028. type : "CursorChange", action : "add", name:"siteModelFloorDrag"
  79029. });
  79030. };
  79031. let mouseleave = (e)=>{
  79032. viewer.dispatchEvent({
  79033. type : "CursorChange", action : "remove", name:"siteModelFloorDrag"
  79034. });
  79035. };
  79036. let firstZ, firstIntersect;
  79037. let drag = (e)=>{
  79038. var intersect = e.intersect.orthoIntersect; //不要点云的intersect,只要orthocamera算出的平面intersect
  79039. if(firstIntersect != void 0){
  79040. let moveZ = intersect.z - firstIntersect;
  79041. if(this.selected.buildType == 'floor'){//楼层
  79042. //限制高度不能超过上下
  79043. if(e.target == height_pull_box_up){
  79044. if(firstZ == void 0)firstZ = this.selected.zMax;
  79045. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  79046. }else {
  79047. if(firstZ == void 0)firstZ = this.selected.zMin;
  79048. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  79049. }
  79050. }else if(this.selected.buildType == 'room'){//房屋
  79051. if(e.target == height_pull_box_up){
  79052. if(firstZ == void 0)firstZ = this.selected.zMax;
  79053. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  79054. }else {
  79055. if(firstZ == void 0)firstZ = this.selected.zMin;
  79056. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  79057. }
  79058. }
  79059. }else {
  79060. firstIntersect = intersect.z;
  79061. }
  79062. };
  79063. let drop = (e)=>{
  79064. firstZ = firstIntersect = null;
  79065. };
  79066. height_pull_box_up.addEventListener('mousemove',mouseover);
  79067. height_pull_box_down.addEventListener('mousemove',mouseover);
  79068. height_pull_box_up.addEventListener('mouseleave',mouseleave);
  79069. height_pull_box_down.addEventListener('mouseleave',mouseleave);
  79070. height_pull_box_up.addEventListener('drag',drag);
  79071. height_pull_box_down.addEventListener('drag',drag);
  79072. height_pull_box_up.addEventListener('drop',drop);
  79073. height_pull_box_down.addEventListener('drop',drop);
  79074. },
  79075. pointInWhichEntity(location, buildType, ifIgnoreHole){//buildType是要找的建筑类型
  79076. //location 可以是pano或者坐标
  79077. //由于房间可能在building外,所以房间要另外单独识别。
  79078. let lastResult; //最接近的上一层结果,如果没有result返回这个
  79079. let result;
  79080. let level = {
  79081. building: 0, floor: 1, room: 2
  79082. };
  79083. let traverse = (parent, buildType)=>{//返回第一个符合标准的实体
  79084. let contains;
  79085. if(location instanceof Vector3){
  79086. contains = parent.ifContainsPoint(location);
  79087. }else {//is pano
  79088. contains = parent.panos.includes(location);
  79089. }
  79090. if(contains){
  79091. if(!lastResult || level[lastResult.buildType] < level[parent.buildType] )lastResult = parent;
  79092. if(parent.buildType == buildType){
  79093. return parent
  79094. }else {
  79095. for(let i=0,len=parent.buildChildren.length; i<len; i++){
  79096. let result1 = traverse(parent.buildChildren[i]);
  79097. if(result1) return result1
  79098. }
  79099. }
  79100. }
  79101. };
  79102. //因为建筑可能重叠,所以需要先找到最接近其中心的建筑物
  79103. result = Common.sortByScore(this.buildings, [(building)=>{
  79104. return traverse(building, 'building') //在building中
  79105. }], [(building)=>{ //写法类似pointInWhichPointcloud
  79106. let boundingBox = building.getBound();
  79107. let center = boundingBox.getCenter(new Vector3());
  79108. let position = location instanceof Vector3 ? location : location.position;
  79109. let dis = position.distanceTo(center);
  79110. let size = boundingBox.getSize(new Vector3());
  79111. let length = size.length() / 2;
  79112. return length / dis
  79113. }]);
  79114. let building = result && result[0] && result[0].score > 1 && result[0].item;
  79115. if(buildType == 'building' || !building)return building
  79116. result = traverse(building, buildType);
  79117. /* if(!result && buildType == 'room'){//如果要找的是room, 且按刚才的顺序找不到的话,就单独从所有rooms中找一遍。因为room可能不在floor和building内。
  79118. let rooms = this.entities.filter(e=>e.buildType == 'room');
  79119. result = rooms.find(e=>e.ifContainsPoint(position))
  79120. }*/
  79121. //虽然房间可以画到上级之外,但是为了方便起见,假定房间绝对在楼层之内。找不到的话要调整空间模型了。
  79122. return result || lastResult
  79123. }
  79124. ,
  79125. findPanos: function(){
  79126. {
  79127. this.entities.forEach(entity=>{
  79128. //清空:
  79129. entity.panos = [];
  79130. entity.flagPano = null;
  79131. viewer.images360.panos.forEach(pano=>{
  79132. if(entity.ifContainsPoint(pano.position)){
  79133. entity.panos.push(pano);
  79134. }
  79135. });
  79136. });
  79137. }
  79138. /* viewer.images360.panos.forEach(pano=>{ //一个漫游点只对应一个实体的话
  79139. let result = this.pointInWhichEntity(pano.position, 'room');
  79140. {//get panos for every entities
  79141. let entity = result
  79142. while(entity){
  79143. entity.panos.push(pano);
  79144. entity = entity.buildParent
  79145. }
  79146. }
  79147. }) */
  79148. {//search center pano
  79149. this.entities.forEach(entity=>{
  79150. let panos = entity.panos;
  79151. if(panos.length == 0)return
  79152. let bound = entity.getBound();
  79153. let center = bound.getCenter(new Vector3);
  79154. let request = [];
  79155. let rank = [
  79156. Images360.scoreFunctions.distanceSquared({position: center})
  79157. ];
  79158. //let panos = entity.panos && entity.panos.length ? entity.panos : viewer.images360.panos //entity没有panos的话,就扩大到所有panos
  79159. let r = Common.sortByScore(panos, request, rank);
  79160. if(r && r.length){
  79161. entity.flagPano = r[0].item;
  79162. }else {
  79163. console.error('no flagPano??');
  79164. }
  79165. });
  79166. }
  79167. }
  79168. ,
  79169. findEntityForDataset:function(){//为每一个数据集寻找它所属的最小实体
  79170. /* var entities = this.entities.filter(e=>e.buildType == 'room' || e.buildType == 'floor' && e.buildChildren.length == 0)
  79171. viewer.scene.pointclouds.forEach(pointcloud=>{
  79172. let cloudVolume = pointcloud.getVolume()
  79173. let scores = []
  79174. entities.forEach(entity=>{
  79175. let volume = entity.intersectPointcloudVolume(pointcloud)
  79176. //注:默认已经findPanos过
  79177. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  79178. let panoCount = panos.length
  79179. let score = volume / cloudVolume + panoCount / pointcloud.panos.length
  79180. scores.push({entity, volume, panoCount, score})
  79181. })
  79182. scores.sort((a,b)=>{ return b.score-a.score })
  79183. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  79184. pointcloud.belongToEntity = null
  79185. }else{
  79186. pointcloud.belongToEntity = scores[0].entity;
  79187. }
  79188. }) */
  79189. let getScores = (pointcloud, entities, cloudVolume)=>{
  79190. let scores = [];
  79191. entities.forEach(entity=>{
  79192. let volume = entity.intersectPointcloudVolume(pointcloud);
  79193. //注:默认已经findPanos过
  79194. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  79195. let panoCount = panos.length;
  79196. let score = volume / cloudVolume;
  79197. if(pointcloud.panos.length > 0){
  79198. score += panoCount / pointcloud.panos.length;
  79199. }else {
  79200. //score += 1
  79201. }
  79202. scores.push({entity, volume, panoCount, score});
  79203. });
  79204. scores.sort((a,b)=>{ return b.score-a.score });
  79205. return scores
  79206. };
  79207. viewer.scene.pointclouds.forEach(pointcloud=>{ //先判断父级,如果父集不通过就不判断子级。
  79208. let cloudVolume = pointcloud.getVolume();
  79209. let entities = this.buildings;
  79210. while(1){
  79211. let scores = getScores(pointcloud, entities, cloudVolume);
  79212. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  79213. if(scores[0] && scores[0].entity.buildType == 'room'){
  79214. pointcloud.belongToEntity = scores[0].entity; //当该数据集在楼层中,但不在楼层中的任意一个房间时,任意挂载在其中一个房间上。
  79215. break
  79216. }
  79217. pointcloud.belongToEntity = null;
  79218. break;
  79219. }else {
  79220. entities = scores[0].entity.buildChildren;
  79221. if(entities.length == 0){
  79222. pointcloud.belongToEntity = scores[0].entity;
  79223. break;
  79224. }
  79225. }
  79226. }
  79227. });
  79228. /*
  79229. 旧版:
  79230. 只需要考虑 floor 和 room, 因为building的只有一个基底没高度
  79231. floor 和 room 在空间中没有完全的从属关系,因为room可以超出floor之外。所以直接混在一起来查找,但要排除有房间的楼层。
  79232. (现在改为层层递进查找,否则数据集包含entity多的,会直接挂载到体积最大的房间里,即使看起来主体点云并不在该房间)
  79233. 有的数据集虽然很高,但只有近地面的部分才是主体,这部分一般含有全部漫游点。为了防止上层的实体因体积较大而分数高,就把包含漫游点的个数也加入考虑。
  79234. 重叠体积大、且包含漫游点最多的最小实体将会拥有该点云。
  79235. 期望: 最好不挂载到最小子级,因为现在有房间都到房间里了。
  79236. */
  79237. }
  79238. ,
  79239. clear:function(){//清空
  79240. /* entities:[], //所有实体
  79241. buildings:[], //所有建筑父集
  79242. meshGroup: new THREE.Object3D, */
  79243. this.selectEntity(null);
  79244. let length = this.entities.length;
  79245. for(let i=0;i<length;i++){
  79246. this.entities[i].dispose();
  79247. }
  79248. this.entities = [];
  79249. this.buildings = [];
  79250. this.inEntity = null;
  79251. }
  79252. ,
  79253. gotoEntity(id, isNearBy, duration=1000) {
  79254. var entity = this.entities.find(e => e.sid == id);
  79255. let aimPano;
  79256. if (!entity) {
  79257. return console.error('没找到entity ')
  79258. }
  79259. if(Potree.settings.displayMode == 'showPanos'){
  79260. if (isNearBy && entity.panos.length) {
  79261. if(entity.panos.includes(viewer.images360.currentPano)) return 'posNoChange' //已在当前实体中
  79262. let position = viewer.scene.getActiveCamera().position;
  79263. let request = [];
  79264. let rank = [Images360.scoreFunctions.distanceSquared({ position })];
  79265. let r = Common.sortByScore(entity.panos, request, rank);
  79266. aimPano = r[0].item;
  79267. } else {
  79268. if (!entity.flagPano) {
  79269. return console.log('没有flagPano')
  79270. }
  79271. aimPano = entity.flagPano;
  79272. }
  79273. if(aimPano == viewer.images360.currentPano) return 'posNoChange'
  79274. viewer.images360.flyToPano(aimPano);
  79275. }else {
  79276. if(isNearBy && entity.ifContainsPoint(viewer.images360.position) ){
  79277. return 'posNoChange' //已在当前实体中
  79278. }
  79279. let boundingBox = entity.getBound();
  79280. let position = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  79281. if(viewer.modules.Clip && viewer.modules.Clip.editing){
  79282. viewer.modules.Clip.bus.dispatchEvent({type:'flyToPos', position});
  79283. }else {
  79284. if(math.closeTo(position, viewer.images360.position)) return 'posNoChange'
  79285. let size = boundingBox.getSize(new Vector3());
  79286. viewer.scene.view.setView({position, duration});
  79287. viewer.mapViewer.moveTo(position, size, duration);
  79288. }
  79289. }
  79290. return true
  79291. },
  79292. focusEntity(id){
  79293. var entity = this.entities.find(e => e.sid == id);
  79294. let boundingBox = entity.getBound();
  79295. //let boundSize = boundingBox.getSize(new THREE.Vector3())
  79296. let center = boundingBox.getCenter(new Vector3());
  79297. this.SplitScreen.focusOnObject(boundingBox, center);
  79298. this.gotoEntity(id, false, 0);
  79299. },
  79300. removeIlligalArchi(){//删除marker数量小于3个的建筑,当保存时
  79301. let needDelete = [];
  79302. this.entities.forEach(e=>{
  79303. if(e.points.length<3){
  79304. needDelete.push(e);
  79305. }
  79306. });
  79307. needDelete.forEach(e=>this.removeEntity(e));
  79308. },
  79309. };
  79310. // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)
  79311. class InfiniteGridHelper extends Mesh{
  79312. constructor(size1, size2, color, distance, opacity1=0.2, opacity2=1){
  79313. color = color || new Color('white');
  79314. size1 = size1 || 10;
  79315. size2 = size2 || 100;
  79316. distance = distance || 8000; //可视距离?越远越模糊
  79317. const geometry = new PlaneBufferGeometry(2, 2, 1, 1);
  79318. const material = new ShaderMaterial({
  79319. side: DoubleSide,
  79320. uniforms: {
  79321. uSize1: {
  79322. value: size1
  79323. },
  79324. uSize2: {
  79325. value: size2
  79326. },
  79327. opacity1:{//线条1的
  79328. value: opacity1
  79329. },
  79330. opacity2:{//线条2的
  79331. value: opacity2
  79332. },
  79333. uColor: {
  79334. value: color
  79335. },
  79336. uDistance: {
  79337. value: distance
  79338. }
  79339. },
  79340. transparent: true,
  79341. vertexShader: `
  79342. varying vec3 worldPosition;
  79343. uniform float uDistance;
  79344. void main() {
  79345. vec3 pos = position.xyz * uDistance;
  79346. pos.xy += cameraPosition.xy;
  79347. worldPosition = pos;
  79348. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
  79349. }
  79350. `,
  79351. fragmentShader: `
  79352. varying vec3 worldPosition;
  79353. uniform float uSize1;
  79354. uniform float uSize2;
  79355. uniform float opacity1;
  79356. uniform float opacity2;
  79357. uniform vec3 uColor;
  79358. uniform float uDistance;
  79359. float getGrid(float size) {
  79360. vec2 r = worldPosition.xy / size;
  79361. vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
  79362. float line = min(grid.x, grid.y);
  79363. return 1.0 - min(line, 1.0);
  79364. }
  79365. //为何侧面看不到线,因为mesh的正侧面都看不到?
  79366. void main() {
  79367. float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);
  79368. float g1 = getGrid(uSize1);
  79369. float g2 = getGrid(uSize2);
  79370. gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
  79371. //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
  79372. gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);
  79373. if ( gl_FragColor.a <= 0.0 ) discard;
  79374. }
  79375. `,
  79376. extensions: {
  79377. derivatives: true
  79378. }
  79379. });
  79380. super(geometry, material);
  79381. this.frustumCulled = false;
  79382. }
  79383. };
  79384. /*
  79385. THREE.InfiniteGridHelper.prototype = {
  79386. ...THREE.Mesh.prototype,
  79387. ...THREE.Object3D.prototype,
  79388. ...THREE.EventDispatcher.prototype
  79389. };
  79390. */
  79391. var TransformControls = function ( camera, domElement, options ) {
  79392. if ( domElement === undefined ) {
  79393. console.warn( 'THREE.TransformControls: The second parameter "domElement" is now mandatory.' );
  79394. domElement = document;
  79395. }
  79396. Object3D.call( this );
  79397. this.visible = false;
  79398. this.domElement = domElement;
  79399. var _gizmo = new TransformControlsGizmo(options);
  79400. this.add( _gizmo );
  79401. this._gizmo = _gizmo;
  79402. var _plane = new TransformControlsPlane(options);
  79403. this.add( _plane );
  79404. /* this.linesAssistance = new TransformControlsLines(options); //水平 垂直 辅助
  79405. this.add( this.linesAssistance ); */
  79406. var scope = this;
  79407. //this.player = options.player;//xzw add
  79408. this.options = options;//xzw add
  79409. // Define properties with getters/setter
  79410. // Setting the defined property will automatically trigger change event
  79411. // Defined properties are passed down to gizmo and plane
  79412. defineProperty( "camera", camera );
  79413. defineProperty( "object", undefined );
  79414. defineProperty( "enabled", true );
  79415. defineProperty( "axis", null );
  79416. defineProperty( "mode", "translate" );
  79417. defineProperty( "translationSnap", null );
  79418. defineProperty( "rotationSnap", null );
  79419. defineProperty( "scaleSnap", null );
  79420. defineProperty( "space", "world" );
  79421. defineProperty( "size", 1 );
  79422. defineProperty( "dragging", false );
  79423. defineProperty( "showX", true );
  79424. defineProperty( "showY", true );
  79425. defineProperty( "showZ", true );
  79426. var changeEvent = { type: "change" };
  79427. var mouseDownEvent = { type: "mouseDown" };
  79428. var mouseUpEvent = { type: "mouseUp", mode: scope.mode };
  79429. var objectChangeEvent = { type: "objectChange" };
  79430. // Reusable utility variables
  79431. var ray = new Raycaster();
  79432. var _tempVector = new Vector3();
  79433. var _tempVector2 = new Vector3();
  79434. var _tempQuaternion = new Quaternion();
  79435. var _unit = {
  79436. X: new Vector3( 1, 0, 0 ),
  79437. Y: new Vector3( 0, 1, 0 ),
  79438. Z: new Vector3( 0, 0, 1 )
  79439. };
  79440. var pointStart = new Vector3();
  79441. var pointEnd = new Vector3();
  79442. var offset = new Vector3();
  79443. var rotationAxis = new Vector3();
  79444. var startNorm = new Vector3();
  79445. var endNorm = new Vector3();
  79446. var rotationAngle = 0;
  79447. var cameraPosition = new Vector3();
  79448. var cameraQuaternion = new Quaternion();
  79449. var cameraScale = new Vector3();
  79450. var parentPosition = new Vector3();
  79451. var parentQuaternion = new Quaternion();
  79452. var parentQuaternionInv = new Quaternion();
  79453. var parentScale = new Vector3();
  79454. var worldPositionStart = new Vector3();
  79455. var worldQuaternionStart = new Quaternion();
  79456. var worldScaleStart = new Vector3();
  79457. var worldPosition = new Vector3();
  79458. var worldQuaternion = new Quaternion();
  79459. var worldQuaternionInv = new Quaternion();
  79460. var worldScale = new Vector3();
  79461. var eye = new Vector3();
  79462. var positionStart = new Vector3();
  79463. var quaternionStart = new Quaternion();
  79464. var scaleStart = new Vector3();
  79465. // TODO: remove properties unused in plane and gizmo
  79466. defineProperty( "worldPosition", worldPosition );
  79467. defineProperty( "worldPositionStart", worldPositionStart );
  79468. defineProperty( "worldQuaternion", worldQuaternion );
  79469. defineProperty( "worldQuaternionStart", worldQuaternionStart );
  79470. defineProperty( "cameraPosition", cameraPosition );
  79471. defineProperty( "cameraQuaternion", cameraQuaternion );
  79472. defineProperty( "pointStart", pointStart );
  79473. defineProperty( "pointEnd", pointEnd );
  79474. defineProperty( "rotationAxis", rotationAxis );
  79475. defineProperty( "rotationAngle", rotationAngle );
  79476. defineProperty( "eye", eye );
  79477. {
  79478. domElement.addEventListener( "mousedown", onPointerDown, false );
  79479. domElement.addEventListener( "touchstart", onPointerDown, false );
  79480. domElement.addEventListener( "mousemove", onPointerHover, false );
  79481. domElement.addEventListener( "touchmove", onPointerHover, false );
  79482. domElement.addEventListener( "touchmove", onPointerMove, false );
  79483. document.addEventListener( "mouseup", onPointerUp, false );
  79484. domElement.addEventListener( "touchend", onPointerUp, false );
  79485. domElement.addEventListener( "touchcancel", onPointerUp, false );
  79486. domElement.addEventListener( "touchleave", onPointerUp, false );
  79487. viewer.addEventListener('global_drag',(e)=>{
  79488. if(this.dragging){
  79489. this.pointerMove();
  79490. return {stopContinue:true}
  79491. }
  79492. },10);
  79493. }
  79494. this.setRotateMethod = function(number){//add 注意为2时 旋转期间不能改变位置 space可能不能为local ._gizmo.hideAxis = { rotate:[这里必须包含'e' ] }
  79495. this.rotateMethod = number;
  79496. };
  79497. this.dispose = function () {
  79498. domElement.removeEventListener( "mousedown", onPointerDown );
  79499. domElement.removeEventListener( "touchstart", onPointerDown );
  79500. domElement.removeEventListener( "mousemove", onPointerHover );
  79501. domElement.removeEventListener( "mousemove", onPointerMove );
  79502. domElement.removeEventListener( "touchmove", onPointerHover );
  79503. domElement.removeEventListener( "touchmove", onPointerMove );
  79504. document.removeEventListener( "mouseup", onPointerUp );
  79505. domElement.removeEventListener( "touchend", onPointerUp );
  79506. domElement.removeEventListener( "touchcancel", onPointerUp );
  79507. domElement.removeEventListener( "touchleave", onPointerUp );
  79508. this.traverse( function ( child ) {
  79509. if ( child.geometry ) child.geometry.dispose();
  79510. if ( child.material ) child.material.dispose();
  79511. } );
  79512. };
  79513. // Set current object
  79514. this.attach = function ( object ) {
  79515. this.object = object;
  79516. this.visible = true;
  79517. //Config.keyCon = false;//add
  79518. //this.linesAssistance.setVisible(true)
  79519. return this;
  79520. };
  79521. // Detatch from object
  79522. this.detach = function () {
  79523. this.object = undefined;
  79524. this.visible = false;
  79525. this.axis = null;
  79526. //Config.keyCon = true;//add
  79527. //this.linesAssistance.setVisible(false)
  79528. return this;
  79529. };
  79530. //this.space = 'local'
  79531. /* this.hideAxis = function ( mode, axis=[] ) {//xzw add 设置不可见的axis
  79532. var handles = [];
  79533. handles = handles.concat( this._gizmo.picker[ mode ].children );
  79534. handles = handles.concat( this._gizmo.gizmo[ mode ].children );
  79535. handles = handles.concat( this._gizmo.helper[ mode ].children );
  79536. handles.forEach(e=>e.visible = false)
  79537. axis.forEach(name=>{
  79538. handles.filter(handle =>!handle.name.includes(name))
  79539. })
  79540. handles.forEach(e=>e.visible = true)
  79541. }; */
  79542. // Defined getter, setter and store for a property
  79543. function defineProperty( propName, defaultValue ) {
  79544. var propValue = defaultValue;
  79545. Object.defineProperty( scope, propName, {
  79546. get: function () {
  79547. return propValue !== undefined ? propValue : defaultValue;
  79548. },
  79549. set: function ( value ) {
  79550. if ( propValue !== value ) {
  79551. propValue = value;
  79552. _plane[ propName ] = value;
  79553. _gizmo[ propName ] = value;
  79554. scope.dispatchEvent( { type: propName + "-changed", value: value } );
  79555. scope.dispatchEvent( changeEvent );
  79556. }
  79557. }
  79558. } );
  79559. scope[ propName ] = defaultValue;
  79560. _plane[ propName ] = defaultValue;
  79561. _gizmo[ propName ] = defaultValue;
  79562. }
  79563. // updateMatrixWorld updates key transformation variables
  79564. this.updateMatrixWorld = function () {
  79565. if(!this.visible)return//add
  79566. if ( this.object !== undefined ) {
  79567. this.object.updateMatrixWorld();
  79568. this.object.parent.matrixWorld.decompose( parentPosition, parentQuaternion, parentScale );
  79569. this.object.matrixWorld.decompose( worldPosition, worldQuaternion, worldScale );
  79570. //add 使坐标轴在boundingBox中心
  79571. this.object.boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  79572. parentQuaternionInv.copy( parentQuaternion ).invert();
  79573. worldQuaternionInv.copy( worldQuaternion ).invert();
  79574. }
  79575. this.camera.updateMatrixWorld();
  79576. this.camera.matrixWorld.decompose( cameraPosition, cameraQuaternion, cameraScale );
  79577. if(this.camera.type == "OrthographicCamera"){//xzw add
  79578. eye.copy( this.view.direction);
  79579. }else {
  79580. eye.copy( cameraPosition ).sub( worldPosition ).normalize();
  79581. }
  79582. Object3D.prototype.updateMatrixWorld.call( this );
  79583. };
  79584. this.pointerHover = function () {
  79585. let pointer = viewer.inputHandler.pointer;
  79586. if ( this.object === undefined)return
  79587. //if(this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return;
  79588. if(!this.dragging){
  79589. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79590. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79591. ray.set(origin, direction);
  79592. viewer.setCameraLayers(ray, //设置能识别到的layers
  79593. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79594. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79595. );
  79596. var intersect = ray.intersectObjects( _gizmo.picker[ this.mode ].children.filter(e=>e.visible), true )[ 0 ] || false;
  79597. if ( intersect ) {
  79598. this.axis = intersect.object.name;
  79599. } else {
  79600. this.axis = null;
  79601. }
  79602. }else {
  79603. //this.pointerMove()
  79604. }
  79605. };
  79606. this.pointerDown = function ( /* pointer */ ) {
  79607. let pointer = viewer.inputHandler.pointer;
  79608. if ( this.object === undefined || this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */ ) return;
  79609. if ( /* ( pointer.button === 0 || pointer.button === undefined ) && */ this.axis !== null ) {
  79610. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79611. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79612. ray.set(origin, direction);
  79613. viewer.setCameraLayers(ray, //设置能识别到的layers
  79614. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79615. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79616. );
  79617. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79618. if ( planeIntersect ) {
  79619. var space = this.space;
  79620. if ( this.mode === 'scale' ) {
  79621. space = 'local';
  79622. } else if ( this.axis === 'E' || this.axis === 'XYZE' || this.axis === 'XYZ' ) {
  79623. space = 'world';
  79624. }
  79625. if ( space === 'local' && this.mode === 'rotate' ) {
  79626. var snap = this.rotationSnap;
  79627. if ( this.axis === 'X' && snap ) this.object.rotation.x = Math.round( this.object.rotation.x / snap ) * snap;
  79628. if ( this.axis === 'Y' && snap ) this.object.rotation.y = Math.round( this.object.rotation.y / snap ) * snap;
  79629. if ( this.axis === 'Z' && snap ) this.object.rotation.z = Math.round( this.object.rotation.z / snap ) * snap;
  79630. }
  79631. this.object.updateMatrixWorld();
  79632. this.object.parent.updateMatrixWorld();
  79633. positionStart.copy( this.object.position );
  79634. quaternionStart.copy( this.object.quaternion );
  79635. scaleStart.copy( this.object.scale );
  79636. this.object.matrixWorld.decompose( worldPositionStart, worldQuaternionStart, worldScaleStart );
  79637. //add: 使坐标轴在boundingBox中心
  79638. this.object.boundingBox && this.object.boundingBox.getCenter(worldPositionStart).applyMatrix4(this.object.matrixWorld);
  79639. pointStart.copy( planeIntersect.point ).sub( worldPositionStart );
  79640. /* if(this.player.cameraControls.activeControl){
  79641. //this.player.cameraControls.activeControl.locked = true; //add
  79642. this.player.cameraControls.activeControl.enabled = false; //add
  79643. } */
  79644. }
  79645. this.dragging = true;
  79646. mouseDownEvent.mode = this.mode;
  79647. this.dispatchEvent( mouseDownEvent );
  79648. }
  79649. };
  79650. this.pointerMove = function ( /* pointer */ ) {
  79651. let pointer = viewer.inputHandler.pointer;
  79652. var axis = this.axis;
  79653. var mode = this.mode;
  79654. var object = this.object;
  79655. var space = this.space;
  79656. if ( mode === 'scale' ) {
  79657. space = 'local';
  79658. } else if ( axis === 'E' || axis === 'XYZE' || axis === 'XYZ' ) {
  79659. space = 'world';
  79660. }
  79661. if ( object === undefined || axis === null || this.dragging === false || ( pointer.button !== undefined && pointer.button !== 0 ) ) return;
  79662. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79663. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79664. ray.set(origin, direction);
  79665. viewer.setCameraLayers(ray, //设置能识别到的layers
  79666. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79667. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79668. );
  79669. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79670. if ( planeIntersect === false ) return;
  79671. pointEnd.copy( planeIntersect.point ).sub( worldPositionStart );
  79672. if ( mode === 'translate' ) {
  79673. // Apply translate
  79674. offset.copy( pointEnd ).sub( pointStart );
  79675. if ( space === 'local' && axis !== 'XYZ' ) {
  79676. offset.applyQuaternion( worldQuaternionInv );
  79677. }
  79678. if ( axis.indexOf( 'X' ) === - 1 ) offset.x = 0;
  79679. if ( axis.indexOf( 'Y' ) === - 1 ) offset.y = 0;
  79680. if ( axis.indexOf( 'Z' ) === - 1 ) offset.z = 0;
  79681. if ( space === 'local' && axis !== 'XYZ' ) {
  79682. //xzw 加,否则会反向---------------
  79683. object.scale.x < 0 && (offset.x *= -1);
  79684. object.scale.y < 0 && (offset.y *= -1);
  79685. object.scale.z < 0 && (offset.z *= -1);
  79686. //---------------------------------
  79687. offset.applyQuaternion( quaternionStart ).divide( parentScale );
  79688. } else {
  79689. offset.applyQuaternion( parentQuaternionInv ).divide( parentScale );
  79690. }
  79691. object.position.copy( offset ).add( positionStart );
  79692. // Apply translation snap
  79693. if ( this.translationSnap ) {
  79694. if ( space === 'local' ) {
  79695. object.position.applyQuaternion( _tempQuaternion.copy( quaternionStart ).invert() );
  79696. if ( axis.search( 'X' ) !== - 1 ) {
  79697. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79698. }
  79699. if ( axis.search( 'Y' ) !== - 1 ) {
  79700. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79701. }
  79702. if ( axis.search( 'Z' ) !== - 1 ) {
  79703. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79704. }
  79705. object.position.applyQuaternion( quaternionStart );
  79706. }
  79707. if ( space === 'world' ) {
  79708. if ( object.parent ) {
  79709. object.position.add( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79710. }
  79711. if ( axis.search( 'X' ) !== - 1 ) {
  79712. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79713. }
  79714. if ( axis.search( 'Y' ) !== - 1 ) {
  79715. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79716. }
  79717. if ( axis.search( 'Z' ) !== - 1 ) {
  79718. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79719. }
  79720. if ( object.parent ) {
  79721. object.position.sub( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79722. }
  79723. }
  79724. }
  79725. //add:
  79726. object.dispatchEvent({
  79727. type: "position_changed"
  79728. });
  79729. } else if ( mode === 'scale' ) {
  79730. if ( axis.search( 'XYZ' ) !== - 1 ) {
  79731. var d = pointEnd.length() / pointStart.length();
  79732. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79733. if(options.NoScaleZ){//xzw add
  79734. _tempVector2.set( d, d, 1 );
  79735. }else {
  79736. _tempVector2.set( d, d, d );
  79737. }
  79738. }else if ( axis.search( 'XY' ) !== - 1 ) { //add 等比例for plane
  79739. var d = pointEnd.length() / pointStart.length();
  79740. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79741. _tempVector2.set( d, d, 1 );
  79742. }else {
  79743. _tempVector.copy( pointStart );
  79744. _tempVector2.copy( pointEnd );
  79745. _tempVector.applyQuaternion( worldQuaternionInv );
  79746. _tempVector2.applyQuaternion( worldQuaternionInv );
  79747. _tempVector2.divide( _tempVector );
  79748. if ( axis.search( 'X' ) === - 1 ) {
  79749. _tempVector2.x = 1;
  79750. }
  79751. if ( axis.search( 'Y' ) === - 1 ) {
  79752. _tempVector2.y = 1;
  79753. }
  79754. if ( axis.search( 'Z' ) === - 1 ) {
  79755. _tempVector2.z = 1;
  79756. }
  79757. }
  79758. // Apply scale
  79759. object.scale.copy( scaleStart ).multiply( _tempVector2 );
  79760. if ( this.scaleSnap ) {
  79761. if ( axis.search( 'X' ) !== - 1 ) {
  79762. object.scale.x = Math.round( object.scale.x / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79763. }
  79764. if ( axis.search( 'Y' ) !== - 1 ) {
  79765. object.scale.y = Math.round( object.scale.y / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79766. }
  79767. if ( axis.search( 'Z' ) !== - 1 ) {
  79768. object.scale.z = Math.round( object.scale.z / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79769. }
  79770. }
  79771. //add:
  79772. object.dispatchEvent({
  79773. type: "scale_changed"
  79774. });
  79775. } else if ( mode === 'rotate' ) {
  79776. if(this.rotateMethod == 2){//新版参照transfromTool的写法,但是有bug,在同时移动位置时或e轴上有问题
  79777. if ( axis === 'E' ) {//绕着视线转
  79778. rotationAxis.copy( eye );//旋转轴
  79779. rotationAngle = pointEnd.angleTo( pointStart );
  79780. startNorm.copy( pointStart ).normalize();
  79781. endNorm.copy( pointEnd ).normalize();
  79782. rotationAngle *= ( endNorm.cross( startNorm ).dot( eye ) < 0 ? 1 : - 1 ); //角度
  79783. }else {
  79784. if ( axis === 'XYZE' ) {//像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动
  79785. offset.copy( pointEnd ).sub( pointStart );
  79786. rotationAxis.copy( offset ).cross( eye ).normalize();
  79787. }else {
  79788. rotationAxis.copy( _unit[ axis ] );
  79789. }
  79790. let center = new Vector3;//坐标轴位置
  79791. if(this.object.boundingBox){
  79792. this.object.boundingBox.getCenter(center).applyMatrix4(this.object.matrixWorld);
  79793. }else {
  79794. center.copy(worldPositionStart);//boundingBox中心可能变化 这里可能要改成直接获取model的position
  79795. }
  79796. let rotationAxis_ = space === 'local' ? rotationAxis.clone().applyQuaternion(worldQuaternion) : rotationAxis;
  79797. let plane = new Plane().setFromNormalAndCoplanarPoint(rotationAxis_, center);//旋转过程中rotationAxis不会变化,但center可能会
  79798. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79799. ray.set(origin, direction);
  79800. let I = ray.ray.intersectPlane(plane, new Vector3());
  79801. if (I) {
  79802. let v2 = I.clone().sub(center);//.normalize();
  79803. if(!this.rotateStart){
  79804. this.rotateStart = {
  79805. v1: v2
  79806. };
  79807. return
  79808. }
  79809. let v1 = this.rotateStart.v1;
  79810. rotationAngle = math.getAngle( v1, v2, rotationAxis_);
  79811. console.log(rotationAngle);
  79812. if (Number.isNaN(rotationAngle)) {
  79813. return;
  79814. }
  79815. this.rotateStart.v1 = v2;
  79816. }
  79817. }
  79818. }else {
  79819. //pointStart 是起始intersect - object中心的向量
  79820. //pointEnd 是当前intersect - object中心的向量
  79821. offset.copy( pointEnd ).sub( pointStart );
  79822. var ROTATION_SPEED = 2 / worldPosition.distanceTo( _tempVector.setFromMatrixPosition( this.camera.matrixWorld ) );
  79823. if ( axis === 'E' ) {//绕着视线转
  79824. rotationAxis.copy( eye );//旋转轴
  79825. rotationAngle = pointEnd.angleTo( pointStart );
  79826. startNorm.copy( pointStart ).normalize();
  79827. endNorm.copy( pointEnd ).normalize();
  79828. rotationAngle *= ( endNorm.cross( startNorm ).dot( eye ) < 0 ? 1 : - 1 ); //角度
  79829. } else if ( axis === 'XYZE' ) {//像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动
  79830. rotationAxis.copy( offset ).cross( eye ).normalize();
  79831. rotationAngle = offset.dot( _tempVector.copy( rotationAxis ).cross( this.eye ) ) * ROTATION_SPEED;
  79832. } else if ( axis === 'X' || axis === 'Y' || axis === 'Z' ) {
  79833. rotationAxis.copy( _unit[ axis ] );
  79834. _tempVector.copy( _unit[ axis ] );
  79835. if ( space === 'local' ) {
  79836. _tempVector.applyQuaternion( worldQuaternion );
  79837. }
  79838. rotationAngle = offset.dot( _tempVector.cross( eye ).normalize() ) * ROTATION_SPEED;
  79839. }
  79840. // Apply rotation snap
  79841. if ( this.rotationSnap ) rotationAngle = Math.round( rotationAngle / this.rotationSnap ) * this.rotationSnap;
  79842. this.rotationAngle = rotationAngle;
  79843. }
  79844. // Apply rotate
  79845. if ( space === 'local' && axis !== 'E' && axis !== 'XYZE' ) {
  79846. object.scale[axis.toLowerCase()] < 0 && (rotationAngle *= -1); //xzw 加,否则会反向
  79847. object.quaternion.copy( quaternionStart );
  79848. object.quaternion.multiply( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) ).normalize();
  79849. } else {
  79850. rotationAxis.applyQuaternion( parentQuaternionInv );
  79851. object.quaternion.copy( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) );
  79852. object.quaternion.multiply( quaternionStart ).normalize();
  79853. }
  79854. if ( this.rotateMethod == 2 && axis != 'E' ) {
  79855. quaternionStart.copy(object.quaternion);
  79856. }
  79857. //add:
  79858. object.dispatchEvent({
  79859. type: "rotation_changed"
  79860. });
  79861. }
  79862. this.dispatchEvent( changeEvent );
  79863. this.dispatchEvent( objectChangeEvent );
  79864. };
  79865. this.pointerUp = function ( pointer ) {
  79866. //if ( pointer.button !== undefined && pointer.button !== 0 ) return;
  79867. if ( this.dragging && ( this.axis !== null ) ) {
  79868. mouseUpEvent.mode = this.mode;
  79869. this.dispatchEvent( mouseUpEvent );
  79870. /* if(this.player.cameraControls.activeControl){
  79871. //this.player.cameraControls.activeControl.locked = false; //add
  79872. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79873. this.player.cameraControls.activeControl.enabled = true
  79874. } */
  79875. this.rotateStart = null;//add
  79876. }
  79877. this.dragging = false;
  79878. //if ( pointer.button === undefined ) this.axis = null;
  79879. /* if(this.player.cameraControls.activeControl){
  79880. //this.player.cameraControls.activeControl.locked = false; //add
  79881. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79882. this.player.cameraControls.activeControl.enabled = true
  79883. } */
  79884. };
  79885. // normalize mouse / touch pointer and remap {x,y} to view space.
  79886. function getPointer( event ) {
  79887. if(!event){
  79888. console.log('hhahhhahah');
  79889. return;
  79890. }
  79891. if ( document.pointerLockElement ) {
  79892. return {
  79893. x: 0,
  79894. y: 0,
  79895. button: event.button
  79896. };
  79897. } else {
  79898. var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event;
  79899. var rect = domElement.getBoundingClientRect();
  79900. return {
  79901. x: ( pointer.clientX - rect.left ) / rect.width * 2 - 1,
  79902. y: - ( pointer.clientY - rect.top ) / rect.height * 2 + 1,
  79903. button: event.button
  79904. };
  79905. }
  79906. }
  79907. // mouse / touch event handlers
  79908. function onPointerHover( event ) {
  79909. if ( ! scope.enabled ) return;
  79910. //scope.pointerHover( getPointer( event ) );
  79911. scope.pointerHover( );
  79912. }
  79913. function onPointerDown( event ) {
  79914. if ( ! scope.enabled ) return;
  79915. //document.addEventListener( "mousemove", onPointerMove, false );
  79916. /* scope.pointerHover( getPointer( event ) );
  79917. scope.pointerDown( getPointer( event ) ); */
  79918. scope.pointerHover( );
  79919. scope.pointerDown();
  79920. }
  79921. this.onPointerDown = onPointerDown;
  79922. function onPointerMove( event ) {
  79923. if ( ! scope.enabled || !this.dragging) return; //xzw change
  79924. //scope.pointerMove( getPointer( event ) );
  79925. scope.pointerMove( );
  79926. }
  79927. this.onPointerMove = onPointerMove;
  79928. function onPointerUp( event ) {
  79929. if ( ! scope.enabled ) return;
  79930. //document.removeEventListener( "mousemove", onPointerMove, false );
  79931. //scope.pointerUp( getPointer( event ) );
  79932. scope.pointerUp( );
  79933. }
  79934. this.onPointerUp = onPointerUp;
  79935. // TODO: deprecate
  79936. this.getMode = function () {
  79937. return scope.mode;
  79938. };
  79939. this.setMode = function ( mode ) {
  79940. scope.mode = mode;
  79941. };
  79942. this.setTranslationSnap = function ( translationSnap ) {
  79943. scope.translationSnap = translationSnap;
  79944. };
  79945. this.setRotationSnap = function ( rotationSnap ) {
  79946. scope.rotationSnap = rotationSnap;
  79947. };
  79948. this.setScaleSnap = function ( scaleSnap ) {
  79949. scope.scaleSnap = scaleSnap;
  79950. };
  79951. this.setSize = function ( size ) {
  79952. scope.size = size;
  79953. };
  79954. this.setSpace = function ( space ) {
  79955. scope.space = space;
  79956. };
  79957. this.update = function () {
  79958. console.warn( 'THREE.TransformControls: update function has no more functionality and therefore has been deprecated.' );
  79959. };
  79960. };
  79961. var TransformControlsGizmo = function (options) {
  79962. 'use strict';
  79963. Object3D.call( this );
  79964. this.type = 'TransformControlsGizmo';
  79965. // shared materials
  79966. this.hideAxis = {};
  79967. var gizmoMaterial = new MeshBasicMaterial( {
  79968. depthTest: false,
  79969. depthWrite: false,
  79970. transparent: true,
  79971. side: DoubleSide,
  79972. fog: false
  79973. } );
  79974. var gizmoLineMaterial = new LineBasicMaterial( {
  79975. depthTest: false,
  79976. depthWrite: false,
  79977. transparent: true,
  79978. fog: false
  79979. } );
  79980. // Make unique material for each axis/color
  79981. var matInvisible = gizmoMaterial.clone();
  79982. matInvisible.opacity = 0.15;
  79983. var matHelper = gizmoMaterial.clone();
  79984. matHelper.opacity = 0.1;
  79985. var matRed = gizmoMaterial.clone();
  79986. matRed.color.set( 0xff0000 );
  79987. var matGreen = gizmoMaterial.clone();
  79988. matGreen.color.set( 0x00ff00 );
  79989. var matBlue = gizmoMaterial.clone();
  79990. matBlue.color.set( 0x0000ff );
  79991. var matWhiteTransparent = gizmoMaterial.clone();
  79992. matWhiteTransparent.opacity = 0.35;
  79993. matWhiteTransparent.color.set( 0x00d0fd );//xzw add
  79994. var matYellowTransparent = matWhiteTransparent.clone();
  79995. matYellowTransparent.color.set( 0xffff00 );
  79996. var matCyanTransparent = matWhiteTransparent.clone();
  79997. matCyanTransparent.color.set( 0x00ffff );
  79998. var matMagentaTransparent = matWhiteTransparent.clone();
  79999. matMagentaTransparent.color.set( 0xff00ff );
  80000. var matYellow = gizmoMaterial.clone();
  80001. matYellow.color.set( 0xffff00 );
  80002. var matLineRed = gizmoLineMaterial.clone();
  80003. matLineRed.color.set( 0xff0000 );
  80004. var matLineGreen = gizmoLineMaterial.clone();
  80005. matLineGreen.color.set( 0x00ff00 );
  80006. var matLineBlue = gizmoLineMaterial.clone();
  80007. matLineBlue.color.set( 0x0000ff );
  80008. var matLineCyan = gizmoLineMaterial.clone();
  80009. matLineCyan.color.set( 0x00ffff );
  80010. var matLineMagenta = gizmoLineMaterial.clone();
  80011. matLineMagenta.color.set( 0xff00ff );
  80012. var matLineYellow = gizmoLineMaterial.clone();
  80013. matLineYellow.color.set( 0xffff00 );
  80014. var matLineGray = gizmoLineMaterial.clone();
  80015. matLineGray.color.set( 0x787878 );
  80016. var matLineYellowTransparent = matLineYellow.clone();
  80017. matLineYellowTransparent.opacity = 0.25;
  80018. // reusable geometry
  80019. var arrowGeometry = new CylinderBufferGeometry( 0, 0.05, 0.2, 12, 1, false );
  80020. var scaleHandleGeometry = new BoxBufferGeometry( 0.125, 0.125, 0.125 );
  80021. var lineGeometry = new BufferGeometry( );
  80022. //lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) );
  80023. lineGeometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 0, 0]), 3 ));
  80024. var CircleGeometry = function ( radius, arc ) {
  80025. var geometry = new BufferGeometry( );
  80026. var vertices = [];
  80027. for ( var i = 0; i <= 64 * arc; ++ i ) {
  80028. vertices.push( 0, Math.cos( i / 32 * Math.PI ) * radius, Math.sin( i / 32 * Math.PI ) * radius );
  80029. }
  80030. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  80031. geometry.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3 ));
  80032. return geometry;
  80033. };
  80034. // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position
  80035. var TranslateHelperGeometry = function () {
  80036. var geometry = new BufferGeometry();
  80037. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) );
  80038. geometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 1, 1 ]), 3 ));
  80039. return geometry;
  80040. };
  80041. // Gizmo definitions - custom hierarchy definitions for setupGizmo() function
  80042. var gizmoTranslate = {
  80043. X: [
  80044. [ new Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, - Math.PI / 2 ], null, 'fwd' ],
  80045. //[ new THREE.Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, Math.PI / 2 ], null, 'bwd' ],
  80046. [ new Line( lineGeometry, matLineRed ) ]
  80047. ],
  80048. Y: [
  80049. [ new Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], null, null, 'fwd' ],
  80050. //[ new THREE.Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], [ Math.PI, 0, 0 ], null, 'bwd' ],
  80051. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ]]
  80052. ],
  80053. Z: [
  80054. [ new Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ Math.PI / 2, 0, 0 ], null, 'fwd' ],
  80055. //[ new THREE.Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ - Math.PI / 2, 0, 0 ], null, 'bwd' ],
  80056. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ]]
  80057. ],
  80058. /* XYZ: [
  80059. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
  80060. ], */
  80061. XY: [
  80062. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent.clone() ), [ 0.15, 0.15, 0 ]],
  80063. [ new Line( lineGeometry, matLineYellow ), [ 0.18, 0.3, 0 ], null, [ 0.125, 1, 1 ]],
  80064. [ new Line( lineGeometry, matLineYellow ), [ 0.3, 0.18, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  80065. ],
  80066. YZ: [
  80067. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matCyanTransparent.clone() ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]],
  80068. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.18, 0.3 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  80069. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.3, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80070. ],
  80071. XZ: [
  80072. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matMagentaTransparent.clone() ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]],
  80073. [ new Line( lineGeometry, matLineMagenta ), [ 0.18, 0, 0.3 ], null, [ 0.125, 1, 1 ]],
  80074. [ new Line( lineGeometry, matLineMagenta ), [ 0.3, 0, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80075. ]
  80076. };
  80077. var pickerTranslate = {
  80078. X: [
  80079. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0.6, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  80080. ],
  80081. Y: [
  80082. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0.6, 0 ]]
  80083. ],
  80084. Z: [
  80085. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0, 0.6 ], [ Math.PI / 2, 0, 0 ]]
  80086. ],
  80087. /* XYZ: [
  80088. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.2, 0 ), matInvisible ) ]
  80089. ], */
  80090. XY: [
  80091. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0.2, 0 ]]
  80092. ],
  80093. YZ: [
  80094. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0, 0.2, 0.2 ], [ 0, Math.PI / 2, 0 ]]
  80095. ],
  80096. XZ: [
  80097. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0, 0.2 ], [ - Math.PI / 2, 0, 0 ]]
  80098. ]
  80099. };
  80100. var helperTranslate = {
  80101. START: [
  80102. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  80103. ],
  80104. END: [
  80105. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  80106. ],
  80107. DELTA: [
  80108. [ new Line( TranslateHelperGeometry(), matHelper ), null, null, null, 'helper' ]
  80109. ],
  80110. X: [
  80111. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80112. ],
  80113. Y: [
  80114. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  80115. ],
  80116. Z: [
  80117. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  80118. ]
  80119. };
  80120. var gizmoRotate = {
  80121. X: [
  80122. [ new Line( CircleGeometry( 1, 0.5 ), matLineRed ) ],
  80123. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matRed ), [ 0, 0, 0.99 ], null, [ 1, 3, 1 ]],
  80124. ],
  80125. Y: [
  80126. [ new Line( CircleGeometry( 1, 0.5 ), matLineGreen ), null, [ 0, 0, - Math.PI / 2 ]],
  80127. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matGreen ), [ 0, 0, 0.99 ], null, [ 3, 1, 1 ]],
  80128. ],
  80129. Z: [
  80130. [ new Line( CircleGeometry( 1, 0.5 ), matLineBlue ), null, [ 0, Math.PI / 2, 0 ]],
  80131. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matBlue ), [ 0.99, 0, 0 ], null, [ 1, 3, 1 ]],
  80132. ],
  80133. E: [
  80134. [ new Line( CircleGeometry( 1.25, 1 ), matLineYellowTransparent ), null, [ 0, Math.PI / 2, 0 ]],
  80135. [ 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 ]],
  80136. [ 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 ]],
  80137. [ 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 ]],
  80138. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ 0, 1.17, 0 ], [ 0, 0, 0 ], [ 1, 1, 0.001 ]],
  80139. ],
  80140. XYZE: [
  80141. [ new Line( CircleGeometry( 1, 1 ), matLineGray ), null, [ 0, Math.PI / 2, 0 ]]
  80142. ]
  80143. };
  80144. var helperRotate = {
  80145. AXIS: [
  80146. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80147. ]
  80148. };
  80149. var pickerRotate = {
  80150. X: [
  80151. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, - Math.PI / 2, - Math.PI / 2 ]],
  80152. ],
  80153. Y: [
  80154. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ]],
  80155. ],
  80156. Z: [
  80157. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  80158. ],
  80159. E: [
  80160. [ new Mesh( new TorusBufferGeometry( 1.25, 0.1, 2, 24 ), matInvisible ) ]
  80161. ],
  80162. XYZE: [
  80163. [ new Mesh( new SphereBufferGeometry( 0.7, 10, 8 ), matInvisible ) ]
  80164. ]
  80165. };
  80166. var gizmoScale = {
  80167. X: [
  80168. [ new Mesh( scaleHandleGeometry, matRed ), [ 0.8, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  80169. [ new Line( lineGeometry, matLineRed ), null, null, [ 0.8, 1, 1 ]]
  80170. ],
  80171. Y: [
  80172. [ new Mesh( scaleHandleGeometry, matGreen ), [ 0, 0.8, 0 ]],
  80173. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ], [ 0.8, 1, 1 ]]
  80174. ],
  80175. Z: [
  80176. [ new Mesh( scaleHandleGeometry, matBlue ), [ 0, 0, 0.8 ], [ Math.PI / 2, 0, 0 ]],
  80177. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ], [ 0.8, 1, 1 ]]
  80178. ],
  80179. XY: [
  80180. [ new Mesh( scaleHandleGeometry, matYellowTransparent ), [ 0.85, 0.85, 0 ], null, [ 2, 2, 0.2 ]],
  80181. [ new Line( lineGeometry, matLineYellow ), [ 0.855, 0.98, 0 ], null, [ 0.125, 1, 1 ]],
  80182. [ new Line( lineGeometry, matLineYellow ), [ 0.98, 0.855, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  80183. ],
  80184. /* YZ: [
  80185. [ new THREE.Mesh( scaleHandleGeometry, matCyanTransparent ), [ 0, 0.85, 0.85 ], null, [ 0.2, 2, 2 ]],
  80186. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.855, 0.98 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  80187. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.98, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80188. ],
  80189. XZ: [
  80190. [ new THREE.Mesh( scaleHandleGeometry, matMagentaTransparent ), [ 0.85, 0, 0.85 ], null, [ 2, 0.2, 2 ]],
  80191. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.855, 0, 0.98 ], null, [ 0.125, 1, 1 ]],
  80192. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80193. ],
  80194. XYZX: [
  80195. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 1.1, 0, 0 ]],
  80196. ],*/
  80197. XYZY: [
  80198. [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 1.1, 0 ]],
  80199. ]/* ,
  80200. XYZZ: [
  80201. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 0, 1.1 ]],
  80202. ] */
  80203. };
  80204. var pickerScale = {
  80205. X: [
  80206. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0.5, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  80207. ],
  80208. Y: [
  80209. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0.5, 0 ]]
  80210. ],
  80211. Z: [
  80212. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ]]
  80213. ],
  80214. XY: [
  80215. [ new Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0.85, 0 ], null, [ 3, 3, 0.2 ]],
  80216. ],
  80217. /*YZ: [
  80218. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0, 0.85, 0.85 ], null, [ 0.2, 3, 3 ]],
  80219. ],
  80220. XZ: [
  80221. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0, 0.85 ], null, [ 3, 0.2, 3 ]],
  80222. ],
  80223. XYZX: [
  80224. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 1.1, 0, 0 ]],
  80225. ],*/
  80226. XYZY: [
  80227. [ new Mesh( new BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 1.1, 0 ]],
  80228. ]/* ,
  80229. XYZZ: [
  80230. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 1.1 ]],
  80231. ] */
  80232. };
  80233. var helperScale = {
  80234. X: [
  80235. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80236. ],
  80237. Y: [
  80238. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  80239. ],
  80240. Z: [
  80241. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  80242. ]
  80243. };
  80244. // Creates an THREE.Object3D with gizmos described in custom hierarchy definition.
  80245. var setupGizmo = function ( gizmoMap ) {
  80246. var gizmo = new Object3D();
  80247. for ( var name in gizmoMap ) {
  80248. for ( var i = gizmoMap[ name ].length; i --; ) {
  80249. var object = gizmoMap[ name ][ i ][ 0 ].clone();
  80250. var position = gizmoMap[ name ][ i ][ 1 ];
  80251. var rotation = gizmoMap[ name ][ i ][ 2 ];
  80252. var scale = gizmoMap[ name ][ i ][ 3 ];
  80253. var tag = gizmoMap[ name ][ i ][ 4 ];
  80254. // name and tag properties are essential for picking and updating logic.
  80255. object.name = name;
  80256. object.tag = tag;
  80257. if ( position ) {
  80258. object.position.set( position[ 0 ], position[ 1 ], position[ 2 ] );
  80259. }
  80260. if ( rotation ) {
  80261. object.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ] );
  80262. }
  80263. if ( scale ) {
  80264. object.scale.set( scale[ 0 ], scale[ 1 ], scale[ 2 ] );
  80265. }
  80266. object.updateMatrix();
  80267. var tempGeometry = object.geometry.clone();
  80268. tempGeometry.applyMatrix4( object.matrix );
  80269. object.geometry = tempGeometry;
  80270. object.renderOrder = Infinity;
  80271. object.position.set( 0, 0, 0 );
  80272. object.rotation.set( 0, 0, 0 );
  80273. object.scale.set( 1, 1, 1 );
  80274. gizmo.add( object );
  80275. }
  80276. }
  80277. return gizmo;
  80278. };
  80279. // Reusable utility variables
  80280. var tempVector = new Vector3( 0, 0, 0 );
  80281. var tempEuler = new Euler();
  80282. var alignVector = new Vector3( 0, 1, 0 );
  80283. var zeroVector = new Vector3( 0, 0, 0 );
  80284. var lookAtMatrix = new Matrix4();
  80285. var tempQuaternion = new Quaternion();
  80286. var tempQuaternion2 = new Quaternion();
  80287. var identityQuaternion = new Quaternion();
  80288. var unitX = new Vector3( 1, 0, 0 );
  80289. var unitY = new Vector3( 0, 1, 0 );
  80290. var unitZ = new Vector3( 0, 0, 1 );
  80291. // Gizmo creation
  80292. this.gizmo = {};
  80293. this.picker = {};
  80294. this.helper = {};
  80295. this.add( this.gizmo[ "translate" ] = setupGizmo( gizmoTranslate ) );
  80296. this.add( this.gizmo[ "rotate" ] = setupGizmo( gizmoRotate ) );
  80297. this.add( this.gizmo[ "scale" ] = setupGizmo( gizmoScale ) );
  80298. this.add( this.picker[ "translate" ] = setupGizmo( pickerTranslate ) );
  80299. this.add( this.picker[ "rotate" ] = setupGizmo( pickerRotate ) );
  80300. this.add( this.picker[ "scale" ] = setupGizmo( pickerScale ) );
  80301. this.add( this.helper[ "translate" ] = setupGizmo( helperTranslate ) );
  80302. this.add( this.helper[ "rotate" ] = setupGizmo( helperRotate ) );
  80303. this.add( this.helper[ "scale" ] = setupGizmo( helperScale ) );
  80304. // Pickers should be hidden always
  80305. this.picker[ "translate" ].visible = false;
  80306. this.picker[ "rotate" ].visible = false;
  80307. this.picker[ "scale" ].visible = false;
  80308. // updateMatrixWorld will update transformations and appearance of individual handles
  80309. this.updateMatrixWorld = function () {
  80310. if(!this.parent.visible)return //add
  80311. var space = this.space;
  80312. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80313. var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion;
  80314. // Show only gizmos for current transform mode
  80315. this.gizmo[ "translate" ].visible = this.mode === "translate";
  80316. this.gizmo[ "rotate" ].visible = this.mode === "rotate";
  80317. this.gizmo[ "scale" ].visible = this.mode === "scale";
  80318. this.helper[ "translate" ].visible = this.mode === "translate";
  80319. this.helper[ "rotate" ].visible = this.mode === "rotate";
  80320. this.helper[ "scale" ].visible = this.mode === "scale";
  80321. var handles = [];
  80322. handles = handles.concat( this.picker[ this.mode ].children );
  80323. handles = handles.concat( this.gizmo[ this.mode ].children );
  80324. handles = handles.concat( this.helper[ this.mode ].children );
  80325. for ( var i = 0; i < handles.length; i ++ ) {
  80326. var handle = handles[ i ];
  80327. //add
  80328. if(this.hideAxis[this.mode] && this.hideAxis[this.mode].some(e=>handle.name.includes(e.toUpperCase()))){
  80329. viewer.updateVisible(handle, 'hidden', false);
  80330. continue
  80331. }
  80332. let visible = true;
  80333. // hide aligned to camera
  80334. handle.rotation.set( 0, 0, 0 );
  80335. handle.position.copy( this.worldPosition );
  80336. if(this.camera.type == "OrthographicCamera"){
  80337. var eyeDistance = 800 / this.camera.zoom;
  80338. }else {
  80339. var eyeDistance = this.worldPosition.distanceTo( this.cameraPosition );
  80340. }
  80341. handle.scale.set( 1, 1, 1 ).multiplyScalar( eyeDistance * this.size / 7 );
  80342. // TODO: simplify helpers and consider decoupling from gizmo
  80343. if ( handle.tag === 'helper' ) {
  80344. visible = false;
  80345. if ( handle.name === 'AXIS' ) {
  80346. handle.position.copy( this.worldPositionStart );
  80347. visible = !!this.axis;
  80348. if ( this.axis === 'X' ) {
  80349. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, 0 ) );
  80350. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80351. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80352. visible = false;
  80353. }
  80354. }
  80355. if ( this.axis === 'Y' ) {
  80356. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, Math.PI / 2 ) );
  80357. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80358. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80359. visible = false;
  80360. }
  80361. }
  80362. if ( this.axis === 'Z' ) {
  80363. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  80364. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80365. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80366. visible = false;
  80367. }
  80368. }
  80369. if ( this.axis === 'XYZE' ) {
  80370. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  80371. alignVector.copy( this.rotationAxis );
  80372. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( zeroVector, alignVector, unitY ) );
  80373. handle.quaternion.multiply( tempQuaternion );
  80374. visible = this.dragging;
  80375. }
  80376. if ( this.axis === 'E' ) {
  80377. visible = false;
  80378. }
  80379. } else if ( handle.name === 'START' ) {
  80380. handle.position.copy( this.worldPositionStart );
  80381. visible = this.dragging;
  80382. } else if ( handle.name === 'END' ) {
  80383. handle.position.copy( this.worldPosition );
  80384. visible = this.dragging;
  80385. } else if ( handle.name === 'DELTA' ) {
  80386. handle.position.copy( this.worldPositionStart );
  80387. handle.quaternion.copy( this.worldQuaternionStart );
  80388. tempVector.set( 1e-10, 1e-10, 1e-10 ).add( this.worldPositionStart ).sub( this.worldPosition ).multiplyScalar( - 1 );
  80389. tempVector.applyQuaternion( this.worldQuaternionStart.clone().invert() );
  80390. handle.scale.copy( tempVector );
  80391. visible = this.dragging;
  80392. } else {
  80393. handle.quaternion.copy( quaternion );
  80394. if ( this.dragging ) {
  80395. handle.position.copy( this.worldPositionStart );
  80396. } else {
  80397. handle.position.copy( this.worldPosition );
  80398. }
  80399. if ( this.axis ) {
  80400. visible = this.axis.search( handle.name ) !== - 1;
  80401. }
  80402. }
  80403. // If updating helper, skip rest of the loop
  80404. viewer.updateVisible(handle, 'hidden', !!visible);
  80405. continue;
  80406. }
  80407. // Align handles to current local or world rotation
  80408. handle.quaternion.copy( quaternion );
  80409. if ( this.mode === 'translate' || this.mode === 'scale' ) {
  80410. // Hide translate and scale axis facing the camera
  80411. var AXIS_HIDE_TRESHOLD = 0.99;
  80412. var PLANE_HIDE_TRESHOLD = 0.2;
  80413. var AXIS_FLIP_TRESHOLD = 0.0;
  80414. if(options.dontHideWhenFaceCamera){//xzw add
  80415. //正对镜头时不隐藏箭头
  80416. }else {
  80417. if ( handle.name === 'X' || handle.name === 'XYZX' ) {
  80418. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80419. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80420. visible = false;
  80421. }
  80422. }
  80423. if ( handle.name === 'Y' || handle.name === 'XYZY' ) {
  80424. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80425. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80426. visible = false;
  80427. }
  80428. }
  80429. if ( handle.name === 'Z' || handle.name === 'XYZZ' ) {
  80430. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80431. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80432. visible = false;
  80433. }
  80434. }
  80435. if ( handle.name === 'XY' ) {
  80436. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80437. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80438. visible = false;
  80439. }
  80440. }
  80441. if ( handle.name === 'YZ' ) {
  80442. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80443. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80444. visible = false;
  80445. }
  80446. }
  80447. if ( handle.name === 'XZ' ) {
  80448. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80449. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80450. visible = false;
  80451. }
  80452. }
  80453. }
  80454. // Flip translate and scale axis ocluded behind another axis
  80455. //xzw 改 去掉反向箭头
  80456. if ( handle.name.search( 'X' ) !== - 1 ) {
  80457. if ( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80458. /* if ( handle.tag === 'fwd' ) {
  80459. handle.visible = false;
  80460. } else {
  80461. handle.scale.x *= - 1;
  80462. }
  80463. } else if ( handle.tag === 'bwd' ) {
  80464. handle.visible = false;*/
  80465. handle.scale.x *= - 1;
  80466. }
  80467. }
  80468. if ( handle.name.search( 'Y' ) !== - 1 ) {
  80469. if ( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80470. /* if ( handle.tag === 'fwd' ) {
  80471. handle.visible = false;
  80472. } else {
  80473. handle.scale.y *= - 1;
  80474. }
  80475. } else if ( handle.tag === 'bwd' ) {
  80476. handle.visible = false;
  80477. */
  80478. handle.scale.y *= - 1;
  80479. }
  80480. }
  80481. if ( handle.name.search( 'Z' ) !== - 1 ) {
  80482. if ( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80483. /* if ( handle.tag === 'fwd' ) {
  80484. handle.visible = false;
  80485. } else {
  80486. handle.scale.z *= - 1;
  80487. }
  80488. } else if ( handle.tag === 'bwd' ) {
  80489. handle.visible = false; */
  80490. handle.scale.z *= - 1;
  80491. }
  80492. }
  80493. } else if ( this.mode === 'rotate' ) {
  80494. // Align handles to current local or world rotation
  80495. tempQuaternion2.copy( quaternion );
  80496. alignVector.copy( this.eye ).applyQuaternion( tempQuaternion.copy( quaternion ).invert() );
  80497. if ( handle.name.search( "E" ) !== - 1 ) {
  80498. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( this.eye, zeroVector, unitY ) );
  80499. }
  80500. if ( handle.name === 'X' ) {
  80501. tempQuaternion.setFromAxisAngle( unitX, Math.atan2( - alignVector.y, alignVector.z ) );
  80502. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80503. handle.quaternion.copy( tempQuaternion );
  80504. }
  80505. if ( handle.name === 'Y' ) {
  80506. tempQuaternion.setFromAxisAngle( unitY, Math.atan2( alignVector.x, alignVector.z ) );
  80507. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80508. handle.quaternion.copy( tempQuaternion );
  80509. }
  80510. if ( handle.name === 'Z' ) {
  80511. tempQuaternion.setFromAxisAngle( unitZ, Math.atan2( alignVector.y, alignVector.x ) );
  80512. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80513. handle.quaternion.copy( tempQuaternion );
  80514. }
  80515. }
  80516. // Hide disabled axes
  80517. visible = visible && ( handle.name.indexOf( "X" ) === - 1 || this.showX );
  80518. visible = visible && ( handle.name.indexOf( "Y" ) === - 1 || this.showY );
  80519. visible = visible && ( handle.name.indexOf( "Z" ) === - 1 || this.showZ );
  80520. visible = visible && ( handle.name.indexOf( "E" ) === - 1 || ( this.showX && this.showY && this.showZ ) );
  80521. viewer.updateVisible(handle, 'hidden', !!visible);
  80522. // highlight selected axis
  80523. handle.material._opacity = handle.material._opacity || handle.material.opacity;
  80524. handle.material._color = handle.material._color || handle.material.color.clone();
  80525. handle.material.color.copy( handle.material._color );
  80526. handle.material.opacity = handle.material._opacity;
  80527. if ( ! this.enabled ) {
  80528. handle.material.opacity *= 0.5;
  80529. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80530. } else if ( this.axis ) {
  80531. if ( handle.name === this.axis ) {
  80532. handle.material.opacity = 1.0;
  80533. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80534. } else if ( this.axis.split( '' ).some( function ( a ) {
  80535. return handle.name === a;
  80536. } ) ) {
  80537. handle.material.opacity = 1.0;
  80538. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80539. } else {
  80540. handle.material.opacity *= 0.25;
  80541. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80542. }
  80543. }
  80544. }
  80545. Object3D.prototype.updateMatrixWorld.call( this );
  80546. };
  80547. };
  80548. /* var TransformControlsLines = function (options) {
  80549. THREE.Object3D.call( this)
  80550. let label1 = new Label2D({ innerHTML:`<div>与相机水平距离</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80551. let label2 = new Label2D({ innerHTML:`<div>与相机高度差</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80552. let css = {'opacity': 0.7, 'color': '#07fceb', transform:'translate(-50%, -50%)'}
  80553. label1.elem.css(css);
  80554. label2.elem.css(css)
  80555. //for(let i=0;i<2;i++){
  80556. // let line = LineDraw.createLine([new THREE.THREE.Vector3, new THREE.THREE.Vector3],{color:'#07fceb', opacity:0.7 })
  80557. // this.add(line)
  80558. //}
  80559. this.updateTransform = function(object){
  80560. object = object || this.parent.object;
  80561. let A = player.position.clone(); //当前相机位置
  80562. let B = object.position //物体位置
  80563. let C = B.clone().setY(A.y); //物体在相机的高度的位置
  80564. let D = A.clone().setY(B.y); //相机在物体的高度的位置
  80565. //LineDraw.moveLine(this.children[0], [B, C]) // 垂直线
  80566. //LineDraw.moveLine(this.children[1], [D, B]) // 水平线
  80567. let dis1 = toPrecision(D.distanceTo(B),1)
  80568. let dis2 = C.y - B.y
  80569. label1.elem.text('与相机水平距离: '+dis1+'米')
  80570. label2.elem.text('在相机之'+ (dis2>0?'下' : '上') +' :'+ toPrecision(dis2 , 1) +'米')
  80571. label1.setPos(new THREE.THREE.Vector3().addVectors(D,B).multiplyScalar(0.5))
  80572. label2.setPos(new THREE.THREE.Vector3().addVectors(B,C).multiplyScalar(0.5))
  80573. }
  80574. this.setVisible = (v,reason)=>{
  80575. label1.setVisible(v, reason || 'unvisi')
  80576. label2.setVisible(v, reason || 'unvisi')
  80577. this.visible = label1.visible
  80578. if(this.visible){
  80579. this.updateTransform()
  80580. }
  80581. }
  80582. this.setVisible(false)
  80583. player.on("mode.changing",(currentMode, mode, pano, duration)=>{
  80584. if(mode != 'panorama'){
  80585. this.setVisible(false, 'isPanorama')
  80586. }else{
  80587. this.setVisible(true, 'isPanorama')
  80588. }
  80589. })
  80590. player.on("flying.started",( )=>{
  80591. this.setVisible(false, 'flying')
  80592. })
  80593. player.on("flying.ended",( )=>{
  80594. this.setVisible(true, 'flying')
  80595. })
  80596. }
  80597. */
  80598. var TransformControlsPlane = function (options) {
  80599. 'use strict';
  80600. Mesh.call( this,
  80601. new PlaneBufferGeometry( 100000, 100000, 2, 2 ),
  80602. new MeshBasicMaterial( { color: "#ff0000", visible: false, wireframe: false, side: DoubleSide, transparent: true, opacity: 0.2 } )
  80603. );
  80604. this.type = 'TransformControlsPlane';
  80605. var unitX = new Vector3( 1, 0, 0 );
  80606. var unitY = new Vector3( 0, 1, 0 );
  80607. var unitZ = new Vector3( 0, 0, 1 );
  80608. var tempVector = new Vector3();
  80609. var dirVector = new Vector3();
  80610. var alignVector = new Vector3();
  80611. var tempMatrix = new Matrix4();
  80612. var identityQuaternion = new Quaternion();
  80613. this.updateMatrixWorld = function () {
  80614. if(!this.visible)return//add
  80615. var space = this.space;
  80616. this.position.copy( this.worldPosition );
  80617. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80618. unitX.set( 1, 0, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80619. unitY.set( 0, 1, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80620. unitZ.set( 0, 0, 1 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80621. // Align the plane for current transform mode, axis and space.
  80622. alignVector.copy( unitY );
  80623. switch ( this.mode ) {
  80624. case 'translate':
  80625. case 'scale':
  80626. switch ( this.axis ) {
  80627. case 'X':
  80628. alignVector.copy( this.eye ).cross( unitX );
  80629. dirVector.copy( unitX ).cross( alignVector );
  80630. break;
  80631. case 'Y':
  80632. alignVector.copy( this.eye ).cross( unitY );
  80633. dirVector.copy( unitY ).cross( alignVector );
  80634. break;
  80635. case 'Z':
  80636. alignVector.copy( this.eye ).cross( unitZ );
  80637. dirVector.copy( unitZ ).cross( alignVector );
  80638. break;
  80639. case 'XY':
  80640. dirVector.copy( unitZ );
  80641. break;
  80642. case 'YZ':
  80643. dirVector.copy( unitX );
  80644. break;
  80645. case 'XZ':
  80646. alignVector.copy( unitZ );
  80647. dirVector.copy( unitY );
  80648. break;
  80649. case 'XYZ':
  80650. case 'E':
  80651. default: //xzw add for scale xyzz
  80652. dirVector.set( 0, 0, 0 );
  80653. break;
  80654. }
  80655. break;
  80656. case 'rotate':
  80657. default:
  80658. // special case for rotate
  80659. dirVector.set( 0, 0, 0 );
  80660. }
  80661. if ( dirVector.length() === 0 ) {
  80662. // If in rotate mode, make the plane parallel to camera
  80663. this.quaternion.copy( this.cameraQuaternion );
  80664. } else {
  80665. tempMatrix.lookAt( tempVector.set( 0, 0, 0 ), dirVector, alignVector );
  80666. this.quaternion.setFromRotationMatrix( tempMatrix );
  80667. }
  80668. Object3D.prototype.updateMatrixWorld.call( this );
  80669. };
  80670. };
  80671. TransformControls.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80672. constructor: TransformControls,
  80673. isTransformControls: true
  80674. } );
  80675. TransformControlsGizmo.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80676. constructor: TransformControlsGizmo,
  80677. isTransformControlsGizmo: true
  80678. } );
  80679. TransformControlsPlane.prototype = Object.assign( Object.create( Mesh.prototype ), {
  80680. constructor: TransformControlsPlane,
  80681. isTransformControlsPlane: true
  80682. } );
  80683. /*
  80684. 备注:
  80685. //这里虽然 使坐标轴在boundingBox中心
  80686. boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  80687. 但是旋转中心并不是这个坐标轴显示的位置,需要再执行 MergeEditor.maintainBoundXY()才能维持在这个中心
  80688. */
  80689. const texLoader$8 = new TextureLoader();
  80690. texLoader$8.crossOrigin = "anonymous";
  80691. const edgeStrengths = {
  80692. pointcloud: 4,
  80693. glb: 100
  80694. };
  80695. const viewportProps$1 = [{
  80696. left:0,
  80697. bottom:0,
  80698. width: 0.5,height:1,
  80699. name : 'top',
  80700. axis:["x","y"],
  80701. direction : new Vector3(0,0,-1), //镜头朝向
  80702. active: true,
  80703. //相机位置在z轴正向
  80704. limitBound: new Box3(new Vector3(-Infinity,-Infinity, 1),new Vector3(Infinity,Infinity,5000)), //在地面以上
  80705. margin:{x:50, y:150} ,
  80706. },
  80707. {
  80708. left:0.5,
  80709. bottom:0,
  80710. width: 0.5,height:1,
  80711. name : 'right',
  80712. axis:["y","z"],
  80713. direction : new Vector3(1,0,0),
  80714. active: true,
  80715. //相机位置在x轴负向 右下角屏
  80716. viewContainsPoints:[new Vector3(0,0,0)],
  80717. margin:{x:300, y:250} ,
  80718. } ];
  80719. let MergeEditor = {
  80720. bus:new EventDispatcher(),
  80721. SplitScreen : new SplitScreen(),
  80722. init(){
  80723. {
  80724. let ground = this.ground = new InfiniteGridHelper(1, 10000, new Color('#fff'), 10000, 0.2, 0.3);
  80725. viewer.scene.scene.add(ground);
  80726. //再加两条线否则在正侧边看不到
  80727. let line1 = LineDraw.createLine([new Vector3(-10000, 0, 0),new Vector3(10000, 0, 0) ], {color:'#666', dontAlwaysSeen:true});
  80728. let line2 = LineDraw.createLine([new Vector3(0, -10000, 0),new Vector3(0, 10000, 0) ], {mat:line1.material});
  80729. ground.renderOrder = Potree.config.renderOrders.model + 1;//line1.renderOrder + 1 //要比模型低,否则模型透明时效果不对
  80730. ground.add(line1);
  80731. ground.add(line2);
  80732. ground.material.polygonOffset = true; //多边形偏移(视觉上没有移动模型位置),防止闪烁
  80733. ground.material.polygonOffsetFactor = 100; //多边形偏移因子
  80734. ground.material.polygonOffsetUnits = 10; //多边形偏移单位
  80735. ground.material.depthWrite = false;
  80736. //ground.material.depthTest = false
  80737. line1.material.polygonOffset = true;
  80738. line1.material.polygonOffsetFactor = 130;
  80739. line1.material.polygonOffsetUnits = 10;
  80740. line1.material.depthWrite = false;
  80741. //见笔记:透明物体的材质设置
  80742. }
  80743. {
  80744. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80745. dontHideWhenFaceCamera: true,
  80746. });
  80747. //this.transformControls.space = 'local'//为了在当前方向上平移
  80748. this.transformControls.setSize(1.5);
  80749. viewer.scene.scene.add(this.transformControls);
  80750. this.transformControls._gizmo.hideAxis = {rotate:['e']};
  80751. this.transformControls.setRotateMethod(2);
  80752. //右屏
  80753. this.transformControls2 = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80754. dontHideWhenFaceCamera: true,
  80755. });
  80756. this.transformControls.setSize(1.5);
  80757. viewer.scene.scene.add(this.transformControls2);
  80758. viewer.setObjectLayers(this.transformControls2, 'layer2' );
  80759. let mouseDown = (e)=>{
  80760. viewer.outlinePass.edgeStrength = 0;//暂时消失线
  80761. };
  80762. let mouseUp = (e)=>{
  80763. this.updateEdgeStrength();
  80764. };
  80765. this.transformControls.addEventListener('mouseDown',mouseDown);
  80766. this.transformControls2.addEventListener('mouseDown',mouseDown);
  80767. this.transformControls.addEventListener('mouseUp',mouseUp);
  80768. this.transformControls2.addEventListener('mouseUp',mouseUp);
  80769. }
  80770. {
  80771. this.secondCompass = new Compass(null);
  80772. }
  80773. viewer.setControls(viewer.orbitControls);
  80774. //viewer.mainViewport.view.fixZWhenPan = true
  80775. viewer.orbitControls.constantlyForward = true;
  80776. viewer.addEventListener('global_single_click',(e)=>{
  80777. if(
  80778. this.noNeedSelection //如模型查看页
  80779. || viewer.scene.cameraAnimations.some(c=>c.onUpdate) //正在播放
  80780. || e.drag && e.drag.notPressMouse //在加测量线
  80781. || viewer.mainViewport.view.isFlying() //有其他校准
  80782. || this.split //分屏中
  80783. || e.clickElement //触发别的点击事件,如测量时click marker /* && e.clickElement != e.intersect.object */
  80784. ){
  80785. return
  80786. }
  80787. if(e.intersect){
  80788. let object = e.intersect.object || e.intersect.pointcloud;
  80789. let objects = this.getAllObjects();
  80790. if(objects.includes(object)){
  80791. this.selectModel(object);
  80792. }else {
  80793. //if(!viewer.inputHandler.selection[0]){//正在平移和旋转,不允许取消
  80794. this.selectModel(null);
  80795. //}
  80796. }
  80797. }else {
  80798. //if(!viewer.inputHandler.selection[0]){
  80799. this.selectModel(null);
  80800. //}
  80801. }
  80802. });
  80803. viewer.inputHandler.addEventListener('keydown', (e)=>{
  80804. if((e.event.key).toLowerCase() == "h" ){
  80805. this.fadeOutlineAuto = !this.fadeOutlineAuto;
  80806. this.showModelOutline(this.selected,!!this.selected);
  80807. }
  80808. });
  80809. viewer.ssaaRenderPass.enabled = false;
  80810. viewer.outlinePass.enabled = true;
  80811. //Potree.settings.intersectWhenHover = false
  80812. //viewer.updateVisible(viewer.reticule, 'force', false)
  80813. viewer.mainViewport.camera.near = 0.05; // too small will result in z-fighting
  80814. viewer.addEventListener('updateModelBound', (e)=>{
  80815. if(this.split){
  80816. this.SplitScreen.updateCameraOutOfModel(/* this.selected && [this.selected] */);
  80817. }
  80818. });
  80819. {//校准页面拖拽
  80820. //左右屏都可以拖拽模型,旋转只能左屏
  80821. let dragInfo;
  80822. let drag = (e)=>{
  80823. if(this.split && this.selected && this.transformState && (e.dragViewport.name == 'top' || this.transformState == 'translate') ){
  80824. if(e.type == 'global_mousedown' ){ //开始
  80825. //if((e.intersect.object || e.intersect.pointcloud) == this.selected){
  80826. if(e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected)){
  80827. dragInfo = {};
  80828. //if(this.selected.isPointcloud){
  80829. viewer.outlinePass.edgeStrength = 0;//暂时消失线
  80830. //}
  80831. }
  80832. }
  80833. if(e.type == 'global_drag' && dragInfo ){
  80834. if(this.transformState == 'translate'){
  80835. let moveVec = Potree.Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, e.dragViewport.camera );//最近一次移动向量
  80836. this.selected.position.add(moveVec);
  80837. this.selected.dispatchEvent("position_changed");
  80838. }else if(this.transformState == 'rotate'){
  80839. let vec = new Vector3().subVectors(e.intersect.orthoIntersect || e.intersect.location, this.selected.boundCenter).setZ(0);
  80840. if(dragInfo.lastVec == void 0){//global_mousedown
  80841. dragInfo.lastVec = vec;
  80842. return
  80843. }
  80844. let angle = math.getAngle(dragInfo.lastVec, vec, 'z');
  80845. dragInfo.lastVec = vec;
  80846. //this.selected.rotation.z += angle //局部
  80847. /* object.quaternion.copy( .setFromAxisAngle( new THREE.Vector3(0,0,1), angle ) );
  80848. object.quaternion.multiply( quaternionStart ).normalize(); */
  80849. let diffQua = new Quaternion().setFromAxisAngle( new Vector3(0,0,1), angle );
  80850. this.selected.quaternion.premultiply(diffQua); //世界
  80851. this.selected.dispatchEvent("rotation_changed");
  80852. }
  80853. return {stopContinue:true}
  80854. }
  80855. }
  80856. };
  80857. viewer.addEventListener('global_mousedown', drag);
  80858. viewer.addEventListener('global_drag', drag, 10);
  80859. viewer.addEventListener('global_mousemove', (e)=>{
  80860. if(this.split && this.transformState && !e.drag && (e.hoverViewport.name == 'top' || this.transformState == 'translate')){
  80861. /* if(this.lastHoverViewport != e.hoverViewport){
  80862. this.lastHoverViewport = e.hoverViewport
  80863. this.transformControls.view = e.hoverViewport.view
  80864. this.transformControls.camera = e.hoverViewport.camera
  80865. this.transformControls.hideAxis( this.transformState, e.hoverViewport.name == 'top' ? [z] : [x,y]);
  80866. } */
  80867. let mouseover = e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected);
  80868. //let mouseover = (e.intersect.object || e.intersect.pointcloud) == this.selected
  80869. if(mouseover){
  80870. if(this.transformState == 'translate'){
  80871. viewer.dispatchEvent({
  80872. type : "CursorChange", action : "add", name:"movePointcloud"
  80873. });
  80874. }else {
  80875. viewer.dispatchEvent({
  80876. type : "CursorChange", action : "add", name:"rotatePointcloud"
  80877. });
  80878. }
  80879. }else {
  80880. this.clearTranCursor();
  80881. }
  80882. }
  80883. });
  80884. viewer.addEventListener('global_drop', (e)=>{
  80885. dragInfo = null;
  80886. this.clearTranCursor();
  80887. this.updateEdgeStrength();
  80888. });
  80889. }
  80890. },
  80891. clearTranCursor(){
  80892. viewer.dispatchEvent({
  80893. type : "CursorChange", action : "remove", name:"movePointcloud"
  80894. });
  80895. viewer.dispatchEvent({
  80896. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  80897. });
  80898. },
  80899. enterSplit(){
  80900. this.split = true;
  80901. if(this.selected) this.SplitScreen.focusCenter = this.selected.boundCenter; //旋转中心。注意 boundCenter不能直接赋值,否则改变后focusCenter也要改
  80902. else this.SplitScreen.focusCenter = null;
  80903. this.SplitScreen.splitStart(viewportProps$1);
  80904. this.beforeSplit = {
  80905. pointDensity: Potree.settings.pointDensity,
  80906. };
  80907. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  80908. /* viewer.scene.pointclouds.forEach(e=>{
  80909. e.material.activeAttributeName = "color"
  80910. e.material.useFilterByNormal = true
  80911. }) */
  80912. //取消outline,改点云颜色为和outline一样的颜色
  80913. /* if(this.selected && this.selected.isPointcloud){
  80914. this.showModelOutline(this.selected, false)
  80915. this.selected.material.activeAttributeName = "color"
  80916. this.selected.material.color = viewer.outlinePass.visibleEdgeColor
  80917. } */
  80918. viewer.setControls(viewer.fpControls);
  80919. viewer.viewports.find(e=>e.name == 'right').rotateSide = true;
  80920. viewer.viewports.find(e=>e.name == 'top').alignment = true;
  80921. viewer.viewports[1].layersAdd('layer2');
  80922. viewer.viewports[0].layersAdd('layer1');
  80923. viewer.setObjectLayers(this.transformControls, 'layer1' );
  80924. this.transformControls.view = viewer.viewports[0].view;
  80925. this.transformControls.camera = viewer.viewports[0].camera;
  80926. this.transformControls._gizmo.hideAxis = {translate:['z'], rotate:['x','y','z'] };
  80927. this.transformControls2.view = viewer.viewports[1].view;
  80928. this.transformControls2.camera = viewer.viewports[1].camera;
  80929. this.transformControls2._gizmo.hideAxis = {translate:['x','y'], rotate:['x','y','z'] };
  80930. this.secondCompass.changeViewport(viewer.viewports[0]);
  80931. this.secondCompass.setDomPos();
  80932. this.secondCompass.setDisplay(true);
  80933. viewer.compass.changeViewport(viewer.viewports[1]);
  80934. viewer.compass.setDomPos();
  80935. },
  80936. leaveSplit(){
  80937. this.split = false;
  80938. this.SplitScreen.unSplit();
  80939. viewer.setControls(viewer.orbitControls);
  80940. Potree.settings.pointDensity = this.beforeSplit.pointDensity;
  80941. /* if(this.selected && this.selected.isPointcloud){
  80942. this.showModelOutline(this.selected, true)
  80943. this.selected.material.activeAttributeName = "rgba"
  80944. } */
  80945. this.transformControls.camera = viewer.viewports[0].camera;
  80946. this.transformControls.view = viewer.viewports[0].view;
  80947. this.transformControls._gizmo.hideAxis = {rotate:['e']};
  80948. viewer.setObjectLayers(this.transformControls, 'sceneObjects' ); //恢复
  80949. viewer.compass.changeViewport(viewer.viewports[0]); //恢复
  80950. viewer.compass.setDomPos();
  80951. this.secondCompass.setDisplay(false);
  80952. },
  80953. rotateSideCamera(angle){
  80954. this.SplitScreen.rotateSideCamera(viewer.viewports.find(e=>e.name == 'right'), angle);
  80955. },
  80956. setTransformState(state){//校准时
  80957. this.transformState = state;
  80958. this.clearTranCursor();
  80959. },
  80960. //---------------------------
  80961. /* writeToHistory(content){
  80962. if(!this.prepareRecord)return;
  80963. this.prepareRecord = false
  80964. this.history.push(content)
  80965. }, */
  80966. //---------------------------
  80967. getAllObjects(){
  80968. return viewer.objs.children.concat(viewer.scene.pointclouds)
  80969. },
  80970. getModel(id){
  80971. let models = this.getAllObjects();
  80972. return models.find(e=>e.dataset_id == id)
  80973. },
  80974. removeModel(model){
  80975. if(this.selected == model) this.selectModel(null);
  80976. let dispose = (e)=>{
  80977. e.geometry && e.geometry.dispose();
  80978. e.material && e.material.dispose();
  80979. };
  80980. if(model.isPointcloud){
  80981. dispose(model);
  80982. viewer.scene.removePointCloud(model);
  80983. }else {
  80984. model.traverse(e=>{
  80985. dispose(e);
  80986. });
  80987. viewer.objs.remove(model);
  80988. }
  80989. },
  80990. selectModel(model, state=true, fitBound, by2d){
  80991. if(!model) {
  80992. model = this.selected;
  80993. state = false;
  80994. }
  80995. if(state){
  80996. if(this.selected){
  80997. if(this.selected == model) return
  80998. else {
  80999. let transToolAttached = !!this.transformControls.object;
  81000. this.selectModel(this.selected, false, fitBound, by2d);
  81001. transToolAttached && this.transformControls.attach(model);
  81002. }
  81003. }
  81004. this.selected = model;
  81005. MergeEditor.focusOn(model, 500, !!fitBound); //通过在场景里点击模型的话,不focus
  81006. this.showModelOutline(model);
  81007. this.updateEdgeStrength();
  81008. //console.log('selectModel', model)
  81009. }else {
  81010. if(this.selected != model)return //model本来就没选中,不需要处理(防止2d先选中新的再取消旧的)
  81011. this.showModelOutline(model, false);
  81012. this.selected = null;
  81013. this.transformControls.detach(); //viewer.transformObject(null);
  81014. //console.log('selectModel', null)
  81015. }
  81016. if(!by2d && model){
  81017. model.dispatchEvent({type:'changeSelect', selected : state});
  81018. }
  81019. },
  81020. showModelOutline(model, state){
  81021. if(this.fadeOutlineAuto){
  81022. if(state === false){
  81023. viewer.outlinePass.selectedObjects = [];
  81024. clearTimeout(this.timer);
  81025. return
  81026. }
  81027. viewer.outlinePass.selectedObjects = [model];
  81028. if(this.timer){
  81029. clearTimeout(this.timer);
  81030. }
  81031. this.timer = setTimeout(()=>{
  81032. viewer.outlinePass.selectedObjects = [];
  81033. }, 1000);
  81034. }else {
  81035. if(state === false){
  81036. viewer.outlinePass.selectedObjects = [];
  81037. }else {
  81038. viewer.outlinePass.selectedObjects = [model];
  81039. }
  81040. }
  81041. },
  81042. updateEdgeStrength(){
  81043. if(!this.selected)return
  81044. if(this.selected.isPointcloud){
  81045. viewer.outlinePass.edgeStrength = edgeStrengths.pointcloud;// / this.selected.material.opacity
  81046. }else {
  81047. viewer.outlinePass.edgeStrength = edgeStrengths.glb;
  81048. }
  81049. },
  81050. focusOn(objects, duration = 400, fitBound=true, dontLookUp){
  81051. if(!(objects instanceof Array)){
  81052. objects = [objects];
  81053. }
  81054. let boundingBox = new Box3;
  81055. objects.forEach(object=>{
  81056. boundingBox.union(object.boundingBox.clone().applyMatrix4(object.matrixWorld));
  81057. });
  81058. if(fitBound){
  81059. viewer.focusOnObject({boundingBox}, 'boundingBox', duration, {dontLookUp, dontChangeCamDir:true});
  81060. }else {
  81061. /*
  81062. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new THREE.Vector3)
  81063. position && viewer.focusOnObject({position}, 'point', duration, {dontChangePos: true})
  81064. */
  81065. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new Vector3);
  81066. if(!position)return
  81067. /* let targetOld = viewer.mainViewport.view.getPivot()
  81068. let projected1 = targetOld.clone().project(viewer.mainViewport.camera);
  81069. let projected2 = position.clone().project(viewer.mainViewport.camera); //使用其z
  81070. let targetNew = projected1.clone().setZ(projected2.z).unproject(viewer.mainViewport.camera);
  81071. viewer.mainViewport.view.lookAt(targetNew) */
  81072. viewer.mainViewport.view.radius = viewer.mainViewport.camera.position.distanceTo(position);
  81073. //为了不改画面,不调节方向了,只能调调radius,一定程度将target靠近model
  81074. }
  81075. },
  81076. moveBoundCenterTo(model,pos){ //使boundCenter在所要的位置
  81077. let diff = new Vector3().subVectors(pos, model.boundCenter);
  81078. model.position.add(diff);
  81079. },
  81080. getBoundCenter(model){
  81081. if(!model.boundCenter) model.boundCenter = new Vector3;
  81082. model.boundingBox.getCenter(model.boundCenter).applyMatrix4(model.matrixWorld);
  81083. },
  81084. setModelBtmHeight(model, z ){
  81085. //无论模型怎么缩放、旋转,都使最低点为z
  81086. if(z == void 0) z = model.btmHeight; //维持离地高度
  81087. else model.btmHeight = z;
  81088. model.updateMatrixWorld();
  81089. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  81090. let size = boundingBox2.getSize(new Vector3);
  81091. let center = boundingBox2.getCenter(new Vector3);
  81092. let hopeZ = z + size.z / 2;
  81093. //model.position.z = z + size.z / 2 - center.z
  81094. model.position.z += (hopeZ - center.z);
  81095. },
  81096. computeBtmHeight(model){ //位移之后重新计算btmHeight
  81097. model.updateMatrixWorld();
  81098. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  81099. let size = boundingBox2.getSize(new Vector3);
  81100. let center = boundingBox2.getCenter(new Vector3);
  81101. model.btmHeight = center.z - size.z / 2;
  81102. },
  81103. maintainBoundXY(model){ //在旋转和缩放后,立即执行这个函数,使boundCenter保持原位
  81104. model.updateMatrixWorld();
  81105. let center1 = model.boundCenter.clone();//还未更新的
  81106. this.getBoundCenter(model);//更新
  81107. let center2 = model.boundCenter.clone();
  81108. let diff = new Vector2$1().subVectors(center1,center2);
  81109. model.position.x += diff.x;
  81110. model.position.y += diff.y;
  81111. model.boundCenter.copy(center1);
  81112. },
  81113. maintainBoundCenter(model){
  81114. model.updateMatrixWorld();
  81115. let center1 = model.boundCenter.clone();//还未更新的
  81116. this.getBoundCenter(model);//更新
  81117. let center2 = model.boundCenter.clone();
  81118. let diff = new Vector3().subVectors(center1,center2);
  81119. model.position.add(diff);
  81120. model.boundCenter.copy(center1);
  81121. },
  81122. modelTransformCallback(model){
  81123. model.updateMatrixWorld();
  81124. if(model.matrixWorld.equals(model.lastMatrixWorld))return
  81125. viewer.scene.measurements.forEach(measure=>{
  81126. let changed;
  81127. measure.points_datasets.forEach((dataset_id,i)=>{
  81128. if(dataset_id == model.dataset_id){
  81129. changed = true;
  81130. measure.points[i] = Potree.Utils.datasetPosTransform({fromDataset:true,datasetId:dataset_id, position:measure.dataset_points[i].clone()});
  81131. measure.updateMarker(measure.markers[i], measure.points[i]);
  81132. }
  81133. });
  81134. if(changed){//仿transformByPointcloud
  81135. measure.getPoint2dInfo(measure.points);
  81136. measure.update();
  81137. measure.setSelected(false);//隐藏edgelabel
  81138. }
  81139. });
  81140. model.lastMatrixWorld = model.matrixWorld.clone();
  81141. }
  81142. };
  81143. /*
  81144. note:
  81145. 要注意getHoveredElements只在getIntersect时才使interactables包含加载的model, 也就是model上不能有使之成为interactables的事件,否则在鼠标hover到模型上开始转动的一瞬间很卡。
  81146. */
  81147. const texLoader$9 = new TextureLoader();
  81148. const circleGeo = new CircleGeometry(1.45,100);
  81149. const sphereGeo = new SphereBufferGeometry(0.018,10,10);
  81150. const magDistance_ = 1;//相机离目标位置的距离的分界线,当离得远时要缩小fov以使看到的视野固定(望远镜效果)
  81151. /* const radius_ = 0.2; //当相机离目标位置的距离>magDistance_时,希望看到的视野的半径
  81152. const maxFov = THREE.Math.radToDeg(Math.atan(radius_ / magDistance_ )) * 2//提前计算出当相机离目标位置的距离<magDistance_时的fov,均使用=magDistance_时的fov。只要保证该fov大于主相机的fov就会有放大效果
  81153. */
  81154. let w$2 = 200/1.43;
  81155. let maxPX = 1366*1024; //ipad pro. 大于这个分辨率的就直接用devicePixelRatio, 如macbook也是
  81156. 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); //触屏或高分辨率的可能要放大些。但在手机上不能太大
  81157. //console.log('width2dPX', width2dPX)
  81158. class Magnifier extends Object3D {//放大镜or望远镜
  81159. constructor (viewer) {
  81160. super();
  81161. this.width = this.height = width2dPX/* * window.devicePixelRatio */;
  81162. this.camera = new PerspectiveCamera(50, 1, 0.01, 10000); //fov aspect near far
  81163. this.camera.up = new Vector3(0,0,1);
  81164. this.viewport = new Viewport( null, this.camera, {
  81165. left:0, bottom:0, width:1, height: 1, name:'magnifier' , cameraLayers:['magnifierContent'],
  81166. pixelRatio:1
  81167. });
  81168. this.viewport.setResolution(this.width, this.height,0,0);
  81169. {
  81170. let density;
  81171. let sizeType;
  81172. let colorType;
  81173. let opacityBefore = new Map();
  81174. this.viewport.beforeRender = ()=>{
  81175. viewer.scene.pointclouds.forEach(e=>{//因为更改pointDensity时会自动变opacity,所以这项最先获取
  81176. opacityBefore.set(e,e.temp.pointOpacity);
  81177. });
  81178. //使放大镜里的pointDensity是'magnifier' 最高质量。
  81179. density = Potree.settings.pointDensity;
  81180. Potree.settings.pointDensity = 'magnifier';
  81181. viewer.scene.pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  81182. sizeType = e.material.pointSizeType;
  81183. e.material.pointSizeType = Potree.config.material.pointSizeType;
  81184. //材质
  81185. colorType = e.material.activeAttributeName;
  81186. e.material.activeAttributeName = 'rgba';
  81187. e.changePointOpacity(1);
  81188. });
  81189. };
  81190. this.viewport.afterRender = ()=>{
  81191. Potree.settings.pointDensity = density;
  81192. viewer.scene.pointclouds.forEach(e=>{
  81193. e.material.pointSizeType = sizeType;
  81194. e.material.activeAttributeName = colorType;
  81195. e.changePointOpacity(opacityBefore.get(e));
  81196. });
  81197. };
  81198. }
  81199. this.renderTarget = new WebGLRenderTarget(this.width,this.height, {
  81200. minFilter: LinearFilter, magFilter: LinearFilter,
  81201. format: RGBAFormat ,
  81202. /* type: THREE.FloatType,
  81203. minFilter: THREE.NearestFilter,
  81204. magFilter: THREE.NearestFilter,
  81205. */
  81206. } );
  81207. this.rtEDL = new WebGLRenderTarget(this.width, this.height, { //好像没用到? 因为这里不绘制测量线
  81208. minFilter: NearestFilter,
  81209. magFilter: NearestFilter,
  81210. format: RGBAFormat,
  81211. type: FloatType,
  81212. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  81213. });
  81214. this.mesh = new Mesh(circleGeo, new MeshBasicMaterial({
  81215. side: DoubleSide ,
  81216. map: this.renderTarget.texture ,
  81217. transparent:true,
  81218. depthTest: !1,
  81219. //depthWrite: !1,
  81220. }));
  81221. this.overlayMesh = new Mesh(circleGeo, new MeshBasicMaterial({
  81222. side: DoubleSide ,
  81223. map:texLoader$9.load(Potree.resourcePath+'/textures/crosshair.png') ,
  81224. transparent:true,
  81225. depthTest: !1,
  81226. //depthWrite: !1,
  81227. }));
  81228. this.targetPoint = new Object3D;
  81229. this.targetPoint.add(new Mesh(sphereGeo, new MeshBasicMaterial({
  81230. color:"#ff0000",
  81231. transparent:true,
  81232. opacity:0.5,
  81233. })));
  81234. this.targetPoint.add(new Mesh(sphereGeo, new MeshBasicMaterial({
  81235. color:"#ff0000",
  81236. transparent:true,
  81237. opacity:0.2,
  81238. depthTest:false //被遮挡层
  81239. })));
  81240. this.targetPoint.name = 'magnifierPointTarget';
  81241. viewer.scene.scene.add(this.targetPoint);
  81242. viewer.setObjectLayers(this.targetPoint, 'magnifierContent' );
  81243. this.add(this.mesh);
  81244. this.add(this.overlayMesh);
  81245. this.position.set(-1000,-1000,-100000);//令它看不见
  81246. this.mesh.renderOrder = 10;
  81247. this.overlayMesh.renderOrder = 11;
  81248. this.aimPos;
  81249. viewer.setObjectLayers(this, 'magnifier' );
  81250. //viewer.inputHandler.addInputListener(this)
  81251. viewer.addEventListener('camera_changed',(e)=>{ // 平移、滚轮时更新
  81252. if(e.viewport == viewer.mainViewport) this.update(); //不过intersectPoint没更新
  81253. });
  81254. this.mesh.layers.set(Potree.config.renderLayers.magnifier);
  81255. this.overlayMesh.layers.set(Potree.config.renderLayers.magnifier);
  81256. //this.layers.set(Potree.config.renderLayers.magnifier);//这句在外层写没用
  81257. this.dontRender = false;
  81258. viewer.addEventListener('global_drag', (e)=>{//拖拽时不渲染。主要是右键平移时渲染延迟了,会闪烁。
  81259. this.dontRender = true;
  81260. });
  81261. viewer.addEventListener('global_drop', (e)=>{
  81262. this.dontRender = false;
  81263. });
  81264. viewer.addEventListener('global_mouseup', (e)=>{//测量时拖拽场景再mouseup
  81265. this.dontRender = false;
  81266. });
  81267. var updateVisi = (e)=>{
  81268. if(e.hoverViewport == viewer.mainViewport){
  81269. viewer.updateVisible(this,"atViewport", true);
  81270. this.update(e.intersect && e.intersect.location);
  81271. }else {
  81272. viewer.updateVisible(this,"atViewport", false); //小地图不显示
  81273. }
  81274. };
  81275. viewer.addEventListener('global_mousemove', updateVisi);
  81276. viewer.addEventListener('global_touchstart', updateVisi);
  81277. /* viewer.addEventListener("beginSplitView",()=>{
  81278. this.updateVisible("splitView", false)
  81279. })
  81280. viewer.addEventListener("finishSplitView",()=>{
  81281. this.updateVisible("splitView", true)
  81282. }) */
  81283. this.addEventListener("setEnable",(e)=>{
  81284. viewer.updateVisible(this, "enable", e.value); //界面开关
  81285. /* if(Potree.settings.displayMode == 'showPanos') && e.value){
  81286. Potree.settings.pointDensity = 'magnifier'
  81287. }else if() */
  81288. });
  81289. if(Potree.settings.isOfficial){
  81290. viewer.updateVisible(this, "enable", false);
  81291. }else {
  81292. viewer.updateVisible(this, "measure", false);
  81293. viewer.addEventListener("measureMovePoint",()=>{//测量开始
  81294. viewer.updateVisible(this, "measure", true);
  81295. });
  81296. viewer.addEventListener("endMeasureMove",()=>{
  81297. viewer.updateVisible(this, "measure", false);
  81298. });
  81299. }
  81300. viewer.scene.view.addEventListener('flyingDone',()=>{
  81301. if(!this.visible)return
  81302. let pickWindowSize = 100;
  81303. let intersect = viewer.inputHandler.getIntersect(viewer.mainViewport, viewer.mainViewport.camera, true, pickWindowSize );
  81304. this.update(intersect && intersect.location);
  81305. });
  81306. }
  81307. //注意:在鼠标没有移动的时候,无法获取到最新的intersect, 放大镜内的内容可能是错误的。全景模式下更奇怪,原因未知
  81308. update(aimPos){//相机靠近 navvis的做法
  81309. var dontRender = this.dontRender || !(aimPos instanceof Vector3) || Potree.settings.displayMode == 'showPanos' && viewer.images360.flying;
  81310. aimPos = aimPos instanceof Vector3 ? aimPos : this.aimPos;
  81311. if(!aimPos || !this.visible)return
  81312. var playerCamera = viewer.scene.getActiveCamera();
  81313. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  81314. var dis = playerPos.distanceTo(aimPos);
  81315. var dirToCamera = new Vector3().subVectors(playerPos, aimPos ).normalize();
  81316. //相机位置
  81317. var finalDisToAim = dis>magDistance_ ? magDistance_ : dis / 2;
  81318. this.camera.position.copy(aimPos).add(dirToCamera.multiplyScalar(finalDisToAim));
  81319. this.camera.lookAt(aimPos);
  81320. this.camera.fov = playerCamera.fov / 2;
  81321. this.camera.updateProjectionMatrix();
  81322. //自身位置
  81323. //let pos2d = viewer.inputHandler.pointer.clone(); //跟随鼠标
  81324. let pos2d = Potree.Utils.getPos2d(aimPos, playerCamera, viewer.renderArea, viewer.mainViewport).vector; //更新目标点的实时二维位置
  81325. let margin = 0.4, maxY = 0.4;
  81326. let screenPos = pos2d.clone().setY(pos2d.y + (pos2d.y>maxY ? -margin : margin ));
  81327. let newPos = new Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  81328. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  81329. let s = dis>magDistance_ ? 1 : dis / magDistance_ ;
  81330. this.position.copy(playerPos.clone().add(dir));
  81331. this.quaternion.copy(playerCamera.quaternion);
  81332. this.targetPoint.position.copy(aimPos);
  81333. this.targetPoint.scale.set(s,s,s);
  81334. this.aimPos = aimPos;
  81335. var scale = math.getScaleForConstantSize({//
  81336. width2d : width2dPX,
  81337. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new Vector3()),
  81338. resolution: viewer.mainViewport.resolution2
  81339. });
  81340. this.scale.set(scale, scale, scale);
  81341. if(!dontRender){
  81342. this.waitRender = true;
  81343. }
  81344. }
  81345. /* update(aimPos){ //仅改fov的版本
  81346. aimPos = aimPos instanceof THREE.Vector3 ? aimPos : this.aimPos
  81347. if(!aimPos || !this.visible)return
  81348. //相机位置
  81349. var playerCamera = viewer.scene.getActiveCamera()
  81350. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  81351. var dis = playerPos.distanceTo(aimPos);
  81352. if(dis<magDistance_){
  81353. this.camera.fov = maxFov
  81354. }else{
  81355. this.camera.fov = THREE.Math.radToDeg(Math.atan(radius_ / dis )) * 2 //radius_是能看到的范围半径。当dis大于magDistance_时就放大,否则维持fov为maxFov
  81356. }
  81357. this.camera.updateProjectionMatrix()
  81358. this.camera.position.copy(playerPos)
  81359. this.camera.lookAt(aimPos)
  81360. this.quaternion.copy(playerCamera.quaternion);
  81361. let pointer = viewer.inputHandler.pointer.clone();
  81362. let margin = 0.4, maxY = 0.4
  81363. let screenPos = pointer.clone().setY(pointer.y + (pointer.y>maxY ? -margin : margin ))
  81364. let newPos = new THREE.Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  81365. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  81366. this.position.copy(playerPos.clone().add(dir))
  81367. this.aimPos = aimPos
  81368. this.targetPoint.position.copy(aimPos);
  81369. var scale = math.getScaleForConstantSize({//
  81370. width2d : width2dPX,
  81371. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new THREE.Vector3()),
  81372. resolution: viewer.mainViewport.resolution2
  81373. })
  81374. this.scale.set(scale, scale, scale);
  81375. if(!this.dontRender){
  81376. this.waitRender = true
  81377. }
  81378. }//位置需要计算,不仅仅是点云,所以需要深度图
  81379. */
  81380. render(){
  81381. if(!this.waitRender)return
  81382. //this.visible = false;//防止放大镜里有自己
  81383. viewer.render({
  81384. target : this.renderTarget,
  81385. viewports : [this.viewport],
  81386. camera : this.camera,
  81387. magnifier : true,
  81388. rtEDL: this.rtEDL
  81389. /* width :this.renderTarget.width,
  81390. height: this.renderTarget.height, */
  81391. });
  81392. //this.visible = true;
  81393. this.waitRender = false;
  81394. }
  81395. }
  81396. let texLoader$a = new TextureLoader();
  81397. let defaultOpacity = 0.7;
  81398. //鼠标指示小圆片
  81399. class Reticule extends Mesh{
  81400. constructor(viewer){
  81401. var defaultTex = texLoader$a.load(Potree.resourcePath+'/textures/whiteCircle.png'/* reticule-256x256.png' */);
  81402. super(new PlaneBufferGeometry(0.11,0.11,1,1),new MeshBasicMaterial({
  81403. side: DoubleSide ,
  81404. map: defaultTex,
  81405. transparent:true,
  81406. depthTest: !1,
  81407. opacity: defaultOpacity,
  81408. //depthWrite: !1,
  81409. }));
  81410. this.name = 'reticule';
  81411. this.defaultTex = defaultTex;
  81412. this.crosshairTex = texLoader$a.load(Potree.resourcePath+'/textures/reticule_cross_hair.png');
  81413. this.forbitTex = texLoader$a.load(Potree.resourcePath+'/textures/pic-forbid.png');
  81414. //this.layers.set(0/* RenderLayers.RETICULE */);
  81415. this.renderOrder = 100;
  81416. this.layers.set(Potree.config.renderLayers.marker);
  81417. this.direction = new Vector3;
  81418. this.mouseLastMoveTime = Date.now();
  81419. this.hoverViewport;
  81420. this.matrixMap = new Map;
  81421. this.matrixAutoUpdate = false;
  81422. this.hide(0);
  81423. //viewer.inputHandler.addInputListener(this);
  81424. Potree.settings.intersectWhenHover && viewer.addEventListener('global_mousemove',this.move.bind(this));
  81425. //viewer.addEventListener('global_click',this.move.bind(this))
  81426. viewer.addEventListener('global_mousedown',this.move.bind(this));//主要针对触屏
  81427. this.state = {};
  81428. let startCrossStyle = ()=>{
  81429. this.state.cross = true;
  81430. this.judgeTex();
  81431. };
  81432. let endCrossStyle = ()=>{
  81433. this.state.cross = false;
  81434. this.judgeTex();
  81435. };
  81436. viewer.addEventListener('measureMovePoint',startCrossStyle);
  81437. viewer.addEventListener('endMeasureMove',endCrossStyle);
  81438. viewer.addEventListener('start_inserting_tag',startCrossStyle);
  81439. viewer.addEventListener('endTagMove',endCrossStyle);
  81440. viewer.addEventListener('reticule_forbit',(e)=>{
  81441. if(this.state.forbit != e.v){
  81442. console.log('change forbit ',e.v);
  81443. }
  81444. this.state.forbit = e.v;
  81445. this.judgeTex();
  81446. });
  81447. viewer.setObjectLayers(this, 'sceneObjects' );
  81448. }
  81449. judgeTex(){
  81450. if(this.state.forbit){
  81451. this.material.map = this.forbitTex;
  81452. }else if(this.state.cross){
  81453. this.material.map = this.crosshairTex;
  81454. }else {
  81455. this.material.map = this.defaultTex;
  81456. }
  81457. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  81458. }
  81459. move(e){
  81460. if(e.type == "global_mousemove" && (e.isTouch || e.buttons != Buttons.NONE) && this.state != 'crosshair'){
  81461. return//按下时不更新,除非拖拽测量
  81462. }
  81463. this.mouseLastMoveTime = Date.now();
  81464. this.updatePosition(e.intersect, e.hoverViewport);
  81465. }
  81466. hide(duration = 500){
  81467. if(this.hidden)return
  81468. this.hidden = !0;
  81469. transitions.start(lerp.property(this.material , "opacity", 0), duration);
  81470. this.dispatchEvent({type:'update', visible:false});
  81471. setTimeout(()=>{
  81472. this.dispatchEvent({type:'update', visible:false});
  81473. },duration);
  81474. }
  81475. show(duration = 300){
  81476. if(!viewer.getObjVisiByReason(this, 'force'))return
  81477. //console.log("show Reticule")
  81478. this.hidden = !1;
  81479. if(this.material.opacity <= 0){
  81480. transitions.start(lerp.property(this.material, "opacity", defaultOpacity), duration);
  81481. this.dispatchEvent({type:'update', visible:true});
  81482. setTimeout(()=>{
  81483. this.dispatchEvent({type:'update', visible:false});
  81484. },duration);
  81485. }
  81486. }
  81487. //鼠标静止一段时间它就会消失
  81488. updateVisible(){
  81489. Date.now() - this.mouseLastMoveTime > 1500 && !this.hidden && this.hide();
  81490. }
  81491. updateScale(viewport){
  81492. let s, camera = viewport.camera;
  81493. if(camera.type == "OrthographicCamera"){
  81494. var sizeInfo = this.state.cross ? {width2d:500} : {minSize : 100, maxSize : 400, nearBound : 100 , farBound : 700};
  81495. s = math.getScaleForConstantSize($.extend( sizeInfo ,
  81496. {position:this.position, camera, resolution:viewport.resolution/* 2 */} ));
  81497. }else {
  81498. let n = camera.position.distanceTo(this.position);
  81499. s = 1 + .1 * n;
  81500. n < 1 && (s -= 1 - n);
  81501. }
  81502. this.scale.set(s, s, s);
  81503. }
  81504. updateAtViewports(viewport){//当多个viewports时更新。更新大小等
  81505. if(viewport.name == 'magnifier' )return
  81506. if(this.hoverViewport && this.hoverViewport.name == 'mapViewport' && viewport != this.hoverViewport){
  81507. //若是在地图上更新,在其他viewport要隐藏。因为在地图上无法得知高度。
  81508. viewer.updateVisible(this, 'hoverMap', false);
  81509. return;
  81510. }
  81511. viewer.updateVisible(this, 'hoverMap', true);
  81512. var matrix = this.matrixMap.get(viewport);
  81513. if(!matrix){
  81514. this.updateScale(viewport);
  81515. this.updateMatrix();
  81516. //this.updateMatrixWorld()
  81517. this.matrixMap.set(viewport, this.matrix.clone());
  81518. }else {
  81519. this.matrix.copy(matrix);
  81520. //this.updateMatrixWorld()
  81521. }
  81522. }
  81523. updatePosition(intersect, viewport ){ //在地图(当地图融合到viewer时)和场景里都显示且完全相同(大小可能不同)
  81524. if (viewer.getObjVisiByReason(this, 'force')) {//没有被强制隐藏,如进入某个页面后强制不显示
  81525. if (!intersect /* || !intersect.point.normal */){
  81526. return //this.hide();
  81527. }
  81528. var atMap = !intersect.location;
  81529. let location = intersect.location || intersect.orthoIntersect.clone();
  81530. let normal;
  81531. //地图上要瞬间变化 , 因为要使needRender为true很麻烦
  81532. this.show(atMap ? 0 : 300);
  81533. if(atMap){
  81534. normal = new Vector3(0,0,1);//地图无normal
  81535. location.setZ(0);//低于相机高度即可
  81536. this.direction = normal.clone();
  81537. }else {
  81538. /* if(intersect.point){
  81539. if(intersect.pointcloud){
  81540. normal = new THREE.Vector3().fromArray(intersect.point.normal ).applyMatrix4( intersect.pointcloud.rotateMatrix );
  81541. }else{//mesh
  81542. normal = new THREE.Vector3().copy(intersect.point.normal).applyQuaternion(intersect.object.quaternion)
  81543. }
  81544. }else{
  81545. normal = intersect.normal //when showPanos
  81546. } */
  81547. normal = intersect.normal;
  81548. if(normal){
  81549. let ratio = /* Potree.settings.useDepthTex ? 1 : */ 0.2;
  81550. this.direction = this.direction.multiplyScalar(1-ratio);
  81551. this.direction.add(normal.clone().multiplyScalar(ratio));
  81552. }
  81553. //this.direction = normal.clone() //改为瞬间变化,否则刚hover上某个点时看起来不太对
  81554. }
  81555. this.position.copy(location);/* .add(normal.clone().multiplyScalar(.01)); */
  81556. this.updateMatrix(); //lookAt之前要保证得到matrix
  81557. this.lookAt(this.position.clone().add(this.direction));
  81558. this.hoverViewport = viewport; //记录下最近一次hover过的viewport
  81559. this.updateScale(viewport);
  81560. {//存储matrix,节省计算
  81561. this.updateMatrix();
  81562. //this.updateMatrixWorld()
  81563. this.matrixMap.clear();//重新计算
  81564. this.matrixMap.set(viewport, this.matrix.clone());
  81565. //别处会updateMatrixWorld
  81566. }
  81567. this.dispatchEvent({type:'update'});
  81568. //为什么navvis在校准数据集时每个viewport里reticule的朝向都刚好垂直于屏幕,似乎限定在了一定范围内,还是在pick时就只pick范围内的点?
  81569. }
  81570. }
  81571. //navvis在地图等地方看reticule是有厚度的
  81572. /* updateMatrixWorld(force){
  81573. console.log('updateMatrixWorld', force)
  81574. super.updateMatrixWorld(force)
  81575. } */
  81576. }
  81577. const FEET_TO_INCHES_FACTOR = 12;
  81578. const EIGHTHS_SYMBOLS = ["", "⅛", "¼", "⅜", "½", "⅝", "¾", "⅞"];//eighths 八分之……
  81579. class UnitOfMeasurement{//转化单位工具
  81580. constructor(t, e, n, i){
  81581. this.name = t,
  81582. this.symbol = e,
  81583. this.base = n,
  81584. this.factor = i;
  81585. }
  81586. toBase(t) {//换算到base
  81587. return t * this.factor
  81588. }
  81589. fromBase(t) {//换算到当前
  81590. return t / this.factor
  81591. }
  81592. }
  81593. /* var o = function t(e) {
  81594. this.gettext = e,
  81595. t.METRIC = this.gettext("metric", void 0, "measurement system"),
  81596. t.IMPERIAL = this.gettext("imperial", void 0, "measurement system")
  81597. };
  81598. e.UoMSystem = o;
  81599. let UoMSystem = {
  81600. } */
  81601. /* var MeasurementDomain = {
  81602. DISTANCE : "DISTANCE",
  81603. t.AREA = "AREA",
  81604. t.VOLUME = "VOLUME",
  81605. t.DATA = "DATA",
  81606. t
  81607. }
  81608. */
  81609. var UnitsOfMeasurement = {
  81610. MILLIMETER : ["Millimeter", "mm"],
  81611. CENTIMETER : ["Centimeter", "cm"],
  81612. METER : ["Meter", "m"],
  81613. KILOMETER : ["Kilometer", "km"],
  81614. INCH : ["Inch", "in"],
  81615. FOOT : ["Foot", "ft"],
  81616. MILE : ["Mile", "mi"],
  81617. SQUAREMETER : ["SquareMeter", "m²"],
  81618. SQUAREFOOT : ["SquareFoot", "ft²"],
  81619. CUBICMETER : ["CubicMeter", "m³"],
  81620. CUBICFOOT : ["CubicFoot", "ft³"],
  81621. BYTE : ["Byte", "B"],
  81622. KILOBYTE : ["Kilobyte", "kB"],
  81623. MEGABYTE : ["Megabyte", "MB"],
  81624. GIGABYTE : ["Gigabyte", "GB"],
  81625. TERABYTE : ["Terabyte", "TB"],
  81626. PETABYTE : ["Petabyte", "PB"],
  81627. init : function() {
  81628. var e, n, i, a, s, c, l, u, d, p, h,
  81629. f = new UnitOfMeasurement(UnitsOfMeasurement.METER[0],UnitsOfMeasurement.METER[1],void 0,1),
  81630. g = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREMETER[0],UnitsOfMeasurement.SQUAREMETER[1],void 0,1),
  81631. m = new UnitOfMeasurement(UnitsOfMeasurement.CUBICMETER[0],UnitsOfMeasurement.CUBICMETER[1],void 0,1),
  81632. v = new UnitOfMeasurement(UnitsOfMeasurement.BYTE[0],UnitsOfMeasurement.BYTE[1],void 0,1);
  81633. UnitsOfMeasurement.DISTANCE = (
  81634. (e = {})['metric'] = ((n = {})[UnitsOfMeasurement.MILLIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILLIMETER[0],UnitsOfMeasurement.MILLIMETER[1],f,.001),
  81635. n[UnitsOfMeasurement.CENTIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CENTIMETER[0],UnitsOfMeasurement.CENTIMETER[1],f,.01),
  81636. n[UnitsOfMeasurement.METER[0]] = f,
  81637. n[UnitsOfMeasurement.KILOMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOMETER[0],UnitsOfMeasurement.KILOMETER[1],f,1e3),
  81638. n),
  81639. e['imperial'] = ((i = {})[UnitsOfMeasurement.INCH[0]] = new UnitOfMeasurement(UnitsOfMeasurement.INCH[0],UnitsOfMeasurement.INCH[1],f,.0254),
  81640. i[UnitsOfMeasurement.FOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.FOOT[0],UnitsOfMeasurement.FOOT[1],f,.3048),
  81641. i[UnitsOfMeasurement.MILE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILE[0],UnitsOfMeasurement.MILE[1],f,1609.344),
  81642. i),
  81643. e);
  81644. UnitsOfMeasurement.AREA = ((a = {})['metric'] = ((s = {})[UnitsOfMeasurement.SQUAREMETER[0]] = g,
  81645. s),
  81646. a['imperial'] = ((c = {})[UnitsOfMeasurement.SQUAREFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREFOOT[0],UnitsOfMeasurement.SQUAREFOOT[1],g,.092903),
  81647. c),
  81648. a);
  81649. UnitsOfMeasurement.VOLUME = ((l = {})['metric'] = ((u = {})[UnitsOfMeasurement.CUBICMETER[0]] = m,
  81650. u),
  81651. l['imperial'] = ((d = {})[UnitsOfMeasurement.CUBICFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CUBICFOOT[0],UnitsOfMeasurement.CUBICFOOT[1],m,.0283168),
  81652. d),
  81653. l);
  81654. //数据大小
  81655. var y = ((p = {})[UnitsOfMeasurement.BYTE[0]] = v,
  81656. p[UnitsOfMeasurement.KILOBYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOBYTE[0],UnitsOfMeasurement.KILOBYTE[1],v,1e3),
  81657. p[UnitsOfMeasurement.MEGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MEGABYTE[0],UnitsOfMeasurement.MEGABYTE[1],v,1e6),
  81658. p[UnitsOfMeasurement.GIGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.GIGABYTE[0],UnitsOfMeasurement.GIGABYTE[1],v,1e9),
  81659. p[UnitsOfMeasurement.TERABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.TERABYTE[0],UnitsOfMeasurement.TERABYTE[1],v,1e12),
  81660. p[UnitsOfMeasurement.PETABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.PETABYTE[0],UnitsOfMeasurement.PETABYTE[1],v,1e15),
  81661. p);
  81662. UnitsOfMeasurement.DATA = ((h = {})['metric'] = y,
  81663. h['imperial'] = y,
  81664. h);
  81665. }
  81666. ,
  81667. getUnitsOfMeasurementByDomain : function(e) {
  81668. return this[e.toUpperCase()]
  81669. /* switch (e.toUpperCase()) {
  81670. case a.DISTANCE:
  81671. return t.DISTANCE;
  81672. case a.AREA:
  81673. return t.AREA;
  81674. case a.VOLUME:
  81675. return t.VOLUME;
  81676. case a.DATA:
  81677. return t.DATA;
  81678. default:
  81679. console.error(e + " measurement domain is not supported.")
  81680. } */
  81681. }
  81682. ,
  81683. getUnitsOfMeasurementByDomainAndSystem : function(domain, system) {
  81684. var r = this.getUnitsOfMeasurementByDomain(domain);
  81685. if (r.hasOwnProperty(system.toLowerCase()))
  81686. return r[system.toLowerCase()];
  81687. console.error(n + " measurement system is not supported.");
  81688. }
  81689. ,
  81690. getDefaultUnitByDomainAndSystem : function(e, n) {
  81691. switch (e.toUpperCase()) {
  81692. case 'DISTANCE':
  81693. switch (n.toLowerCase()) {
  81694. case 'metric':
  81695. return this.DISTANCE['metric'][this.METER[0]];
  81696. case 'imperial':
  81697. return this.DISTANCE['imperial'][this.FOOT[0]];
  81698. default:
  81699. console.error(n + " measurement system is not supported.");
  81700. }
  81701. case 'AREA':
  81702. switch (n.toLowerCase()) {
  81703. case 'metric':
  81704. return this.AREA['metric'][this.SQUAREMETER[0]];
  81705. case 'imperial':
  81706. return this.AREA['imperial'][this.SQUAREFOOT[0]];
  81707. default:
  81708. console.error(n + " measurement system is not supported.");
  81709. }
  81710. case 'VOLUME':
  81711. switch (n.toLowerCase()) {
  81712. case 'metric':
  81713. return this.VOLUME['metric'][this.CUBICMETER[0]];
  81714. case 'imperial':
  81715. return this.VOLUME['imperial'][this.CUBICFOOT[0]];
  81716. default:
  81717. console.error(n + " measurement system is not supported.");
  81718. }
  81719. case 'DATA':
  81720. switch (n.toLowerCase()) {
  81721. case 'metric':
  81722. return this.DATA['metric'][this.BYTE[0]];
  81723. case 'imperial':
  81724. return this.DATA['imperial'][this.BYTE[0]];
  81725. default:
  81726. console.error(n + " measurement system is not supported.");
  81727. }
  81728. default:
  81729. console.error(e + " measurement domain is not supported.");
  81730. }
  81731. }
  81732. };
  81733. class UnitService{
  81734. constructor(/* e, n, i */){
  81735. //this.LanguageService = e,
  81736. //this.localStorageService = n,
  81737. //this.gettext = i,
  81738. //this.unitChanged = new r.Signal,
  81739. this.LOCAL_STORAGE_KEY = "iv_unit_key";//?
  81740. UnitsOfMeasurement.init();
  81741. this.unitSystems = ['metric', 'imperial'];//[o.UoMSystem.METRIC, o.UoMSystem.IMPERIAL],
  81742. this.defaultSystem = 'metric';//'imperial'
  81743. //var a = this.LanguageService.getBrowserLocaleString().toLowerCase();
  81744. //this.defaultSystem = t.isLocaleImperial(a) ? o.UoMSystem.IMPERIAL : o.UoMSystem.METRIC,
  81745. //this.initUnit()
  81746. }
  81747. /* initUnit() {
  81748. var t = this.localStorageService.get(this.LOCAL_STORAGE_KEY);
  81749. if (t)
  81750. for (var e = 0, n = this.unitSystems; e < n.length; e++) {
  81751. var i = n[e];
  81752. if (i === t)
  81753. return void this.setUnit(i, !0)
  81754. }
  81755. this.setUnit(this.defaultSystem, !1)
  81756. }
  81757. setUnit(t, e) {
  81758. this.currentSystem !== t && (this.currentSystem = t,
  81759. this.unitChanged.emit()),
  81760. e && this.localStorageService.set(this.LOCAL_STORAGE_KEY, t)
  81761. } */
  81762. /*isLocaleImperial(e) {
  81763. return t.IMPERIAL_LOCALES.indexOf(e.toLowerCase()) >= 0
  81764. }
  81765. ,
  81766. t.IMPERIAL_LOCALES = ["en_us"],
  81767. t.ɵfac(e) {
  81768. return new (e || t)(c.ɵɵinject(l.LanguageService),
  81769. c.ɵɵinject("localStorageService"),c.ɵɵinject("gettext"))
  81770. }
  81771. ,
  81772. t.ɵprov = c.ɵɵdefineInjectable({
  81773. token: t,
  81774. factory: t.ɵfac,
  81775. providedIn: "root"
  81776. }), */
  81777. }
  81778. class UoMService{
  81779. constructor(/* UnitService */){
  81780. this.UnitService = new UnitService();/* UnitService */
  81781. }
  81782. scopedConvert (t, n, precision = 2, r, minFactor) {
  81783. return this.convert(t, n, precision, r, minFactor)
  81784. }
  81785. convert(number, domain, precision = 2, system, minFactor, ifEighths = !1) {
  81786. if (!number) return "";
  81787. var s = this.getMostRelevantMeasurement(domain, system || this.UnitService.currentSystem, number, minFactor);
  81788. return this.getFormattedMeasurementString(s[0], s[1], precision, ifEighths)
  81789. }
  81790. convertBack(number, domain, precision = 2, fromSystem, minFactor ) { //从英制转到'metric'
  81791. if (!number) return "";
  81792. var d = UnitsOfMeasurement.getDefaultUnitByDomainAndSystem(domain,'metric');
  81793. var s = this.getMostRelevantMeasurement2(domain, fromSystem, number, minFactor);
  81794. return this.getFormattedMeasurementString(s[0], d, precision )
  81795. /* 栗子:
  81796. viewer.unitConvert.convertBack(1, 'area', 5, 'imperial')
  81797. '0.09290 m²'
  81798. viewer.unitConvert.convertBack(1, 'Distance', 2, 'imperial')
  81799. '0.03 m'
  81800. */
  81801. }
  81802. getFormattedMeasurementString(number, unit, precision, ifEighths) {
  81803. var result;
  81804. if(ifEighths && unit.name === UnitsOfMeasurement.FOOT[0]){
  81805. result = this.formatImperialDistance(number * FEET_TO_INCHES_FACTOR);
  81806. }else if(ifEighths && unit.name === UnitsOfMeasurement.INCH[0]){
  81807. result = this.formatImperialDistance(number);
  81808. }else {
  81809. result = number.toLocaleString(void 0, {
  81810. minimumFractionDigits: precision,
  81811. maximumFractionDigits: precision
  81812. }) + " " + unit.symbol;
  81813. }
  81814. return result
  81815. }
  81816. formatImperialDistance(e) {
  81817. var n = Math.round(8 * e)
  81818. , i = Math.floor(n / 8)
  81819. , r = Math.floor(i / FEET_TO_INCHES_FACTOR)
  81820. , o = i - r * FEET_TO_INCHES_FACTOR
  81821. , a = EIGHTHS_SYMBOLS[n % 8]
  81822. , s = 0 === o && "" !== a ? "" : o;
  81823. "" !== s && "" !== a && (a = " " + a);
  81824. return 0 !== r ? r + "' " + s + a + '"' : "" + s + a + '"'
  81825. }
  81826. getMostRelevantMeasurement(domain, system, number, minFactor=0) {
  81827. /* var a = r.values(UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system))
  81828. , s = r.filter(a, function(t) {
  81829. return t.factor >= i
  81830. })
  81831. , c = r.reduce(s, function(t, e) {
  81832. return e.fromBase(number) < t.fromBase(number) && e.fromBase(number) >= 1 ? e : t
  81833. }); */
  81834. let a = [];
  81835. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  81836. for(let i in u){a.push(u[i]);}
  81837. let s = a.filter(m=>m.factor >= minFactor);
  81838. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  81839. return currentValue.fromBase(number) < prev.fromBase(number) && currentValue.fromBase(number) >= 1 ? currentValue : prev
  81840. });
  81841. return c ? [c.fromBase(number), c] : void 0
  81842. }
  81843. getMostRelevantMeasurement2(domain, system, number, minFactor=0) {//add
  81844. let a = [];
  81845. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  81846. for(let i in u){a.push(u[i]);}
  81847. let s = a.filter(m=>m.factor >= minFactor);
  81848. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  81849. return currentValue.toBase(number) < prev.toBase(number) && currentValue.toBase(number) >= 1 ? currentValue : prev
  81850. });
  81851. return c ? [c.toBase(number), c] : void 0
  81852. }
  81853. /* ɵfac(e){
  81854. return new (e || t)(c.ɵɵinject(l.UnitService))
  81855. }
  81856. ɵprov = c.ɵɵdefineInjectable({
  81857. token: t,
  81858. factory: t.ɵfac,
  81859. providedIn: "root"
  81860. }) */
  81861. }
  81862. const texLoader$b = new TextureLoader();
  81863. const arrowSpacing = 1; //间隔
  81864. const arrowSize = arrowSpacing * 0.5;
  81865. const planeGeo$4 = new PlaneBufferGeometry(1,1);
  81866. const sphereSizeInfo = {
  81867. nearBound : 2, scale:arrowSize, restricMeshScale : true,
  81868. };
  81869. //const arrowsShowingCount = 25; //场景里最多展示多少个箭头
  81870. const arrowShowMinDis = 10;
  81871. class RouteGuider extends EventDispatcher{
  81872. constructor () {
  81873. super();
  81874. this.route = [];
  81875. this.curve = [];
  81876. this.scenePoints = [];
  81877. this.sceneMeshGroup = new Object3D;
  81878. this.mapMeshGroup = new Object3D;
  81879. this.generateDeferred;
  81880. viewer.addEventListener('loadPointCloudDone',this.init.bind(this));
  81881. this.lastResult;//保存上一个的结果,以便于反向
  81882. this.datasetIds = [];//起始和终点的datasetId
  81883. }
  81884. init(){
  81885. if(this.inited) return;
  81886. let zoom;
  81887. viewer.mapViewer.addEventListener('camera_changed', e => {
  81888. if(!this.routeStart || !this.routeEnd) return
  81889. var camera = e.viewport.camera;
  81890. Common.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81891. if(camera.zoom != zoom){
  81892. //console.log('updateMapArrows')
  81893. this.updateMapArrows(true);
  81894. zoom = camera.zoom;
  81895. return true
  81896. }
  81897. }, browser.isMobile()?500:200);
  81898. });
  81899. //let lastPos = new THREE.Vector3
  81900. viewer.addEventListener('camera_changed', e => {
  81901. if(!this.routeStart || !this.routeEnd || !e.changeInfo.positionChanged) return
  81902. Common.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81903. //let currPos = viewer.scene.getActiveCamera().position
  81904. //if(!currPos.equals(lastPos)){
  81905. // lastPos.copy(currPos)
  81906. this.updateArrowDisplay();
  81907. return true
  81908. //}
  81909. }, 1000);
  81910. });
  81911. var polesMats = {
  81912. shadowMat: new MeshBasicMaterial({
  81913. transparent:true, depthTest:false,
  81914. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_bottomMarker.png' )
  81915. }),
  81916. sphereMat : new MeshBasicMaterial({
  81917. transparent:true, depthTest:false,
  81918. map: texLoader$b.load(Potree.resourcePath+'/textures/whiteCircle.png' )
  81919. }),
  81920. hatMats:{
  81921. start: new MeshBasicMaterial({
  81922. transparent:true, depthTest:false,
  81923. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_start_route.png' )
  81924. }),
  81925. end: new MeshBasicMaterial({
  81926. transparent:true, depthTest:false,
  81927. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_target_reached.png' )
  81928. })
  81929. }
  81930. };
  81931. polesMats.shadowMat.map.anisotropy = 4;
  81932. this.poleStart = this.createPole(polesMats, 'start');
  81933. this.poleEnd = this.createPole(polesMats, 'end');
  81934. this.sceneMeshGroup.add(this.poleStart);
  81935. this.sceneMeshGroup.add(this.poleEnd);
  81936. let map = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_panorama.png' );
  81937. map.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  81938. this.arrow = new Mesh(planeGeo$4, new MeshBasicMaterial({
  81939. transparent:true,
  81940. depthTest:false,
  81941. map
  81942. }));
  81943. this.arrow.scale.set(arrowSize,arrowSize,arrowSize);
  81944. viewer.setObjectLayers(this.arrow, 'sceneObjects' );
  81945. /* this.testArrow = this.arrow.clone();
  81946. this.testArrow.material = this.arrow.material.clone()
  81947. this.testArrow.material.color = 'red' */
  81948. this.arrows = new Object3D;
  81949. this.sceneMeshGroup.add(this.arrows);
  81950. viewer.setObjectLayers(this.sceneMeshGroup, 'sceneObjects' );
  81951. //this.sceneMeshGroup.traverse(e=>e.renderOrder = 90)
  81952. viewer.scene.scene.add(this.sceneMeshGroup);
  81953. this.sceneMeshGroup.visible = /* this.poleStart.visibile = this.poleEnd.visibile = */ false;
  81954. //-------------map---------------------
  81955. /* this.mapMarkStart = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81956. transparent:true, depthTest:false,
  81957. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_start_route.png' )
  81958. }))
  81959. this.mapMarkEnd = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81960. transparent:true, depthTest:false,
  81961. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_target_reached.png' )
  81962. }))
  81963. this.mapMarkStart.renderOrder = this.mapMarkEnd.renderOrder = 2//在箭头之上 */
  81964. let map2 = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_map_fsna.png' );
  81965. this.mapArrowMats = {
  81966. default: new MeshBasicMaterial({
  81967. transparent:true, depthTest:false,
  81968. map:map2,
  81969. }),
  81970. fade: new MeshBasicMaterial({
  81971. transparent:true, depthTest:false,
  81972. map:map2,
  81973. opacity:0.4
  81974. }),
  81975. };
  81976. this.mapArrow = new Mesh( planeGeo$4, this.mapArrowMats.default);
  81977. this.mapArrow.scale.set(arrowSize,arrowSize,arrowSize);
  81978. this.mapArrows = new Object3D;
  81979. this.mapArrows.name = 'mapArrows';
  81980. this.mapMeshGroup.add(this.mapArrows);
  81981. this.mapMeshGroup.name = 'mapRouteLayer';
  81982. this.mapMeshGroup.visible = false;
  81983. viewer.mapViewer.dispatchEvent({type:'add', object:this.mapMeshGroup, name:'route'});
  81984. this.mapArrow.layers.mask = this.mapArrows.layers.mask; // 修改成和map中的layer一样的
  81985. viewer.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  81986. if(this.routeStart && this.routeEnd){
  81987. this.updateOpacityAtMap();
  81988. }
  81989. });
  81990. this.inited = true;
  81991. }
  81992. updateOpacityAtMap(){//只有当前楼层的透明度为1
  81993. var currentFloor = viewer.modules.SiteModel.currentFloor;
  81994. //console.log('updateOpacityAtMap', currentFloor && currentFloor.name)
  81995. const lift = 0.3; // 因为发送请求时用的是floorPosition的高度,而它可能会到画好的floor之下,所以有误差
  81996. this.mapArrows.children.forEach((arrow,index)=>{
  81997. let pos = this.mapPoints[index].clone();
  81998. pos.z += lift;
  81999. let inSide = currentFloor && currentFloor.ifContainsPoint(pos);
  82000. arrow.material = inSide ? this.mapArrowMats.default : this.mapArrowMats.fade;
  82001. //console.log('arrow',index, arrow.material.opacity)
  82002. });
  82003. viewer.mapViewer.dispatchEvent('content_changed');
  82004. }//但是如果楼层刚好只框柱相机位置而没框住地面位置就不好了……
  82005. createPole(polesMats, name){
  82006. const height = 1.5, sphereCount = 6, shadowSize = sphereSizeInfo.scale, sphereSize = 0.04;
  82007. var group = new Object3D;
  82008. group.name = 'pole_'+name;
  82009. var shadow = new Mesh(planeGeo$4,polesMats.shadowMat);
  82010. shadow.scale.set(shadowSize,shadowSize,shadowSize);
  82011. var sliceDis = height / (sphereCount+1);
  82012. group.add(shadow);
  82013. for(let i=0;i<sphereCount;i++){
  82014. var sphere = new Sprite$1({mat: polesMats.sphereMat});
  82015. sphere.position.set(0,0,sliceDis*(i+1));
  82016. sphere.scale.set(sphereSize,sphereSize,sphereSize);
  82017. sphere.visible = false;
  82018. group.add(sphere);
  82019. }
  82020. var hatSphere = new Sprite$1({mat: polesMats.hatMats[name], sizeInfo:sphereSizeInfo});
  82021. sphere.visible = false;
  82022. hatSphere.position.set(0,0,height);
  82023. hatSphere.scale.copy(shadow.scale);
  82024. group.add(hatSphere);
  82025. return group
  82026. }
  82027. addTestArrow(){
  82028. }
  82029. addArrow(position){
  82030. var arrow = this.arrow.clone();
  82031. arrow.position.copy(position);
  82032. this.arrows.add(arrow);
  82033. }
  82034. addMapArrow(position){
  82035. var mapArrow = this.mapArrow.clone();
  82036. mapArrow.position.copy(position).setZ(0);
  82037. this.mapArrows.add(mapArrow);
  82038. }
  82039. setArrowDir(arrows,index){
  82040. let arrow = arrows[index];
  82041. var nextOne = arrows[index+1];
  82042. var nextPos = nextOne ? nextOne.position : this.endPolePos; //routeEnd
  82043. var direction = new Vector3().subVectors(arrow.position, nextPos).setZ(0);
  82044. //direction.normalize();
  82045. //console.log(direction.toArray())
  82046. var angle = Math.atan2(direction.y, direction.x ) + Math.PI/2; //Math.PI/2是因为贴图本身箭头方向不朝x
  82047. arrow.rotation.z = angle;
  82048. //console.log(angle)
  82049. }
  82050. setRouteStart(pos, dealZ , datasetId ){
  82051. if(this.routeStart && pos && this.routeStart.equals(pos)) return //可能重复设置
  82052. this.routeStart = pos && new Vector3().copy(pos);
  82053. if(dealZ && this.routeStart){
  82054. this.routeStart.setZ(this.getZAtMap());
  82055. this.bus && this.bus.emit('reposStartMarker', this.routeStart);
  82056. }
  82057. console.log('setRouteStart',this.routeStart&&this.routeStart.toArray());
  82058. this.datasetIds[0] = datasetId;
  82059. //this.setStartPole(pos)
  82060. this.generateRoute();
  82061. }
  82062. setStartPole(pos){
  82063. this.startPolePos = pos;
  82064. this.bus && this.bus.emit('reposStartMarker', pos);
  82065. }
  82066. setRouteEnd(pos, dealZ , datasetId ){
  82067. if(this.routeEnd && pos && this.routeEnd.equals(pos)) return
  82068. this.routeEnd = pos && new Vector3().copy(pos);
  82069. if(dealZ && this.routeEnd){
  82070. this.routeEnd.setZ(this.getZAtMap());
  82071. this.bus && this.bus.emit('reposEndMarker', this.routeEnd);
  82072. }
  82073. console.log('setRouteEnd',this.routeEnd&&this.routeEnd.toArray());
  82074. this.datasetIds[1] = datasetId;
  82075. //this.setEndPole(pos)
  82076. this.generateRoute();
  82077. }
  82078. getZAtMap(){
  82079. //找到position.z与当前高度最接近的漫游点
  82080. let result = Common.sortByScore(viewer.images360.panos,[],[e=> -(Math.abs(e.position.z - viewer.images360.position.z)) ]);
  82081. let pano = result && result[0] && result[0].item;
  82082. return pano ? pano.floorPosition.z : viewer.bound.boundingBox.min.z + 1
  82083. //若在平面图上画实在得不到当前楼层的,大概率是楼层画得不好,那就只能去获取当前楼层的了
  82084. //navvis的高度取的是主视图所在楼层的中心高度(可能再高些)
  82085. }
  82086. setEndPole(pos){
  82087. this.endPolePos = pos;
  82088. this.bus && this.bus.emit('reposEndMarker', pos);
  82089. }
  82090. getSourceProjectionIndex(route) {//真正的起始
  82091. var e = route.findIndex(function(t) {
  82092. return t.instruction && t.instruction.type === 'source_projection_to_navgraph'
  82093. });
  82094. return e < 0 ? 0 : e
  82095. }
  82096. getDestinationProjectionIndex(route) {//真正的终点
  82097. var e = route.findIndex(function(t) {
  82098. return t.instruction && t.instruction.type === "destination_projection_to_navgraph"
  82099. });
  82100. return e < 0 ? route.length - 1 : e
  82101. }
  82102. generateRoute(){
  82103. if(!this.routeStart || !this.routeEnd){
  82104. return
  82105. }
  82106. //array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  82107. let create = ()=>{
  82108. this.routeLength = this.route.reduce((total, currentValue, currentIndex, arr)=>{
  82109. if(currentIndex == 0)return 0
  82110. return total + currentValue.distanceTo(arr[currentIndex-1]);
  82111. },0);
  82112. let count = Math.max(2,Math.round(this.routeLength / arrowSpacing));//点数
  82113. const curve = new CatmullRomCurve3( this.route );
  82114. curve.curveType = 'chordal';//'centripetal' 'catmullrom'这个可能会超出路径外
  82115. this.curve = curve;
  82116. const scenePoints = curve.getSpacedPoints( count );//更平均
  82117. //const scenePoints = curve.getPoints( count );
  82118. scenePoints.splice(0,1);//去掉首尾
  82119. scenePoints.pop();
  82120. this.scenePoints = scenePoints;
  82121. this.updateMapArrows();
  82122. this.displayRoute();
  82123. {//map focus on this area
  82124. const minBound = new Vector2$1(1,1);//针对垂直线,在地图上只有一个点
  82125. let bound = new Box2;
  82126. this.route.forEach(e=>{
  82127. bound.expandByPoint(e);
  82128. });
  82129. let size = bound.getSize(new Vector2$1);
  82130. let markerSize = new Vector2$1(115,40); //起始和终点的标识呈长方形
  82131. let areaSize = viewer.mapViewer.viewports[0].resolution2;
  82132. let areaArea = areaSize.x * areaSize.y;
  82133. if(areaArea> 800 * 400){//是放大的
  82134. markerSize.multiplyScalar(areaArea / (800 * 400) /* / (size.x * size.y) */);
  82135. }
  82136. let margin = size.clone().divide(viewer.mapViewer.viewports[0].resolution2).multiply(markerSize); ///边距 重点是起始和终点的标识占据较大
  82137. size.add(margin);
  82138. let center = bound.getCenter(new Vector2$1);
  82139. size.x = Math.max(size.x, minBound.x );
  82140. size.y = Math.max(size.y, minBound.y );
  82141. let duration = 1000;
  82142. viewer.mapViewer.moveTo(center, size, duration);
  82143. }
  82144. this.bus.emit('gotResult', {dis:this.routeLength});
  82145. /* this.generateDeferred && this.generateDeferred.resolve({dis:this.routeLength})
  82146. this.generateDeferred = null */
  82147. };
  82148. if(Potree.fileServer){
  82149. let dealData = (data)=>{
  82150. if(!data.data){
  82151. console.log('没有数据');
  82152. let result;
  82153. if(data && data.code == 4002){
  82154. result = data;//正被修改数据集
  82155. }else if(this.routeStart.distanceTo(this.routeEnd) < 1){
  82156. result = { code: 500, msg: '距离太短,无法规划路线' };
  82157. }else {
  82158. result = { code: 500, msg: '超出数据集范围,无法规划路线' };
  82159. }
  82160. this.clearRoute();
  82161. this.setStartPole(this.routeStart);
  82162. this.setEndPole(this.routeEnd);
  82163. this.displayRoute(); //还是要显示一下起始
  82164. this.bus && this.bus.emit('gotResult', result );
  82165. return //this.generateDeferred && this.generateDeferred.resolve()
  82166. }
  82167. data = data.data;
  82168. this.clearRoute();
  82169. let length = data.length;
  82170. if(length < 2){//可能距离太短
  82171. console.log('路径点数为'+length+',直接取起点和终点连线');
  82172. this.route = [this.routeStart, this.routeEnd];
  82173. }else {
  82174. let startIndex = this.getSourceProjectionIndex(data);
  82175. let endIndex = this.getDestinationProjectionIndex(data);
  82176. let effectiveItems = data.slice(startIndex, endIndex + 1 );//只要点云范围内的点
  82177. effectiveItems.forEach((item,i)=>{
  82178. let pos = viewer.transform.lonlatToLocal.forward(item.location.slice(0));
  82179. pos = new Vector3().fromArray(pos);//.setZ(item.z)
  82180. this.route.push(pos);
  82181. });
  82182. console.log(this.route);
  82183. }
  82184. this.setStartPole(this.route[0]);
  82185. this.setEndPole(this.route[this.route.length-1]);
  82186. create();
  82187. /*
  82188. distance: 0.17581000000000116
  82189. distance_to_previous: 0.17581000000000116
  82190. id: 567
  82191. instruction: {type: 'source_projection_to_navgraph'}
  82192. latitude: 22.366605927999238
  82193. location: (3) [113.5957510575092, 22.366605927999238, -1.12419]
  82194. longitude: 113.5957510575092
  82195. z: -1.12419
  82196. */
  82197. };
  82198. if(this.lastResult && (this.lastResult.data || this.lastResult.data.code != 4002)){//正被修改数据集的话要重新计算
  82199. let data = Common.CloneObject(this.lastResult.data) , use; //直接用上次的结果
  82200. if(this.lastResult.routeStart.equals(this.routeStart) && this.lastResult.routeEnd.equals(this.routeEnd)){//和上次请求相同
  82201. use = true;
  82202. }else if(this.lastResult.routeStart.equals(this.routeEnd) && this.lastResult.routeEnd.equals(this.routeStart)){//..反向
  82203. use = true;
  82204. if(data.data){
  82205. data.data = this.lastResult.data.data.slice(0).reverse();
  82206. }
  82207. }
  82208. if(use){
  82209. console.log('直接用上次的结果');
  82210. return setTimeout(()=>{dealData(data);}, 1)//延迟是为了等待获得 RouteGuider.generateDeferred
  82211. }
  82212. }
  82213. let start = this.routeStart.clone();
  82214. let end = this.routeEnd.clone();
  82215. let startLonlat = viewer.transform.lonlatToLocal.inverse(start);
  82216. let endLonlat = viewer.transform.lonlatToLocal.inverse(end);
  82217. var query = {
  82218. source_longitude: startLonlat.x,
  82219. source_latitude: startLonlat.y,
  82220. source_z: start.z,
  82221. destination_longitude: endLonlat.x,
  82222. destination_latitude: endLonlat.y,
  82223. destination_z: end.z
  82224. };
  82225. //let url = `/laser/route/${Potree.settings.number}/getRoute/${this.datasetIds[0]}/${this.datasetIds[1]}?`
  82226. let url = `/laser/route/${Potree.settings.number}/getRoute/${Potree.settings.originDatasetId}?`;
  82227. for(let i in query){
  82228. url+= (i + '='+ query[i] +'&');
  82229. }
  82230. Potree.fileServer.get(url).then((data)=>{
  82231. console.log(data.data);
  82232. if(!this.routeStart || !this.routeEnd)return
  82233. this.lastResult = {//保存数据
  82234. routeStart : this.routeStart.clone(),
  82235. routeEnd: this.routeEnd.clone(),
  82236. data,
  82237. };
  82238. dealData(data);
  82239. });
  82240. }else {
  82241. //创个直线
  82242. /* const sliceDis = 1
  82243. let dis = this.routeStart.distanceTo(this.routeEnd);
  82244. let count = Math.max(2,Math.round(dis / sliceDis))//点数
  82245. let realSlideDis = dis / (count-1);
  82246. let dir = new THREE.Vector3().subVectors(this.routeEnd, this.routeStart).normalize().multiplyScalar(realSlideDis);
  82247. this.route = [this.routeStart];
  82248. for(let i=0;i<count-1;i++){
  82249. let lastOne = this.route[i];
  82250. this.route.push(new THREE.Vector3().addVectors(lastOne,dir))
  82251. }
  82252. this.route.splice(0,1) //route不用包含收尾 */
  82253. this.clearRoute();
  82254. this.route = [this.routeStart, this.routeEnd];
  82255. create();
  82256. }
  82257. }
  82258. updateMapArrows(ifReset){
  82259. if(this.route.length == 0)return
  82260. var zoom = viewer.mapViewer.camera.zoom;
  82261. let count = Math.max(2,Math.round(this.routeLength * zoom / arrowSpacing / 25));//点数
  82262. if(count == this.mapPoints.length+1)return//没变
  82263. const mapPoints = this.curve.getSpacedPoints( count );
  82264. mapPoints.splice(0,1);//去掉首尾
  82265. mapPoints.pop();
  82266. this.mapPoints = mapPoints;
  82267. var scale = 25/zoom;
  82268. this.mapArrow.scale.set(scale*0.6,scale*0.6,scale*0.6);
  82269. /* this.mapMarkStart.scale.set(scale,scale,scale)
  82270. this.mapMarkEnd.scale.set(scale,scale,scale) */
  82271. if(ifReset){//因为缩放而重新排布箭头
  82272. this.clearRoute({resetMap:true});
  82273. this.displayRoute({resetMap:true});
  82274. }
  82275. this.updateOpacityAtMap();
  82276. }
  82277. updateArrowDisplay(){//根据当前位置更新显示一定范围内的箭头'
  82278. if(this.scenePoints.length == 0)return
  82279. /* var a = Common.sortByScore(this.scenePoints , null, [(point)=>{ //是否还要再requires里限制最远距离?
  82280. var playerPos = viewer.scene.getActiveCamera().position.clone().setZ(0)
  82281. var pos = point.clone().setZ(0)
  82282. return -pos.distanceTo(playerPos);
  82283. }]);
  82284. //获得展示的起始点
  82285. let start = a[0].item
  82286. let startIndex = this.scenePoints.indexOf(start)
  82287. this.arrows.children.forEach((e,i)=>{
  82288. if(i<startIndex || i>startIndex+arrowsShowingCount)e.visible = false
  82289. else e.visible = true
  82290. }) */
  82291. let cameraPos = viewer.scene.getActiveCamera().position;
  82292. this.arrows.children.forEach((e,i)=>{
  82293. if(e.position.distanceTo(cameraPos) < arrowShowMinDis) e.visible = true;
  82294. else e.visible = false;
  82295. });
  82296. }
  82297. displayRoute(o={}){
  82298. if(!o.resetMap){
  82299. this.poleStart.position.copy(this.startPolePos || this.routeStart);
  82300. this.poleEnd.position.copy(this.endPolePos || this.routeEnd);
  82301. /* this.mapMarkStart.position.copy(this.routeStart).setZ(0)
  82302. this.mapMarkEnd.position.copy(this.routeEnd).setZ(0) */
  82303. this.scenePoints.forEach(e=>this.addArrow(e));
  82304. this.arrows.children.forEach((e,i)=>this.setArrowDir(this.arrows.children,i));
  82305. }
  82306. this.sceneMeshGroup.traverse(e=>e.visible = true);
  82307. this.mapMeshGroup.visible = true;
  82308. this.mapPoints.forEach(e=>this.addMapArrow(e));
  82309. this.mapArrows.children.forEach((e,i)=>this.setArrowDir(this.mapArrows.children,i));
  82310. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  82311. this.updateArrowDisplay();
  82312. }
  82313. clearRoute(o={}){
  82314. if(!o.resetMap){
  82315. this.routeLength = 0;
  82316. this.route = [];
  82317. this.scenePoints = [];
  82318. this.mapPoints = [];
  82319. let arrows = this.arrows.children.slice(0);
  82320. arrows.forEach(e=>{
  82321. this.arrows.remove(e);
  82322. });
  82323. }
  82324. let mapArrows = this.mapArrows.children.slice(0);
  82325. mapArrows.forEach(e=>{
  82326. this.mapArrows.remove(e);
  82327. });
  82328. this.sceneMeshGroup.traverse(e=>e.visible = false); //包括sprite也要设置,防止update
  82329. this.mapMeshGroup.visible = false;
  82330. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  82331. }
  82332. clear(){//退出
  82333. console.log('导航clear');
  82334. this.routeStart = null;
  82335. this.routeEnd = null;
  82336. this.clearRoute();
  82337. }
  82338. }
  82339. //大概每十米要花一秒
  82340. /*
  82341. 存在的问题:
  82342. 路径不准确。起始点和终点偏移。
  82343. */
  82344. const vertexShader = `
  82345. attribute float randam;
  82346. attribute float sprite;
  82347. attribute float centerHeight; //add
  82348. //uniform float fireHeight; //add
  82349. uniform float time;
  82350. uniform float size;
  82351. uniform float heightOfNearPlane;
  82352. //varying float heightRatio;
  82353. varying float vSprite;
  82354. varying float vOpacity;
  82355. float PI = 3.14;
  82356. float quadraticIn( float t )
  82357. {
  82358. float tt = t * t;
  82359. return tt * tt;
  82360. //变化曲线 越来越快
  82361. }
  82362. void main() {
  82363. float progress = fract( time + ( 2.0 * randam - 1.0 ) );
  82364. float progressNeg = 1.0 - progress;
  82365. float ease = quadraticIn( progress );
  82366. float influence = sin( PI * ease );
  82367. //vec3 newPosition = position * vec3( 1.0, 1.0 , ease);
  82368. vec3 newPosition = position;
  82369. newPosition.z = (newPosition.z - centerHeight) * ease + centerHeight;
  82370. gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
  82371. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  82372. vOpacity = min( influence * 4.0, 1.0 ) * progressNeg;
  82373. vSprite = sprite;
  82374. //heightRatio = (newPosition.z - centerHeight) / fireHeight ;
  82375. }
  82376. `;
  82377. const fragmentShader = `
  82378. uniform vec3 color;
  82379. uniform sampler2D u_sampler;
  82380. varying float vSprite;
  82381. varying float vOpacity;
  82382. //varying float heightRatio;
  82383. void main()
  82384. {
  82385. vec2 texCoord = vec2(gl_PointCoord.x * 0.25 + vSprite, gl_PointCoord.y);
  82386. gl_FragColor = vec4( texture2D( u_sampler, texCoord ).xyz * color * vOpacity, 1.0 );
  82387. }
  82388. `;
  82389. // import { vertexShader, fragmentShader } from './shaders'
  82390. let ONE_SPRITE_ROW_LENGTH = 0.25; //对应着色器的0.25
  82391. let texture;
  82392. const getTexture = ()=>{
  82393. if(!texture){
  82394. texture = new TextureLoader().load( Potree.resourcePath+'/textures/fire.png');
  82395. }
  82396. return texture
  82397. };
  82398. const boxGeo = new BoxBufferGeometry(1,1,1,1);
  82399. const boxMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82400. class FireParticle extends Points{
  82401. constructor (prop) {
  82402. super();
  82403. for ( var key in prop ){
  82404. this[key] = prop[key];
  82405. }
  82406. this.strength = this.strength || 1;
  82407. this.radius = prop.radius || 1;
  82408. this.height = prop.height || 5;
  82409. this.computeParams();
  82410. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82411. if(this.color == void 0) this.color = 0xff3200;
  82412. this.createMaterial( ); //小蓝火:0x00338f
  82413. //---?:
  82414. this.velocity = new Vector3();
  82415. this.acceleration = new Vector3();
  82416. this.angle = 0;
  82417. this.angleVelocity = 0;
  82418. this.angleAcceleration = 0;
  82419. this.size = 16;
  82420. this.opacity = 1;
  82421. this.age = 0;
  82422. this.alive = 0;
  82423. this.sizeTween = null;
  82424. this.colorTween = null;
  82425. this.opacityTween = null;
  82426. this.setSize({viewport:viewer.mainViewport});
  82427. this.setFov(viewer.fov);
  82428. let setSize = (e)=>{
  82429. if(e.viewport.name != "MainView")return
  82430. this.setSize(e);
  82431. };
  82432. let setFov = (e)=>{
  82433. this.setFov(e.fov);
  82434. };
  82435. viewer.addEventListener('resize',setSize);
  82436. viewer.addEventListener('fov_changed',setFov);
  82437. this.addEventListener('dispose',()=>{
  82438. viewer.removeEventListener('resize',setSize);
  82439. viewer.removeEventListener('fov_changed',setFov);
  82440. });
  82441. }
  82442. computeParams(){
  82443. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82444. const minSize = 0.3, maxSize = 3, minRadiusBound = 0.3, maxRadiusBound = 10;
  82445. this.size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius, minRadiusBound, maxRadiusBound);
  82446. //console.log('fire material particle size:', size )
  82447. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height ) * this.radius / (this.size * this.size) * 25 );
  82448. //console.log('fire particleCount',this.particleCount)
  82449. }
  82450. getPointsForBound(){
  82451. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82452. }
  82453. getBound(points){ // points为生成点(圆心)
  82454. this.boundPoints = [];
  82455. let boundingBox = new Box3();
  82456. let margin = this.size * 0.13 + 0.3;
  82457. points.forEach(bottom=>{
  82458. let top = bottom.clone();
  82459. top.z += this.height;
  82460. boundingBox.expandByPoint(bottom);
  82461. boundingBox.expandByPoint(top);
  82462. this.boundPoints.push(bottom,top);
  82463. });
  82464. let xyExpand = this.radius+margin;
  82465. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,margin));
  82466. this.boundingBox = boundingBox;
  82467. /* if(!this.debugBox){
  82468. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82469. this.add(this.debugBox)
  82470. }
  82471. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82472. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82473. }
  82474. createGeometry( radius, height, particleCount){
  82475. let geometry = new BufferGeometry();
  82476. let count , points;
  82477. if(this.positions.length>1){
  82478. const spaceDis = 0.2;//间隔距离
  82479. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82480. //console.log('count', count)
  82481. points = this.curve.getSpacedPoints( count ); //得到的数量会比count多一个
  82482. count = points.length;
  82483. //得到的点不太均匀,两端容易点少。
  82484. this.getBound(points);
  82485. }else {
  82486. this.getBound(this.positions);
  82487. }
  82488. var position = new Float32Array(particleCount * 3);
  82489. var randam = new Float32Array(particleCount);
  82490. var sprite = new Float32Array(particleCount);
  82491. var centerHeight = new Float32Array(particleCount);
  82492. for (var i = 0; i < particleCount; i++) {
  82493. var center = new Vector3().copy(this.positions.length>1 ? points[Math.floor(i/particleCount * count)] : this.positions[0]);
  82494. centerHeight[i] = center.z;
  82495. if (i === 0) {
  82496. // to avoid going out of Frustum
  82497. position[i * 3 + 0] = center.x;
  82498. position[i * 3 + 1] = center.y;
  82499. position[i * 3 + 2] = center.z;
  82500. }else {
  82501. var r = Math.sqrt(Math.random()) * radius;
  82502. var angle = Math.random() * 2 * Math.PI;
  82503. position[i * 3 + 0] = center.x + Math.cos(angle) * r;
  82504. position[i * 3 + 1] = center.y + Math.sin(angle) * r;
  82505. position[i * 3 + 2] = center.z + (radius - r) / radius * height/2 + height/2; //不太明白这句为什么能达到height高度
  82506. sprite[i] = 0.25 * (Math.random() * 4 | 0);
  82507. randam[i] = Math.random();
  82508. //center在底部
  82509. }
  82510. }
  82511. geometry.setAttribute('centerHeight', new BufferAttribute(centerHeight, 1));
  82512. geometry.setAttribute('position', new BufferAttribute(position, 3));
  82513. geometry.setAttribute('randam', new BufferAttribute(randam, 1));
  82514. geometry.setAttribute('sprite', new BufferAttribute(sprite, 1));
  82515. return geometry;
  82516. }
  82517. updateGeometry(){
  82518. this.computeParams();
  82519. this.geometry.dispose();
  82520. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82521. this.material.uniforms.size.value = this.size;
  82522. }
  82523. createMaterial(){
  82524. const material = new ShaderMaterial( {
  82525. uniforms:{
  82526. color: { type: "c", value: new Color(this.color) },
  82527. size: { type: "f", value: this.size},
  82528. u_sampler: { type: "t", value: getTexture() },
  82529. time: { type: "f", value: 0.0 },
  82530. heightOfNearPlane: { type: "f", value:0}, //相对far ,以确保画面缩放时点的大小也会缩放
  82531. height :{ type: "f", value:this.height} ,
  82532. },
  82533. vertexShader,
  82534. fragmentShader,
  82535. blending: AdditiveBlending, //加法融合模式 glBlendFunc(GL_ONE, GL_ONE)
  82536. depthTest: true,
  82537. depthWrite: false,
  82538. transparent: true
  82539. } );
  82540. this.material = material;
  82541. this.setPerspective(this.fov, this.screenHeight);
  82542. }
  82543. setSize(e){
  82544. let viewport = e.viewport;
  82545. this.screenHeight = viewport.resolution.y;
  82546. this.setPerspective(this.fov, this.screenHeight);
  82547. }
  82548. setFov(fov){
  82549. this.fov = fov;
  82550. this.setPerspective(this.fov, this.screenHeight);
  82551. }
  82552. setPerspective(fov, height){
  82553. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  82554. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  82555. this.material.uniforms.heightOfNearPlane.value = far;
  82556. }
  82557. update(delta){
  82558. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82559. return
  82560. }
  82561. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82562. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82563. //console.log('unvi')
  82564. return
  82565. }else {
  82566. viewer.updateVisible(this,'isInsideFrustum', true );
  82567. }
  82568. delta *= 1;//更改速度
  82569. this.material.uniforms.time.value = (this.material.uniforms.time.value + delta) % 1;
  82570. }
  82571. dispose(){
  82572. this.geometry.dispose();
  82573. this.material.dispose();
  82574. this.dispatchEvent('dispose');
  82575. }
  82576. }
  82577. class Tween {
  82578. constructor(times, values) {
  82579. this.times = times || [];
  82580. this.values = values || [];
  82581. }
  82582. lerp(t) {
  82583. if(this.times.length == 0) return
  82584. let i = 0, n = this.times.length;
  82585. while(i < n && t > this.times[i]) i++;
  82586. if(i == 0) return this.values[0]
  82587. if(i == n) return this.values[n-1]
  82588. const ratio = (t - this.times[i-1]) / (this.times[i] - this.times[i-1]);
  82589. if(this.values[0] instanceof Vector3) {
  82590. return this.values[i-1].clone().lerp(this.values[i], ratio)
  82591. } else {
  82592. return this.values[i-1] + ratio * (this.values[i] - this.values[i-1])
  82593. }
  82594. }
  82595. clone () {
  82596. return Common.CloneClassObject(this)
  82597. }
  82598. }
  82599. class Particle$1{
  82600. constructor(prop={}){
  82601. this.position = new Vector3();
  82602. this.velocity = new Vector3(); // units per second
  82603. this.angle = 0;
  82604. this.angleVelocity = 0; // degrees per second
  82605. this.angleAcceleration = 0; // degrees per second, per second
  82606. this.size = 16.0;
  82607. this.color = new Color();
  82608. this.opacity = 1.0;
  82609. this.age = 0;
  82610. this.alive = 0; // use float instead of boolean for shader purposes
  82611. this.lastChangeVage = 0; //add
  82612. this.sizeTween = prop.sizeTween || new Tween( [0, 1], [32, 128] );
  82613. this.opacityTween = prop.opacityTween || new Tween( [0.8, 2], [0.5, 0] );
  82614. this.colorTween = prop.colorTween || new Tween( [0.4, 1], [ new Vector3(0,0,0.2), new Vector3(0, 0, 0.5) ] );
  82615. }
  82616. update(dt)
  82617. {
  82618. this.position.add(this.velocity.clone().multiplyScalar(dt));
  82619. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  82620. // convert from degrees to radians: 0.01745329251 = Math.PI/180
  82621. this.angle += this.angleVelocity * 0.01745329251 * dt;
  82622. this.angleVelocity += this.angleAcceleration * 0.01745329251 * dt;
  82623. this.age += dt;
  82624. // if the tween for a given attribute is nonempty,
  82625. // then use it to update the attribute's value
  82626. if ( this.sizeTween.times.length > 0 )
  82627. this.size = this.sizeTween.lerp( this.age/this.deathAge );
  82628. if ( this.colorTween.times.length > 0 )
  82629. {
  82630. var colorHSL = this.colorTween.lerp( this.age/this.deathAge );
  82631. this.color = new Color().setHSL( colorHSL.x, colorHSL.y, colorHSL.z );
  82632. }
  82633. if ( this.opacityTween.times.length > 0 )
  82634. {
  82635. this.opacity = this.opacityTween.lerp( this.age/this.deathAge);
  82636. }
  82637. }
  82638. }
  82639. const vertexShader$1 = `
  82640. attribute vec3 customColor;
  82641. attribute float customOpacity;
  82642. attribute float customSize;
  82643. attribute float customAngle;
  82644. attribute float customVisible;
  82645. uniform float heightOfNearPlane;
  82646. varying vec4 vColor;
  82647. varying float vAngle;
  82648. void main()
  82649. {
  82650. if ( customVisible > 0.5 )
  82651. vColor = vec4( customColor, customOpacity );
  82652. else
  82653. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  82654. vAngle = customAngle;
  82655. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  82656. //gl_PointSize = customSize * ( 300.0 / length( mvPosition.xyz ) );
  82657. gl_Position = projectionMatrix * mvPosition;
  82658. gl_PointSize = ( heightOfNearPlane * customSize ) / gl_Position.w;
  82659. }
  82660. `;
  82661. const fragmentShader$1 = `
  82662. uniform sampler2D u_sampler;
  82663. varying vec4 vColor;
  82664. varying float vAngle;
  82665. void main()
  82666. {
  82667. gl_FragColor = vColor;
  82668. float c = cos(vAngle);
  82669. float s = sin(vAngle);
  82670. 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);
  82671. vec4 rotatedTexture = texture2D( u_sampler, rotatedUV );
  82672. gl_FragColor = gl_FragColor * rotatedTexture;
  82673. }
  82674. `;
  82675. const Type = Object.freeze({ "CUBE":1, "SPHERE":2 });
  82676. let particleTexture;
  82677. const getTexture$1 = ()=>{
  82678. if(!particleTexture){
  82679. particleTexture = new TextureLoader().load( Potree.resourcePath+'/textures/smokeparticle.png');
  82680. }
  82681. return particleTexture
  82682. };
  82683. const boxGeo$1 = new BoxBufferGeometry(1,1,1,1);
  82684. const boxMat$1 = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82685. const defaults =
  82686. {
  82687. positions: [],
  82688. positionStyle : "sphere",
  82689. positionBase : new Vector3( 0, 0, 0 ),
  82690. positionSpread : new Vector3( 1, 1, 0), //cube
  82691. radius : 1, // sphere
  82692. velocityStyle : 'cube',
  82693. velocityBase : new Vector3( 0, 0, 0.5), // cube 基础速度
  82694. velocitySpread : new Vector3( 1, 1, 0.3),
  82695. accelerationBase : 0.3, //基础加速度
  82696. accelerationSpread : 0.6,
  82697. //没使用
  82698. speedBase : 0.1, //sphere
  82699. speedSpread : 0.5,
  82700. angleBase : 0,
  82701. angleSpread : 360,
  82702. angleVelocityBase : 1,
  82703. angleVelocitySpread : 30,
  82704. angleAccelerationBase : 1,
  82705. angleAccelerationSpread : 5,
  82706. sizeBase : 0,
  82707. sizeSpread : 0,
  82708. sizeTween : [[0, 0.3, 1], [0.3, 1.4, 6 ]],
  82709. colorBase : new Vector3(0.0, 1.0, 0.5),
  82710. colorSpread : new Vector3(0.0, 0.0, 0.0),
  82711. colorTween : new Tween( [0.2, 1], [ new Vector3(0,0,0.4), new Vector3(0, 0, 0.1) ] ),
  82712. opacityBase : 0.1,//1.0,
  82713. opacitySpread : 0.2,
  82714. opacityTween :[ [0, 0.1, 0.9, 1], [0.1, 0.4 , 0.03, 0 ] ],
  82715. //particlesPerSecond : 20,
  82716. strength : 1,
  82717. particleDeathAge : 3, //从底下升起后能持续的时间
  82718. //emitterDeathAge : 60 // time (seconds) at which to stop creating particles.
  82719. height : 3,
  82720. };
  82721. const debugSphere = new Mesh(new SphereBufferGeometry(0.03, 5,5), new MeshBasicMaterial({color:'white',depthTest:false}));
  82722. class SmokeParticle extends Points{
  82723. constructor(prop={}) {
  82724. super();
  82725. this.blendStyle = NormalBlending; // false;
  82726. this.emitterAge = 0.0;
  82727. //this.emitterAlive = true;
  82728. prop = $.extend({}, defaults, prop);
  82729. for ( var key in prop ){
  82730. let value = prop[key];
  82731. if(value instanceof Array && value[0] instanceof Array ) this[ key ] = new Tween(...value);
  82732. else if(value instanceof Vector3 || value instanceof Color){
  82733. this[ key ] = value.clone();
  82734. }else {
  82735. this[ key ] = value;
  82736. }
  82737. }
  82738. this.defaultSizeTween = this.sizeTween.clone();
  82739. this.defaultOpacityTween = this.opacityTween.clone();
  82740. this.geometry = new BufferGeometry();
  82741. this.computeParams();
  82742. this.createMaterial();
  82743. this.createGeometry();
  82744. this.dynamic = true;
  82745. this.sortParticles = true;
  82746. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  82747. prop.position && this.position.copy(prop.position);
  82748. //---------------------------------------
  82749. this.setSize({viewport:viewer.mainViewport});
  82750. this.setFov(viewer.fov);
  82751. let setSize = (e)=>{
  82752. if(e.viewport.name != "MainView")return
  82753. this.setSize(e);
  82754. };
  82755. let setFov = (e)=>{
  82756. this.setFov(e.fov);
  82757. };
  82758. /* let reStart = (e)=>{
  82759. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  82760. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  82761. //console.log('归零')
  82762. //this.reStart()
  82763. },1)
  82764. }
  82765. } */
  82766. viewer.addEventListener('resize',setSize);
  82767. viewer.addEventListener('fov_changed',setFov);
  82768. //viewer.addEventListener('pageVisible', reStart)
  82769. this.addEventListener('dispose',()=>{
  82770. viewer.removeEventListener('resize',setSize);
  82771. viewer.removeEventListener('fov_changed',setFov);
  82772. //viewer.removeEventListener('pageVisible', reStart)
  82773. });
  82774. }
  82775. computeParams(){
  82776. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82777. //注意:烟最低高度一米, 0<strength<1
  82778. if(this.positionStyle == 'cube'){
  82779. this.positionSpread.set(this.radius,this.radius,0);
  82780. }
  82781. this.velocityBase.set(0,0, (this.height - 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge) / this.particleDeathAge );
  82782. //let height = this.velocityBase.z * this.particleDeathAge + 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge;//s = V0 * t + 0.5 * a * t*t ;
  82783. this.velocityBase.z = Math.max(0,this.velocityBase.z);
  82784. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height * this.radius ) );
  82785. this.particleCount = Math.max(5,this.particleCount);
  82786. {
  82787. const minSize = 1, maxSize = 2, minBound = 0.01, maxBound = 1;
  82788. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82789. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  82790. }
  82791. {
  82792. const minSize = 1 , maxSize = 1.5, minBound = 0.01, maxBound = 1;
  82793. let opac = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82794. this.opacityTween.values = this.defaultOpacityTween.values.map(e=> e*opac );
  82795. }
  82796. //console.log('smoke particleCount',this.particleCount)
  82797. }
  82798. reStart(){
  82799. this.emitterAge = 0;
  82800. this.createGeometry();
  82801. }
  82802. updateGeometry(){
  82803. this.computeParams();
  82804. this.reStart();
  82805. }
  82806. createParticle(center)
  82807. {
  82808. var particle = new Particle$1({
  82809. sizeTween : this.sizeTween,
  82810. opacityTween : this.opacityTween,
  82811. colorTween : this.colorTween,
  82812. });
  82813. particle.deathAge = this.particleDeathAge;
  82814. particle.center = center;
  82815. if (this.positionStyle == 'cube')
  82816. particle.position = this.randomVector3( this.positionBase, this.positionSpread );
  82817. if (this.positionStyle == 'sphere')
  82818. {
  82819. /* var z = 2 * Math.random() - 1
  82820. var t = Math.PI * 2 * Math.random();
  82821. var r = Math.sqrt( 1 - z*z ) ;
  82822. var vec3 = new THREE.Vector3( r * Math.cos(t), r * Math.sin(t), z );
  82823. particle.position = new THREE.Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82824. */
  82825. //怎么改半径
  82826. let y = 2 * Math.random() - 1;
  82827. let t = Math.PI * 2 * Math.random();
  82828. let r = Math.sqrt( 1 - y*y ) ; //因为 r*r = 1-y*y = x*x + z*z = r*r(cos^2 + sin^2 );
  82829. let lowDownRatio = 0.2; //压低近平面
  82830. let vec3 = new Vector3( r * Math.cos(t), y, Math.abs(r * Math.sin(t) ) * lowDownRatio);
  82831. particle.position = new Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82832. }
  82833. particle.position.add(center);//add
  82834. if ( this.velocityStyle == 'cube' )
  82835. {
  82836. particle.velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82837. }
  82838. if ( this.velocityStyle == 'sphere' )
  82839. {
  82840. //var direction = particle.position.clone()
  82841. var direction = new Vector3(0,0,1); //烟应该都是向上的
  82842. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82843. particle.velocity = direction.normalize().multiplyScalar( speed );
  82844. }
  82845. particle.acceleration = this.randomValue( this.accelerationBase, this.accelerationSpread );
  82846. particle.angle = this.randomValue( this.angleBase, this.angleSpread );
  82847. particle.angleVelocity = this.randomValue( this.angleVelocityBase, this.angleVelocitySpread );
  82848. particle.angleAcceleration = this.randomValue( this.angleAccelerationBase, this.angleAccelerationSpread );
  82849. particle.size = this.randomValue( this.sizeBase, this.sizeSpread );
  82850. var color = this.randomVector3( this.colorBase, this.colorSpread );
  82851. particle.color = new Color().setHSL( color.x, color.y, color.z );
  82852. particle.opacity = this.randomValue( this.opacityBase, this.opacitySpread );
  82853. particle.age = 0;
  82854. particle.alive = 0; // particles initialize as inactive
  82855. return particle;
  82856. }
  82857. getPointsForBound(){
  82858. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82859. }
  82860. getBound(points){ // points为生成点(圆心)
  82861. this.boundPoints = [];
  82862. let boundingBox = new Box3();
  82863. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  82864. let margin0 = maxSize * 0.11;
  82865. let margin1 = margin0 + 0.5 ;//保守估计还会飘出这么多距离吧: size + 飘动
  82866. points.forEach(bottom=>{
  82867. let top = bottom.clone();
  82868. top.z += this.height;
  82869. boundingBox.expandByPoint(bottom);
  82870. boundingBox.expandByPoint(top);
  82871. this.boundPoints.push(bottom,top);
  82872. });
  82873. let xyExpand = this.radius+margin1;
  82874. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,0));
  82875. boundingBox.min.z -= margin0;
  82876. boundingBox.max.z += margin1;
  82877. this.boundingBox = boundingBox;
  82878. /* if(!this.debugBox){
  82879. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82880. this.add(this.debugBox)
  82881. }
  82882. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82883. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82884. }
  82885. createGeometry(){
  82886. this.particleArray = [];
  82887. const positions = [];
  82888. const colors = [];
  82889. const alives = [];
  82890. const opacitys = [];
  82891. const sizes = [];
  82892. const angles = [];
  82893. let count, points;
  82894. if(this.positions.length>1){
  82895. const spaceDis = 0.6;//间隔距离
  82896. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82897. points = this.curve.getSpacedPoints( count );
  82898. count = points.length;
  82899. /* points.forEach(e=> {
  82900. var sphere = debugSphere.clone();
  82901. sphere.position.copy(e)
  82902. viewer.scene.scene.add(sphere)
  82903. }) */
  82904. let haventGetPoints = points.slice();
  82905. var getRanPoints = function(i){
  82906. var a = Math.random();
  82907. let choseIndex = Math.floor(haventGetPoints.length * a);
  82908. var point = haventGetPoints[choseIndex];
  82909. if(haventGetPoints.length == 1){
  82910. haventGetPoints = points.slice();
  82911. }else {
  82912. haventGetPoints.splice(choseIndex, 1);
  82913. }
  82914. return point
  82915. };
  82916. this.getBound(points);
  82917. }else {
  82918. this.getBound(this.positions);
  82919. }
  82920. for (var i = 0; i < this.particleCount; i++)
  82921. {
  82922. var center = new Vector3().copy(this.positions.length>1 ? getRanPoints(i) : this.positions[0]);
  82923. //var center = new THREE.Vector3().copy(this.positions.length>1 ? points[Math.floor(i/this.particleCount * count)] : this.positions[0])
  82924. // remove duplicate code somehow, here and in update function below.
  82925. this.particleArray[i] = this.createParticle(center);
  82926. positions[3*i] = this.particleArray[i].position.x;
  82927. positions[3*i+1] = this.particleArray[i].position.y;
  82928. positions[3*i+2] = this.particleArray[i].position.z;
  82929. colors[3*i] = this.particleArray[i].color.r;
  82930. colors[3*i+1] = this.particleArray[i].color.g;
  82931. colors[3*i+2] = this.particleArray[i].color.b;
  82932. alives[i] = this.particleArray[i].alive;
  82933. opacitys[i] = this.particleArray[i].opacity;
  82934. sizes[i] = this.particleArray[i].size;
  82935. angles[i] = this.particleArray[i].angle;
  82936. }
  82937. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ));
  82938. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82939. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82940. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82941. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82942. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82943. }
  82944. createMaterial(){
  82945. this.material = new ShaderMaterial(
  82946. {
  82947. uniforms:
  82948. {
  82949. u_sampler: { type: "t", value: getTexture$1() },
  82950. heightOfNearPlane: { type: "f", value:0} //相对far ,以确保画面缩放时点的大小也会缩放
  82951. },
  82952. vertexShader: vertexShader$1,vertexShader: vertexShader$1,
  82953. fragmentShader: fragmentShader$1,
  82954. transparent: true,
  82955. alphaTest: 0.5, // if having transparency issues, try including: alphaTest: 0.5,
  82956. blending: this.blendStyle,
  82957. depthTest: this.blendStyle != NormalBlending
  82958. });
  82959. this.setPerspective(this.fov, this.screenHeight);
  82960. }
  82961. update(dt){
  82962. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82963. return
  82964. }
  82965. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82966. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82967. //console.log('unvi')
  82968. return
  82969. }else {
  82970. viewer.updateVisible(this,'isInsideFrustum', true );
  82971. }
  82972. if(dt > 1){
  82973. console.log('update dt>1', dt);
  82974. }
  82975. //dt *= 0.5;
  82976. const recycleIndices = [];
  82977. const recycleAges = [];
  82978. const positions = [];
  82979. const colors = [];
  82980. const alives = [];
  82981. const opacitys = [];
  82982. const sizes = [];
  82983. const angles = [];
  82984. for (var i = 0; i < this.particleCount; i++)
  82985. {
  82986. if ( this.particleArray[i].alive )
  82987. {
  82988. if ( this.velocityStyle == 'cube' )
  82989. { //一定几率改变下方向
  82990. let ratio = Math.random();
  82991. if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*ratio ){
  82992. this.particleArray[i].velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82993. this.particleArray[i].lastChangeVage = this.particleArray[i].age;
  82994. }
  82995. }else {
  82996. /* if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*0.3 ){
  82997. if( Math.random()>0.1){//一定几率改变下方向
  82998. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82999. this.particleArray[i].velocity = this.randomVector3( new THREE.Vector3, new THREE.Vector3(1,1,1) );
  83000. this.particleArray[i].velocity.normalize().multiplyScalar( speed );
  83001. }
  83002. this.particleArray[i].lastChangeVage = this.particleArray[i].age
  83003. } */
  83004. }
  83005. this.particleArray[i].update(dt);
  83006. // check if particle should expire
  83007. // could also use: death by size<0 or alpha<0.
  83008. if ( this.particleArray[i].age > this.particleDeathAge )
  83009. {
  83010. this.particleArray[i].alive = 0.0;
  83011. recycleIndices.push(i);
  83012. recycleAges.push((this.particleArray[i].age - this.particleDeathAge)%(this.particleDeathAge ));
  83013. }
  83014. // update particle properties in shader
  83015. positions[3*i] = this.particleArray[i].position.x;
  83016. positions[3*i+1] = this.particleArray[i].position.y;
  83017. positions[3*i+2] = this.particleArray[i].position.z;
  83018. colors[3*i] = this.particleArray[i].color.r;
  83019. colors[3*i+1] = this.particleArray[i].color.g;
  83020. colors[3*i+2] = this.particleArray[i].color.b;
  83021. alives[i] = this.particleArray[i].alive;
  83022. opacitys[i] = this.particleArray[i].opacity;
  83023. sizes[i] = this.particleArray[i].size;
  83024. angles[i] = this.particleArray[i].angle;
  83025. }
  83026. }
  83027. // check if particle emitter is still running
  83028. //if ( !this.emitterAlive ) return;
  83029. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  83030. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  83031. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  83032. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  83033. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  83034. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  83035. this.geometry.attributes.customColor.needsUpdate = true;
  83036. this.geometry.attributes.customVisible.needsUpdate = true;
  83037. this.geometry.attributes.customOpacity.needsUpdate = true;
  83038. this.geometry.attributes.customSize.needsUpdate = true;
  83039. this.geometry.attributes.customAngle.needsUpdate = true;
  83040. // if no particles have died yet, then there are still particles to activate
  83041. if ( this.emitterAge < this.particleDeathAge ) //开始时一个个放出来
  83042. {
  83043. let particlesPerSecond = this.particleCount / this.particleDeathAge;
  83044. // determine indices of particles to activate
  83045. var startIndex = Math.round( particlesPerSecond * (this.emitterAge + 0) );
  83046. var endIndex = Math.round( particlesPerSecond * (this.emitterAge + dt) );
  83047. if ( endIndex > this.particleCount )
  83048. endIndex = this.particleCount;
  83049. for (var i = startIndex; i < endIndex; i++)
  83050. this.particleArray[i].alive = 1.0;
  83051. }
  83052. // if any particles have died while the emitter is still running, we imediately recycle them
  83053. for (var j = 0; j < recycleIndices.length; j++)
  83054. {
  83055. var i = recycleIndices[j];
  83056. this.particleArray[i] = this.createParticle(this.particleArray[i].center);
  83057. this.particleArray[i].alive = 1.0; // activate right away
  83058. this.particleArray[i].age = recycleAges[j];
  83059. positions[3*i] = this.particleArray[i].position.x;
  83060. positions[3*i+1] = this.particleArray[i].position.y;
  83061. positions[3*i+2] = this.particleArray[i].position.z;
  83062. }
  83063. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  83064. this.geometry.attributes.position.needsUpdate = true;
  83065. // stop emitter?
  83066. this.emitterAge += dt;
  83067. //if ( this.emitterAge > this.emitterDeathAge ) this.emitterAlive = false;
  83068. }
  83069. randomValue(base, spread)
  83070. {
  83071. //return base + spread * (Math.random() - 0.5);
  83072. let p = Math.random();
  83073. return base * p + spread * (1-p)
  83074. }
  83075. randomVector3(base, spread)
  83076. {
  83077. var rand3 = new Vector3( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 );
  83078. return new Vector3().addVectors( base, new Vector3().multiplyVectors( spread, rand3 ) );
  83079. }
  83080. setSize(e){
  83081. let viewport = e.viewport;
  83082. this.screenHeight = viewport.resolution.y;
  83083. this.setPerspective(this.fov, this.screenHeight);
  83084. }
  83085. setFov(fov){
  83086. this.fov = fov;
  83087. this.setPerspective(this.fov, this.screenHeight);
  83088. }
  83089. setPerspective(fov, height){
  83090. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  83091. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  83092. this.material.uniforms.heightOfNearPlane.value = far;
  83093. }
  83094. dispose(){
  83095. this.geometry.dispose();
  83096. this.material.dispose();
  83097. this.dispatchEvent('dispose');
  83098. }
  83099. }
  83100. /*
  83101. 改进:如果有必要
  83102. 根据curve中分成的点,分成多个簇,每个簇掌管该部分的可见性和particle的数量。
  83103. 在camera_changed时根据远近修改每个簇的particle的数量,当然不会大于初始创建的个数。多出的随机隐藏。
  83104. */
  83105. const vertexShader$2 = `
  83106. attribute vec3 color;
  83107. attribute float size;
  83108. attribute float angle;
  83109. attribute float opacity;
  83110. attribute float visible;
  83111. varying vec4 vColor;
  83112. varying float vAngle;
  83113. uniform float heightOfNearPlane;
  83114. void main() {
  83115. if(visible > 0.5) {
  83116. vColor = vec4(color, opacity);
  83117. } else {
  83118. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  83119. }
  83120. vAngle = angle;
  83121. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
  83122. gl_Position = projectionMatrix * mvPosition;
  83123. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  83124. }
  83125. `;
  83126. const fragmentShader$2 = `
  83127. uniform sampler2D u_sampler;
  83128. varying vec4 vColor;
  83129. varying float vAngle;
  83130. void main() {
  83131. gl_FragColor = vColor;
  83132. float u = cos(vAngle);
  83133. float v = sin(vAngle);
  83134. vec2 uv = vec2(
  83135. u * (gl_PointCoord.x - 0.5) + v * (gl_PointCoord.y - 0.5) + 0.5,
  83136. u * (gl_PointCoord.y - 0.5) - v * (gl_PointCoord.x - 0.5) + 0.5
  83137. );
  83138. vec4 texture = texture2D(u_sampler, uv);
  83139. gl_FragColor = gl_FragColor * texture;
  83140. }
  83141. `;
  83142. // import { vertexShader, fragmentShader } from './shader'
  83143. const DEG2RAD = Math.PI / 180;
  83144. class Particle$2 {
  83145. constructor() {
  83146. this.position = new Vector3();
  83147. this.velocity = new Vector3();
  83148. this.angle = 0;
  83149. this.angleVelocity = 0;
  83150. this.angleAcceleration = 0;
  83151. this.size = 16;
  83152. this.color = new Color();
  83153. this.opacity = 1;
  83154. this.rebornCount = 0;//重生次数
  83155. this.age = 0;
  83156. this.alive = 0; //注意,一开始时是未出生的
  83157. this.deadAge = 0;//已死亡时间
  83158. this.sizeTween = null;
  83159. this.colorTween = null;
  83160. this.opacityTween = null;
  83161. }
  83162. update(dt) {
  83163. //s = s0 + (v0 + at) * t 或 lastS + delta(vt)
  83164. this.position.add(this.velocity.clone().multiplyScalar(dt));
  83165. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  83166. this.angle += this.angleVelocity * DEG2RAD * dt;
  83167. this.angleVelocity += this.angleAcceleration * DEG2RAD * dt;
  83168. this.age += dt;
  83169. if(this.sizeTween.times.length > 0) {
  83170. this.size = this.sizeTween.lerp(this.age/this.deathAge);
  83171. }
  83172. if(this.colorTween.times.length > 0) {
  83173. const colorHSL = this.colorTween.lerp(this.age/this.deathAge);
  83174. this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z);
  83175. }
  83176. if(this.opacityTween.times.length > 0) {
  83177. this.opacity = this.opacityTween.lerp(this.age/this.deathAge);
  83178. }
  83179. }
  83180. }
  83181. class Util {
  83182. constructor() {}
  83183. randomValue(min, max) {
  83184. //return min + max * (Math.random() - 0.5)
  83185. let p = Math.random();
  83186. return min * p + max * (1-p)
  83187. }
  83188. randomVector3(min, max) {
  83189. const rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
  83190. return new Vector3().addVectors(min, new Vector3().multiplyVectors(max, rand3))
  83191. }
  83192. }
  83193. const util$1 = new Util();
  83194. const Shape$1 = {
  83195. CUBE: 1,
  83196. SPHERE: 2
  83197. };
  83198. let particleTexture$1;
  83199. const getTexture$2 = ()=>{
  83200. if (!particleTexture$1) {
  83201. particleTexture$1 = new TextureLoader().load(Potree.resourcePath + '/textures/explode.png');
  83202. }
  83203. return particleTexture$1
  83204. };
  83205. const sphereGeo$1 = new SphereBufferGeometry(1, 10,4);
  83206. const sphereMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  83207. const defaults$1 = {
  83208. position: new Vector3(0,0,1),
  83209. positionShape: Shape$1.SPHERE,
  83210. positionRange: new Vector3(1,1,1),
  83211. //cube
  83212. radius: 1.3,
  83213. //sphere
  83214. velocityShape: Shape$1.SPHERE,
  83215. velocity: new Vector3(0,0,2),
  83216. //cube
  83217. velocityRange: new Vector3(0,0,3),
  83218. //sphere
  83219. speed: 0.4,
  83220. speedRange: 1,
  83221. size: 0.4,
  83222. sizeRange: 2,
  83223. //sizeTween: new Tween( [0, 0.05, 0.3, 0.45], [0, 1, 3, 0.1] ),
  83224. sizeTween: [[0, 0.04, 0.2, 1],[0.1, 1, 6, 8]] ,
  83225. color: new Vector3(1.0,1.0,1.0),
  83226. colorRange: new Vector3(0,0,0),
  83227. colorTween: new Tween(),
  83228. opacity: 1.0,
  83229. opacityRange: 0.0,
  83230. opacityTween: new Tween([0, 0.06, 0.3, 0.8, 1],[0, 1, 0.3, 0.05, 0]),
  83231. blendMode: AdditiveBlending,
  83232. acceleration: 0.5,
  83233. accelerationRange: 0,
  83234. angle: 0,
  83235. angleRange: 0,
  83236. angleVelocity: 0,
  83237. angleVelocityRange: 0,
  83238. angleAcceleration: 0,
  83239. angleAccelerationRange: 0,
  83240. strength:1,
  83241. //particlesPerSecond: 8,
  83242. particleDeathAge: 0.7 ,
  83243. recycleTimes : 3 , //每个粒子在一次爆炸后循环次数,循环完毕进入particleSpaceTime,等待下一次爆炸.
  83244. //爆炸时长: particleDeathAge * (recycleTimes+1)
  83245. particleSpaceTime: 3, //间隔
  83246. };
  83247. class ExplodeParticle extends Points {
  83248. constructor(params) {
  83249. super();
  83250. this.age = 0;
  83251. this.alive = true;
  83252. //this.deathAge = 60
  83253. this.loop = true;
  83254. this.blendMode = NormalBlending;
  83255. this.setParameters(params);
  83256. this.createParticles();
  83257. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  83258. //------------------------------------
  83259. this.setSize({viewport:viewer.mainViewport});
  83260. this.setFov(viewer.fov);
  83261. let setSize = (e)=>{
  83262. if(e.viewport.name != "MainView")return
  83263. this.setSize(e);
  83264. };
  83265. let setFov = (e)=>{
  83266. this.setFov(e.fov);
  83267. };
  83268. /* let reStart = (e)=>{
  83269. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  83270. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  83271. //console.log('归零')
  83272. //this.reStart()
  83273. },1)
  83274. }
  83275. } */
  83276. viewer.addEventListener('resize',setSize);
  83277. viewer.addEventListener('fov_changed',setFov);
  83278. //viewer.addEventListener('pageVisible', reStart)
  83279. this.addEventListener('dispose',()=>{
  83280. viewer.removeEventListener('resize',setSize);
  83281. viewer.removeEventListener('fov_changed',setFov);
  83282. //viewer.removeEventListener('pageVisible', reStart)
  83283. });
  83284. }
  83285. computeParams(){
  83286. if(this.curve){
  83287. this.position.copy(this.curve.points[0]);
  83288. }
  83289. const minSize = 0.8, maxSize = 10, minRadiusBound = 0.2, maxRadiusBound = 20;
  83290. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius*this.strength , minRadiusBound, maxRadiusBound);
  83291. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  83292. this.particleCount = Math.ceil( this.strength * this.radius * 5 /* * this.radius * this.radius */ );
  83293. this.speed = defaults$1.speed * this.radius;
  83294. this.speedRange = defaults$1.speedRange * this.radius;
  83295. console.log(this.particleCount);
  83296. {
  83297. this.boundPoints = [];
  83298. this.boundPoints.push(this.position.clone());
  83299. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  83300. let margin = maxSize * 0.35 + 0.5;
  83301. let scale = this.radius+margin;
  83302. let sphere = new Sphere(this.position, scale);//加上防止剪裁
  83303. this.boundingSphere = sphere; //虽然还是会有一些后续移动的会超出
  83304. this.boundingBox = new Box3().setFromCenterAndSize(this.position, new Vector3(scale*2,scale*2,scale*2));
  83305. /* if(!this.debugSphere){
  83306. this.debugSphere = new THREE.Mesh(sphereGeo, sphereMat)
  83307. this.add(this.debugSphere)
  83308. }
  83309. this.debugSphere.scale.set(scale,scale,scale) */
  83310. }
  83311. }
  83312. getPointsForBound(){
  83313. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  83314. }
  83315. reStart(){
  83316. this.age = 0;
  83317. this.createParticles();
  83318. }
  83319. setParameters(params) {
  83320. params = $.extend({}, defaults$1, params);
  83321. for (var key in params) {
  83322. let value = params[key];
  83323. if (key == 'position')
  83324. this.position.copy(value);
  83325. else if (value instanceof Array && value[0]instanceof Array){
  83326. this[key] = new Tween(...value);
  83327. }else if(value instanceof Vector3 || value instanceof Color){
  83328. this[ key ] = value.clone();
  83329. }else {
  83330. this[key] = value;
  83331. }
  83332. }
  83333. this.defaultSizeTween = this.sizeTween.clone();
  83334. //Object.assign(this, params)
  83335. this.particles = [];
  83336. this.age = 0.0;
  83337. this.alive = true;
  83338. this.geometry = new BufferGeometry();
  83339. this.computeParams();
  83340. this.material = new ShaderMaterial({
  83341. uniforms: {
  83342. u_sampler: {
  83343. value: this.texture || getTexture$2()
  83344. },
  83345. heightOfNearPlane: {
  83346. type: "f",
  83347. value: 0
  83348. }//相对far ,以确保画面缩放时点的大小也会缩放
  83349. },
  83350. vertexShader: vertexShader$2,
  83351. fragmentShader: fragmentShader$2,
  83352. transparent: true,
  83353. alphaTest: 0.5,
  83354. depthTest: this.blendMode == NormalBlending,
  83355. blending: this.blendMode
  83356. });
  83357. }
  83358. createParticles() {
  83359. this.particles = [];
  83360. const count = this.particleCount;
  83361. const positionArray = new Float32Array(count * 3);
  83362. const colorArray = new Float32Array(count * 3);
  83363. const sizeArray = new Float32Array(count);
  83364. const angleArray = new Float32Array(count);
  83365. const opacityArray = new Float32Array(count);
  83366. const visibleArray = new Float32Array(count);
  83367. for (let i = 0; i < count; i++) {
  83368. const particle = this.createParticle();
  83369. /* positionArray[i * 3] = particle.position.x
  83370. positionArray[i * 3 + 1] = particle.position.y
  83371. positionArray[i * 3 + 2] = particle.position.z
  83372. colorArray[i * 3] = particle.color.r
  83373. colorArray[i * 3 + 1] = particle.color.g
  83374. colorArray[i * 3 + 2] = particle.color.b
  83375. sizeArray[i] = particle.size
  83376. angleArray[i] = particle.angel
  83377. opacityArray[i] = particle.opacity
  83378. visibleArray[i] = particle.alive */
  83379. this.particles[i] = particle;
  83380. }
  83381. this.geometry.setAttribute('position', new BufferAttribute(positionArray,3));
  83382. this.geometry.setAttribute('color', new BufferAttribute(colorArray,3));
  83383. this.geometry.setAttribute('angle', new BufferAttribute(angleArray,1));
  83384. this.geometry.setAttribute('size', new BufferAttribute(sizeArray,1));
  83385. this.geometry.setAttribute('visible', new BufferAttribute(visibleArray,1));
  83386. this.geometry.setAttribute('opacity', new BufferAttribute(opacityArray,1));
  83387. }
  83388. createParticle() {
  83389. const particle = new Particle$2();
  83390. particle.sizeTween = this.sizeTween;
  83391. particle.colorTween = this.colorTween;
  83392. particle.opacityTween = this.opacityTween;
  83393. particle.deathAge = this.particleDeathAge;
  83394. if (this.positionShape == Shape$1.CUBE) {
  83395. particle.position = util$1.randomVector3(new Vector3, this.positionRange);
  83396. }
  83397. if (this.positionShape == Shape$1.SPHERE) {
  83398. /* const z = 2 * Math.random() - 1
  83399. const t = Math.PI * 2 * Math.random()
  83400. const r = Math.sqrt(1 - z*z)
  83401. const vec3 = new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), z)
  83402. particle.position = vec3.multiplyScalar(this.radius) */
  83403. const y = 2 * Math.random() - 1;
  83404. const t = Math.PI * 2 * Math.random();
  83405. const r = Math.sqrt(1 - y * y);
  83406. const vec3 = new Vector3(r * Math.cos(t),y,r * Math.sin(t));
  83407. particle.position = vec3.multiplyScalar(this.radius);
  83408. }
  83409. if (this.velocityShape == Shape$1.CUBE) {
  83410. particle.velocity = util$1.randomVector3(this.velocity, this.velocityRange);
  83411. }
  83412. if (this.velocityShape == Shape$1.SPHERE) {
  83413. const direction = new Vector3().addVectors(particle.position, new Vector3(0,0,this.radius*2));//向上升?
  83414. const speed = util$1.randomValue(this.speed, this.speedRange);
  83415. particle.velocity = direction.normalize().multiplyScalar(speed);
  83416. }
  83417. particle.acceleration = util$1.randomValue(this.acceleration, this.accelerationRange);
  83418. particle.angle = util$1.randomValue(this.angle, this.angleRange);
  83419. particle.angleVelocity = util$1.randomValue(this.angleVelocity, this.angleVelocityRange);
  83420. particle.angleAcceleration = util$1.randomValue(this.angleAcceleration, this.angleAccelerationRange);
  83421. particle.size = util$1.randomValue(this.size, this.sizeRange);
  83422. const color = util$1.randomVector3(this.color, this.colorRange);
  83423. particle.color = new Color().setHSL(color.x, color.y, color.z);
  83424. particle.opacity = util$1.randomValue(this.opacity, this.opacityRange);
  83425. return particle
  83426. }
  83427. update(dt) {
  83428. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  83429. return
  83430. }
  83431. if(this.delayStartTime>0){ // 爆炸延迟
  83432. return this.delayStartTime -= dt
  83433. }
  83434. if(!Potree.Utils.isInsideFrustum(this.boundingSphere, viewer.scene.getActiveCamera())){
  83435. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  83436. return
  83437. }else {
  83438. viewer.updateVisible(this,'isInsideFrustum', true );
  83439. }
  83440. //const timeRatio = 0.5
  83441. if(dt > 1){
  83442. console.log('update dt>1', dt);
  83443. }
  83444. //dt *= timeRatio
  83445. let particleDeathAge = this.particleDeathAge;/* * timeRatio */
  83446. let particleSpaceTime = this.particleSpaceTime; /* * timeRatio */
  83447. const recycleIndices = [];
  83448. const recycleAges = [];
  83449. const recycleRebornCount = [];
  83450. const positionArray = this.geometry.attributes.position.array;
  83451. const opacityArray = this.geometry.attributes.opacity.array;
  83452. const visibleArray = this.geometry.attributes.visible.array;
  83453. const colorArray = this.geometry.attributes.color.array;
  83454. const angleArray = this.geometry.attributes.angle.array;
  83455. const sizeArray = this.geometry.attributes.size.array;
  83456. for (let i = 0; i < this.particleCount; i++) {
  83457. const particle = this.particles[i];
  83458. if (particle.alive) {
  83459. particle.update(dt);
  83460. if (particle.age > particleDeathAge) {
  83461. particle.alive = 0.0;
  83462. if(particle.rebornCount >= this.recycleTimes){
  83463. particle.deadAge = particle.age - particleDeathAge; //已死亡时间
  83464. }else {//直接循环
  83465. recycleIndices.push(i);
  83466. recycleAges.push(/* ( */particle.age - particleDeathAge/* )%(this.particleDeathAge ) */);
  83467. recycleRebornCount.push(particle.rebornCount+1);
  83468. }
  83469. }
  83470. positionArray[i * 3] = particle.position.x;
  83471. positionArray[i * 3 + 1] = particle.position.y;
  83472. positionArray[i * 3 + 2] = particle.position.z;
  83473. colorArray[i * 3] = particle.color.r;
  83474. colorArray[i * 3 + 1] = particle.color.g;
  83475. colorArray[i * 3 + 2] = particle.color.b;
  83476. visibleArray[i] = particle.alive;
  83477. opacityArray[i] = particle.opacity;
  83478. angleArray[i] = particle.angle;
  83479. sizeArray[i] = particle.size;
  83480. }else {
  83481. if(particle.rebornCount >= this.recycleTimes){
  83482. if(particle.age > particleDeathAge) {//其他已经死亡的粒子的时间继续增加
  83483. particle.deadAge += dt;
  83484. }
  83485. }
  83486. }
  83487. if (particle.rebornCount >= this.recycleTimes && particle.age > particleDeathAge) {//已经死亡
  83488. if(particle.deadAge >= particleSpaceTime){//死亡时间超过设定的间隔时间后重启
  83489. recycleIndices.push(i);
  83490. let wholeTime = particleDeathAge * (this.recycleTimes+1) + particleSpaceTime;
  83491. recycleAges.push((particle.deadAge - particleSpaceTime)% wholeTime ); //剩余时间就是重生后的age
  83492. recycleRebornCount.push(0);
  83493. }
  83494. }
  83495. }
  83496. this.geometry.attributes.size.needsUpdate = true;
  83497. this.geometry.attributes.color.needsUpdate = true;
  83498. this.geometry.attributes.angle.needsUpdate = true;
  83499. this.geometry.attributes.visible.needsUpdate = true;
  83500. this.geometry.attributes.opacity.needsUpdate = true;
  83501. this.geometry.attributes.position.needsUpdate = true;
  83502. if (!this.alive)
  83503. return
  83504. if (this.age < particleDeathAge) {
  83505. let startIndex = Math.round(this.particleCount * (this.age + 0)/ particleDeathAge);
  83506. let endIndex = Math.round(this.particleCount * (this.age + dt)/ particleDeathAge);
  83507. if (endIndex > this.particleCount) {
  83508. endIndex = this.particleCount;
  83509. }
  83510. for (let i = startIndex; i < endIndex; i++) {
  83511. this.particles[i].alive = 1.0;
  83512. }
  83513. }
  83514. for (let j = 0; j < recycleIndices.length; j++) {
  83515. let i = recycleIndices[j];
  83516. this.particles[i] = this.createParticle();
  83517. this.particles[i].alive = 1.0; //出生
  83518. this.particles[i].age = recycleAges[j];
  83519. this.particles[i].rebornCount= recycleRebornCount[j];
  83520. /* if(this.particles[i].age < particleDeathAge){
  83521. positionArray[i * 3] = this.particles[i].position.x
  83522. positionArray[i * 3 + 1] = this.particles[i].position.y
  83523. positionArray[i * 3 + 2] = this.particles[i].position.z
  83524. visibleArray[i] = particle.alive?
  83525. } */
  83526. }
  83527. this.geometry.attributes.position.needsUpdate = true;
  83528. this.age += dt;
  83529. if (this.age > this.deathAge && !this.loop) {
  83530. this.alive = false;
  83531. }
  83532. }
  83533. setSize(e) {
  83534. let viewport = e.viewport;
  83535. this.screenHeight = viewport.resolution.y;
  83536. this.setPerspective(this.fov, this.screenHeight);
  83537. }
  83538. setFov(fov) {
  83539. this.fov = fov;
  83540. this.setPerspective(this.fov, this.screenHeight);
  83541. }
  83542. setPerspective(fov, height) {
  83543. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  83544. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  83545. this.material.uniforms.heightOfNearPlane.value = far;
  83546. }
  83547. updateGeometry(){
  83548. this.computeParams();
  83549. this.reStart();
  83550. }
  83551. dispose(){
  83552. this.geometry.dispose();
  83553. this.material.dispose();
  83554. this.dispatchEvent('dispose');
  83555. }
  83556. }
  83557. const colors$1 = {
  83558. 'fire+smoke':0xffffff,
  83559. 'smoke': 0xffffff,
  83560. 'explode':0xffffff,
  83561. };
  83562. let depthMatPrefix = {
  83563. clipDistance : 100, occlusionDistance:60, /* 变为backColor距离 */
  83564. maxClipFactor:0.5, backColor:"#777" ,
  83565. useDepth:true, transparent: !0,
  83566. };
  83567. let lineMats$2;
  83568. let getLineMat$1 = function(type){
  83569. if(!lineMats$2){
  83570. lineMats$2 = {
  83571. 'fire+smoke':LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83572. color: colors$1['fire+smoke'],
  83573. lineWidth: 2
  83574. })),
  83575. 'smoke' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83576. color: colors$1['smoke'],
  83577. lineWidth: 2
  83578. })),
  83579. 'explode' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83580. color: colors$1['explode'],
  83581. lineWidth: 2
  83582. })),
  83583. };
  83584. }
  83585. return lineMats$2[type]
  83586. };
  83587. let handleMats;
  83588. let getHandleMat = function(type){
  83589. if(!handleMats){
  83590. let texLoader = new TextureLoader();
  83591. handleMats = {
  83592. "fire+smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83593. map: texLoader.load(Potree.resourcePath+'/textures/icon-fire.png' ),
  83594. color: colors$1['fire+smoke'],
  83595. })),
  83596. "smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83597. map: texLoader.load(Potree.resourcePath+'/textures/icon-smoke.png' ),
  83598. color: colors$1['smoke'],
  83599. })),
  83600. "explode" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83601. map: texLoader.load(Potree.resourcePath+'/textures/icon-explode.png' ),
  83602. color: colors$1['explode'],
  83603. })),
  83604. };
  83605. }
  83606. return handleMats[type]
  83607. };
  83608. let ParticleEditor = {
  83609. bus: new EventDispatcher$1,
  83610. particleGroup : new Object3D ,
  83611. curveGroup:new Object3D ,
  83612. init:function(){
  83613. this.particleGroup.name = 'particles';
  83614. viewer.scene.scene.add( this.particleGroup );
  83615. this.curveGroup.name = 'particles-curves';
  83616. viewer.scene.scene.add( this.curveGroup );
  83617. },
  83618. addParticle : function(prop={}){
  83619. let particle;
  83620. if(prop.type == 'fire'){
  83621. particle = new FireParticle(prop);
  83622. }else if(prop.type == 'smoke'){
  83623. particle = new SmokeParticle(prop);
  83624. }else if(prop.type == 'explode'){
  83625. particle = new ExplodeParticle(prop);
  83626. }
  83627. this.particleGroup.add(particle);
  83628. return particle
  83629. }
  83630. ,
  83631. removeParticle(particle){
  83632. //particle.dispatchEvent('delete')
  83633. particle.dispose();
  83634. this.particleGroup.remove(particle);
  83635. particle.curve.dispose();
  83636. }
  83637. ,
  83638. update(delta){
  83639. this.particleGroup.children.forEach(e=>e.update(delta));
  83640. }
  83641. ,
  83642. startInsertion(type = 'fire', prop={}){ //viewer.modules.ParticleEditor.startInsertion()
  83643. let deferred = $.Deferred();
  83644. let particles = [];
  83645. let finish = (ifDone)=>{
  83646. if(ifDone){
  83647. deferred.resolve(particles);
  83648. }
  83649. viewer.dispatchEvent({
  83650. type : "CursorChange", action : "remove", name:"addSth"
  83651. });
  83652. viewer.removeEventListener('global_click', click);
  83653. this.bus.removeEventListener('cancel_insertions',cancel);
  83654. };
  83655. let curve = new CurveCtrl([], getLineMat$1(type), colors$1[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83656. this.curveGroup.add(curve);
  83657. prop.curve = curve;
  83658. prop.type = type;
  83659. //console.log('创建curve',type,curve.uuid)
  83660. let cancel = ()=>{
  83661. console.log('cancel_insertions', curve.uuid );
  83662. curve.dispose();
  83663. finish(false);
  83664. };
  83665. this.bus.dispatchEvent('cancel_insertions');//删除旧的
  83666. this.bus.addEventListener('cancel_insertions',cancel);
  83667. var click = (e)=>{
  83668. if(e.button === MOUSE.RIGHT){
  83669. if(curve.points.length>=1){ //if(type.includes('fire') || type.includes('smoke') ){
  83670. particles = this.createFromData(prop);
  83671. finish(true);
  83672. }
  83673. return
  83674. }
  83675. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  83676. if(!I)return
  83677. curve.addPoint(I, null, true);
  83678. if(type == 'explode'){
  83679. particles = this.createFromData(prop);
  83680. finish(true);
  83681. }
  83682. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  83683. };
  83684. viewer.addEventListener('global_click', click, 10);//add importance:10
  83685. viewer.dispatchEvent({
  83686. type : "CursorChange", action : "add", name:"addSth"
  83687. });
  83688. return deferred.promise()
  83689. },
  83690. createFromData(prop){
  83691. const type = prop.type;
  83692. var particles = [];
  83693. let curve = prop.curve;
  83694. if(!curve){
  83695. curve = new CurveCtrl(prop.points, getLineMat$1(type), colors$1[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83696. this.curveGroup.add(curve);
  83697. }
  83698. if(type.includes('fire') || type.includes('smoke') ){
  83699. if(type.includes('fire')){
  83700. var fire = this.addParticle({
  83701. type : 'fire',
  83702. positions : curve.points,
  83703. curve,
  83704. radius : prop.radius,
  83705. height: prop.height,
  83706. strength : prop.strength,
  83707. });
  83708. particles.push(fire);
  83709. }
  83710. if(type.includes('smoke')){
  83711. var smoke = this.addParticle({
  83712. type : 'smoke',
  83713. positions : curve.points,
  83714. curve,
  83715. positionStyle : 'sphere' ,
  83716. strength : prop.smokeStrength,
  83717. radius: prop.smokeRadius,
  83718. height: prop.smokeHeight,
  83719. });
  83720. particles.push(smoke);
  83721. }
  83722. }else if(type == 'explode'){
  83723. var explode = this.addParticle({
  83724. type : 'explode',
  83725. position : curve.points[0],
  83726. strength: prop.strength,
  83727. radius : prop.radius,
  83728. particleSpaceTime: prop.particleSpaceTime,
  83729. curve,
  83730. delayStartTime:prop.delayStartTime,
  83731. });
  83732. particles.push(explode);
  83733. }
  83734. var geoNeedsUpdate;
  83735. curve.addEventListener('dragCurvePoint',()=>{
  83736. geoNeedsUpdate = true;
  83737. Common.intervalTool.isWaiting('particlePointChange', ()=>{ //延时update,防止卡顿
  83738. if(geoNeedsUpdate){
  83739. particles.forEach(e=>e.updateGeometry());
  83740. geoNeedsUpdate = false;
  83741. curve.dispatchEvent('sendUpdatePoints');
  83742. return true
  83743. }
  83744. }, 400);
  83745. });
  83746. return particles
  83747. }
  83748. };
  83749. let CamAniEditor = {
  83750. createAnimation(data){
  83751. let animation = new CameraAnimation(viewer);
  83752. if(data) {
  83753. animation.name = data.name;
  83754. animation.duration = data.duration;
  83755. animation.useDurSlice = data.useDurSlice;
  83756. for(const cpdata of data.points){
  83757. /* const position = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.position, datasetId: Potree.settings.originDatasetId })
  83758. const target = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.target, datasetId: Potree.settings.originDatasetId })
  83759. */
  83760. const position = new Vector3().copy(cpdata.position);
  83761. const target = new Vector3().copy(cpdata.target);
  83762. const duration = cpdata.time;
  83763. const cp = animation.createControlPoint(null, {position, target, duration});
  83764. }
  83765. }
  83766. animation.changeCallback();
  83767. viewer.scene.addCameraAnimation(animation);
  83768. return animation
  83769. },
  83770. removeAnimation(animation){
  83771. animation.dispatchEvent('dispose');
  83772. viewer.scene.removeCameraAnimation(animation);
  83773. }
  83774. };
  83775. let images360, Alignment$1, SiteModel$1;
  83776. const texLoader$c = new TextureLoader();
  83777. texLoader$c.crossOrigin = "anonymous";
  83778. const rotQua = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI);
  83779. const lineMats$3 = {};
  83780. const circleMats = {};
  83781. const renderOrders$1 = {
  83782. circleSelected:3,
  83783. circle:2,
  83784. line:1,
  83785. };
  83786. const pointColor = {
  83787. /* selected:"#c80",
  83788. default:'#1ac' */
  83789. selected:"#c60",
  83790. default:'#17c'
  83791. };
  83792. const opacitys = {
  83793. default:1.3,
  83794. selected: 2.0
  83795. };
  83796. const cameraProps = [
  83797. {
  83798. name : 'top',
  83799. axis:["x","y"],
  83800. direction : new Vector3(0,0,-1), //镜头朝向
  83801. openCount:0,
  83802. },
  83803. {
  83804. name : 'right',
  83805. axis:["y","z"],
  83806. direction : new Vector3(1,0,0),
  83807. openCount:0,
  83808. }
  83809. ];
  83810. class PanoEditor extends EventDispatcher{
  83811. constructor(){
  83812. super();
  83813. this.panoGroup = [], //分组
  83814. this.viewports = {},
  83815. this.panoLink = {},
  83816. this.panoMeshs = new Object3D,
  83817. this.lineMeshes = new Object3D;
  83818. this.views = {};
  83819. this.cameras = {};
  83820. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  83821. this.selectedPano;
  83822. this.selectedGroup;
  83823. this.operation;
  83824. this.visiblePanos = [];
  83825. }
  83826. init(){
  83827. {//init lineMats
  83828. lineMats$3.default = LineDraw.createFatLineMat({
  83829. color: '#eeeeee',
  83830. lineWidth: 2,
  83831. depthTest:false
  83832. });
  83833. lineMats$3.hovered = LineDraw.createFatLineMat({
  83834. color: '#00c8af',
  83835. lineWidth: 2,
  83836. depthTest:false
  83837. });
  83838. lineMats$3.selected = LineDraw.createFatLineMat({
  83839. color: '#00c8af',
  83840. lineWidth: 3,
  83841. depthTest:false
  83842. });
  83843. }
  83844. {
  83845. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  83846. dontHideWhenFaceCamera: true,
  83847. });
  83848. this.transformControls.setSize(1.5);
  83849. viewer.scene.scene.add(this.transformControls);
  83850. this.transformControls._gizmo.hideAxis = {translate:[], rotate:['x','y','e'] };
  83851. this.transformControls.setRotateMethod(2);
  83852. this.fakeMarkerForTran = new Mesh(new BoxBufferGeometry(0.3,0.3,0.3) , new MeshBasicMaterial({
  83853. color:"#FFFFFF", opacity:0.4, transparent:true, visible:false
  83854. }));//一个看不见的mesh,只是为了让transformControls移动点云
  83855. viewer.scene.scene.add(this.fakeMarkerForTran);
  83856. let afterMoveCircle = (type)=>{
  83857. if(type == 'position'){
  83858. let moveVec = new Vector3().subVectors(this.fakeMarkerForTran.position, this.fakeMarkerForTran.oldState.position);
  83859. this.selectedClouds.forEach(cloud=>Alignment$1.translate(cloud, moveVec));
  83860. }else {
  83861. let center = this.selectedPano.position;
  83862. let forward = new Vector3(0,1,0);
  83863. let vec1 = forward.clone().applyQuaternion(this.fakeMarkerForTran.oldState.quaternion);
  83864. let vec2 = forward.clone().applyQuaternion(this.fakeMarkerForTran.quaternion);
  83865. let diffAngle = math.getAngle(vec1,vec2,'z');
  83866. this.selectedClouds.forEach(cloud=>{
  83867. Alignment$1.rotateAround(center, cloud, null, diffAngle);
  83868. });
  83869. }
  83870. this.fakeMarkerForTran.oldState = {
  83871. position: this.fakeMarkerForTran.position.clone(),
  83872. quaternion: this.fakeMarkerForTran.quaternion.clone(),
  83873. };
  83874. };
  83875. this.fakeMarkerForTran.addEventListener('position_changed', afterMoveCircle.bind(this,'position'));
  83876. this.fakeMarkerForTran.addEventListener("rotation_changed", afterMoveCircle.bind(this,'rotation') );
  83877. }
  83878. this.initViews();
  83879. viewer.addEventListener('allLoaded',()=>{
  83880. images360 = viewer.images360;
  83881. Alignment$1 = viewer.modules.Alignment;
  83882. SiteModel$1 = viewer.modules.SiteModel;
  83883. this.panoMeshs.name = 'panoMeshs';
  83884. viewer.scene.scene.add(this.panoMeshs);
  83885. this.lineMeshes.name = 'lineMeshes';
  83886. viewer.scene.scene.add(this.lineMeshes);
  83887. this.initPanoLink();
  83888. this.addPanoMesh();
  83889. viewer.scene.pointclouds.forEach(e=>{
  83890. e.material.color = pointColor.default;
  83891. });
  83892. this.switchView('top');
  83893. SiteModel$1.bus.addEventListener('initDataDone',()=>{
  83894. let floor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.length); //选择有漫游点的一层
  83895. if(!floor){
  83896. floor = 'all'; //SiteModel.entities.find(e=>e.buildType == 'floor')
  83897. console.log('没有一层有漫游点?!');
  83898. }
  83899. this.gotoFloor(floor);
  83900. });
  83901. Alignment$1.bus.addEventListener('switchHandle', this.updateCursor.bind(this));
  83902. viewer.addEventListener('global_click',(e)=>{
  83903. if(e.button === MOUSE.RIGHT){//取消旋转和平移
  83904. console.log('right click',e);
  83905. this.setLinkOperateState('addLink',false);
  83906. this.setLinkOperateState('removeLink',false);
  83907. }else if(this.clickToZoomInEnabled){
  83908. if(this.activeViewName == 'mainView'){
  83909. viewer.controls.zoomToLocation(e.mouse);
  83910. }else {
  83911. this.zoomIn(e.intersect.orthoIntersect, e.pointer);
  83912. }
  83913. this.setZoomInState(false);
  83914. }
  83915. });
  83916. {//旋转时的辅助线
  83917. this.rotGuideLine = LineDraw.createLine([], {color:'#aaffee'});
  83918. this.rotGuideLine.visible = false;
  83919. this.rotGuideLine.name = 'rotGuideLine';
  83920. this.rotGuideLine.renderOrder = renderOrders$1.line;
  83921. viewer.scene.scene.add(this.rotGuideLine);
  83922. let startPoint;
  83923. Alignment$1.bus.addEventListener('rotateStart', (e)=>{
  83924. startPoint = e.startPoint;
  83925. });
  83926. Alignment$1.bus.addEventListener('rotate', (e)=>{
  83927. LineDraw.updateLine(this.rotGuideLine, [startPoint, e.endPoint] );
  83928. this.rotGuideLine.visible = true;
  83929. });
  83930. viewer.fpControls.addEventListener("end",(e)=>{
  83931. startPoint = null;
  83932. this.rotGuideLine.visible = false;
  83933. });
  83934. }
  83935. {//连接时的辅助线
  83936. this.linkGuideLine = LineDraw.createLine([], {color:'#aaa', deshed:true, dashSize:0.1,gapSize:0.1,});
  83937. this.linkGuideLine.visible = false;
  83938. this.linkGuideLine.name = 'linkGuideLine';
  83939. viewer.scene.scene.add(this.linkGuideLine);
  83940. this.linkGuideLine.renderOrder = renderOrders$1.line;
  83941. let update = (e)=>{
  83942. if(this.operation != 'addLink' || this.activeViewName != 'top' || !this.selectedPano){
  83943. return this.linkGuideLine.visible = false
  83944. }
  83945. LineDraw.updateLine(this.linkGuideLine, [this.selectedPano.position, e.intersect.orthoIntersect.clone().setZ(this.selectedPano.position.z)] );
  83946. this.linkGuideLine.visible = true;
  83947. };
  83948. viewer.addEventListener('global_mousemove', (e)=>{
  83949. update(e);
  83950. });
  83951. this.addEventListener('updateLinkGuideLine', update);
  83952. //为何打开调试时移动很卡
  83953. }
  83954. });
  83955. }
  83956. setTranMode(mode){//rotate or translate
  83957. this.tranMode = mode;
  83958. if(this.activeViewName == 'mainView'){
  83959. mode && this.transformControls.setMode(mode);
  83960. this.updateTranCtl();
  83961. }else {
  83962. Alignment$1.switchHandle(mode);
  83963. }
  83964. }
  83965. updateTranCtl(){// 设置3D页面的transformControls相关
  83966. if(!this.tranMode || !this.selectedPano || this.activeViewName != 'mainView' ) {
  83967. return this.transformControls.detach()
  83968. }else if(this.checkIfAllLinked({group:this.selectedGroup})){
  83969. this.dispatchEvent('needToDisConnect');
  83970. return this.transformControls.detach()
  83971. }
  83972. this.transformControls.attach(this.fakeMarkerForTran);
  83973. let {position, quaternion} = this.getPanoPose(this.selectedPano);
  83974. this.fakeMarkerForTran.position.copy(position);
  83975. this.fakeMarkerForTran.quaternion.copy(quaternion);
  83976. this.fakeMarkerForTran.oldState = {
  83977. position: position.clone(),
  83978. quaternion: quaternion.clone(),
  83979. };
  83980. }
  83981. //////////////////////////////////
  83982. initViews(){
  83983. this.splitScreenTool = new SplitScreen;
  83984. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  83985. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  83986. for(let i=0;i<2;i++){
  83987. let prop = cameraProps[i];
  83988. let view = new View();
  83989. this.views[prop.name] = view;
  83990. this.cameras[prop.name] = this.orthoCamera;
  83991. view.direction = prop.direction;
  83992. }
  83993. this.views.mainView = viewer.mainViewport.view;
  83994. this.cameras.mainView = viewer.mainViewport.camera;
  83995. }
  83996. switchView(name){//替换view和camera到mainViewport
  83997. let view = this.views[name];
  83998. let camera = this.cameras[name];
  83999. let prop = cameraProps.find(e=>e.name == name);
  84000. let {boundSize, center} = viewer.bound;
  84001. this.lastViewName = this.activeViewName;
  84002. this.activeViewName = name;
  84003. let lastView = this.views[this.lastViewName];
  84004. let lastCamera = this.cameras[this.lastViewName];
  84005. viewer.mainViewport.view = view;
  84006. viewer.mainViewport.camera = camera;
  84007. if(lastCamera)lastView.zoom = lastCamera.zoom;
  84008. this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center );
  84009. this.targetPlane.projectPoint(view.position, this.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  84010. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  84011. if(view.zoom)camera.zoom = view.zoom;//恢复上次的zoom
  84012. viewer.updateScreenSize({forceUpdateSize:true});//更新camera aspect left等
  84013. this.updateCursor();
  84014. if(name == 'mainView'){
  84015. viewer.mainViewport.alignment = null;
  84016. viewer.scene.pointclouds.forEach(e=>{
  84017. e.material.activeAttributeName = 'rgba';
  84018. e.material.useFilterByNormal = false;
  84019. e.changePointOpacity(1,true);
  84020. });
  84021. viewer.updateVisible(viewer.reticule, 'force', true);
  84022. if(lastView){
  84023. view.copy(lastView);
  84024. //view.position.
  84025. let direction = view.direction;
  84026. let panos = images360.panos.filter(e=>e.circle.visible);
  84027. let nearestPano = Common.sortByScore(panos , [], [(pano)=>{
  84028. let vec = new Vector3().subVectors(pano.position, view.position);
  84029. return -vec.dot(direction);
  84030. }], true);
  84031. console.log('最近',nearestPano );
  84032. if(nearestPano && nearestPano[0] ){ //尽量不变画面范围,使pano点保持原位,转换到mainView
  84033. let halfHeight = lastCamera.top/lastCamera.zoom;
  84034. let dis = halfHeight / Math.tan( MathUtils.degToRad(camera.fov/2));
  84035. view.position.add(direction.clone().multiplyScalar(-nearestPano[0].score - dis));
  84036. //console.log('getCloser', -nearestPano[0].score - dis)
  84037. this.lastDisToPano = dis; //记录一下
  84038. }
  84039. }
  84040. viewer.fpControls.lockKey = false;
  84041. }else {
  84042. if(prop.openCount == 0){//只需执行一次
  84043. this.viewportFitBound(name, boundSize, center);
  84044. }
  84045. prop.openCount ++;
  84046. viewer.scene.pointclouds.forEach(e=>{
  84047. e.material.activeAttributeName = 'color';
  84048. e.material.useFilterByNormal = true; //defines : use_filter_by_normal attenuated_opacity
  84049. if(this.selectedPano && this.selectedClouds.includes(e) /* this.selectedPano.pointcloud == e */){
  84050. e.changePointOpacity(opacitys.selected,true);
  84051. }else {
  84052. e.changePointOpacity(opacitys.default,true);
  84053. }
  84054. });
  84055. viewer.updateVisible(viewer.reticule, 'force', false);
  84056. if(name == 'top') viewer.mainViewport.alignment = {rotate:true,translate:true};
  84057. if(name == 'right'){
  84058. viewer.mainViewport.alignment = {translate:true, rotateSide:true};
  84059. viewer.mainViewport.rotateSide = true;
  84060. }else {
  84061. viewer.mainViewport.rotateSide = false;
  84062. }
  84063. viewer.fpControls.lockKey = true;
  84064. }
  84065. this.updateTranCtl();
  84066. this.setTranMode(); // update
  84067. this.setZoomInState(false); //取消放大模式
  84068. }
  84069. //new THREE.Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] )
  84070. viewportFitBound(/* name, boundSize_, target */){ //使一个viewport聚焦在某个范围
  84071. /* let viewport = viewer.mainViewport
  84072. let {boundSize, center} = viewer.bound
  84073. var prop = cameraProps.find(v => name == v.name )
  84074. let expand = 10;
  84075. targetPlane.setFromNormalAndCoplanarPoint( prop.direction.clone(), center )
  84076. let shiftTarget = targetPlane.projectPoint(target, new THREE.Vector3() ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  84077. this.setCameraPose(shiftTarget, prop.direction)
  84078. if(name == 'top'){
  84079. let axis = prop.axis
  84080. var width = Math.max(boundSize_[axis[0]], boundSize_[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  84081. }else{//因为侧面可能旋转
  84082. let vec1 = new THREE.Vector3(boundSize_.x, 0,0);
  84083. let vec2 = new THREE.Vector3(0,boundSize_.y,0);
  84084. let v1 = vec1.projectOnPlane( prop.direction.clone() )
  84085. let v2 = vec2.projectOnPlane( prop.direction.clone() )
  84086. var width = Math.max(v1.length()+v2.length(), boundSize_.z * viewport.camera.aspect)//视口宽度(米)
  84087. }
  84088. var margin = 50 //px
  84089. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  84090. viewport.camera.updateProjectionMatrix() */
  84091. if(viewer.mainViewport.resolution.x == 0 || viewer.mainViewport.resolution.y == 0){
  84092. return setTimeout(()=>{
  84093. this.viewportFitBound(/* name, boundSize_, target */);
  84094. },10)
  84095. }
  84096. this.gotoFloor(this.currentFloor, true, 0, null, true);
  84097. }
  84098. rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  84099. this.splitScreenTool.rotateSideCamera(viewer.mainViewport, angle);
  84100. }
  84101. /* rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  84102. var prop = cameraProps.find(v => v.name == 'right' )
  84103. let {boundSize, center} = viewer.bound
  84104. //找到平移向量
  84105. targetPlane.setFromNormalAndCoplanarPoint(viewer.mainViewport.view.direction , center )
  84106. targetPlane.projectPoint(viewer.mainViewport.view.position, this.shiftTarget ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  84107. let vec = new THREE.Vector3().subVectors(center, this.shiftTarget)//相对于中心的偏移值,旋转后偏移值也旋转
  84108. //旋转
  84109. var rotMatrix = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0,0,1), angle)
  84110. //prop.direction.applyMatrix4(rotMatrix)
  84111. viewer.mainViewport.view.direction = viewer.mainViewport.view.direction.applyMatrix4(rotMatrix)
  84112. vec.applyMatrix4(rotMatrix)
  84113. this.shiftTarget.subVectors(center,vec) //新的
  84114. viewer.mainViewport.view.position = this.splitScreenTool.getPosOutOfModel(viewer.mainViewport) // this.getPosOutOfModel()
  84115. } */
  84116. /* getPosOutOfModel(){//已知shiftTarget和currentDir后
  84117. let {boundSize, center} = viewer.bound
  84118. let expand = 10;
  84119. let view = viewer.mainViewport.view
  84120. let radius = boundSize.length() / 2
  84121. let position = this.shiftTarget.clone().sub(view.direction.clone().multiplyScalar(radius + expand))
  84122. return position
  84123. } */
  84124. zoomIn(intersect, pointer){
  84125. let camera = viewer.mainViewport.camera;
  84126. let endZoom = 700;
  84127. //this.moveFit(intersect, {endZoom:viewer.mainViewport.camera.zoom < aimZoom ? aimZoom : null} , 300)
  84128. let startZoom = camera.zoom;
  84129. if(startZoom >= endZoom){return}
  84130. viewer.mainViewport.view.zoomOrthoCamera(camera, endZoom, pointer, 300);
  84131. }
  84132. /* getRadius(){
  84133. let {boundSize, center} = viewer.bound
  84134. let expand = 10;
  84135. let radius = boundSize.length() / 2
  84136. return radius + expand
  84137. } */
  84138. moveFit(pos, info, duration){
  84139. var margin = {x:200, y:230};
  84140. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin );
  84141. /* targetPlane.projectPoint(pos, this.shiftTarget) //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  84142. info.endPosition = this.getPosOutOfModel()
  84143. info
  84144. let view = viewer.mainViewport.view
  84145. view.moveOrthoCamera(viewer.mainViewport, info , duration ) */
  84146. }
  84147. setZoomInState(state, informinformBy2d){//是否点击后可放大
  84148. //if(state && this.activeViewName == 'mainView')return console.log('3D不可放大')
  84149. this.clickToZoomInEnabled = !!state;
  84150. if(state){
  84151. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"zoomInCloud"} );
  84152. }else {
  84153. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"zoomInCloud" });
  84154. }
  84155. if(!state && !informinformBy2d){
  84156. this.dispatchEvent({type:'operationCancel', operation: 'zoomIn'});
  84157. }
  84158. }
  84159. gotoFloor(floor, force, duration = 600, informBy2d, fitBound){// 选择不同楼层, 切换点位显示。 'all'为全部显示
  84160. floor = floor || 'all';
  84161. if(this.currentFloor == floor && !force)return
  84162. //let pointclouds = viewer.findPointcloudsAtFloor(floor)
  84163. let panos = floor == 'all' ? viewer.images360.panos : floor.panos;
  84164. viewer.images360.panos.forEach(pano=>{
  84165. let v = panos.includes(pano);
  84166. this.switchPanoVisible(pano,v);
  84167. });
  84168. this.updateLinesVisible();
  84169. //切换楼层时清空选择状态
  84170. if(this.selectedPano && floor != 'all' && !floor.panos.includes(this.selectedPano)){
  84171. this.selectedPano.circle.dispatchEvent('click');
  84172. }
  84173. if(this.selectedLine){
  84174. this.selectedLine.dispatchEvent('click');
  84175. }
  84176. let bound, center;
  84177. if(floor == 'all'){
  84178. bound = viewer.images360.bound.bounding;
  84179. center = viewer.images360.bound.center;
  84180. }else {
  84181. bound = this.getPanosBound(floor);
  84182. center = bound.getCenter(new Vector3());
  84183. if(floor.panos.length == 0)console.log(floor.name, 'floor无漫游点' );
  84184. }
  84185. if(this.activeViewName != 'mainView' ){
  84186. fitBound && this.moveFit(center, {bound}, duration);
  84187. }else if(this.activeViewName == 'mainView'){
  84188. if(floor != 'all'){ //切换一下位置,因为原处点云会消失
  84189. viewer.scene.view.setView({position:center, duration });
  84190. }
  84191. }
  84192. this.currentFloor = floor;
  84193. if(!informBy2d){
  84194. this.dispatchEvent({type:'changeFloor', floor});
  84195. }
  84196. }
  84197. getPanosBound(floor){
  84198. if(!floor.panosBound){
  84199. if(floor.panos.length == 0){
  84200. floor.panosBound = viewer.images360.bound.bounding.clone();
  84201. }else {
  84202. /* floor.panosBound = new THREE.Box3
  84203. floor.panos.forEach(pano=>{
  84204. floor.panosBound.expandByPoint(pano.position)
  84205. })
  84206. let center = floor.panosBound.getCenter(new THREE.Vector3)
  84207. let minBound = (new THREE.Box3()).setFromCenterAndSize(center, new THREE.Vector3(5,5,5))
  84208. floor.panosBound.union(minBound) */
  84209. let minSize = new Vector3(5,5,5);
  84210. let bound = math.getBoundByPoints(floor.panos.map(e=>e.position), minSize);
  84211. floor.panosBound = bound.bounding;
  84212. }
  84213. }
  84214. return floor.panosBound
  84215. }
  84216. switchPanoVisible(pano, v, informBy2d){
  84217. pano.circle.visible = v;
  84218. viewer.updateVisible(pano, 'panoEditor', v);
  84219. viewer.updateVisible(pano.pointcloud, 'panoEditor', v);
  84220. if(v){
  84221. this.visiblePanos.includes(pano) || this.visiblePanos.push(pano);
  84222. }else {
  84223. let index = this.visiblePanos.indexOf(pano);
  84224. index>-1 && this.visiblePanos.splice(index,1);
  84225. }
  84226. if(informBy2d){
  84227. this.updateLinesVisible();
  84228. }
  84229. informBy2d || this.dispatchEvent({type:"switchPanoVisible", pano, v});
  84230. }
  84231. updateLinesVisible(){
  84232. this.lineMeshes.children.forEach(line=>{
  84233. let names = line.name.split('-');
  84234. var pano0 = images360.getPano(names[0]);
  84235. var pano1 = images360.getPano(names[1]);
  84236. line.visible = this.visiblePanos.includes(pano0) || this.visiblePanos.includes(pano1);
  84237. });
  84238. }
  84239. updateCursor(){
  84240. let cursor;
  84241. if(this.activeViewName == 'mainView' || !this.selectedPano){
  84242. cursor = null;
  84243. }else {
  84244. cursor = Alignment$1.handleState;
  84245. }
  84246. if(cursor == 'rotate'){
  84247. viewer.dispatchEvent({
  84248. type : "CursorChange", action : "add", name:"rotatePointcloud"
  84249. });
  84250. viewer.dispatchEvent({
  84251. type : "CursorChange", action : "remove", name:"movePointcloud"
  84252. });
  84253. }else if(cursor == 'translate'){
  84254. viewer.dispatchEvent({
  84255. type : "CursorChange", action : "add", name:"movePointcloud"
  84256. });
  84257. viewer.dispatchEvent({
  84258. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  84259. });
  84260. }else {
  84261. viewer.dispatchEvent({
  84262. type : "CursorChange", action : "remove", name:"movePointcloud"
  84263. });
  84264. viewer.dispatchEvent({
  84265. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  84266. });
  84267. }
  84268. //this.cursorState = cursor
  84269. }
  84270. setLinkOperateState(name, state, informinformBy2d){
  84271. if(state && name == this.operation || !state && name != this.operation)return
  84272. let old = this.operation;
  84273. this.operation = state ? name : null;
  84274. if(this.operation == 'removeLink'){
  84275. if(this.selectedLine){
  84276. this.selectedLine.dispatchEvent('click');//删除
  84277. }
  84278. if(this.selectedPano){
  84279. this.selectedPano.circle.dispatchEvent('click');//删除
  84280. }
  84281. }
  84282. if(this.operation != 'addLink'){
  84283. this.linkGuideLine.visible = false;
  84284. }
  84285. if(!state && !informinformBy2d){
  84286. this.dispatchEvent({type: "operationCancel", operation: old});
  84287. }
  84288. if(this.operation == 'addLink'){
  84289. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"connectPano"} );
  84290. }else {
  84291. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"connectPano"} );
  84292. }
  84293. if(this.operation == 'removeLink'){
  84294. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"disconnectPano"} );
  84295. }else {
  84296. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"disconnectPano"} );
  84297. }
  84298. }
  84299. /////////////////////////////////
  84300. initPanoLink(){
  84301. images360.panos.forEach((pano)=>{
  84302. this.panoLink[pano.id] = {};
  84303. });
  84304. images360.panos.forEach((pano)=>{
  84305. pano.visibles.forEach(index=>{//visibles中存的是下标!
  84306. this.linkChange(pano, images360.getPano(index,'index'), 'add');
  84307. });
  84308. });
  84309. console.log('panoLink',this.panoLink);
  84310. }
  84311. groupChange(pano0, pano1, type){//修改group (type == 'remove'时,pano1可以为空)
  84312. if(type == 'add'){
  84313. Common.pushToGroupAuto([pano0, pano1], this.panoGroup );
  84314. }else {
  84315. let atGroup = this.panoGroup.find(e=>e.includes(pano0) && (e.includes(pano1) || !pano1));//所在组
  84316. if(!atGroup){
  84317. if(pano1){
  84318. console.log('这两个pano原本就不在一个组', pano0.id, pano1.id);
  84319. }else {
  84320. console.log('pano0不在任何组', pano0);
  84321. }
  84322. return
  84323. }
  84324. //断开连接时,因为组内没有其他成员的连接信息,所以需要清除整组,并将剩余的一个个重新连接
  84325. this.panoGroup.splice(this.panoGroup.indexOf(atGroup),1); //删除
  84326. atGroup.forEach(pano=>{//然后再重新生成这两个和组的关系,各自分组
  84327. if(pano == pano0 || pano == pano1)return
  84328. for(let id in this.panoLink[pano.id]){
  84329. if(this.panoLink[pano.id][id]){
  84330. let pano_ = images360.getPano(id);
  84331. Common.pushToGroupAuto([pano, pano_], this.panoGroup );
  84332. }
  84333. }
  84334. });
  84335. }
  84336. }
  84337. linkChange(pano0, pano1, type){//修改link (type == 'remove'时,pano1可以为空)
  84338. let temp = [];
  84339. if(type == 'add'){
  84340. if(!pano1)return console.error('不支持add时pano1为空')
  84341. this.panoLink[pano0.id][pano1.id] = this.panoLink[pano0.id][pano1.id] || {};
  84342. this.panoLink[pano1.id][pano0.id] = this.panoLink[pano1.id][pano0.id] || {};
  84343. }else {
  84344. if(!pano1){
  84345. for(let id in this.panoLink[pano0.id]){
  84346. if(this.panoLink[pano0.id][id]){
  84347. this.panoLink[id][pano0.id] = false;
  84348. temp.push(id);
  84349. }
  84350. }
  84351. this.panoLink[pano0.id] = {}; //全部断连
  84352. }else {
  84353. this.panoLink[pano0.id][pano1.id] = false;
  84354. this.panoLink[pano1.id][pano0.id] = false;
  84355. }
  84356. }
  84357. if(!pano1){ //全部断连
  84358. temp.forEach(id=>{
  84359. this.lineChange(pano0, images360.getPano(id) , type);
  84360. });
  84361. }else {
  84362. this.lineChange(pano0, pano1, type);
  84363. }
  84364. this.groupChange(pano0, pano1, type);
  84365. //this.updateSelectGroup()
  84366. this.selectPano(this.selectedPano, false,true); //更新选中点云显示
  84367. }
  84368. lineChange(pano0, pano1, type){//修改line
  84369. if(type == 'add'){
  84370. if(this.panoLink[pano0.id][pano1.id].line) return
  84371. let line = LineDraw.createFatLine([pano0.position, pano1.position], {material:lineMats$3.default});
  84372. line.name = `${pano0.id}-${pano1.id}`;
  84373. line.renderOrder = line.pickOrder = renderOrders$1.line;
  84374. this.lineMeshes.add(line);
  84375. this.panoLink[pano0.id][pano1.id].line = this.panoLink[pano1.id][pano0.id].line = line;
  84376. line.addEventListener('mouseover', ()=>{
  84377. if(this.clickToZoomInEnabled)return
  84378. if(this.activeViewName == 'mainView')return
  84379. if(this.selectedLine != line)line.material = lineMats$3.hovered;
  84380. viewer.dispatchEvent({
  84381. type : "CursorChange", action : "add", name:"hoverLine"
  84382. });
  84383. });
  84384. line.addEventListener('mouseleave', ()=>{
  84385. if(this.clickToZoomInEnabled)return
  84386. //if(this.activeViewName == 'mainView')return
  84387. if(this.selectedLine != line)line.material = lineMats$3.default;
  84388. viewer.dispatchEvent({
  84389. type : "CursorChange", action : "remove", name:"hoverLine"
  84390. });
  84391. });
  84392. line.addEventListener('click', (e)=>{
  84393. if(this.clickToZoomInEnabled)return
  84394. if(this.activeViewName == 'mainView')return
  84395. if(this.operation == 'removeLink'){
  84396. if(this.selectedLine == line) this.selectLine(null);
  84397. return this.linkChange(pano0, pano1, 'remove')
  84398. }
  84399. this.selectLine(line);
  84400. });
  84401. }else {
  84402. let line = this.lineMeshes.children.find(e=>e.name == `${pano0.id}-${pano1.id}` || e.name == `${pano1.id}-${pano0.id}` );
  84403. if(line){
  84404. this.lineMeshes.remove(line);
  84405. line.geometry.dispose();
  84406. }
  84407. }
  84408. }
  84409. selectLine(line){
  84410. if(this.selectedLine == line)return
  84411. if(this.selectedLine){
  84412. this.selectedLine.material = lineMats$3.default;
  84413. }
  84414. if(line){
  84415. line.material = lineMats$3.selected;
  84416. }
  84417. this.selectedLine = line;
  84418. }
  84419. addPanoMesh(){
  84420. let map = texLoader$c.load(Potree.resourcePath+'/textures/correct_n.png' );
  84421. circleMats.default = new MeshBasicMaterial({
  84422. map,
  84423. color: 0xffffff,
  84424. transparent: true,
  84425. depthTest: false,
  84426. depthWrite: false,
  84427. });
  84428. circleMats.hovered = new MeshBasicMaterial({
  84429. map,
  84430. color: 0xffff00,
  84431. transparent: true,
  84432. depthTest: false,
  84433. depthWrite: false,
  84434. });
  84435. circleMats.selected = new MeshBasicMaterial({
  84436. map: texLoader$c.load(Potree.resourcePath+'/textures/correct_s.png' ) ,
  84437. color: 0xffffff,
  84438. transparent: true,
  84439. depthTest: false,
  84440. depthWrite: false,
  84441. });
  84442. let setPos = (circle)=>{
  84443. circle.position.copy(circle.pano.position);
  84444. for(let id in this.panoLink[circle.pano.id]){
  84445. let linkInfo = this.panoLink[circle.pano.id][id];
  84446. if(linkInfo){
  84447. LineDraw.updateLine(linkInfo.line, [circle.pano.position, images360.getPano(id).position] );
  84448. }
  84449. }
  84450. circle.update(); //update sprite Matrix
  84451. };
  84452. images360.panos.forEach(pano=>{
  84453. var circle = new Sprite$1({mat: circleMats.default, sizeInfo:{
  84454. minSize : 50 , maxSize : 120, nearBound : 2, farBound : 10,
  84455. },
  84456. renderOrder : renderOrders$1.circle,
  84457. pickOrder: renderOrders$1.circle
  84458. }); //new THREE.Sprite(circleMats.default)
  84459. circle.name = 'panoCircle';
  84460. circle.sid = pano.id;
  84461. circle.pano = pano;
  84462. pano.circle = circle;
  84463. this.panoMeshs.add(circle);
  84464. setPos(circle);
  84465. pano.addEventListener('rePos', setPos.bind(this,circle));
  84466. let drag = ()=>{
  84467. if(this.activeViewName == 'mainView')return
  84468. this.selectPano(circle.pano); //为了方便拖拽点云,拖动circle就直接选中
  84469. viewer.inputHandler.drag.object = null; //取消拖拽状态,否则不触发点云拖动
  84470. };
  84471. circle.addEventListener('drag', drag);
  84472. /* circle.addEventListener('drop', ()=>{
  84473. }) */
  84474. circle.addEventListener('mouseover', ()=>{
  84475. this.hoverPano(pano,true);
  84476. });
  84477. circle.addEventListener('mouseleave', ()=>{
  84478. this.hoverPano(pano,false);
  84479. });
  84480. circle.addEventListener('click', ()=>{
  84481. //if(this.activeViewName == 'mainView')return
  84482. if(this.clickToZoomInEnabled)return
  84483. if(this.operation == 'removeLink'){
  84484. this.linkChange(pano, null, 'remove'); //删除所有连接
  84485. }
  84486. if(this.selectedPano == circle.pano) return this.selectPano(null)
  84487. if(this.operation == 'addLink' && this.selectedPano){
  84488. this.linkChange(this.selectedPano, circle.pano, 'add');
  84489. //this.setLinkOperateState('addLink',false)
  84490. return
  84491. }
  84492. //if(this.operation == 'removeLink' && this.selectedPano){ //和选择中心点冲突
  84493. // this.linkChange(this.selectedPano, circle.pano, 'remove')
  84494. // //this.setLinkOperateState('removeLink',false)
  84495. // return
  84496. // }
  84497. this.selectPano(circle.pano);
  84498. });
  84499. });
  84500. }
  84501. hoverPano(pano, state){
  84502. if(this.clickToZoomInEnabled)return
  84503. if(pano && state){ //在hover一个pano之前,一定会先取消已经hover的pano, 最多存在一个hovered的pano
  84504. if(this.hoveredPano == pano)return
  84505. if(this.hoveredPano){
  84506. this.hoverPano(this.hoveredPano,false);
  84507. }
  84508. this.hoveredPano = pano;
  84509. pano.hovered = true;
  84510. if(/* this.activeViewName == 'mainView' || */Alignment$1.handleState && this.selectedPano && this.selectedPano == pano)return
  84511. if(this.operation != 'addLink' || !this.selectedPano || this.selectedPano == pano){ // this.selectedPano == pano?
  84512. viewer.dispatchEvent({
  84513. type : "CursorChange", action : "add", name:"hoverPano"
  84514. });
  84515. }
  84516. if(this.selectedPano != pano) pano.circle.material = circleMats.hovered;
  84517. }else if(pano && !state){//unhover
  84518. if(this.hoveredPano != pano)return
  84519. pano.hovered = false;
  84520. viewer.dispatchEvent({
  84521. type : "CursorChange", action : "remove", name:"hoverPano"
  84522. });
  84523. if(this.selectedPano != pano) pano.circle.material = circleMats.default;
  84524. this.hoveredPano = null;
  84525. }else {//unhover any
  84526. if(this.hoveredPano){
  84527. this.hoverPano(this.hoveredPano, false);
  84528. }
  84529. }
  84530. }
  84531. selectPano(pano, informinformBy2d, force){
  84532. if(this.selectedPano == pano && !force)return
  84533. let lastSeletedPano = this.selectedPano;
  84534. if(this.selectedPano){
  84535. this.selectedPano.circle.material = circleMats.default;
  84536. this.selectedPano.circle.renderOrder = renderOrders$1.circle;
  84537. if(this.activeViewName == 'mainView'){
  84538. }else {
  84539. this.selectedClouds.forEach(e=>{
  84540. e.changePointOpacity(opacitys.default,true);
  84541. e.material.color = pointColor.default;
  84542. });
  84543. }
  84544. }
  84545. this.selectedPano = pano || null;
  84546. this.updateSelectGroup();
  84547. if(pano){
  84548. this.selectedPano.circle.material = circleMats.selected;
  84549. this.selectedPano.circle.renderOrder = this.selectedPano.circle.pickOrder = renderOrders$1.circleSelected; //侧视图能显示在最前
  84550. if(this.activeViewName == 'mainView'){
  84551. }else {
  84552. this.selectedClouds.forEach(e=>{
  84553. e.changePointOpacity(opacitys.selected,true);
  84554. e.material.color = pointColor.selected;
  84555. });
  84556. }
  84557. {//自动切换楼层
  84558. let atFloor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.includes(pano));
  84559. if(!atFloor){
  84560. atFloor = 'all';
  84561. }else {
  84562. }
  84563. this.gotoFloor(atFloor, false, 600 );
  84564. }
  84565. }
  84566. this.updateCursor();
  84567. this.updateTranCtl();
  84568. if(informinformBy2d){
  84569. if(this.selectedPano){
  84570. if(this.activeViewName == 'mainView'){ //平移,focus选中的pano
  84571. let distance = this.lastDisToPano || 5;
  84572. if(lastSeletedPano){
  84573. distance = viewer.mainViewport.camera.position.distanceTo(lastSeletedPano.position);
  84574. }
  84575. viewer.focusOnObject({ position:this.selectedPano.position}, 'point', null, {distance });
  84576. }else {
  84577. this.moveFit(this.selectedPano.position, {}, 500);
  84578. }
  84579. }
  84580. }else {
  84581. this.dispatchEvent({type:'panoSelect', pano });
  84582. }
  84583. }
  84584. updateSelectGroup(){//更新选中的组
  84585. this.selectedGroup = this.panoGroup.find(e=>e.includes(this.selectedPano));
  84586. this.selectedClouds = this.selectedPano ? (this.selectedGroup || [this.selectedPano]).map(e=>e.pointcloud) : [];
  84587. }
  84588. checkIfCanSave(){//如果未全部相连,不能保存
  84589. for(let datasetId in Potree.settings.datasetsPanos ) {
  84590. if(!this.checkIfAllLinked({datasetId})){
  84591. console.log('没有全部连通,不能保存。其中一个:', datasetId);
  84592. return
  84593. }
  84594. }
  84595. return true
  84596. }
  84597. checkIfAllLinked(o){//某个(or组所在的)数据集是否全部连通
  84598. let datasetId, group;
  84599. if(o.group){
  84600. group = o.group;
  84601. let pano = o.group[0];
  84602. if(!pano)return //会有没有漫游点的点云来编辑吗
  84603. datasetId = pano.pointcloud.dataset_id;
  84604. }else if(o.datasetId){
  84605. datasetId = o.datasetId;
  84606. group = this.panoGroup.find(panos=>panos[0].pointcloud.dataset_id == datasetId );
  84607. if(!group)return //要找的数据集的pano全部都孤立了
  84608. }
  84609. if(!datasetId)return
  84610. let panos = Potree.settings.datasetsPanos[datasetId].panos;
  84611. return panos.length == group.length
  84612. }
  84613. getPanoPose(pano){
  84614. let pose = {
  84615. position: pano.position.clone(),
  84616. quaternion: new Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ,
  84617. };
  84618. return pose
  84619. }
  84620. exportSavingData(){//输出漫游点新的坐标和朝向、以及连接信息
  84621. let sweepLocations = {};
  84622. for(let datasetId in Potree.settings.datasetsPanos ) {
  84623. let {panos} = Potree.settings.datasetsPanos[datasetId];
  84624. let data = panos.map(pano=>{
  84625. let visibles = [];
  84626. for(let id in this.panoLink[pano.id]){
  84627. if(this.panoLink[pano.id][id]){
  84628. visibles.push(viewer.images360.getPano(id).index);
  84629. }
  84630. }
  84631. let {position, quaternion} = this.getPanoPose(pano);
  84632. return Object.assign({}, pano.panosData, {
  84633. uuid: pano.uuid,
  84634. /* pose:{
  84635. translation: dealData(pano.position.clone() ),
  84636. rotation: dealData(new THREE.Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ),
  84637. }, */
  84638. pose : {
  84639. translation : dealData(position),
  84640. rotation : dealData(quaternion)
  84641. },
  84642. visibles,
  84643. //subgroup: 0,group: 1, "id_view":..
  84644. })
  84645. });
  84646. sweepLocations[datasetId] = {sweepLocations:data};
  84647. }
  84648. /* this.lineMeshes.children.forEach(e=>{//从line中搜集连接信息,而不从linkInfo,这样visibles不会重复一次
  84649. let names = e.name.split('-') //是不是该转成数字
  84650. var pano0 = names[0]
  84651. var pano1 = names[1]
  84652. sweepLocations.find(s=>s.uuid == pano0).visibles.push(pano1)
  84653. }) */
  84654. function dealData(value){
  84655. let v = math.toPrecision(value, 6);
  84656. if(v instanceof Quaternion){
  84657. return {x:v.x, y:v.y, z:v.z, w:v.w}
  84658. }else if(v instanceof Vector3){
  84659. return {x:v.x, y:v.y, z:v.z}
  84660. }
  84661. }
  84662. console.log(sweepLocations);
  84663. return sweepLocations
  84664. }
  84665. }
  84666. /*
  84667. 不同数据集之间不能连线
  84668. 不同楼层可能也不能
  84669. 如果楼层在不同建筑物怎么办? 楼层切换按钮只能在一个建筑内切换。
  84670. 全部相连时不能移动和旋转
  84671. 如果未全部相连,不能保存
  84672. */
  84673. var PanoEditor$1 = new PanoEditor();
  84674. var OBJLoader = ( function () {
  84675. // o object_name | g group_name
  84676. var object_pattern = /^[og]\s*(.+)?/;
  84677. // mtllib file_reference
  84678. var material_library_pattern = /^mtllib /;
  84679. // usemtl material_name
  84680. var material_use_pattern = /^usemtl /;
  84681. // usemap map_name
  84682. var map_use_pattern = /^usemap /;
  84683. var vA = new Vector3();
  84684. var vB = new Vector3();
  84685. var vC = new Vector3();
  84686. var ab = new Vector3();
  84687. var cb = new Vector3();
  84688. function ParserState() {
  84689. var state = {
  84690. objects: [],
  84691. object: {},
  84692. vertices: [],
  84693. normals: [],
  84694. colors: [],
  84695. uvs: [],
  84696. materials: {},
  84697. materialLibraries: [],
  84698. startObject: function ( name, fromDeclaration ) {
  84699. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  84700. // file. We need to use it for the first parsed g/o to keep things in sync.
  84701. if ( this.object && this.object.fromDeclaration === false ) {
  84702. this.object.name = name;
  84703. this.object.fromDeclaration = ( fromDeclaration !== false );
  84704. return;
  84705. }
  84706. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  84707. if ( this.object && typeof this.object._finalize === 'function' ) {
  84708. this.object._finalize( true );
  84709. }
  84710. this.object = {
  84711. name: name || '',
  84712. fromDeclaration: ( fromDeclaration !== false ),
  84713. geometry: {
  84714. vertices: [],
  84715. normals: [],
  84716. colors: [],
  84717. uvs: [],
  84718. hasUVIndices: false
  84719. },
  84720. materials: [],
  84721. smooth: true,
  84722. startMaterial: function ( name, libraries ) {
  84723. var previous = this._finalize( false );
  84724. // New usemtl declaration overwrites an inherited material, except if faces were declared
  84725. // after the material, then it must be preserved for proper MultiMaterial continuation.
  84726. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  84727. this.materials.splice( previous.index, 1 );
  84728. }
  84729. var material = {
  84730. index: this.materials.length,
  84731. name: name || '',
  84732. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  84733. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  84734. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  84735. groupEnd: - 1,
  84736. groupCount: - 1,
  84737. inherited: false,
  84738. clone: function ( index ) {
  84739. var cloned = {
  84740. index: ( typeof index === 'number' ? index : this.index ),
  84741. name: this.name,
  84742. mtllib: this.mtllib,
  84743. smooth: this.smooth,
  84744. groupStart: 0,
  84745. groupEnd: - 1,
  84746. groupCount: - 1,
  84747. inherited: false
  84748. };
  84749. cloned.clone = this.clone.bind( cloned );
  84750. return cloned;
  84751. }
  84752. };
  84753. this.materials.push( material );
  84754. return material;
  84755. },
  84756. currentMaterial: function () {
  84757. if ( this.materials.length > 0 ) {
  84758. return this.materials[ this.materials.length - 1 ];
  84759. }
  84760. return undefined;
  84761. },
  84762. _finalize: function ( end ) {
  84763. var lastMultiMaterial = this.currentMaterial();
  84764. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  84765. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  84766. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  84767. lastMultiMaterial.inherited = false;
  84768. }
  84769. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  84770. if ( end && this.materials.length > 1 ) {
  84771. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  84772. if ( this.materials[ mi ].groupCount <= 0 ) {
  84773. this.materials.splice( mi, 1 );
  84774. }
  84775. }
  84776. }
  84777. // Guarantee at least one empty material, this makes the creation later more straight forward.
  84778. if ( end && this.materials.length === 0 ) {
  84779. this.materials.push( {
  84780. name: '',
  84781. smooth: this.smooth
  84782. } );
  84783. }
  84784. return lastMultiMaterial;
  84785. }
  84786. };
  84787. // Inherit previous objects material.
  84788. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  84789. // If a usemtl declaration is encountered while this new object is being parsed, it will
  84790. // overwrite the inherited material. Exception being that there was already face declarations
  84791. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  84792. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  84793. var declared = previousMaterial.clone( 0 );
  84794. declared.inherited = true;
  84795. this.object.materials.push( declared );
  84796. }
  84797. this.objects.push( this.object );
  84798. },
  84799. finalize: function () {
  84800. if ( this.object && typeof this.object._finalize === 'function' ) {
  84801. this.object._finalize( true );
  84802. }
  84803. },
  84804. parseVertexIndex: function ( value, len ) {
  84805. var index = parseInt( value, 10 );
  84806. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84807. },
  84808. parseNormalIndex: function ( value, len ) {
  84809. var index = parseInt( value, 10 );
  84810. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84811. },
  84812. parseUVIndex: function ( value, len ) {
  84813. var index = parseInt( value, 10 );
  84814. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  84815. },
  84816. addVertex: function ( a, b, c ) {
  84817. var src = this.vertices;
  84818. var dst = this.object.geometry.vertices;
  84819. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84820. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84821. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84822. },
  84823. addVertexPoint: function ( a ) {
  84824. var src = this.vertices;
  84825. var dst = this.object.geometry.vertices;
  84826. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84827. },
  84828. addVertexLine: function ( a ) {
  84829. var src = this.vertices;
  84830. var dst = this.object.geometry.vertices;
  84831. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84832. },
  84833. addNormal: function ( a, b, c ) {
  84834. var src = this.normals;
  84835. var dst = this.object.geometry.normals;
  84836. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84837. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84838. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84839. },
  84840. addFaceNormal: function ( a, b, c ) {
  84841. var src = this.vertices;
  84842. var dst = this.object.geometry.normals;
  84843. vA.fromArray( src, a );
  84844. vB.fromArray( src, b );
  84845. vC.fromArray( src, c );
  84846. cb.subVectors( vC, vB );
  84847. ab.subVectors( vA, vB );
  84848. cb.cross( ab );
  84849. cb.normalize();
  84850. dst.push( cb.x, cb.y, cb.z );
  84851. dst.push( cb.x, cb.y, cb.z );
  84852. dst.push( cb.x, cb.y, cb.z );
  84853. },
  84854. addColor: function ( a, b, c ) {
  84855. var src = this.colors;
  84856. var dst = this.object.geometry.colors;
  84857. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84858. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84859. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84860. },
  84861. addUV: function ( a, b, c ) {
  84862. var src = this.uvs;
  84863. var dst = this.object.geometry.uvs;
  84864. dst.push( src[ a + 0 ], src[ a + 1 ] );
  84865. dst.push( src[ b + 0 ], src[ b + 1 ] );
  84866. dst.push( src[ c + 0 ], src[ c + 1 ] );
  84867. },
  84868. addDefaultUV: function () {
  84869. var dst = this.object.geometry.uvs;
  84870. dst.push( 0, 0 );
  84871. dst.push( 0, 0 );
  84872. dst.push( 0, 0 );
  84873. },
  84874. addUVLine: function ( a ) {
  84875. var src = this.uvs;
  84876. var dst = this.object.geometry.uvs;
  84877. dst.push( src[ a + 0 ], src[ a + 1 ] );
  84878. },
  84879. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  84880. var vLen = this.vertices.length;
  84881. var ia = this.parseVertexIndex( a, vLen );
  84882. var ib = this.parseVertexIndex( b, vLen );
  84883. var ic = this.parseVertexIndex( c, vLen );
  84884. this.addVertex( ia, ib, ic );
  84885. this.addColor( ia, ib, ic );
  84886. // normals
  84887. if ( na !== undefined && na !== '' ) {
  84888. var nLen = this.normals.length;
  84889. ia = this.parseNormalIndex( na, nLen );
  84890. ib = this.parseNormalIndex( nb, nLen );
  84891. ic = this.parseNormalIndex( nc, nLen );
  84892. this.addNormal( ia, ib, ic );
  84893. } else {
  84894. this.addFaceNormal( ia, ib, ic );
  84895. }
  84896. // uvs
  84897. if ( ua !== undefined && ua !== '' ) {
  84898. var uvLen = this.uvs.length;
  84899. ia = this.parseUVIndex( ua, uvLen );
  84900. ib = this.parseUVIndex( ub, uvLen );
  84901. ic = this.parseUVIndex( uc, uvLen );
  84902. this.addUV( ia, ib, ic );
  84903. this.object.geometry.hasUVIndices = true;
  84904. } else {
  84905. // add placeholder values (for inconsistent face definitions)
  84906. this.addDefaultUV();
  84907. }
  84908. },
  84909. addPointGeometry: function ( vertices ) {
  84910. this.object.geometry.type = 'Points';
  84911. var vLen = this.vertices.length;
  84912. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  84913. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  84914. this.addVertexPoint( index );
  84915. this.addColor( index );
  84916. }
  84917. },
  84918. addLineGeometry: function ( vertices, uvs ) {
  84919. this.object.geometry.type = 'Line';
  84920. var vLen = this.vertices.length;
  84921. var uvLen = this.uvs.length;
  84922. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  84923. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  84924. }
  84925. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  84926. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  84927. }
  84928. }
  84929. };
  84930. state.startObject( '', false );
  84931. return state;
  84932. }
  84933. //
  84934. function OBJLoader( manager ) {
  84935. Loader.call( this, manager );
  84936. this.materials = null;
  84937. }
  84938. OBJLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  84939. constructor: OBJLoader,
  84940. load: function ( url, onLoad, onProgress, onError ) {
  84941. var scope = this;
  84942. var loader = new FileLoader( this.manager );
  84943. loader.setPath( this.path );
  84944. loader.setRequestHeader( this.requestHeader );
  84945. loader.setWithCredentials( this.withCredentials );
  84946. loader.load( url, function ( text , total ) {// xzw add total
  84947. try {
  84948. onLoad( scope.parse( text ) , total );
  84949. } catch ( e ) {
  84950. if ( onError ) {
  84951. onError( e );
  84952. } else {
  84953. console.error( e );
  84954. }
  84955. scope.manager.itemError( url );
  84956. }
  84957. }, onProgress, onError );
  84958. },
  84959. setMaterials: function ( materials ) {
  84960. this.materials = materials;
  84961. return this;
  84962. },
  84963. parse: function ( text ) {
  84964. var state = new ParserState();
  84965. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  84966. // This is faster than String.split with regex that splits on both
  84967. text = text.replace( /\r\n/g, '\n' );
  84968. }
  84969. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  84970. // join lines separated by a line continuation character (\)
  84971. text = text.replace( /\\\n/g, '' );
  84972. }
  84973. var lines = text.split( '\n' );
  84974. var line = '', lineFirstChar = '';
  84975. var lineLength = 0;
  84976. var result = [];
  84977. // Faster to just trim left side of the line. Use if available.
  84978. var trimLeft = ( typeof ''.trimLeft === 'function' );
  84979. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  84980. line = lines[ i ];
  84981. line = trimLeft ? line.trimLeft() : line.trim();
  84982. lineLength = line.length;
  84983. if ( lineLength === 0 ) continue;
  84984. lineFirstChar = line.charAt( 0 );
  84985. // @todo invoke passed in handler if any
  84986. if ( lineFirstChar === '#' ) continue;
  84987. if ( lineFirstChar === 'v' ) {
  84988. var data = line.split( /\s+/ );
  84989. switch ( data[ 0 ] ) {
  84990. case 'v':
  84991. state.vertices.push(
  84992. parseFloat( data[ 1 ] ),
  84993. parseFloat( data[ 2 ] ),
  84994. parseFloat( data[ 3 ] )
  84995. );
  84996. if ( data.length >= 7 ) {
  84997. state.colors.push(
  84998. parseFloat( data[ 4 ] ),
  84999. parseFloat( data[ 5 ] ),
  85000. parseFloat( data[ 6 ] )
  85001. );
  85002. } else {
  85003. // if no colors are defined, add placeholders so color and vertex indices match
  85004. state.colors.push( undefined, undefined, undefined );
  85005. }
  85006. break;
  85007. case 'vn':
  85008. state.normals.push(
  85009. parseFloat( data[ 1 ] ),
  85010. parseFloat( data[ 2 ] ),
  85011. parseFloat( data[ 3 ] )
  85012. );
  85013. break;
  85014. case 'vt':
  85015. state.uvs.push(
  85016. parseFloat( data[ 1 ] ),
  85017. parseFloat( data[ 2 ] )
  85018. );
  85019. break;
  85020. }
  85021. } else if ( lineFirstChar === 'f' ) {
  85022. var lineData = line.substr( 1 ).trim();
  85023. var vertexData = lineData.split( /\s+/ );
  85024. var faceVertices = [];
  85025. // Parse the face vertex data into an easy to work with format
  85026. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  85027. var vertex = vertexData[ j ];
  85028. if ( vertex.length > 0 ) {
  85029. var vertexParts = vertex.split( '/' );
  85030. faceVertices.push( vertexParts );
  85031. }
  85032. }
  85033. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  85034. var v1 = faceVertices[ 0 ];
  85035. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  85036. var v2 = faceVertices[ j ];
  85037. var v3 = faceVertices[ j + 1 ];
  85038. state.addFace(
  85039. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  85040. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  85041. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  85042. );
  85043. }
  85044. } else if ( lineFirstChar === 'l' ) {
  85045. var lineParts = line.substring( 1 ).trim().split( ' ' );
  85046. var lineVertices = [], lineUVs = [];
  85047. if ( line.indexOf( '/' ) === - 1 ) {
  85048. lineVertices = lineParts;
  85049. } else {
  85050. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  85051. var parts = lineParts[ li ].split( '/' );
  85052. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  85053. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  85054. }
  85055. }
  85056. state.addLineGeometry( lineVertices, lineUVs );
  85057. } else if ( lineFirstChar === 'p' ) {
  85058. var lineData = line.substr( 1 ).trim();
  85059. var pointData = lineData.split( ' ' );
  85060. state.addPointGeometry( pointData );
  85061. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  85062. // o object_name
  85063. // or
  85064. // g group_name
  85065. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  85066. // var name = result[ 0 ].substr( 1 ).trim();
  85067. var name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  85068. state.startObject( name );
  85069. } else if ( material_use_pattern.test( line ) ) {
  85070. // material
  85071. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  85072. } else if ( material_library_pattern.test( line ) ) {
  85073. // mtl file
  85074. state.materialLibraries.push( line.substring( 7 ).trim() );
  85075. } else if ( map_use_pattern.test( line ) ) {
  85076. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  85077. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  85078. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  85079. } else if ( lineFirstChar === 's' ) {
  85080. result = line.split( ' ' );
  85081. // smooth shading
  85082. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  85083. // but does not define a usemtl for each face set.
  85084. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  85085. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  85086. // where explicit usemtl defines geometry groups.
  85087. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  85088. /*
  85089. * http://paulbourke.net/dataformats/obj/
  85090. * or
  85091. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  85092. *
  85093. * From chapter "Grouping" Syntax explanation "s group_number":
  85094. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  85095. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  85096. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  85097. * than 0."
  85098. */
  85099. if ( result.length > 1 ) {
  85100. var value = result[ 1 ].trim().toLowerCase();
  85101. state.object.smooth = ( value !== '0' && value !== 'off' );
  85102. } else {
  85103. // ZBrush can produce "s" lines #11707
  85104. state.object.smooth = true;
  85105. }
  85106. var material = state.object.currentMaterial();
  85107. if ( material ) material.smooth = state.object.smooth;
  85108. } else {
  85109. // Handle null terminated files without exception
  85110. if ( line === '\0' ) continue;
  85111. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  85112. }
  85113. }
  85114. state.finalize();
  85115. var container = new Group();
  85116. container.materialLibraries = [].concat( state.materialLibraries );
  85117. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  85118. if ( hasPrimitives === true ) {
  85119. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  85120. var object = state.objects[ i ];
  85121. var geometry = object.geometry;
  85122. var materials = object.materials;
  85123. var isLine = ( geometry.type === 'Line' );
  85124. var isPoints = ( geometry.type === 'Points' );
  85125. var hasVertexColors = false;
  85126. // Skip o/g line declarations that did not follow with any faces
  85127. if ( geometry.vertices.length === 0 ) continue;
  85128. var buffergeometry = new BufferGeometry();
  85129. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  85130. if ( geometry.normals.length > 0 ) {
  85131. buffergeometry.setAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  85132. }
  85133. if ( geometry.colors.length > 0 ) {
  85134. hasVertexColors = true;
  85135. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  85136. }
  85137. if ( geometry.hasUVIndices === true ) {
  85138. buffergeometry.setAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  85139. }
  85140. // Create materials
  85141. var createdMaterials = [];
  85142. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  85143. var sourceMaterial = materials[ mi ];
  85144. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  85145. var material = state.materials[ materialHash ];
  85146. if ( this.materials !== null ) {
  85147. material = this.materials.create( sourceMaterial.name );
  85148. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  85149. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  85150. var materialLine = new LineBasicMaterial();
  85151. Material.prototype.copy.call( materialLine, material );
  85152. materialLine.color.copy( material.color );
  85153. material = materialLine;
  85154. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  85155. var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  85156. Material.prototype.copy.call( materialPoints, material );
  85157. materialPoints.color.copy( material.color );
  85158. materialPoints.map = material.map;
  85159. material = materialPoints;
  85160. }
  85161. }
  85162. if ( material === undefined ) {
  85163. if ( isLine ) {
  85164. material = new LineBasicMaterial();
  85165. } else if ( isPoints ) {
  85166. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  85167. } else {
  85168. material = new MeshPhongMaterial();
  85169. }
  85170. material.name = sourceMaterial.name;
  85171. material.flatShading = sourceMaterial.smooth ? false : true;
  85172. material.vertexColors = hasVertexColors;
  85173. state.materials[ materialHash ] = material;
  85174. }
  85175. createdMaterials.push( material );
  85176. }
  85177. // Create mesh
  85178. var mesh;
  85179. if ( createdMaterials.length > 1 ) {
  85180. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  85181. var sourceMaterial = materials[ mi ];
  85182. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  85183. }
  85184. if ( isLine ) {
  85185. mesh = new LineSegments( buffergeometry, createdMaterials );
  85186. } else if ( isPoints ) {
  85187. mesh = new Points( buffergeometry, createdMaterials );
  85188. } else {
  85189. mesh = new Mesh( buffergeometry, createdMaterials );
  85190. }
  85191. } else {
  85192. if ( isLine ) {
  85193. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  85194. } else if ( isPoints ) {
  85195. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  85196. } else {
  85197. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  85198. }
  85199. }
  85200. mesh.name = object.name;
  85201. container.add( mesh );
  85202. }
  85203. } else {
  85204. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  85205. if ( state.vertices.length > 0 ) {
  85206. var material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  85207. var buffergeometry = new BufferGeometry();
  85208. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( state.vertices, 3 ) );
  85209. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  85210. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( state.colors, 3 ) );
  85211. material.vertexColors = true;
  85212. }
  85213. var points = new Points( buffergeometry, material );
  85214. container.add( points );
  85215. }
  85216. }
  85217. return container;
  85218. }
  85219. } );
  85220. return OBJLoader;
  85221. } )();
  85222. /**
  85223. * Loads a Wavefront .mtl file specifying materials
  85224. */
  85225. var MTLLoader = function ( manager ) {
  85226. Loader.call( this, manager );
  85227. };
  85228. MTLLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  85229. constructor: MTLLoader,
  85230. /**
  85231. * Loads and parses a MTL asset from a URL.
  85232. *
  85233. * @param {String} url - URL to the MTL file.
  85234. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  85235. * @param {Function} [onProgress] - Callback for download progress.
  85236. * @param {Function} [onError] - Callback for download errors.
  85237. *
  85238. * @see setPath setResourcePath
  85239. *
  85240. * @note In order for relative texture references to resolve correctly
  85241. * you must call setResourcePath() explicitly prior to load.
  85242. */
  85243. load: function ( url, onLoad, onProgress, onError ) {
  85244. var scope = this;
  85245. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  85246. var loader = new FileLoader( this.manager );
  85247. loader.setPath( this.path );
  85248. loader.setRequestHeader( this.requestHeader );
  85249. loader.setWithCredentials( this.withCredentials );
  85250. loader.load( url, function ( text ) {
  85251. try {
  85252. onLoad( scope.parse( text, path ) );
  85253. } catch ( e ) {
  85254. if ( onError ) {
  85255. onError( e );
  85256. } else {
  85257. console.error( e );
  85258. }
  85259. scope.manager.itemError( url );
  85260. }
  85261. }, onProgress, onError );
  85262. },
  85263. setMaterialOptions: function ( value ) {
  85264. this.materialOptions = value;
  85265. return this;
  85266. },
  85267. /**
  85268. * Parses a MTL file.
  85269. *
  85270. * @param {String} text - Content of MTL file
  85271. * @return {MTLLoader.MaterialCreator}
  85272. *
  85273. * @see setPath setResourcePath
  85274. *
  85275. * @note In order for relative texture references to resolve correctly
  85276. * you must call setResourcePath() explicitly prior to parse.
  85277. */
  85278. parse: function ( text, path ) {
  85279. var lines = text.split( '\n' );
  85280. var info = {};
  85281. var delimiter_pattern = /\s+/;
  85282. var materialsInfo = {};
  85283. for ( var i = 0; i < lines.length; i ++ ) {
  85284. var line = lines[ i ];
  85285. line = line.trim();
  85286. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  85287. // Blank line or comment ignore
  85288. continue;
  85289. }
  85290. var pos = line.indexOf( ' ' );
  85291. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  85292. key = key.toLowerCase();
  85293. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  85294. value = value.trim();
  85295. if ( key === 'newmtl' ) {
  85296. // New material
  85297. info = { name: value };
  85298. materialsInfo[ value ] = info;
  85299. } else {
  85300. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  85301. var ss = value.split( delimiter_pattern, 3 );
  85302. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  85303. } else {
  85304. info[ key ] = value;
  85305. }
  85306. }
  85307. }
  85308. var materialCreator = new MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  85309. materialCreator.setCrossOrigin( this.crossOrigin );
  85310. materialCreator.setManager( this.manager );
  85311. materialCreator.setMaterials( materialsInfo );
  85312. return materialCreator;
  85313. }
  85314. } );
  85315. /**
  85316. * Create a new MTLLoader.MaterialCreator
  85317. * @param baseUrl - Url relative to which textures are loaded
  85318. * @param options - Set of options on how to construct the materials
  85319. * side: Which side to apply the material
  85320. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  85321. * wrap: What type of wrapping to apply for textures
  85322. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  85323. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  85324. * Default: false, assumed to be already normalized
  85325. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  85326. * Default: false
  85327. * @constructor
  85328. */
  85329. MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  85330. this.baseUrl = baseUrl || '';
  85331. this.options = options;
  85332. this.materialsInfo = {};
  85333. this.materials = {};
  85334. this.materialsArray = [];
  85335. this.nameLookup = {};
  85336. this.side = ( this.options && this.options.side ) ? this.options.side : FrontSide;
  85337. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : RepeatWrapping;
  85338. };
  85339. MTLLoader.MaterialCreator.prototype = {
  85340. constructor: MTLLoader.MaterialCreator,
  85341. crossOrigin: 'anonymous',
  85342. setCrossOrigin: function ( value ) {
  85343. this.crossOrigin = value;
  85344. return this;
  85345. },
  85346. setManager: function ( value ) {
  85347. this.manager = value;
  85348. },
  85349. setMaterials: function ( materialsInfo ) {
  85350. this.materialsInfo = this.convert( materialsInfo );
  85351. this.materials = {};
  85352. this.materialsArray = [];
  85353. this.nameLookup = {};
  85354. },
  85355. convert: function ( materialsInfo ) {
  85356. if ( ! this.options ) return materialsInfo;
  85357. var converted = {};
  85358. for ( var mn in materialsInfo ) {
  85359. // Convert materials info into normalized form based on options
  85360. var mat = materialsInfo[ mn ];
  85361. var covmat = {};
  85362. converted[ mn ] = covmat;
  85363. for ( var prop in mat ) {
  85364. var save = true;
  85365. var value = mat[ prop ];
  85366. var lprop = prop.toLowerCase();
  85367. switch ( lprop ) {
  85368. case 'kd':
  85369. case 'ka':
  85370. case 'ks':
  85371. // Diffuse color (color under white light) using RGB values
  85372. if ( this.options && this.options.normalizeRGB ) {
  85373. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  85374. }
  85375. if ( this.options && this.options.ignoreZeroRGBs ) {
  85376. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  85377. // ignore
  85378. save = false;
  85379. }
  85380. }
  85381. break;
  85382. default:
  85383. break;
  85384. }
  85385. if ( save ) {
  85386. covmat[ lprop ] = value;
  85387. }
  85388. }
  85389. }
  85390. return converted;
  85391. },
  85392. preload: function () {
  85393. for ( var mn in this.materialsInfo ) {
  85394. this.create( mn );
  85395. }
  85396. },
  85397. getIndex: function ( materialName ) {
  85398. return this.nameLookup[ materialName ];
  85399. },
  85400. getAsArray: function () {
  85401. var index = 0;
  85402. for ( var mn in this.materialsInfo ) {
  85403. this.materialsArray[ index ] = this.create( mn );
  85404. this.nameLookup[ mn ] = index;
  85405. index ++;
  85406. }
  85407. return this.materialsArray;
  85408. },
  85409. create: function ( materialName ) {
  85410. if ( this.materials[ materialName ] === undefined ) {
  85411. this.createMaterial_( materialName );
  85412. }
  85413. return this.materials[ materialName ];
  85414. },
  85415. createMaterial_: function ( materialName ) {
  85416. // Create material
  85417. var scope = this;
  85418. var mat = this.materialsInfo[ materialName ];
  85419. var params = {
  85420. name: materialName,
  85421. side: this.side
  85422. };
  85423. function resolveURL( baseUrl, url ) {
  85424. if ( typeof url !== 'string' || url === '' )
  85425. return '';
  85426. // Absolute URL
  85427. if ( /^https?:\/\//i.test( url ) ) return url;
  85428. return baseUrl + url;
  85429. }
  85430. function setMapForType( mapType, value ) {
  85431. if ( params[ mapType ] ) return; // Keep the first encountered texture
  85432. var texParams = scope.getTextureParams( value, params );
  85433. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  85434. map.repeat.copy( texParams.scale );
  85435. map.offset.copy( texParams.offset );
  85436. map.wrapS = scope.wrap;
  85437. map.wrapT = scope.wrap;
  85438. params[ mapType ] = map;
  85439. }
  85440. for ( var prop in mat ) {
  85441. var value = mat[ prop ];
  85442. var n;
  85443. if ( value === '' ) continue;
  85444. switch ( prop.toLowerCase() ) {
  85445. // Ns is material specular exponent
  85446. case 'kd':
  85447. // Diffuse color (color under white light) using RGB values
  85448. params.color = new Color().fromArray( value );
  85449. break;
  85450. case 'ks':
  85451. // Specular color (color when light is reflected from shiny surface) using RGB values
  85452. //params.specular = new Color().fromArray( value );
  85453. //console.log('specular',value)
  85454. break;
  85455. case 'ke':
  85456. // Emissive using RGB values
  85457. params.emissive = new Color().fromArray( value );
  85458. break;
  85459. case 'map_kd':
  85460. // Diffuse texture map
  85461. setMapForType( 'map', value );
  85462. break;
  85463. case 'map_ks':
  85464. // Specular map
  85465. setMapForType( 'specularMap', value );
  85466. break;
  85467. case 'map_ke':
  85468. // Emissive map
  85469. setMapForType( 'emissiveMap', value );
  85470. break;
  85471. case 'norm':
  85472. setMapForType( 'normalMap', value );
  85473. break;
  85474. case 'map_bump':
  85475. case 'bump':
  85476. // Bump texture map
  85477. setMapForType( 'bumpMap', value );
  85478. break;
  85479. case 'map_d':
  85480. // Alpha map
  85481. setMapForType( 'alphaMap', value );
  85482. params.transparent = true;
  85483. break;
  85484. case 'ns':
  85485. // The specular exponent (defines the focus of the specular highlight)
  85486. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  85487. //params.shininess = parseFloat( value );
  85488. //console.log('shininess',value)
  85489. break;
  85490. case 'd':
  85491. n = parseFloat( value );
  85492. if ( n < 1 ) {
  85493. params.opacity = n;
  85494. params.transparent = true;
  85495. }
  85496. break;
  85497. case 'tr':
  85498. n = parseFloat( value );
  85499. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  85500. if ( n > 0 ) {
  85501. params.opacity = 1 - n;
  85502. params.transparent = true;
  85503. }
  85504. break;
  85505. default:
  85506. break;
  85507. }
  85508. }
  85509. this.materials[ materialName ] = new MeshStandardMaterial( params );//MeshPhongMaterial( params );
  85510. return this.materials[ materialName ];
  85511. },
  85512. getTextureParams: function ( value, matParams ) {
  85513. var texParams = {
  85514. scale: new Vector2$1( 1, 1 ),
  85515. offset: new Vector2$1( 0, 0 )
  85516. };
  85517. var items = value.split( /\s+/ );
  85518. var pos;
  85519. pos = items.indexOf( '-bm' );
  85520. if ( pos >= 0 ) {
  85521. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  85522. items.splice( pos, 2 );
  85523. }
  85524. pos = items.indexOf( '-s' );
  85525. if ( pos >= 0 ) {
  85526. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85527. items.splice( pos, 4 ); // we expect 3 parameters here!
  85528. }
  85529. pos = items.indexOf( '-o' );
  85530. if ( pos >= 0 ) {
  85531. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85532. items.splice( pos, 4 ); // we expect 3 parameters here!
  85533. }
  85534. texParams.url = items.join( ' ' ).trim();
  85535. return texParams;
  85536. },
  85537. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  85538. var texture;
  85539. var manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  85540. var loader = manager.getHandler( url );
  85541. if ( loader === null ) {
  85542. loader = new TextureLoader( manager );
  85543. }
  85544. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  85545. texture = loader.load( url, onLoad, onProgress, onError );
  85546. if ( mapping !== undefined ) texture.mapping = mapping;
  85547. return texture;
  85548. }
  85549. };
  85550. /**
  85551. * @author alteredq / http://alteredqualia.com/
  85552. */
  85553. let Pass = function () {
  85554. // if set to true, the pass is processed by the composer
  85555. this.enabled = true;
  85556. // if set to true, the pass indicates to swap read and write buffer after rendering
  85557. this.needsSwap = true;
  85558. // if set to true, the pass clears its buffer before rendering
  85559. this.clear = false;
  85560. // if set to true, the result of the pass is rendered to screen
  85561. this.renderToScreen = false;
  85562. };
  85563. Object.assign( Pass.prototype, {
  85564. setSize: function ( width, height ) {},
  85565. render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
  85566. console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
  85567. }
  85568. } );
  85569. let ShaderPass = function ( shader, textureID ) {
  85570. Pass.call( this );
  85571. this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse";
  85572. if ( shader instanceof ShaderMaterial ) {
  85573. this.uniforms = shader.uniforms;
  85574. this.material = shader;
  85575. } else if ( shader ) {
  85576. this.uniforms = UniformsUtils.clone( shader.uniforms );
  85577. this.material = new ShaderMaterial( {
  85578. defines: Object.assign( {}, shader.defines ),
  85579. uniforms: this.uniforms,
  85580. vertexShader: shader.vertexShader,
  85581. fragmentShader: shader.fragmentShader,
  85582. transparent:true,//add
  85583. } );
  85584. }
  85585. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85586. this.scene = new Scene();
  85587. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  85588. this.quad.frustumCulled = false; // Avoid getting clipped
  85589. this.scene.add( this.quad );
  85590. };
  85591. ShaderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85592. constructor: ShaderPass,
  85593. render: function(scene,camera, renderer, writeBuffer, readBuffer, delta, maskActive ) {
  85594. let oldTarget = renderer.getRenderTarget();
  85595. /* if(this.readTarget){ //add
  85596. readBuffer = oldTarget
  85597. } */
  85598. if ( this.uniforms[ this.textureID ] ) {
  85599. this.uniforms[ this.textureID ].value = readBuffer.texture;
  85600. }
  85601. this.quad.material = this.material;
  85602. if ( this.renderToScreen ) {
  85603. renderer.render( this.scene, this.camera );
  85604. } else {
  85605. renderer.setRenderTarget(writeBuffer);
  85606. if(this.clear) renderer.clear();
  85607. renderer.render( this.scene, this.camera );
  85608. renderer.setRenderTarget(oldTarget);
  85609. }
  85610. }
  85611. } );
  85612. /**
  85613. * @author alteredq / http://alteredqualia.com/
  85614. *
  85615. * Full-screen textured quad shader
  85616. */
  85617. let CopyShader = {
  85618. uniforms: {
  85619. "tDiffuse": { value: null },
  85620. "opacity": { value: 1.0 }
  85621. },
  85622. vertexShader: [
  85623. "varying vec2 vUv;",
  85624. "void main() {",
  85625. "vUv = uv;",
  85626. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  85627. "}"
  85628. ].join( "\n" ),
  85629. fragmentShader: [
  85630. "uniform float opacity;",
  85631. "uniform sampler2D tDiffuse;",
  85632. "varying vec2 vUv;",
  85633. "void main() {",
  85634. "vec4 texel = texture2D( tDiffuse, vUv );", //如果开启premultipliedAlpha用这个,否则用注释的
  85635. "gl_FragColor = opacity * texel;",
  85636. //"gl_FragColor = texture2D( tDiffuse, vUv );",
  85637. //"gl_FragColor.a *= opacity;",
  85638. "}"
  85639. ].join( "\n" )
  85640. };
  85641. /**
  85642. *
  85643. * Supersample Anti-Aliasing Render Pass
  85644. *
  85645. * @author bhouston / http://clara.io/
  85646. *
  85647. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  85648. *
  85649. * References: https://en.wikipedia.org/wiki/Supersampling
  85650. *
  85651. */
  85652. //较为原始的一种抗锯齿 (超级采样抗锯齿)
  85653. let SSAARenderPass = function ( clearColor, clearAlpha ) {
  85654. Pass.call( this );
  85655. //this.scene //= scene;
  85656. //this.camera = camera;
  85657. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  85658. this.unbiased = true;
  85659. // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
  85660. this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
  85661. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  85662. this.renderUniforms = {
  85663. bgTex : {value:null},
  85664. outlineTex : {value:null},
  85665. opacity : {value:1},
  85666. };
  85667. this.renderMat = new ShaderMaterial({
  85668. uniforms: this.renderUniforms,
  85669. vertexShader: CopyShader.vertexShader,
  85670. /* fragmentShader: CopyShader.fragmentShader, */
  85671. fragmentShader: `
  85672. uniform sampler2D bgTex;
  85673. uniform sampler2D outlineTex;
  85674. uniform float opacity;
  85675. varying vec2 vUv;
  85676. void main() {
  85677. vec4 color1 = texture2D( bgTex, vUv );
  85678. vec4 color2 = texture2D( outlineTex, vUv );
  85679. gl_FragColor = opacity * mix(color1, color2, color2.a) ;
  85680. }
  85681. `,
  85682. premultipliedAlpha: true,
  85683. blending: AdditiveBlending,
  85684. depthTest: false,
  85685. depthWrite: false,
  85686. transparent: true
  85687. });
  85688. this.renderMat2 = new ShaderMaterial({
  85689. uniforms: UniformsUtils.clone(CopyShader.uniforms) ,
  85690. vertexShader: CopyShader.vertexShader,
  85691. fragmentShader:`uniform float opacity;
  85692. uniform sampler2D tDiffuse;
  85693. varying vec2 vUv;
  85694. void main() {
  85695. vec4 texel = texture2D( tDiffuse, vUv );
  85696. if(texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0){
  85697. discard;
  85698. }else{
  85699. gl_FragColor = opacity * texel;
  85700. }
  85701. }
  85702. ` ,
  85703. depthTest: false,
  85704. depthWrite: false,
  85705. transparent: true
  85706. });
  85707. ////////////////////
  85708. /* this.renderMat.blendSrc = THREE.OneFactor //即将写入缓冲区的颜色。
  85709. this.renderMat.blendDst = THREE.OneFactor //缓冲区已经存在的颜色
  85710. this.renderMat.blendEquation = THREE.AddEquation;
  85711. this.renderMat.blendEquationAlpha = THREE.AddEquation;
  85712. this.renderMat.blendDstAlpha = THREE.SrcAlphaFactor
  85713. this.renderMat.blendSrcAlpha = THREE.SrcAlphaFactor */
  85714. this.camera2 = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85715. this.scene2 = new Scene();
  85716. this.quad2 = new Mesh( new PlaneBufferGeometry( 2, 2 ), this.renderMat/* this.copyMaterial */ );
  85717. this.quad2.frustumCulled = false; // Avoid getting clipped
  85718. this.scene2.add( this.quad2 );
  85719. this.copyPass = new ShaderPass( CopyShader );
  85720. this.copyPass.renderToScreen = true;
  85721. };
  85722. SSAARenderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85723. constructor: SSAARenderPass,
  85724. dispose: function () {
  85725. if ( this.sampleRenderTarget ) {
  85726. this.sampleRenderTarget.dispose();
  85727. this.sampleRenderTarget = null;
  85728. }
  85729. },
  85730. setSize: function ( width, height ) {
  85731. if ( this.sampleRenderTarget ) this.sampleRenderTarget.setSize( width, height );
  85732. this.childPass && this.childPass.setSize(width, height);
  85733. },
  85734. addPass: function (pass){
  85735. this.childPass = pass;
  85736. },
  85737. render: function (scene, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  85738. if(this.useCopy ){
  85739. scene = this.copyPass.scene; camera = this.copyPass.camera;
  85740. }
  85741. if ( ! this.sampleRenderTarget ) {
  85742. this.sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat } );
  85743. this.sampleRenderTarget.texture.name = "SSAARenderPass.sample";
  85744. }
  85745. var jitterOffsets = SSAARenderPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  85746. var autoClear = renderer.autoClear;
  85747. renderer.autoClear = false;
  85748. var oldClearColor = renderer.getClearColor(new Color).getHex();
  85749. var oldClearAlpha = renderer.getClearAlpha();
  85750. renderer.setClearColor( this.clearColor, this.clearAlpha );
  85751. var baseSampleWeight = 1.0 / jitterOffsets.length;
  85752. var roundingRange = 1 / 32;
  85753. //this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
  85754. let oldTarget = renderer.getRenderTarget();
  85755. if(oldTarget){
  85756. if(oldTarget.scissorTest){
  85757. var width = oldTarget.scissor.w, height = oldTarget.scissor.z;
  85758. }else {
  85759. var width = oldTarget.width, height = oldTarget.height;
  85760. }
  85761. }else {
  85762. var width = readBuffer.width, height = readBuffer.height;
  85763. }
  85764. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  85765. let opa = 0;
  85766. for ( var i = 0; i < jitterOffsets.length; i ++ ) {
  85767. var jitterOffset = jitterOffsets[ i ];
  85768. if ( camera.setViewOffset ) {
  85769. camera.setViewOffset( width, height,
  85770. jitterOffset[ 0 ] * 0.0625 , jitterOffset[ 1 ] * 0.0625 , // 0.0625 = 1 / 16
  85771. width, height );
  85772. }
  85773. var sampleWeight = baseSampleWeight;
  85774. if ( this.unbiased ) {//更柔和
  85775. var uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  85776. sampleWeight += roundingRange * uniformCenteredDistribution;
  85777. }
  85778. renderer.setRenderTarget(this.sampleRenderTarget);
  85779. renderer.clear();
  85780. if(this.useCopy){
  85781. this.copyPass.render(scene,camera, renderer, writeBuffer, readBuffer );
  85782. }else {
  85783. if(renderFun){
  85784. renderFun({target : this.sampleRenderTarget});
  85785. }else {
  85786. renderer.render( scene, camera );
  85787. }
  85788. }
  85789. renderer.setRenderTarget(oldTarget);
  85790. //---------------------
  85791. //获取outline tex
  85792. let hasOutline = this.childPass && this.childPass.render(scene, camera, renderer, writeBuffer, readBuffer, null, renderFun );
  85793. //合成到该材质
  85794. this.renderUniforms[ "bgTex" ].value = this.sampleRenderTarget.texture;
  85795. this.renderUniforms[ "outlineTex" ].value = hasOutline ? readBuffer.texture : null;
  85796. this.renderUniforms[ "opacity" ].value = sampleWeight;
  85797. /* console.log('sampleWeight', sampleWeight)
  85798. opa += sampleWeight */
  85799. if(!this.renderToScreen){
  85800. renderer.setRenderTarget(writeBuffer);
  85801. }
  85802. if(i === 0 ){
  85803. renderer.setClearColor( 0x000000, 0 ); //叠加前颜色必须0
  85804. renderer.clear();
  85805. }
  85806. renderer.render( this.scene2, this.camera2); // , this.renderToScreen ? null : writeBuffer, ( i === 0 )
  85807. if(!this.renderToScreen){
  85808. renderer.setRenderTarget(oldTarget);
  85809. }
  85810. //if(i==2)break;
  85811. }
  85812. //console.log('sum:',opa)
  85813. if ( camera.clearViewOffset )camera.clearViewOffset();
  85814. //renderer.setRenderTarget(readBuffer)
  85815. //renderer.setClearColor( 0x000000, 0 );
  85816. //renderer.clear()
  85817. /* this.quad2.material = this.renderMat2
  85818. this.renderMat2.uniforms.tDiffuse.value = writeBuffer.texture;
  85819. renderer.render( this.scene2, this.camera2);
  85820. this.quad2.material = this.renderMat */
  85821. //renderer.setRenderTarget(oldTarget)
  85822. renderer.autoClear = autoClear;
  85823. renderer.setClearColor( oldClearColor, oldClearAlpha );
  85824. /* 试了好几次,测量线的透明度还是还原不了。 clearAlpha十分影响结果。
  85825. 因为绘制测量线需要背景透明。 或许可以先全部绘制完后,再 copyshader中 抗锯齿?
  85826. 另外会有黑边。
  85827. */
  85828. }
  85829. } );
  85830. // These jitter vectors are specified in integers because it is easier.
  85831. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  85832. // before being used, thus these integers need to be scaled by 1/16.
  85833. //
  85834. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  85835. SSAARenderPass.JitterVectors = [
  85836. [
  85837. [ 0, 0 ]
  85838. ],
  85839. [
  85840. [ 4, 4 ], [ - 4, - 4 ]
  85841. ],
  85842. [
  85843. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  85844. ],
  85845. [
  85846. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  85847. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  85848. ],
  85849. [
  85850. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  85851. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  85852. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  85853. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  85854. ],
  85855. [
  85856. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  85857. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  85858. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  85859. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  85860. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  85861. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  85862. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  85863. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  85864. ]
  85865. ];
  85866. class MaskPass extends Pass {
  85867. constructor( scene, camera ) {
  85868. super();
  85869. this.scene = scene;
  85870. this.camera = camera;
  85871. this.clear = true;
  85872. this.needsSwap = false;
  85873. this.inverse = false;
  85874. }
  85875. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  85876. const context = renderer.getContext();
  85877. const state = renderer.state;
  85878. // don't update color or depth
  85879. state.buffers.color.setMask( false );
  85880. state.buffers.depth.setMask( false );
  85881. // lock buffers
  85882. state.buffers.color.setLocked( true );
  85883. state.buffers.depth.setLocked( true );
  85884. // set up stencil
  85885. let writeValue, clearValue;
  85886. if ( this.inverse ) {
  85887. writeValue = 0;
  85888. clearValue = 1;
  85889. } else {
  85890. writeValue = 1;
  85891. clearValue = 0;
  85892. }
  85893. state.buffers.stencil.setTest( true );
  85894. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  85895. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  85896. state.buffers.stencil.setClear( clearValue );
  85897. state.buffers.stencil.setLocked( true );
  85898. // draw into the stencil buffer
  85899. renderer.setRenderTarget( readBuffer );
  85900. if ( this.clear ) renderer.clear();
  85901. renderer.render( this.scene, this.camera );
  85902. renderer.setRenderTarget( writeBuffer );
  85903. if ( this.clear ) renderer.clear();
  85904. renderer.render( this.scene, this.camera );
  85905. // unlock color and depth buffer for subsequent rendering
  85906. state.buffers.color.setLocked( false );
  85907. state.buffers.depth.setLocked( false );
  85908. // only render where stencil is set to 1
  85909. state.buffers.stencil.setLocked( false );
  85910. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  85911. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  85912. state.buffers.stencil.setLocked( true );
  85913. }
  85914. }
  85915. class ClearMaskPass extends Pass {
  85916. constructor() {
  85917. super();
  85918. this.needsSwap = false;
  85919. }
  85920. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  85921. renderer.state.buffers.stencil.setLocked( false );
  85922. renderer.state.buffers.stencil.setTest( false );
  85923. }
  85924. }
  85925. /**
  85926. * @author alteredq / http://alteredqualia.com/
  85927. */
  85928. var EffectComposer = function ( renderer, renderTarget ) {
  85929. this.renderer = renderer;
  85930. if ( renderTarget === undefined ) {
  85931. var parameters = {
  85932. minFilter: LinearFilter,
  85933. magFilter: LinearFilter,
  85934. format: RGBAFormat,
  85935. stencilBuffer: false,
  85936. };
  85937. var size = renderer.getDrawingBufferSize(new Vector2$1);
  85938. renderTarget = new WebGLRenderTarget( size.width, size.height , parameters );
  85939. renderTarget.texture.name = 'EffectComposer.rt1';
  85940. }
  85941. this.renderTarget1 = renderTarget;
  85942. this.renderTarget2 = renderTarget.clone();
  85943. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  85944. this.writeBuffer = this.renderTarget1;
  85945. this.readBuffer = this.renderTarget2;
  85946. this.passes = [];
  85947. // dependencies
  85948. /* if ( THREE.CopyShader === undefined ) {
  85949. console.error( 'THREE.EffectComposer relies on THREE.CopyShader' );
  85950. }
  85951. if ( THREE.ShaderPass === undefined ) {
  85952. console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' );
  85953. } */
  85954. this.copyPass = new ShaderPass( CopyShader );
  85955. };
  85956. Object.assign( EffectComposer.prototype, {
  85957. swapBuffers: function () {
  85958. var tmp = this.readBuffer;
  85959. this.readBuffer = this.writeBuffer;
  85960. this.writeBuffer = tmp;
  85961. },
  85962. addPass: function ( pass ) {
  85963. this.passes.push( pass );
  85964. var size = this.renderer.getDrawingBufferSize(new Vector2$1);
  85965. pass.setSize( size.width, size.height );
  85966. },
  85967. removePass: function(pass){ //add
  85968. let index = this.passes.indexOf(pass);
  85969. index > -1 && this.passes.splice(index,1);
  85970. },
  85971. insertPass: function ( pass, index ) {
  85972. this.passes.splice( index, 0, pass );
  85973. },
  85974. render: function ( scene, camera, viewports, renderFun ) {
  85975. var maskActive = false;
  85976. let passes = this.passes.filter(e=>e.enabled);
  85977. var pass, i, il = passes.length;
  85978. if(this.readTarget){ //add 使用当前renderTarget中的像素
  85979. this.copyPass.render(scene, this.renderer, this.readBuffer, this.renderer.getRenderTarget() );
  85980. }
  85981. for ( i = 0; i < il; i ++ ) {
  85982. pass = passes[ i ];
  85983. //if(i == il-1)pass.renderToScreen = true//
  85984. pass.render( scene, camera, viewports, this.renderer, this.writeBuffer, this.readBuffer, maskActive, renderFun );
  85985. if ( pass.needsSwap ) {
  85986. if ( maskActive ) {
  85987. var context = this.renderer.context;
  85988. context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
  85989. this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer );// delta
  85990. context.stencilFunc( context.EQUAL, 1, 0xffffffff );
  85991. }
  85992. this.swapBuffers();
  85993. }
  85994. if ( MaskPass !== undefined ) {
  85995. if ( pass instanceof MaskPass ) {
  85996. maskActive = true;
  85997. } else if ( pass instanceof ClearMaskPass ) {
  85998. maskActive = false;
  85999. }
  86000. }
  86001. }
  86002. //add
  86003. if(!pass.renderToScreen){ //最后一个如果没有绘制到屏幕or target上
  86004. this.copyPass.renderToScreen = true;
  86005. this.copyPass.render(null,null, this.renderer, this.writeBuffer, this.readBuffer);
  86006. }
  86007. },
  86008. reset: function ( renderTarget ) {
  86009. if ( renderTarget === undefined ) {
  86010. var size = this.renderer.getDrawingBufferSize(new Vector2$1);
  86011. renderTarget = this.renderTarget1.clone();
  86012. renderTarget.setSize( size.width, size.height );
  86013. }
  86014. this.renderTarget1.dispose();
  86015. this.renderTarget2.dispose();
  86016. this.renderTarget1 = renderTarget;
  86017. this.renderTarget2 = renderTarget.clone();
  86018. this.writeBuffer = this.renderTarget1;
  86019. this.readBuffer = this.renderTarget2;
  86020. },
  86021. setSize: function ( width, height, scaleRatio ) {
  86022. scaleRatio = scaleRatio || 1;
  86023. this.renderTarget1.setSize( width * scaleRatio , height * scaleRatio );
  86024. this.renderTarget2.setSize( width * scaleRatio, height * scaleRatio );
  86025. for ( var i = 0; i < this.passes.length; i ++ ) {
  86026. this.passes[ i ].setSize( width * scaleRatio, height * scaleRatio );
  86027. }
  86028. }
  86029. } );
  86030. /**
  86031. * @author alteredq / http://alteredqualia.com/
  86032. */
  86033. class RenderPass extends Pass {
  86034. constructor( overrideMaterial, clearColor, clearAlpha ) {
  86035. super();
  86036. /* this.scene = scene;
  86037. this.camera = camera; */
  86038. this.overrideMaterial = overrideMaterial;
  86039. this.clearColor = clearColor;
  86040. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  86041. this.clear = true;
  86042. this.clearDepth = false;
  86043. this.needsSwap = false;
  86044. this._oldClearColor = new Color();
  86045. }
  86046. render(scene, camera, renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  86047. const oldAutoClear = renderer.autoClear;
  86048. renderer.autoClear = false;
  86049. let oldClearAlpha, oldOverrideMaterial;
  86050. if ( this.overrideMaterial !== undefined ) {
  86051. oldOverrideMaterial = this.scene.overrideMaterial;
  86052. scene.overrideMaterial = this.overrideMaterial;
  86053. }
  86054. if ( this.clearColor ) {
  86055. renderer.getClearColor( this._oldClearColor );
  86056. oldClearAlpha = renderer.getClearAlpha();
  86057. renderer.setClearColor( this.clearColor, this.clearAlpha );
  86058. }
  86059. if ( this.clearDepth ) {
  86060. renderer.clearDepth();
  86061. }
  86062. let oldTarget = renderer.getRenderTarget();
  86063. if(!this.renderToScreen)renderer.setRenderTarget( readBuffer );
  86064. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  86065. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  86066. renderer.render( scene, camera );
  86067. if(!this.renderToScreen)renderer.setRenderTarget( oldTarget );
  86068. if ( this.clearColor ) {
  86069. renderer.setClearColor( this._oldClearColor, oldClearAlpha );
  86070. }
  86071. if ( this.overrideMaterial !== undefined ) {
  86072. scene.overrideMaterial = oldOverrideMaterial;
  86073. }
  86074. renderer.autoClear = oldAutoClear;
  86075. }
  86076. }
  86077. /**
  86078. * NVIDIA FXAA by Timothy Lottes
  86079. * https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf
  86080. * - WebGL port by @supereggbert
  86081. * http://www.glge.org/demos/fxaa/
  86082. * Further improved by Daniel Sturk
  86083. */
  86084. const FXAAShader = {
  86085. uniforms: {
  86086. 'tDiffuse': { value: null },
  86087. 'resolution': { value: new Vector2$1( 1 / 1024, 1 / 512 ) }
  86088. },
  86089. vertexShader: /* glsl */`
  86090. varying vec2 vUv;
  86091. void main() {
  86092. vUv = uv;
  86093. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  86094. }`,
  86095. fragmentShader: `
  86096. precision highp float;
  86097. uniform sampler2D tDiffuse;
  86098. uniform vec2 resolution;
  86099. varying vec2 vUv;
  86100. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  86101. //----------------------------------------------------------------------------------
  86102. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  86103. // SDK Version: v3.00
  86104. // Email: gameworks@nvidia.com
  86105. // Site: http://developer.nvidia.com/
  86106. //
  86107. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  86108. //
  86109. // Redistribution and use in source and binary forms, with or without
  86110. // modification, are permitted provided that the following conditions
  86111. // are met:
  86112. // * Redistributions of source code must retain the above copyright
  86113. // notice, this list of conditions and the following disclaimer.
  86114. // * Redistributions in binary form must reproduce the above copyright
  86115. // notice, this list of conditions and the following disclaimer in the
  86116. // documentation and/or other materials provided with the distribution.
  86117. // * Neither the name of NVIDIA CORPORATION nor the names of its
  86118. // contributors may be used to endorse or promote products derived
  86119. // from this software without specific prior written permission.
  86120. //
  86121. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  86122. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  86123. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  86124. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  86125. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  86126. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  86127. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  86128. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  86129. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  86130. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  86131. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  86132. //
  86133. //----------------------------------------------------------------------------------
  86134. #ifndef FXAA_DISCARD
  86135. //
  86136. // Only valid for PC OpenGL currently.
  86137. // Probably will not work when FXAA_GREEN_AS_LUMA = 1.
  86138. //
  86139. // 1 = Use discard on pixels which don't need AA.
  86140. // For APIs which enable concurrent TEX+ROP from same surface.
  86141. // 0 = Return unchanged color on pixels which don't need AA.
  86142. //
  86143. #define FXAA_DISCARD 0
  86144. #endif
  86145. /*--------------------------------------------------------------------------*/
  86146. #define FxaaTexTop(t, p) texture2D(t, p, -100.0)
  86147. #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), -100.0)
  86148. /*--------------------------------------------------------------------------*/
  86149. #define NUM_SAMPLES 5
  86150. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  86151. float contrast( vec4 a, vec4 b ) {
  86152. vec4 diff = abs( a - b );
  86153. return max( max( max( diff.r, diff.g ), diff.b ), diff.a );
  86154. }
  86155. /*============================================================================
  86156. FXAA3 QUALITY - PC
  86157. ============================================================================*/
  86158. /*--------------------------------------------------------------------------*/
  86159. vec4 FxaaPixelShader(
  86160. vec2 posM,
  86161. sampler2D tex,
  86162. vec2 fxaaQualityRcpFrame,
  86163. float fxaaQualityEdgeThreshold,
  86164. float fxaaQualityinvEdgeThreshold
  86165. ) {
  86166. vec4 rgbaM = FxaaTexTop(tex, posM);
  86167. vec4 rgbaS = FxaaTexOff(tex, posM, vec2( 0.0, 1.0), fxaaQualityRcpFrame.xy);
  86168. vec4 rgbaE = FxaaTexOff(tex, posM, vec2( 1.0, 0.0), fxaaQualityRcpFrame.xy);
  86169. vec4 rgbaN = FxaaTexOff(tex, posM, vec2( 0.0,-1.0), fxaaQualityRcpFrame.xy);
  86170. vec4 rgbaW = FxaaTexOff(tex, posM, vec2(-1.0, 0.0), fxaaQualityRcpFrame.xy);
  86171. // . S .
  86172. // W M E
  86173. // . N .
  86174. bool earlyExit = max( max( max(
  86175. contrast( rgbaM, rgbaN ),
  86176. contrast( rgbaM, rgbaS ) ),
  86177. contrast( rgbaM, rgbaE ) ),
  86178. contrast( rgbaM, rgbaW ) )
  86179. < fxaaQualityEdgeThreshold;
  86180. // . 0 .
  86181. // 0 0 0
  86182. // . 0 .
  86183. #if (FXAA_DISCARD == 1)
  86184. if(earlyExit) FxaaDiscard;
  86185. #else
  86186. if(earlyExit) return rgbaM;
  86187. #endif
  86188. float contrastN = contrast( rgbaM, rgbaN );
  86189. float contrastS = contrast( rgbaM, rgbaS );
  86190. float contrastE = contrast( rgbaM, rgbaE );
  86191. float contrastW = contrast( rgbaM, rgbaW );
  86192. float relativeVContrast = ( contrastN + contrastS ) - ( contrastE + contrastW );
  86193. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  86194. bool horzSpan = relativeVContrast > 0.;
  86195. // . 1 .
  86196. // 0 0 0
  86197. // . 1 .
  86198. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  86199. if( abs( relativeVContrast ) < .3 ) {
  86200. // locate the edge
  86201. vec2 dirToEdge;
  86202. dirToEdge.x = contrastE > contrastW ? 1. : -1.;
  86203. dirToEdge.y = contrastS > contrastN ? 1. : -1.;
  86204. // . 2 . . 1 .
  86205. // 1 0 2 ~= 0 0 1
  86206. // . 1 . . 0 .
  86207. // tap 2 pixels and see which ones are "outside" the edge, to
  86208. // determine if the edge is vertical or horizontal
  86209. vec4 rgbaAlongH = FxaaTexOff(tex, posM, vec2( dirToEdge.x, -dirToEdge.y ), fxaaQualityRcpFrame.xy);
  86210. float matchAlongH = contrast( rgbaM, rgbaAlongH );
  86211. // . 1 .
  86212. // 0 0 1
  86213. // . 0 H
  86214. vec4 rgbaAlongV = FxaaTexOff(tex, posM, vec2( -dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy);
  86215. float matchAlongV = contrast( rgbaM, rgbaAlongV );
  86216. // V 1 .
  86217. // 0 0 1
  86218. // . 0 .
  86219. relativeVContrast = matchAlongV - matchAlongH;
  86220. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  86221. if( abs( relativeVContrast ) < .3 ) { // 45 deg edge
  86222. // 1 1 .
  86223. // 0 0 1
  86224. // . 0 1
  86225. // do a simple blur
  86226. return mix(
  86227. rgbaM,
  86228. (rgbaN + rgbaS + rgbaE + rgbaW) * .25,
  86229. .4
  86230. );
  86231. }
  86232. horzSpan = relativeVContrast > 0.;
  86233. }
  86234. if(!horzSpan) rgbaN = rgbaW;
  86235. if(!horzSpan) rgbaS = rgbaE;
  86236. // . 0 . 1
  86237. // 1 0 1 -> 0
  86238. // . 0 . 1
  86239. bool pairN = contrast( rgbaM, rgbaN ) > contrast( rgbaM, rgbaS );
  86240. if(!pairN) rgbaN = rgbaS;
  86241. vec2 offNP;
  86242. offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;
  86243. offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;
  86244. bool doneN = false;
  86245. bool doneP = false;
  86246. float nDist = 0.;
  86247. float pDist = 0.;
  86248. vec2 posN = posM;
  86249. vec2 posP = posM;
  86250. int iterationsUsed = 0;
  86251. int iterationsUsedN = 0;
  86252. int iterationsUsedP = 0;
  86253. for( int i = 0; i < NUM_SAMPLES; i++ ) {
  86254. iterationsUsed = i;
  86255. float increment = float(i + 1);
  86256. if(!doneN) {
  86257. nDist += increment;
  86258. posN = posM + offNP * nDist;
  86259. vec4 rgbaEndN = FxaaTexTop(tex, posN.xy);
  86260. doneN = contrast( rgbaEndN, rgbaM ) > contrast( rgbaEndN, rgbaN );
  86261. iterationsUsedN = i;
  86262. }
  86263. if(!doneP) {
  86264. pDist += increment;
  86265. posP = posM - offNP * pDist;
  86266. vec4 rgbaEndP = FxaaTexTop(tex, posP.xy);
  86267. doneP = contrast( rgbaEndP, rgbaM ) > contrast( rgbaEndP, rgbaN );
  86268. iterationsUsedP = i;
  86269. }
  86270. if(doneN || doneP) break;
  86271. }
  86272. if ( !doneP && !doneN ) return rgbaM; // failed to find end of edge
  86273. float dist = min(
  86274. doneN ? float( iterationsUsedN ) / float( NUM_SAMPLES - 1 ) : 1.,
  86275. doneP ? float( iterationsUsedP ) / float( NUM_SAMPLES - 1 ) : 1.
  86276. );
  86277. // hacky way of reduces blurriness of mostly diagonal edges
  86278. // but reduces AA quality
  86279. dist = pow(dist, .5);
  86280. dist = 1. - dist;
  86281. return mix(
  86282. rgbaM,
  86283. rgbaN,
  86284. dist * .5
  86285. );
  86286. }
  86287. void main() {
  86288. const float edgeDetectionQuality = .05 ; //越高,越保留细节;越低,越平滑 但模糊
  86289. const float invEdgeDetectionQuality = 1. / edgeDetectionQuality;
  86290. gl_FragColor = FxaaPixelShader(
  86291. vUv,
  86292. tDiffuse,
  86293. resolution,
  86294. edgeDetectionQuality, // [0,1] contrast needed, otherwise early discard
  86295. invEdgeDetectionQuality
  86296. );
  86297. }
  86298. `
  86299. };
  86300. /**
  86301. * @author spidersharma / http://eduperiment.com/
  86302. */
  86303. let OutlinePass = function ( selectedObjects ) {
  86304. /* scene = scene;
  86305. camera = camera; */
  86306. this.selectedObjects = selectedObjects !== undefined ? selectedObjects : [];
  86307. this.visibleEdgeColor = new Color( 1, 1, 1 );
  86308. this.hiddenEdgeColor = new Color( 0.1, 0.04, 0.02 );
  86309. this.edgeGlow = 0.0;
  86310. this.usePatternTexture = false;
  86311. //this.edgeThickness = 1.0;
  86312. this.edgeStrength = 50;
  86313. this.downSampleRatio = 1;//2; // 抗锯齿 值越低renderTarget size越大,抗锯齿越强,线条可越细(或许可以把模糊化去掉?)
  86314. this.pulsePeriod = 0;
  86315. Pass.call( this );
  86316. this.resolution = new Vector2$1( 256, 256 );
  86317. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  86318. var resx = Math.round( this.resolution.x / this.downSampleRatio );
  86319. var resy = Math.round( this.resolution.y / this.downSampleRatio );
  86320. //this.maskBufferMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff } );
  86321. //this.maskBufferMaterial.side = THREE.DoubleSide;
  86322. this.renderTargetMaskBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  86323. this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask";
  86324. this.renderTargetMaskBuffer.texture.generateMipmaps = false;
  86325. this.depthMaterial = new MeshDepthMaterial();
  86326. this.depthMaterial.side = DoubleSide;
  86327. this.depthMaterial.depthPacking = RGBADepthPacking;
  86328. this.depthMaterial.blending = NoBlending;
  86329. this.prepareMaskMaterial = this.getPrepareMaskMaterial();
  86330. this.prepareMaskMaterial.side = DoubleSide;
  86331. //this.replaceDepthToViewZ( viewer.mainViewport.camera /* camera */ );
  86332. this.renderTargetDepthBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  86333. this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth";
  86334. this.renderTargetDepthBuffer.texture.generateMipmaps = false;
  86335. /* this.renderTargetMaskDownSampleBuffer = new THREE.WebGLRenderTarget( resx, resy, pars );
  86336. this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample";
  86337. this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false;
  86338. this.renderTargetBlurBuffer1 = new THREE.WebGLRenderTarget( resx, resy, pars );
  86339. this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1";
  86340. this.renderTargetBlurBuffer1.texture.generateMipmaps = false;
  86341. this.renderTargetBlurBuffer2 = new THREE.WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), pars );
  86342. this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2";
  86343. this.renderTargetBlurBuffer2.texture.generateMipmaps = false; */
  86344. this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(this.edgeStrength);
  86345. this.renderTargetEdgeBuffer1 = new WebGLRenderTarget( resx, resy, pars );
  86346. this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1";
  86347. this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
  86348. /* this.renderTargetEdgeBuffer2 = new THREE.WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), pars );
  86349. this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2";
  86350. this.renderTargetEdgeBuffer2.texture.generateMipmaps = false;
  86351. var MAX_EDGE_THICKNESS = 4;
  86352. var MAX_EDGE_GLOW = 4;
  86353. this.separableBlurMaterial1 = this.getSeperableBlurMaterial( MAX_EDGE_THICKNESS );
  86354. this.separableBlurMaterial1.uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
  86355. this.separableBlurMaterial1.uniforms[ "kernelRadius" ].value = 1;
  86356. this.separableBlurMaterial2 = this.getSeperableBlurMaterial( MAX_EDGE_GLOW );
  86357. this.separableBlurMaterial2.uniforms[ "texSize" ].value = new THREE.Vector2( Math.round( resx / 2 ), Math.round( resy / 2 ) );
  86358. this.separableBlurMaterial2.uniforms[ "kernelRadius" ].value = MAX_EDGE_GLOW;
  86359. */
  86360. // Overlay material
  86361. this.overlayMaterial = this.getOverlayMaterial();
  86362. // copy material
  86363. this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
  86364. this.copyUniforms[ "opacity" ].value = 1.0;
  86365. this.materialCopy = new ShaderMaterial( {
  86366. uniforms: this.copyUniforms,
  86367. vertexShader: CopyShader.vertexShader,
  86368. fragmentShader: CopyShader.fragmentShader,
  86369. blending: NoBlending,
  86370. depthTest: false,
  86371. depthWrite: false,
  86372. transparent: true
  86373. } );
  86374. this.enabled = true;
  86375. this.needsSwap = false;
  86376. this.oldClearColor = new Color();
  86377. this.oldClearAlpha = 1;
  86378. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  86379. this.scene = new Scene();
  86380. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  86381. this.quad.frustumCulled = false; // Avoid getting clipped
  86382. this.scene.add( this.quad );
  86383. /* this.tempPulseColor1 = new THREE.Color();
  86384. this.tempPulseColor2 = new THREE.Color(); */
  86385. this.textureMatrix = new Matrix4();
  86386. };
  86387. OutlinePass.prototype = Object.assign( Object.create( Pass.prototype ), {
  86388. constructor: OutlinePass,
  86389. dispose: function () {
  86390. this.renderTargetMaskBuffer.dispose();
  86391. this.renderTargetEdgeBuffer1.dispose();
  86392. this.renderTargetDepthBuffer.dispose();
  86393. },
  86394. replaceDepthToViewZ( camera ) {
  86395. var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
  86396. if(type == this.lastCameraType )return
  86397. this.lastCameraType = type;
  86398. this.prepareMaskMaterial.fragmentShader = this.prepareMaskMaterial.fragmentShader.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );
  86399. this.prepareMaskMaterial.needsUpdate = true;
  86400. },
  86401. setSize: function ( width, height ) {
  86402. this.renderTargetEdgeBuffer1.setSize( width, height );
  86403. this.renderTargetMaskBuffer.setSize( width, height );
  86404. this.resolution.set(width,height);
  86405. },
  86406. changeVisibilityOfSelectedObjects: function ( bVisible ) {
  86407. function gatherSelectedMeshesCallBack( object ) {
  86408. /* if ( object.isMesh ) { */
  86409. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  86410. /* if ( bVisible ) {
  86411. object.visible = object.userData.oldVisible;
  86412. delete object.userData.oldVisible;
  86413. } else {
  86414. object.userData.oldVisible = object.visible;
  86415. object.visible = bVisible;
  86416. } */
  86417. viewer.updateVisible(object, 'overlinePass', bVisible);
  86418. }
  86419. }
  86420. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  86421. var selectedObject = this.selectedObjects[ i ];
  86422. selectedObject.traverse( gatherSelectedMeshesCallBack );
  86423. }
  86424. },
  86425. changeVisibilityOfNonSelectedObjects: function ( bVisible , scenes) {
  86426. var selectedMeshes = [];
  86427. function gatherSelectedMeshesCallBack( object ) {
  86428. //if ( object.isMesh ) selectedMeshes.push( object );
  86429. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  86430. selectedMeshes.push( object );
  86431. }
  86432. }
  86433. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  86434. var selectedObject = this.selectedObjects[ i ];
  86435. selectedObject.traverse( gatherSelectedMeshesCallBack );
  86436. }
  86437. function VisibilityChangeCallBack( object ) {
  86438. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  86439. var bFound = false;
  86440. for ( var i = 0; i < selectedMeshes.length; i ++ ) {
  86441. var selectedObjectId = selectedMeshes[ i ].id;
  86442. if ( selectedObjectId === object.id ) {
  86443. bFound = true;
  86444. break;
  86445. }
  86446. }
  86447. if ( ! bFound ) {
  86448. var visibility = object.visible;
  86449. viewer.updateVisible(object, 'overlinePass', bVisible); //add
  86450. //但保不齐在设置为false后,渲染时又true了,所以在其他地方update时设置visible 得用updateVisible
  86451. if(!bVisible){
  86452. object.visible = false;
  86453. }else {
  86454. object.visible = !!object.bVisible;
  86455. }
  86456. object.bVisible = visibility;
  86457. //这两种updateVisible 和 visible 设置都不能去掉, 第一块是为了防止有的visible不是通过updateVisible设置的; 第二块是为了防止渲染时updateVisible又修改了visible为true, 另外渲染时
  86458. return {stopContinue:true} //for pointcloud
  86459. }
  86460. }
  86461. }
  86462. scenes.forEach(scene=>scene.traverse( VisibilityChangeCallBack ));
  86463. },
  86464. updateTextureMatrix: function (camera) {
  86465. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  86466. 0.0, 0.5, 0.0, 0.5,
  86467. 0.0, 0.0, 0.5, 0.5,
  86468. 0.0, 0.0, 0.0, 1.0 );
  86469. this.textureMatrix.multiply( camera.projectionMatrix );
  86470. this.textureMatrix.multiply( camera.matrixWorldInverse );
  86471. },
  86472. render: function (scenes, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  86473. if(!(scenes instanceof Array))scenes = [scenes];
  86474. if ( this.selectedObjects.length > 0 && this.edgeStrength > 0) {
  86475. let render2 = (target, dontRenderRtEDL=true)=>{
  86476. if(renderFun){
  86477. renderFun({target , dontRenderRtEDL});
  86478. }else {
  86479. renderer.setRenderTarget(target);
  86480. renderer.clear();
  86481. scenes.forEach(scene=>renderer.render( scene, camera));
  86482. }
  86483. };
  86484. viewports.forEach(e=>{
  86485. e.oldBeforeRender = e.beforeRender;
  86486. e.beforeRender = ()=>{
  86487. e.oldBeforeRender && e.oldBeforeRender();
  86488. this.replaceDepthToViewZ( e.camera );
  86489. };
  86490. });
  86491. this.oldClearColor.copy( renderer.getClearColor(new Color) );
  86492. this.oldClearAlpha = renderer.getClearAlpha();
  86493. let oldAutoClear = renderer.autoClear;
  86494. let oldTarget = renderer.getRenderTarget();
  86495. renderer.autoClear = false;
  86496. if ( maskActive ) renderer.context.disable( renderer.context.STENCIL_TEST );
  86497. renderer.setClearColor( 0xffffff, 1 );
  86498. // Make selected objects invisible
  86499. this.changeVisibilityOfSelectedObjects( false );
  86500. scenes.forEach(scene=>{
  86501. scene.currentBackground = scene.background;
  86502. scene.background = null;
  86503. // 1. Draw Non Selected objects in the depth buffer
  86504. scene.overrideMaterial = this.depthMaterial;
  86505. });
  86506. render2(this.renderTargetDepthBuffer);
  86507. //renderer.setRenderTarget(this.renderTargetDepthBuffer)
  86508. //renderer.clear()
  86509. //renderer.render( scene, camera/* , this.renderTargetDepthBuffer, true */);
  86510. // Make selected objects visible
  86511. this.changeVisibilityOfSelectedObjects( true );
  86512. viewports.forEach(e=>{
  86513. e.beforeRender = ()=>{
  86514. e.oldBeforeRender && e.oldBeforeRender();
  86515. // Update Texture Matrix for Depth compare
  86516. this.updateTextureMatrix(e.camera);
  86517. this.prepareMaskMaterial.uniforms[ "cameraNearFar" ].value = new Vector2$1( e.camera.near, e.camera.far );
  86518. };
  86519. });
  86520. // Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects
  86521. this.changeVisibilityOfNonSelectedObjects( false , scenes);
  86522. scenes.forEach(scene=>{
  86523. scene.overrideMaterial = this.prepareMaskMaterial;
  86524. });
  86525. this.prepareMaskMaterial.uniforms[ "depthTexture" ].value = this.renderTargetDepthBuffer.texture;
  86526. this.prepareMaskMaterial.uniforms[ "textureMatrix" ].value = this.textureMatrix;
  86527. //renderer.setRenderTarget(this.renderTargetMaskBuffer)
  86528. //renderer.clear()
  86529. //renderer.render( scene, camera/* , this.renderTargetMaskBuffer, true */ );
  86530. viewer.scene.pointclouds.forEach(e=>{ //先将点云透明度变为1,因为点云透明度莫名其妙会影响其r值
  86531. e.material._oldOpa = e.material.opacity;
  86532. e.material.opacity = 1;
  86533. });
  86534. render2(this.renderTargetMaskBuffer);
  86535. viewer.scene.pointclouds.forEach(e=>{//恢复
  86536. e.material.opacity = e.material._oldOpa;
  86537. delete e.material._oldOpa;
  86538. });
  86539. viewports.forEach((e)=>{e.beforeRender = e.oldBeforeRender;});
  86540. this.changeVisibilityOfNonSelectedObjects( true , scenes);
  86541. scenes.forEach(scene=>{
  86542. scene.overrideMaterial = null;
  86543. scene.background = scene.currentBackground;
  86544. });
  86545. // 3. Apply Edge Detection Pass
  86546. this.quad.material = this.edgeDetectionMaterial;
  86547. this.edgeDetectionMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;//this.renderTargetMaskDownSampleBuffer.texture;
  86548. this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new Vector2$1(this.resolution.x, this.resolution.y );//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  86549. //this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2(this.renderTargetMaskBuffer.width, this.renderTargetMaskBuffer.height)//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  86550. this.edgeDetectionMaterial.uniforms[ "edgeStrength" ].value = this.edgeStrength;
  86551. this.edgeDetectionMaterial.uniforms[ "visibleEdgeColor" ].value = this.visibleEdgeColor;//this.tempPulseColor1;
  86552. this.edgeDetectionMaterial.uniforms[ "hiddenEdgeColor" ].value = this.hiddenEdgeColor; //this.tempPulseColor2;
  86553. let buffer = readBuffer;
  86554. if ( this.renderToScreen ) {
  86555. this.quad.material.transparent = true;
  86556. buffer = null;
  86557. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  86558. render2(null,false);
  86559. //绘制到全屏
  86560. let renderSize = renderer.getSize(new Vector2$1()); //是client大小
  86561. renderer.setViewport(0, 0, renderSize.x, renderSize.y); //规定视口,影响图形变换(画布的使用范围)
  86562. renderer.setScissorTest( false );
  86563. }else {
  86564. renderer.setClearColor( 0x000000, 0 );
  86565. renderer.clear();
  86566. }
  86567. renderer.setRenderTarget(buffer/* this.renderTargetEdgeBuffer1 */);
  86568. renderer.render( this.scene, this.camera/* , this.renderTargetEdgeBuffer1, true */);
  86569. //这次删掉
  86570. /* // Blend it additively over the input texture
  86571. this.quad.material = this.overlayMaterial;
  86572. //this.overlayMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;
  86573. this.overlayMaterial.uniforms[ "edgeTexture1" ].value = this.renderTargetEdgeBuffer1.texture;
  86574. //this.overlayMaterial.uniforms[ "edgeTexture2" ].value = this.renderTargetEdgeBuffer2.texture;
  86575. //this.overlayMaterial.uniforms[ "patternTexture" ].value = this.patternTexture;
  86576. this.overlayMaterial.uniforms[ "edgeStrength" ].value = this.edgeStrength;
  86577. //this.overlayMaterial.uniforms[ "edgeGlow" ].value = this.edgeGlow;
  86578. //this.overlayMaterial.uniforms[ "usePatternTexture" ].value = this.usePatternTexture;
  86579. if ( maskActive ) renderer.context.enable( renderer.context.STENCIL_TEST );
  86580. //renderer.render( this.scene, camera, readBuffer, false );
  86581. //改:清空readBuffer, 仅绘制出outline的部分
  86582. renderer.setClearColor( 0x000000, 0 );
  86583. renderer.setRenderTarget(readBuffer)
  86584. renderer.clear()
  86585. renderer.render( this.scene, this.camera );
  86586. */
  86587. renderer.setRenderTarget(oldTarget);
  86588. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  86589. renderer.autoClear = oldAutoClear;
  86590. return true
  86591. }
  86592. /* if ( this.renderToScreen ) {
  86593. this.quad.material = this.materialCopy;
  86594. this.copyUniforms[ "tDiffuse" ].value = readBuffer.texture;
  86595. renderer.render( this.scene , this.camera );
  86596. } */
  86597. },
  86598. getPrepareMaskMaterial: function () {
  86599. return new ShaderMaterial( {
  86600. uniforms: {
  86601. "depthTexture": { value: null },
  86602. "cameraNearFar": { value: new Vector2$1( 0.5, 0.5 ) },
  86603. "textureMatrix": { value: new Matrix4() }
  86604. },
  86605. vertexShader: [
  86606. 'varying vec4 projTexCoord;',
  86607. 'varying vec4 vPosition;',
  86608. 'uniform mat4 textureMatrix;',
  86609. 'void main() {',
  86610. ' vPosition = modelViewMatrix * vec4( position, 1.0 );',
  86611. ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
  86612. ' projTexCoord = textureMatrix * worldPosition;',
  86613. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  86614. '}'
  86615. ].join( '\n' ),
  86616. fragmentShader: [
  86617. '#include <packing>',
  86618. 'varying vec4 vPosition;',
  86619. 'varying vec4 projTexCoord;',
  86620. 'uniform sampler2D depthTexture;',
  86621. 'uniform vec2 cameraNearFar;',
  86622. 'void main() {',
  86623. ' float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));',
  86624. ' float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );',
  86625. ' float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;',
  86626. ' gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);',
  86627. '}'
  86628. ].join( '\n' )
  86629. //scene.overrideMaterial
  86630. //为什么画出来红色通道不为0,且depthTest似乎会改变红色通道的值
  86631. } );
  86632. },
  86633. getEdgeDetectionMaterial: function (edgeStrength) {
  86634. return new ShaderMaterial( {
  86635. uniforms: {
  86636. "edgeStrength": { value: edgeStrength },
  86637. "maskTexture": { value: null },
  86638. "texSize": { value: new Vector2$1( 10, 10 ) },
  86639. "visibleEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  86640. "hiddenEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  86641. },
  86642. vertexShader:
  86643. "varying vec2 vUv;\n\
  86644. void main() {\n\
  86645. vUv = uv;\n\
  86646. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86647. }",
  86648. /* fragmentShader:
  86649. "varying vec2 vUv;\
  86650. uniform sampler2D maskTexture;\
  86651. uniform vec2 texSize;\
  86652. uniform vec3 visibleEdgeColor;\
  86653. uniform vec3 hiddenEdgeColor;\
  86654. \
  86655. void main() {\n\
  86656. vec2 invSize = 1.0 / texSize;\
  86657. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\
  86658. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\
  86659. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\
  86660. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\
  86661. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\
  86662. float diff1 = (c1.r - c2.r)*0.5;\
  86663. float diff2 = (c3.r - c4.r)*0.5;\
  86664. float d = length( vec2(diff1, diff2) );\
  86665. float a1 = min(c1.g, c2.g);\
  86666. float a2 = min(c3.g, c4.g);\
  86667. float visibilityFactor = min(a1, a2);\
  86668. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\
  86669. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\
  86670. }" */
  86671. fragmentShader:
  86672. `varying vec2 vUv;
  86673. uniform sampler2D maskTexture;
  86674. uniform float edgeStrength;
  86675. uniform vec2 texSize;
  86676. uniform vec3 visibleEdgeColor;
  86677. uniform vec3 hiddenEdgeColor;
  86678. void main() {
  86679. const float thickness = 1.0;
  86680. vec2 invSize = thickness / texSize;
  86681. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);
  86682. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);
  86683. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);
  86684. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);
  86685. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);
  86686. float diff1 = (c1.r - c2.r)*0.5; //检测边缘,
  86687. float diff2 = (c3.r - c4.r)*0.5;
  86688. float d = length( vec2(diff1, diff2) ) * edgeStrength;
  86689. float a1 = min(c1.g, c2.g);
  86690. float a2 = min(c3.g, c4.g);
  86691. float visibilityFactor = min(a1, a2);
  86692. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;
  86693. //gl_FragColor = vec4(0.0,1.0,0.0,1.0);
  86694. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);
  86695. }`
  86696. } );
  86697. //为什么vec4(0.0,1.0,1.0,1.0); 显示出来的是rgb(109,255,255) ? 几乎只有绿色通道会影响红色通道
  86698. },
  86699. getSeperableBlurMaterial: function ( maxRadius ) {
  86700. return new ShaderMaterial( {
  86701. defines: {
  86702. "MAX_RADIUS": maxRadius,
  86703. },
  86704. uniforms: {
  86705. "colorTexture": { value: null },
  86706. "texSize": { value: new Vector2$1( 0.5, 0.5 ) },
  86707. "direction": { value: new Vector2$1( 0.5, 0.5 ) },
  86708. "kernelRadius": { value: 1.0 }
  86709. },
  86710. vertexShader:
  86711. "varying vec2 vUv;\n\
  86712. void main() {\n\
  86713. vUv = uv;\n\
  86714. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86715. }",
  86716. fragmentShader:
  86717. "#include <common>\
  86718. varying vec2 vUv;\
  86719. uniform sampler2D colorTexture;\
  86720. uniform vec2 texSize;\
  86721. uniform vec2 direction;\
  86722. uniform float kernelRadius;\
  86723. \
  86724. float gaussianPdf(in float x, in float sigma) {\
  86725. return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
  86726. }\
  86727. void main() {\
  86728. vec2 invSize = 1.0 / texSize;\
  86729. float weightSum = gaussianPdf(0.0, kernelRadius);\
  86730. vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
  86731. vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);\
  86732. vec2 uvOffset = delta;\
  86733. for( int i = 1; i <= MAX_RADIUS; i ++ ) {\
  86734. float w = gaussianPdf(uvOffset.x, kernelRadius);\
  86735. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
  86736. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
  86737. diffuseSum += ((sample1 + sample2) * w);\
  86738. weightSum += (2.0 * w);\
  86739. uvOffset += delta;\
  86740. }\
  86741. gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\
  86742. }"
  86743. } );
  86744. },
  86745. getOverlayMaterial: function () {
  86746. return new ShaderMaterial( {
  86747. uniforms: {
  86748. "maskTexture": { value: null },
  86749. "edgeTexture1": { value: null },
  86750. "edgeTexture2": { value: null },
  86751. "patternTexture": { value: null },
  86752. "edgeStrength": { value: 1.0 },
  86753. "edgeGlow": { value: 1.0 },
  86754. "usePatternTexture": { value: 0.0 }
  86755. },
  86756. vertexShader:
  86757. "varying vec2 vUv;\n\
  86758. void main() {\n\
  86759. vUv = uv;\n\
  86760. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86761. }",
  86762. /* fragmentShader:
  86763. "varying vec2 vUv;\
  86764. uniform sampler2D maskTexture;\
  86765. uniform sampler2D edgeTexture1;\
  86766. uniform sampler2D edgeTexture2;\
  86767. uniform sampler2D patternTexture;\
  86768. uniform float edgeStrength;\
  86769. uniform float edgeGlow;\
  86770. uniform bool usePatternTexture;\
  86771. \
  86772. void main() {\
  86773. vec4 edgeValue1 = texture2D(edgeTexture1, vUv);\
  86774. vec4 edgeValue2 = texture2D(edgeTexture2, vUv);\
  86775. vec4 maskColor = texture2D(maskTexture, vUv);\
  86776. vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);\
  86777. float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;\
  86778. vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;\
  86779. vec4 finalColor = edgeStrength * maskColor.r * edgeValue;\ // 删除 * maskColor.r 也就是去掉遮罩,使模型部分也有outline
  86780. if(usePatternTexture)\
  86781. finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);\
  86782. gl_FragColor = finalColor;\
  86783. }", */
  86784. fragmentShader:
  86785. `varying vec2 vUv;
  86786. uniform sampler2D edgeTexture1;
  86787. uniform float edgeStrength;
  86788. void main() {
  86789. gl_FragColor = edgeStrength * texture2D(edgeTexture1, vUv);
  86790. }`,
  86791. blending: AdditiveBlending,
  86792. depthTest: false,
  86793. depthWrite: false,
  86794. transparent: true
  86795. } );
  86796. }
  86797. } );
  86798. OutlinePass.BlurDirectionX = new Vector2$1( 1.0, 0.0 );
  86799. OutlinePass.BlurDirectionY = new Vector2$1( 0.0, 1.0 );
  86800. class BasicMaterial extends ShaderMaterial{
  86801. constructor(o={}){
  86802. super( Object.assign({},{
  86803. uniforms:{
  86804. tDiffuse: { type: 't', value: o.map },
  86805. alpha : {type:'f', value : 1 }
  86806. },
  86807. vertexShader: Shaders['basicTextured.vs'],
  86808. fragmentShader: Shaders['basicTextured.fs']
  86809. },o));
  86810. }
  86811. set opacity(o){
  86812. this.uniforms && (this.uniforms.alpha.value = o);
  86813. }
  86814. get opacity(){
  86815. return this.uniforms.alpha.value
  86816. }
  86817. set map(o){
  86818. this.uniforms.tDiffuse.value = o;
  86819. }
  86820. get map(){
  86821. return this.uniforms.tDiffuse.value
  86822. }
  86823. }
  86824. const manager = new LoadingManager();
  86825. let loaders = {};
  86826. let mapArea;
  86827. let blockedByIntersectHistory = new Map();
  86828. class Viewer extends ViewerBase{
  86829. constructor(domElement, mapArea_, args = {}){
  86830. super(domElement, $.extend(args,{name:'mainViewer'}));
  86831. window.viewer = this;
  86832. if(Potree.settings.editType == "pano" || Potree.settings.editType == "merge"){
  86833. this.modules = {
  86834. Alignment,
  86835. SiteModel
  86836. };
  86837. Potree.settings.useDepthTex = false;
  86838. if(Potree.settings.editType == "pano" ){
  86839. this.modules.PanoEditor = PanoEditor$1;
  86840. }else if(Potree.settings.editType == "merge"){
  86841. this.modules.MergeEditor = MergeEditor;
  86842. this.modules.CamAniEditor = CamAniEditor;
  86843. }
  86844. }else {
  86845. this.modules = {
  86846. Clip,
  86847. Alignment,
  86848. SiteModel,
  86849. RouteGuider : new RouteGuider,
  86850. ParticleEditor,
  86851. CamAniEditor,
  86852. };
  86853. }
  86854. //console.log('create viewer')
  86855. this.navigateMode = 'free'; // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点,
  86856. this.isEdit = true;
  86857. this.waitQueue = [];
  86858. this.unitConvert = new UoMService();
  86859. mapArea = mapArea_;
  86860. this.visible = true;
  86861. this.fpVisiDatasets = [];
  86862. this.atDatasets = [];
  86863. this.objs = new Object3D;
  86864. //this.lastPos = new THREE.Vector3(Infinity,Infinity,Infinity)
  86865. //-------------
  86866. var supportExtFragDepth = !!Features.EXT_DEPTH.isSupported() ;//iphoneX居然不支持
  86867. //这意味着边缘增强和测量线遮挡失效
  86868. if(!supportExtFragDepth)console.error('ExtFragDepth unsupported! 边缘增强和测量线遮挡失效');
  86869. this.guiLoaded = false;
  86870. this.guiLoadTasks = [];
  86871. this.onVrListeners = [];
  86872. this.messages = [];
  86873. this.elMessages = $(`
  86874. <div id="message_listing"
  86875. style="position: absolute; z-index: 1000; left: 10px; bottom: 10px">
  86876. </div>`);
  86877. $(domElement).append(this.elMessages);
  86878. this.paused;
  86879. document.addEventListener('visibilitychange',(e)=>{
  86880. //console.log('visibilitychange', !document.hidden )
  86881. this.dispatchEvent({type:'pageVisible', v:!document.hidden} );
  86882. });
  86883. try{
  86884. if(!Potree.settings.isOfficial)
  86885. { // generate missing dom hierarchy
  86886. if ($(domElement).find('#potree_map').length === 0) {
  86887. let potreeMap = $(`
  86888. <div id="potree_map" class="mapBox" style="position: absolute; left: 50px; top: 50px; width: 400px; height: 400px; display: none">
  86889. <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;">
  86890. </div>
  86891. <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>
  86892. </div>
  86893. `);
  86894. $(domElement).append(potreeMap);
  86895. }
  86896. if ($(domElement).find('#potree_description').length === 0) {
  86897. let potreeDescription = $(`<div id="potree_description" class="potree_info_text"></div>`);
  86898. $(domElement).append(potreeDescription);
  86899. }
  86900. if ($(domElement).find('#potree_annotations').length === 0) {
  86901. let potreeAnnotationContainer = $(`
  86902. <div id="potree_annotation_container"
  86903. style="position: absolute; z-index: 100000; width: 100%; height: 100%; pointer-events: none;"></div>`);
  86904. $(domElement).append(potreeAnnotationContainer);
  86905. }
  86906. if ($(domElement).find('#potree_quick_buttons').length === 0) {
  86907. let potreeMap = $(`
  86908. <div id="potree_quick_buttons" class="quick_buttons_container" style="">
  86909. </div>
  86910. `);
  86911. $(domElement).append(potreeMap);
  86912. }
  86913. //add
  86914. {
  86915. if(!mapArea && Potree.settings.editType != 'merge'){
  86916. $(domElement).append($("<div id='potree_labels'></div>"));
  86917. mapArea = $("<div id='mapGaode'></div>");
  86918. $(domElement).append(mapArea);
  86919. mapArea = mapArea[0];
  86920. }
  86921. }
  86922. /* let domRoot = this.renderer.domElement.parentElement;
  86923. let elAttach = $("<input type='button' value='test'></input>");
  86924. elAttach.css({
  86925. position : "absolute",
  86926. right : '10%',
  86927. bottom: '20px',
  86928. zIndex: "10000",
  86929. fontSize:'1em', color:"black",
  86930. background:'rgba(255,255,255,0.8)',
  86931. })
  86932. let state = false
  86933. elAttach.on("click", () => {
  86934. window.buttonFunction && window.buttonFunction()
  86935. });
  86936. domRoot.appendChild(elAttach[0]); */
  86937. }
  86938. this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {};
  86939. // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  86940. // defaultSettings.navigation = "Orbit";
  86941. // }
  86942. this.server = null;
  86943. this.fov = 60;
  86944. this.isFlipYZ = false;
  86945. this.useDEMCollisions = false;
  86946. this.generateDEM = false;
  86947. this.minNodeSize = 30;
  86948. this.edlStrength = 1.0;
  86949. this.edlRadius = 1.4;
  86950. this.edlOpacity = 1.0;
  86951. this.useEDL = false;
  86952. this.description = "";
  86953. this.classifications = ClassificationScheme.DEFAULT;
  86954. this.moveSpeed = 10;
  86955. this.lengthUnit = LengthUnits.METER;
  86956. this.lengthUnitDisplay = LengthUnits.METER;
  86957. this.showBoundingBox = false;
  86958. this.showAnnotations = true;
  86959. this.freeze = false;
  86960. this.clipTask = ClipTask.HIGHLIGHT;
  86961. this.clipMethod = ClipMethod.INSIDE_ANY;
  86962. this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP;
  86963. this.filterReturnNumberRange = [0, 7];
  86964. this.filterNumberOfReturnsRange = [0, 7];
  86965. this.filterGPSTimeRange = [-Infinity, Infinity];
  86966. this.filterPointSourceIDRange = [0, 65535];
  86967. this.potreeRenderer = null;
  86968. this.edlRenderer = null;
  86969. this.pRenderer = null;
  86970. this.scene = null;
  86971. this.sceneVR = null;
  86972. this.overlay = null;
  86973. this.overlayCamera = null;
  86974. this.inputHandler = null;
  86975. this.controls = null;
  86976. this.clippingTool = null;
  86977. this.transformationTool = null;
  86978. this.navigationCube = null;
  86979. this.compass = null;
  86980. this.skybox = null;
  86981. this.clock = new Clock();
  86982. this.background = null;
  86983. if(args.noDragAndDrop){
  86984. }else {
  86985. this.initDragAndDrop();
  86986. }
  86987. if(typeof Stats !== "undefined"){
  86988. this.stats = new Stats();
  86989. this.stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
  86990. document.body.appendChild( this.stats.dom );
  86991. }
  86992. {
  86993. let canvas = this.renderer.domElement;
  86994. canvas.addEventListener("webglcontextlost", (e) => {
  86995. console.log(e);
  86996. this.postMessage("WebGL context lost. \u2639");
  86997. let gl = this.renderer.getContext();
  86998. let error = gl.getError();
  86999. console.log(error);
  87000. this.dispatchEvent({type:'webglError', msg:'webglcontextlost'});
  87001. }, false);
  87002. }
  87003. {
  87004. this.overlay = new Scene();
  87005. this.overlayCamera = new OrthographicCamera(
  87006. 0, 1,
  87007. 1, 0,
  87008. -1000, 1000
  87009. );
  87010. }
  87011. this.pRenderer = new Renderer(this.renderer);
  87012. {
  87013. let near = 2.5;
  87014. let far = 10.0;
  87015. let fov = 90;
  87016. this.shadowTestCam = new PerspectiveCamera(90, 1, near, far);
  87017. this.shadowTestCam.position.set(3.50, -2.80, 8.561);
  87018. this.shadowTestCam.lookAt(new Vector3(0, 0, 4.87));
  87019. }
  87020. let scene = new Scene$1(this.renderer);
  87021. { // create VR scene
  87022. this.sceneVR = new Scene();
  87023. // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  87024. // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
  87025. // let infoMaterial = new THREE.MeshBasicMaterial({map: texture});
  87026. // let infoNode = new THREE.Mesh(plane, infoMaterial);
  87027. // infoNode.position.set(-0.5, 1, 0);
  87028. // infoNode.scale.set(0.4, 0.3, 1);
  87029. // infoNode.lookAt(0, 1, 0)
  87030. // this.sceneVR.add(infoNode);
  87031. // window.infoNode = infoNode;
  87032. }
  87033. this.setScene(scene);
  87034. //add: for 截图时抗锯齿
  87035. {
  87036. this.composer = new EffectComposer( this.renderer );
  87037. this.ssaaRenderPass = new SSAARenderPass(0x000000, 0);
  87038. this.composer.addPass( this.ssaaRenderPass );
  87039. //this.ssaaRenderPass.useCopy = true
  87040. //this.ssaaRenderPass.renderToScreen = true;
  87041. //this.ssaaRenderPass.needsSwap = false
  87042. //见 https://threejs.org/examples/?q=AA#webgl_postprocessing_fxaa 效果和SSAA差不多,都对透明不太友好。
  87043. /* const renderPass = new RenderPass();
  87044. renderPass.clearColor = new THREE.Color( 0, 0, 0 );
  87045. renderPass.clearAlpha = 0;
  87046. this.composer.addPass( renderPass );
  87047. this.fxaaPass = new ShaderPass( FXAAShader );
  87048. this.composer.addPass( this.fxaaPass );
  87049. this.fxaaPass.setSize = function(width, height){
  87050. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width );
  87051. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height );
  87052. }
  87053. this.fxaaPass.renderToScreen = true; */
  87054. /* this.fxaaPass = new ShaderPass( FXAAShader );
  87055. //this.fxaaPass.readTarget = true //add
  87056. this.composer.addPass( this.fxaaPass );
  87057. this.composer.readTarget = true
  87058. this.fxaaPass.setSize = function(width, height){
  87059. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width );
  87060. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height );
  87061. }
  87062. this.fxaaPass.renderToScreen = true; */
  87063. //for 融合页面
  87064. /* let outlinePass = this.outlinePass = new OutlinePass( );
  87065. //composer.addPass( outlinePass );
  87066. outlinePass.edgeStrength = 10
  87067. outlinePass.edgeGlow = 0
  87068. outlinePass.visibleEdgeColor = new THREE.Color("#09a1b3")
  87069. outlinePass.hiddenEdgeColor = new THREE.Color("#09a1b3")
  87070. this.ssaaRenderPass.addPass(outlinePass)
  87071. */
  87072. let outlinePass = this.outlinePass = new OutlinePass( );
  87073. outlinePass.renderToScreen = true; //这样更流畅,不用ssaa了,缺点是outline有锯齿
  87074. outlinePass.enabled = false;
  87075. this.composer.addPass( outlinePass );
  87076. outlinePass.edgeStrength = 10;
  87077. outlinePass.edgeGlow = 0;
  87078. outlinePass.visibleEdgeColor = new Color("#09a1b3");
  87079. outlinePass.hiddenEdgeColor = new Color("#09a1b3");
  87080. }
  87081. {
  87082. this.mainViewport = new Viewport( this.scene.view, this.scene.cameraP, {
  87083. left:0, bottom:0, width:1, height: 1, name:'MainView'
  87084. });
  87085. this.viewports = [this.mainViewport];
  87086. Potree.settings.showCompass && (this.compass = new Compass(Potree.settings.compassDom, this.mainViewport));
  87087. this.magnifier = new Magnifier(this);
  87088. this.reticule = new Reticule(this);
  87089. this.scene.scene.add(this.magnifier);
  87090. this.scene.scene.add(this.reticule);
  87091. if(Potree.settings.editType != "pano" && Potree.settings.editType != 'merge'){
  87092. this.mapViewer = new MapViewer(mapArea/* $('#mapGaode')[0] */);
  87093. }
  87094. this.inputHandler = new InputHandler(this, this.scene.scene);
  87095. //this.inputHandler.setScene(this.scene);
  87096. //this.inputHandler.addInputListener(this);//add
  87097. this.clippingTool = new ClippingTool(this);
  87098. this.transformationTool = new TransformationTool(this);
  87099. this.navigationCube = new NavigationCube(this);
  87100. this.navigationCube.visible = false;
  87101. this.createControls();
  87102. this.clippingTool.setScene(this.scene);
  87103. let onPointcloudAdded = (e) => {
  87104. if (this.scene.pointclouds.length === 1) {
  87105. let speed = e.pointcloud.boundingBox.getSize(new Vector3()).length();
  87106. speed = speed / 2000;
  87107. this.setMoveSpeed(speed);
  87108. }
  87109. };
  87110. let onVolumeRemoved = (e) => {
  87111. this.inputHandler.deselect(e.volume);
  87112. };
  87113. this.addEventListener('scene_changed', (e) => {
  87114. this.inputHandler.setScene(e.scene);
  87115. this.clippingTool.setScene(this.scene);
  87116. if(!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)){
  87117. e.scene.addEventListener("pointcloud_added", onPointcloudAdded);
  87118. }
  87119. if(!e.scene.hasEventListener("volume_removed", onPointcloudAdded)){
  87120. e.scene.addEventListener("volume_removed", onVolumeRemoved);
  87121. }
  87122. });
  87123. this.scene.addEventListener("volume_removed", onVolumeRemoved);
  87124. this.scene.addEventListener('pointcloud_added', onPointcloudAdded);
  87125. }
  87126. { // set defaults
  87127. this.setFOV(60);
  87128. this.setEDLEnabled(false);
  87129. this.setEDLRadius(1.4);
  87130. this.setEDLStrength(0.4);
  87131. this.setEDLOpacity(1.0);
  87132. this.setClipTask(ClipTask.HIGHLIGHT);
  87133. this.setClipMethod(ClipMethod.INSIDE_ANY);
  87134. this.setPointBudget(1*1000*1000);
  87135. this.setShowBoundingBox(false);
  87136. this.setFreeze(false);
  87137. this.setControls(this.fpControls/* orbitControls */);
  87138. this.setBackground( new Color(Potree.config.background),1 /* 'gradient' */ );
  87139. this.scaleFactor = 1;
  87140. this.loadSettingsFromURL();
  87141. }
  87142. // start rendering!
  87143. //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){
  87144. //requestAnimationFrame(this.loop.bind(this));
  87145. //}
  87146. this.renderer.setAnimationLoop(this.loop.bind(this));
  87147. this.loadGUI = this.loadGUI.bind(this);
  87148. this.annotationTool = new AnnotationTool(this);
  87149. this.measuringTool = new MeasuringTool(this);
  87150. this.profileTool = new ProfileTool(this);
  87151. this.volumeTool = new VolumeTool(this);
  87152. this.tagTool = new TagTool(this);
  87153. //-----------
  87154. CursorDeal.init(this, this.mapViewer ? [this, this.mapViewer] : [this]);//ADD
  87155. if(Potree.settings.editType == "pano"){
  87156. this.modules.PanoEditor.init();
  87157. }else if(Potree.settings.editType == "merge"){
  87158. this.modules.MergeEditor.init();
  87159. }else {
  87160. this.modules.SiteModel.init();
  87161. this.modules.ParticleEditor.init();
  87162. }
  87163. this.modules.Alignment.init();
  87164. this.images360 = new Images360(this);
  87165. this.scene.scene.add(this.objs);
  87166. loaders = {
  87167. objLoader : new OBJLoader( manager ),
  87168. mtlLoader : new MTLLoader( manager ),
  87169. glbLoader : new GLTFLoader(undefined, this.renderer, Potree.settings.libsUrl )
  87170. };
  87171. //add test
  87172. /* const environment = new RoomEnvironment();
  87173. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  87174. this.scene.scene.environment = pmremGenerator.fromScene( environment ).texture;
  87175. */
  87176. //-----------
  87177. }catch(e){
  87178. this.onCrash(e);
  87179. }
  87180. //-----------------------add----------------------------------------------------
  87181. /* {
  87182. let ratio
  87183. this.addEventListener('resize',(e)=>{
  87184. if(ratio != e.deviceRatio){ //因为devicePixelRatio会影响到点云大小,所以改变时计算下点云大小
  87185. viewer.scene.pointclouds.forEach(p => {
  87186. p.changePointSize()
  87187. })
  87188. }
  87189. ratio = e.deviceRatio
  87190. })
  87191. } */
  87192. {
  87193. let pointDensity = '';
  87194. Object.defineProperty(Potree.settings , "pointDensity",{
  87195. get: function() {
  87196. return pointDensity
  87197. },
  87198. set: (density)=>{
  87199. if(density && density != pointDensity){
  87200. let pointBudget;
  87201. var config = Potree.config.pointDensity[density];
  87202. if(this.magnifier.visible){//放大镜打开时不要切换pointBudget,否则点云会闪烁。这时使用最高密度。
  87203. pointBudget = Potree.config.pointDensity['magnifier'].pointBudget;
  87204. }else {
  87205. pointBudget = config.pointBudget;
  87206. }
  87207. viewer.setPointBudget(pointBudget );
  87208. //Potree.maxPointLevel = config.maxLevel
  87209. pointDensity = density;
  87210. this.setPointLevels();
  87211. }
  87212. }
  87213. });
  87214. let UserPointDensity = '';
  87215. Object.defineProperty(Potree.settings , "UserPointDensity",{
  87216. get: function() {
  87217. return UserPointDensity
  87218. },
  87219. set: (density)=>{
  87220. if(UserPointDensity != density){
  87221. if(Potree.settings.displayMode == 'showPointCloud' && this.viewports.length != 4){//漫游模式和四屏时都有自己的pointDensity
  87222. Potree.settings.pointDensity = density;
  87223. }
  87224. UserPointDensity = density;
  87225. }
  87226. }
  87227. });
  87228. }
  87229. {
  87230. let cameraFar = Potree.settings.cameraFar;
  87231. Object.defineProperty(Potree.settings , "cameraFar",{
  87232. get: function() {
  87233. return cameraFar
  87234. },
  87235. set: (far)=>{
  87236. if(far != cameraFar){
  87237. if(Potree.settings.displayMode != 'showPanos'){
  87238. this.mainViewport.camera.far = far;
  87239. this.mainViewport.camera.updateProjectionMatrix();
  87240. }
  87241. cameraFar = far;
  87242. }
  87243. }
  87244. });
  87245. }
  87246. this.addEventListener('allLoaded', ()=>{
  87247. setTimeout(this.testPointcloudsMaxLevel.bind(this), 2000); //延迟一丢丢,等画面出现
  87248. });
  87249. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  87250. this.addEventListener('switchFloorplanSelect',(e)=>{//进入平面图设置后 切换选中的数据集
  87251. this.selectedFloorplan = e.pointcloud; //绝对显示
  87252. this.updateFpVisiDatasets();
  87253. let pointclouds;
  87254. if(e.pointcloud){
  87255. pointclouds = [e.pointcloud];
  87256. }else if(this.fpVisiDatasets.length){
  87257. pointclouds = this.fpVisiDatasets;
  87258. }
  87259. pointclouds && this.mapViewer.fitToDatasets(pointclouds);
  87260. });
  87261. this.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  87262. this.updateFpVisiDatasets();
  87263. });
  87264. this.mapViewer.mapLayer.addEventListener('floorplanLoaded',()=>{
  87265. this.updateCadVisibles(this.fpVisiDatasets, true); //加载完成后重新更新下
  87266. });
  87267. /* this.modules.Clip.bus.addEventListener('updateSelectedDatasets',()=>{
  87268. this.updateFpVisiDatasets()
  87269. }) */
  87270. }
  87271. {
  87272. //更新所在数据集
  87273. this.addEventListener('camera_changed', e => {
  87274. if(e.changeInfo.positionChanged){
  87275. blockedByIntersectHistory.clear(); //清空
  87276. this.updateDatasetAt();
  87277. }
  87278. });
  87279. }
  87280. }
  87281. ifPointBlockedByIntersect(pos3d, object){//点是否被遮挡
  87282. let ifShelter;
  87283. let shelter = blockedByIntersectHistory.get(object || pos3d);
  87284. if(shelter){
  87285. ifShelter = shelter.ifShelter;
  87286. }else {
  87287. ifShelter = viewer.inputHandler.ifBlockedByIntersect(pos3d, 0.3, true);//由于热点都是使用点云得到的位置,所以判断遮挡时也用点云
  87288. blockedByIntersectHistory.set(object || pos3d, {ifShelter});
  87289. }
  87290. return ifShelter
  87291. }
  87292. updateDatasetAt(force){//更新所在数据集
  87293. let fun = ()=>{
  87294. let currPos = viewer.mainViewport.view.position;
  87295. //if(force || !currPos.equals(this.lastPos)){
  87296. //this.lastPos.copy(currPos)
  87297. var at = this.scene.pointclouds.filter(e=>e.ifContainsPoint(currPos));
  87298. if(Common.getDifferenceSet(at, this.atDatasets).length){
  87299. //console.log('atDatasets', at)
  87300. this.atDatasets = at;
  87301. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge')this.updateFpVisiDatasets();
  87302. this.dispatchEvent({type:'pointcloudAtChange',pointclouds:at});
  87303. }
  87304. force = false;
  87305. return true
  87306. //}
  87307. };
  87308. if(force)fun();
  87309. else Common.intervalTool.isWaiting('atWhichDataset', fun , 500);
  87310. }
  87311. updatePanosVisibles(currentFloor){//显示当前楼层的所有panos
  87312. viewer.images360.panos.forEach(pano=>{
  87313. let visible = currentFloor && currentFloor.panos.includes(pano);
  87314. viewer.updateVisible(pano, 'buildingChange', visible, 2);
  87315. });
  87316. }
  87317. updateFpVisiDatasets(){
  87318. let Clip = this.modules.Clip;
  87319. let SiteModel = this.modules.SiteModel;
  87320. let Alignment = this.modules.Alignment;
  87321. var currentFloor = SiteModel.currentFloor;
  87322. /* if(Clip.editing){//下载页面已经改为和普通时一样,根据位置判断
  87323. this.updateCadVisibles(Clip.selectedDatasets)
  87324. }else */if(this.selectedFloorplan){//平面图设置中
  87325. let pointclouds = [this.selectedFloorplan];
  87326. this.updateCadVisibles(pointclouds);
  87327. }else if(SiteModel.editing || Alignment.editing){//只显示勾选的,也就是显示的点云的
  87328. let pointclouds = this.scene.pointclouds.filter(p => this.getObjVisiByReason(p,'datasetSelection') );
  87329. this.updateCadVisibles(pointclouds);
  87330. this.updatePanosVisibles(currentFloor/* , pointclouds */);
  87331. }else {
  87332. let pointclouds = currentFloor ? this.findPointcloudsAtFloor(currentFloor) : [];
  87333. if(pointclouds.length == 0){//如果当前不在任何楼层或楼层中无数据集,就用当前所在数据集
  87334. pointclouds = this.atDatasets;
  87335. }
  87336. this.updateCadVisibles(pointclouds);
  87337. this.updatePanosVisibles(currentFloor/* , pointclouds */);
  87338. }
  87339. }
  87340. findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。
  87341. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  87342. //重叠体积>50% 或 包含>50%的漫游点
  87343. const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95;
  87344. var lowScores = [];
  87345. var pointclouds = viewer.scene.pointclouds.filter(e=>{
  87346. let score = 0;
  87347. if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  87348. return true
  87349. }
  87350. if(e.panos.length){//条件2
  87351. var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position));
  87352. let panoCountRatio = insidePanos.length / e.panos.length;
  87353. if(panoCountRatio > ratio2)return true
  87354. if(panoCountRatio < ratio1){
  87355. score += panoCountRatio;//return false
  87356. }
  87357. }
  87358. //条件3
  87359. let volume = entity.intersectPointcloudVolume(e);
  87360. let volumeRatio = volume / entity.getVolume(true); //注:hole加入计算
  87361. if(volumeRatio > ratio3){ //ratio3要高一些,因为点云bounding可能很大,包含很多无点云的空间。即使整个数据集包含entity都不一定看起来在数据集中。(千万要防止两层楼都显示了)
  87362. return true
  87363. }else {
  87364. score += volumeRatio;
  87365. }
  87366. lowScores.push({score, pointcloud:e});
  87367. });
  87368. if(pointclouds.length == 0){//从低分项挑一个出来。
  87369. lowScores.sort((a,b)=>{return a.score - b.score});
  87370. if(lowScores[0].score > 0.4){
  87371. pointclouds = [lowScores[0].pointcloud];
  87372. }
  87373. }
  87374. return pointclouds
  87375. }
  87376. updateCadVisibles(visiClouds, force){
  87377. let oldVisi = this.fpVisiDatasets;
  87378. var visiClouds = this.fpVisiDatasets = visiClouds;
  87379. if(!force){
  87380. var difference = Common.getDifferenceSet(oldVisi , visiClouds);
  87381. if(difference.length == 0)return
  87382. }
  87383. //console.log('visiClouds',visiClouds.map(e=>e.name))
  87384. viewer.scene.pointclouds.forEach(pointcloud=>{
  87385. var floorplan = viewer.mapViewer.mapLayer.getFloorplan(pointcloud.dataset_id);
  87386. var visi = visiClouds.includes(pointcloud);
  87387. if(floorplan){
  87388. viewer.updateVisible(floorplan.objectGroup, 'buildingChange', visi);
  87389. }/* else if(!visi){
  87390. let changeVisi = (e)=>{
  87391. viewer.updateVisible(e.floorplan.objectGroup, 'buildingChange', this.fpVisiDatasets.includes(pointcloud))
  87392. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', changeVisi)
  87393. console.log('updateCadVisibles加载后更改显示',e)
  87394. }
  87395. viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', changeVisi)
  87396. } */
  87397. //已经添加了全局的 floorplanLoaded后会updateCadVisibles,这段就删了
  87398. });
  87399. viewer.mapViewer.mapLayer.needUpdate = true; //可能需要更新加载的level程度
  87400. viewer.mapViewer.needRender = true; //若上句不触发加载也要立即重新绘制
  87401. }
  87402. //促使点云加载出最高级别
  87403. testPointcloudsMaxLevel(){ //所有点云都无需testMaxNodeLevel 就停止
  87404. let camera_changed, count = 0;
  87405. let test = ()=>{
  87406. camera_changed = true;
  87407. Common.intervalTool.isWaiting('testPointcloudsMaxLevel', ()=>{
  87408. if(!camera_changed && count>20 )return //只有当camera_changed后才继续循环, 除了最开始几次需要连续加载下
  87409. camera_changed = false;
  87410. count ++;
  87411. //console.log('testPointcloudsMaxLevel中')
  87412. var success = true;
  87413. viewer.scene.pointclouds.forEach(e=>{
  87414. var wait = e.testMaxNodeLevel();
  87415. if(wait){
  87416. success = false;
  87417. }
  87418. });
  87419. if(!success)return true //没有全部加载完,继续循环
  87420. else {
  87421. this.removeEventListener('camera_changed',test);
  87422. console.log('testPointcloudsMaxLevel结束');
  87423. }
  87424. }, count<10 ? 150 : 500);
  87425. };
  87426. this.addEventListener('camera_changed',test);
  87427. test();
  87428. /* 检验:
  87429. viewer.scene.pointclouds.sort((a,b)=>a.nodeMaxLevelPredict.min - b.nodeMaxLevelPredict.min).forEach(e=>console.log(e.nodeMaxLevel, e.nodeMaxLevelPredict.min))
  87430. */
  87431. }
  87432. setPointLevels(){
  87433. this.scene.pointclouds.forEach(e=>{
  87434. e.setPointLevel();
  87435. });
  87436. }
  87437. onCrash(error){
  87438. $(this.renderArea).empty();
  87439. if ($(this.renderArea).find('#potree_failpage').length === 0) {
  87440. let elFailPage = $(`
  87441. <div id="#potree_failpage" class="potree_failpage">
  87442. <h1>Potree Encountered An Error </h1>
  87443. <p>
  87444. This may happen if your browser or graphics card is not supported.
  87445. <br>
  87446. We recommend to use
  87447. <a href="https://www.google.com/chrome/browser" target="_blank" style="color:initial">Chrome</a>
  87448. or
  87449. <a href="https://www.mozilla.org/" target="_blank">Firefox</a>.
  87450. </p>
  87451. <p>
  87452. Please also visit <a href="http://webglreport.com/" target="_blank">webglreport.com</a> and
  87453. check whether your system supports WebGL.
  87454. </p>
  87455. <p>
  87456. If you are already using one of the recommended browsers and WebGL is enabled,
  87457. consider filing an issue report at <a href="https://github.com/potree/potree/issues" target="_blank">github</a>,<br>
  87458. including your operating system, graphics card, browser and browser version, as well as the
  87459. error message below.<br>
  87460. Please do not report errors on unsupported browsers.
  87461. </p>
  87462. <pre id="potree_error_console" style="width: 100%; height: 100%"></pre>
  87463. </div>`);
  87464. let elErrorMessage = elFailPage.find('#potree_error_console');
  87465. elErrorMessage.html(error.stack);
  87466. $(this.renderArea).append(elFailPage);
  87467. }
  87468. throw error;
  87469. }
  87470. // ------------------------------------------------------------------------------------
  87471. // Viewer API
  87472. // ------------------------------------------------------------------------------------
  87473. setScene (scene) {
  87474. if (scene === this.scene) {
  87475. return;
  87476. }
  87477. let oldScene = this.scene;
  87478. this.scene = scene;
  87479. this.dispatchEvent({
  87480. type: 'scene_changed',
  87481. oldScene: oldScene,
  87482. scene: scene
  87483. });
  87484. { // Annotations
  87485. $('.annotation').detach();
  87486. // for(let annotation of this.scene.annotations){
  87487. // this.renderArea.appendChild(annotation.domElement[0]);
  87488. // }
  87489. this.scene.annotations.traverse(annotation => {
  87490. this.renderArea.appendChild(annotation.domElement[0]);
  87491. });
  87492. if (!this.onAnnotationAdded) {
  87493. this.onAnnotationAdded = e => {
  87494. // console.log("annotation added: " + e.annotation.title);
  87495. e.annotation.traverse(node => {
  87496. $("#potree_annotation_container").append(node.domElement);
  87497. //this.renderArea.appendChild(node.domElement[0]);
  87498. node.scene = this.scene;
  87499. });
  87500. };
  87501. }
  87502. if (oldScene) {
  87503. oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  87504. }
  87505. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  87506. }
  87507. };
  87508. setControls(controls/* , setSpeed */){
  87509. if (controls !== this.controls) {
  87510. if (this.controls) {
  87511. this.controls.setEnable(false);
  87512. //this.inputHandler.removeInputListener(this.controls);
  87513. this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小)
  87514. }
  87515. this.controls = controls;
  87516. controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed); //add
  87517. this.controls.setEnable(true);
  87518. //this.inputHandler.addInputListener(this.controls);
  87519. }
  87520. }
  87521. getControls () {
  87522. if(this.renderer.xr.isPresenting){
  87523. return this.vrControls;
  87524. }else {
  87525. return this.controls;
  87526. }
  87527. }
  87528. getMinNodeSize () {
  87529. return this.minNodeSize;
  87530. };
  87531. setMinNodeSize (value) {
  87532. if (this.minNodeSize !== value) {
  87533. this.minNodeSize = value;
  87534. this.dispatchEvent({'type': 'minnodesize_changed', 'viewer': this});
  87535. }
  87536. };
  87537. getBackground () {
  87538. return this.background;
  87539. }
  87540. setBackground(bg){
  87541. if (this.background === bg) {
  87542. return;
  87543. }
  87544. if(bg === "skybox"){
  87545. this.skybox = Utils.loadSkybox(new URL(Potree.resourcePath + '/textures/skybox2/').href);
  87546. }
  87547. this.background = bg;
  87548. this.backgroundOpacity = 1;//add
  87549. this.dispatchEvent({'type': 'background_changed', 'viewer': this});
  87550. }
  87551. setDescription (value) {
  87552. this.description = value;
  87553. $('#potree_description').html(value);
  87554. //$('#potree_description').text(value);
  87555. }
  87556. getDescription(){
  87557. return this.description;
  87558. }
  87559. setShowBoundingBox (value) {
  87560. if (this.showBoundingBox !== value) {
  87561. this.showBoundingBox = value;
  87562. this.dispatchEvent({'type': 'show_boundingbox_changed', 'viewer': this});
  87563. }
  87564. };
  87565. getShowBoundingBox () {
  87566. return this.showBoundingBox;
  87567. };
  87568. setMoveSpeed (value) {
  87569. if (this.getMoveSpeed() !== value) {
  87570. this.mainViewport.setMoveSpeed(value);
  87571. this.dispatchEvent({'type': 'move_speed_changed', 'viewer': this, 'speed': value});
  87572. }
  87573. };
  87574. getMoveSpeed () {
  87575. return this.mainViewport.moveSpeed;
  87576. };
  87577. setWeightClassification (w) {
  87578. for (let i = 0; i < this.scene.pointclouds.length; i++) {
  87579. this.scene.pointclouds[i].material.weightClassification = w;
  87580. this.dispatchEvent({'type': 'attribute_weights_changed' + i, 'viewer': this});
  87581. }
  87582. };
  87583. setFreeze (value) {
  87584. value = Boolean(value);
  87585. if (this.freeze !== value) {
  87586. this.freeze = value;
  87587. this.dispatchEvent({'type': 'freeze_changed', 'viewer': this});
  87588. }
  87589. };
  87590. getFreeze () {
  87591. return this.freeze;
  87592. };
  87593. getClipTask(){
  87594. return this.clipTask;
  87595. }
  87596. getClipMethod(){
  87597. return this.clipMethod;
  87598. }
  87599. setClipTask(value){
  87600. if(this.clipTask !== value){
  87601. this.clipTask = value;
  87602. this.dispatchEvent({
  87603. type: "cliptask_changed",
  87604. viewer: this});
  87605. }
  87606. }
  87607. setClipMethod(value){
  87608. if(this.clipMethod !== value){
  87609. this.clipMethod = value;
  87610. this.dispatchEvent({
  87611. type: "clipmethod_changed",
  87612. viewer: this});
  87613. }
  87614. }
  87615. setElevationGradientRepeat(value){
  87616. if(this.elevationGradientRepeat !== value){
  87617. this.elevationGradientRepeat = value;
  87618. this.dispatchEvent({
  87619. type: "elevation_gradient_repeat_changed",
  87620. viewer: this});
  87621. }
  87622. }
  87623. setPointBudget (value) {
  87624. if (Potree.pointBudget !== value) {
  87625. Potree.pointBudget = parseInt(value);
  87626. this.dispatchEvent({'type': 'point_budget_changed', 'viewer': this});
  87627. }
  87628. };
  87629. getPointBudget () {
  87630. return Potree.pointBudget;
  87631. };
  87632. setShowAnnotations (value) {
  87633. if (this.showAnnotations !== value) {
  87634. this.showAnnotations = value;
  87635. this.dispatchEvent({'type': 'show_annotations_changed', 'viewer': this});
  87636. }
  87637. }
  87638. getShowAnnotations () {
  87639. return this.showAnnotations;
  87640. }
  87641. setDEMCollisionsEnabled(value){
  87642. if(this.useDEMCollisions !== value){
  87643. this.useDEMCollisions = value;
  87644. this.dispatchEvent({'type': 'use_demcollisions_changed', 'viewer': this});
  87645. };
  87646. };
  87647. getDEMCollisionsEnabled () {
  87648. return this.useDEMCollisions;
  87649. };
  87650. setEDLEnabled (value) {
  87651. value = Boolean(value) && Features.SHADER_EDL.isSupported();
  87652. if (this.useEDL !== value) {
  87653. this.useEDL = value;
  87654. this.dispatchEvent({'type': 'use_edl_changed', 'viewer': this});
  87655. }
  87656. };
  87657. getEDLEnabled () {
  87658. return this.useEDL;
  87659. };
  87660. setEDLRadius (value) {
  87661. if (this.edlRadius !== value) {
  87662. this.edlRadius = value;
  87663. this.dispatchEvent({'type': 'edl_radius_changed', 'viewer': this});
  87664. }
  87665. };
  87666. getEDLRadius () {
  87667. return this.edlRadius;
  87668. };
  87669. setEDLStrength (value) {
  87670. if (this.edlStrength !== value) {
  87671. this.edlStrength = value;
  87672. this.dispatchEvent({'type': 'edl_strength_changed', 'viewer': this});
  87673. }
  87674. };
  87675. getEDLStrength () {
  87676. return this.edlStrength;
  87677. };
  87678. setEDLOpacity (value) {
  87679. if (this.edlOpacity !== value) {
  87680. this.edlOpacity = value;
  87681. this.dispatchEvent({'type': 'edl_opacity_changed', 'viewer': this});
  87682. }
  87683. };
  87684. getEDLOpacity () {
  87685. return this.edlOpacity;
  87686. };
  87687. setFOV (value) {
  87688. if (this.fov !== value) {
  87689. let oldFov = this.fov;
  87690. this.fov = value;
  87691. this.scene.cameraP.fov = this.fov;
  87692. this.scene.cameraP.updateProjectionMatrix();
  87693. this.dispatchEvent({'type': 'fov_changed', 'viewer': this, oldFov, fov:this.fov});
  87694. }
  87695. };
  87696. getFOV () {
  87697. return this.fov;
  87698. };
  87699. disableAnnotations () {
  87700. this.scene.annotations.traverse(annotation => {
  87701. annotation.domElement.css('pointer-events', 'none');
  87702. // return annotation.visible;
  87703. });
  87704. };
  87705. enableAnnotations () {
  87706. this.scene.annotations.traverse(annotation => {
  87707. annotation.domElement.css('pointer-events', 'auto');
  87708. // return annotation.visible;
  87709. });
  87710. }
  87711. setClassifications(classifications){
  87712. this.classifications = classifications;
  87713. this.dispatchEvent({'type': 'classifications_changed', 'viewer': this});
  87714. }
  87715. setClassificationVisibility (key, value) {
  87716. if (!this.classifications[key]) {
  87717. this.classifications[key] = {visible: value, name: 'no name'};
  87718. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87719. } else if (this.classifications[key].visible !== value) {
  87720. this.classifications[key].visible = value;
  87721. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87722. }
  87723. }
  87724. toggleAllClassificationsVisibility(){
  87725. let numVisible = 0;
  87726. let numItems = 0;
  87727. for(const key of Object.keys(this.classifications)){
  87728. if(this.classifications[key].visible){
  87729. numVisible++;
  87730. }
  87731. numItems++;
  87732. }
  87733. let visible = true;
  87734. if(numVisible === numItems){
  87735. visible = false;
  87736. }
  87737. let somethingChanged = false;
  87738. for(const key of Object.keys(this.classifications)){
  87739. if(this.classifications[key].visible !== visible){
  87740. this.classifications[key].visible = visible;
  87741. somethingChanged = true;
  87742. }
  87743. }
  87744. if(somethingChanged){
  87745. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87746. }
  87747. }
  87748. setFilterReturnNumberRange(from, to){
  87749. this.filterReturnNumberRange = [from, to];
  87750. this.dispatchEvent({'type': 'filter_return_number_range_changed', 'viewer': this});
  87751. }
  87752. setFilterNumberOfReturnsRange(from, to){
  87753. this.filterNumberOfReturnsRange = [from, to];
  87754. this.dispatchEvent({'type': 'filter_number_of_returns_range_changed', 'viewer': this});
  87755. }
  87756. setFilterGPSTimeRange(from, to){
  87757. this.filterGPSTimeRange = [from, to];
  87758. this.dispatchEvent({'type': 'filter_gps_time_range_changed', 'viewer': this});
  87759. }
  87760. setFilterPointSourceIDRange(from, to){
  87761. this.filterPointSourceIDRange = [from, to];
  87762. this.dispatchEvent({'type': 'filter_point_source_id_range_changed', 'viewer': this});
  87763. }
  87764. setLengthUnit (value) {
  87765. switch (value) {
  87766. case 'm':
  87767. this.lengthUnit = LengthUnits.METER;
  87768. this.lengthUnitDisplay = LengthUnits.METER;
  87769. break;
  87770. case 'ft':
  87771. this.lengthUnit = LengthUnits.FEET;
  87772. this.lengthUnitDisplay = LengthUnits.FEET;
  87773. break;
  87774. case 'in':
  87775. this.lengthUnit = LengthUnits.INCH;
  87776. this.lengthUnitDisplay = LengthUnits.INCH;
  87777. break;
  87778. }
  87779. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: value});
  87780. };
  87781. setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) {
  87782. switch (lengthUnitValue) {
  87783. case 'm':
  87784. this.lengthUnit = LengthUnits.METER;
  87785. break;
  87786. case 'ft':
  87787. this.lengthUnit = LengthUnits.FEET;
  87788. break;
  87789. case 'in':
  87790. this.lengthUnit = LengthUnits.INCH;
  87791. break;
  87792. }
  87793. switch (lengthUnitDisplayValue) {
  87794. case 'm':
  87795. this.lengthUnitDisplay = LengthUnits.METER;
  87796. break;
  87797. case 'ft':
  87798. this.lengthUnitDisplay = LengthUnits.FEET;
  87799. break;
  87800. case 'in':
  87801. this.lengthUnitDisplay = LengthUnits.INCH;
  87802. break;
  87803. }
  87804. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: lengthUnitValue });
  87805. };
  87806. zoomTo(node, factor, animationDuration = 0){
  87807. let view = this.scene.view;
  87808. let camera = this.scene.cameraP.clone();
  87809. camera.rotation.copy(this.scene.cameraP.rotation);
  87810. camera.rotation.order = "ZXY";
  87811. camera.rotation.x = Math.PI / 2 + view.pitch;
  87812. camera.rotation.z = view.yaw;
  87813. camera.updateMatrix();
  87814. camera.updateMatrixWorld();
  87815. camera.zoomTo(node, factor);
  87816. let bs;
  87817. if (node.boundingSphere) {
  87818. bs = node.boundingSphere;
  87819. } else if (node.geometry && node.geometry.boundingSphere) {
  87820. bs = node.geometry.boundingSphere;
  87821. } else {
  87822. bs = node.boundingBox.getBoundingSphere(new Sphere());
  87823. }
  87824. bs = bs.clone().applyMatrix4(node.matrixWorld);
  87825. let startPosition = view.position.clone();
  87826. let endPosition = camera.position.clone();
  87827. let startTarget = view.getPivot();
  87828. let endTarget = bs.center;
  87829. let startRadius = view.radius;
  87830. let endRadius = endPosition.distanceTo(endTarget);
  87831. let easing = TWEEN.Easing.Quartic.Out;
  87832. { // animate camera position
  87833. let pos = startPosition.clone();
  87834. let tween = new TWEEN.Tween(pos).to(endPosition, animationDuration);
  87835. tween.easing(easing);
  87836. tween.onUpdate(() => {
  87837. view.position.copy(pos);
  87838. });
  87839. tween.start();
  87840. }
  87841. { // animate camera target
  87842. let target = startTarget.clone();
  87843. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  87844. tween.easing(easing);
  87845. tween.onUpdate(() => {
  87846. view.lookAt(target);
  87847. });
  87848. tween.onComplete(() => {
  87849. view.lookAt(target);
  87850. this.dispatchEvent({type: 'focusing_finished', target: this});
  87851. });
  87852. this.dispatchEvent({type: 'focusing_started', target: this});
  87853. tween.start();
  87854. }
  87855. };
  87856. moveToGpsTimeVicinity(time){
  87857. const result = Potree.Utils.findClosestGpsTime(time, viewer);
  87858. const box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox();
  87859. const diameter = box.min.distanceTo(box.max);
  87860. const camera = this.scene.getActiveCamera();
  87861. const offset = camera.getWorldDirection(new Vector3()).multiplyScalar(diameter);
  87862. const newCamPos = result.position.clone().sub(offset);
  87863. this.scene.view.position.copy(newCamPos);
  87864. this.scene.view.lookAt(result.position);
  87865. }
  87866. showAbout () {
  87867. $(function () {
  87868. $('#about-panel').dialog();
  87869. });
  87870. };
  87871. getGpsTimeExtent(){
  87872. const range = [Infinity, -Infinity];
  87873. for(const pointcloud of this.scene.pointclouds){
  87874. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  87875. const aGpsTime = attributes.find(a => a.name === "gps-time");
  87876. if(aGpsTime){
  87877. range[0] = Math.min(range[0], aGpsTime.range[0]);
  87878. range[1] = Math.max(range[1], aGpsTime.range[1]);
  87879. }
  87880. }
  87881. return range;
  87882. }
  87883. fitToScreen (factor = 1, animationDuration = 0) {
  87884. let box = this.getBoundingBox(this.scene.pointclouds);
  87885. let node = new Object3D();
  87886. node.boundingBox = box;
  87887. this.zoomTo(node, factor, animationDuration);
  87888. this.controls.stop();
  87889. };
  87890. toggleNavigationCube() {
  87891. this.navigationCube.visible = !this.navigationCube.visible;
  87892. }
  87893. /* setView(pos, view) {
  87894. if(!pos) return;
  87895. switch(pos) {
  87896. case "F":
  87897. this.setFrontView(view);
  87898. break;
  87899. case "B":
  87900. this.setBackView(view);
  87901. break;
  87902. case "L":
  87903. this.setLeftView(view);
  87904. break;
  87905. case "R":
  87906. this.setRightView(view);
  87907. break;
  87908. case "U":
  87909. this.setTopView(view);
  87910. break;
  87911. case "D":
  87912. this.setBottomView(view);
  87913. break;
  87914. }
  87915. } */
  87916. setTopView(view){
  87917. view = view || this.scene.view;
  87918. view.setCubeView("top");
  87919. this.fitToScreen();
  87920. };
  87921. setBottomView(){
  87922. this.scene.view.yaw = -Math.PI;
  87923. this.scene.view.pitch = Math.PI / 2;
  87924. this.fitToScreen();
  87925. };
  87926. setFrontView(view){
  87927. view = view || this.scene.view;
  87928. view.yaw = 0;
  87929. view.pitch = 0;
  87930. this.fitToScreen();
  87931. };
  87932. setBackView(view){
  87933. view = view || this.scene.view;
  87934. view.yaw = Math.PI;
  87935. view.pitch = 0;
  87936. this.fitToScreen();
  87937. };
  87938. setLeftView(){
  87939. this.scene.view.yaw = -Math.PI / 2;
  87940. this.scene.view.pitch = 0;
  87941. this.fitToScreen();
  87942. };
  87943. setRightView () {
  87944. this.scene.view.yaw = Math.PI / 2;
  87945. this.scene.view.pitch = 0;
  87946. this.fitToScreen();
  87947. };
  87948. flipYZ () {
  87949. this.isFlipYZ = !this.isFlipYZ;
  87950. // TODO flipyz
  87951. console.log('TODO');
  87952. }
  87953. setCameraMode(mode){
  87954. this.scene.cameraMode = mode;
  87955. for(let pointcloud of this.scene.pointclouds) {
  87956. pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC;
  87957. }
  87958. }
  87959. getProjection(){
  87960. const pointcloud = this.scene.pointclouds[0];
  87961. if(pointcloud){
  87962. return pointcloud.projection;
  87963. }else {
  87964. return null;
  87965. }
  87966. }
  87967. async loadProject(url,done){
  87968. const response = await fetch(url);
  87969. if(response.ok){
  87970. const text = await response.text();
  87971. const json = lib.parse(text);
  87972. // const json = JSON.parse(text);
  87973. if(json.type === "Potree"){
  87974. Potree.loadProject(viewer, json, done);
  87975. }
  87976. }else {
  87977. console.warn("未能加载:"+url );
  87978. }
  87979. }
  87980. saveProject(){
  87981. return Potree.saveProject(this);
  87982. }
  87983. loadSettingsFromURL(){
  87984. if(Utils.getParameterByName("pointSize")){
  87985. this.setPointSize(parseFloat(Utils.getParameterByName("pointSize")));
  87986. }
  87987. if(Utils.getParameterByName("FOV")){
  87988. this.setFOV(parseFloat(Utils.getParameterByName("FOV")));
  87989. }
  87990. if(Utils.getParameterByName("opacity")){
  87991. this.setOpacity(parseFloat(Utils.getParameterByName("opacity")));
  87992. }
  87993. if(Utils.getParameterByName("edlEnabled")){
  87994. let enabled = Utils.getParameterByName("edlEnabled") === "true";
  87995. this.setEDLEnabled(enabled);
  87996. }
  87997. if (Utils.getParameterByName('edlRadius')) {
  87998. this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius')));
  87999. }
  88000. if (Utils.getParameterByName('edlStrength')) {
  88001. this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength')));
  88002. }
  88003. if (Utils.getParameterByName('pointBudget')) {
  88004. this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget')));
  88005. }
  88006. if (Utils.getParameterByName('showBoundingBox')) {
  88007. let enabled = Utils.getParameterByName('showBoundingBox') === 'true';
  88008. if (enabled) {
  88009. this.setShowBoundingBox(true);
  88010. } else {
  88011. this.setShowBoundingBox(false);
  88012. }
  88013. }
  88014. if (Utils.getParameterByName('material')) {
  88015. let material = Utils.getParameterByName('material');
  88016. this.setMaterial(material);
  88017. }
  88018. if (Utils.getParameterByName('pointSizing')) {
  88019. let sizing = Utils.getParameterByName('pointSizing');
  88020. this.setPointSizing(sizing);
  88021. }
  88022. if (Utils.getParameterByName('quality')) {
  88023. let quality = Utils.getParameterByName('quality');
  88024. this.setQuality(quality);
  88025. }
  88026. if (Utils.getParameterByName('position')) {
  88027. let value = Utils.getParameterByName('position');
  88028. value = value.replace('[', '').replace(']', '');
  88029. let tokens = value.split(';');
  88030. let x = parseFloat(tokens[0]);
  88031. let y = parseFloat(tokens[1]);
  88032. let z = parseFloat(tokens[2]);
  88033. this.scene.view.position.set(x, y, z);
  88034. }
  88035. if (Utils.getParameterByName('target')) {
  88036. let value = Utils.getParameterByName('target');
  88037. value = value.replace('[', '').replace(']', '');
  88038. let tokens = value.split(';');
  88039. let x = parseFloat(tokens[0]);
  88040. let y = parseFloat(tokens[1]);
  88041. let z = parseFloat(tokens[2]);
  88042. this.scene.view.lookAt(new Vector3(x, y, z));
  88043. }
  88044. if (Utils.getParameterByName('background')) {
  88045. let value = Utils.getParameterByName('background');
  88046. this.setBackground(value);
  88047. }
  88048. // if(Utils.getParameterByName("elevationRange")){
  88049. // let value = Utils.getParameterByName("elevationRange");
  88050. // value = value.replace("[", "").replace("]", "");
  88051. // let tokens = value.split(";");
  88052. // let x = parseFloat(tokens[0]);
  88053. // let y = parseFloat(tokens[1]);
  88054. //
  88055. // this.setElevationRange(x, y);
  88056. // //this.scene.view.target.set(x, y, z);
  88057. // }
  88058. };
  88059. // ------------------------------------------------------------------------------------
  88060. // Viewer Internals
  88061. // ------------------------------------------------------------------------------------
  88062. createControls () {
  88063. { // create FIRST PERSON CONTROLS
  88064. this.fpControls = new FirstPersonControls(this, this.mainViewport);
  88065. this.fpControls.enabled = false;
  88066. this.fpControls.addEventListener('start', this.disableAnnotations.bind(this));
  88067. this.fpControls.addEventListener('end', this.enableAnnotations.bind(this));
  88068. /* this.addEventListener("loadPointCloudDone", ()=>{
  88069. let boundPlane = new THREE.Box3()
  88070. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  88071. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  88072. FirstPersonControls.boundPlane = boundPlane
  88073. FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  88074. }) */
  88075. }
  88076. // { // create GEO CONTROLS
  88077. // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement);
  88078. // this.geoControls.enabled = false;
  88079. // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this));
  88080. // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this));
  88081. // this.geoControls.addEventListener("move_speed_changed", (event) => {
  88082. // this.setMoveSpeed(this.geoControls.moveSpeed);
  88083. // });
  88084. // }
  88085. { // create ORBIT CONTROLS
  88086. this.orbitControls = new OrbitControls(this);
  88087. this.orbitControls.enabled = false;
  88088. this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this));
  88089. this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this));
  88090. }
  88091. { // create EARTH CONTROLS
  88092. this.earthControls = new EarthControls(this);
  88093. this.earthControls.enabled = false;
  88094. this.earthControls.addEventListener('start', this.disableAnnotations.bind(this));
  88095. this.earthControls.addEventListener('end', this.enableAnnotations.bind(this));
  88096. }
  88097. { // create DEVICE ORIENTATION CONTROLS
  88098. this.deviceControls = new DeviceOrientationControls(this);
  88099. this.deviceControls.enabled = false;
  88100. this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this));
  88101. this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this));
  88102. }
  88103. /* { // create VR CONTROLS
  88104. this.vrControls = new VRControls(this);
  88105. this.vrControls.enabled = false;
  88106. this.vrControls.addEventListener('start', this.disableAnnotations.bind(this));
  88107. this.vrControls.addEventListener('end', this.enableAnnotations.bind(this));
  88108. } */
  88109. };
  88110. toggleSidebar () {
  88111. let renderArea = $('#potree_render_area');
  88112. let isVisible = renderArea.css('left') !== '0px';
  88113. if (isVisible) {
  88114. renderArea.css('left', '0px');
  88115. } else {
  88116. renderArea.css('left', '300px');
  88117. }
  88118. };
  88119. toggleMap () {
  88120. // let map = $('#potree_map');
  88121. // map.toggle(100);
  88122. if (this.mapView) {
  88123. this.mapView.toggle();
  88124. }
  88125. };
  88126. onGUILoaded(callback){
  88127. if(this.guiLoaded){
  88128. callback();
  88129. }else {
  88130. this.guiLoadTasks.push(callback);
  88131. }
  88132. }
  88133. promiseGuiLoaded(){
  88134. return new Promise( resolve => {
  88135. if(this.guiLoaded){
  88136. resolve();
  88137. }else {
  88138. this.guiLoadTasks.push(resolve);
  88139. }
  88140. });
  88141. }
  88142. loadGUI(callback){
  88143. if(callback){
  88144. this.onGUILoaded(callback);
  88145. }
  88146. let viewer = this;
  88147. let sidebarContainer = $('#potree_sidebar_container');
  88148. sidebarContainer.load(new URL(Potree.scriptPath + '/' + (Potree.settings.sidebar || 'sidebar.html')).href, () => {
  88149. sidebarContainer.css('width', '300px');
  88150. sidebarContainer.css('height', '100%');
  88151. let imgMenuToggle = document.createElement('img');
  88152. imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href;
  88153. imgMenuToggle.onclick = this.toggleSidebar;
  88154. imgMenuToggle.classList.add('potree_menu_toggle');
  88155. let imgMapToggle = document.createElement('img');
  88156. imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href;
  88157. imgMapToggle.style.display = 'none';
  88158. imgMapToggle.onclick = e => { this.toggleMap(); };
  88159. imgMapToggle.id = 'potree_map_toggle';
  88160. let elButtons = $("#potree_quick_buttons").get(0);
  88161. elButtons.append(imgMenuToggle);
  88162. elButtons.append(imgMapToggle);
  88163. /*
  88164. VRButton.createButton(this.renderer).then(vrButton => {
  88165. if(vrButton == null){
  88166. console.log("VR not supported or active.");
  88167. return;
  88168. }
  88169. this.renderer.xr.enabled = true;
  88170. let element = vrButton.element;
  88171. element.style.position = "";
  88172. element.style.bottom = "";
  88173. element.style.left = "";
  88174. element.style.margin = "4px";
  88175. element.style.fontSize = "100%";
  88176. element.style.width = "2.5em";
  88177. element.style.height = "2.5em";
  88178. element.style.padding = "0";
  88179. element.style.textShadow = "black 2px 2px 2px";
  88180. element.style.display = "block";
  88181. elButtons.append(element);
  88182. vrButton.onStart(() => {
  88183. this.dispatchEvent({type: "vr_start"});
  88184. });
  88185. vrButton.onEnd(() => {
  88186. this.dispatchEvent({type: "vr_end"});
  88187. });
  88188. });
  88189. this.mapView = new MapView(this);
  88190. this.mapView.init(); */
  88191. i18n.init({
  88192. lng: 'en',
  88193. resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json',
  88194. preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'],
  88195. getAsync: true,
  88196. debug: false
  88197. }, function (t) {
  88198. // Start translation once everything is loaded
  88199. $('body').i18n();
  88200. });
  88201. $(() => {
  88202. //initSidebar(this);
  88203. let sidebar = new Sidebar(this);
  88204. sidebar.init();
  88205. this.sidebar = sidebar;
  88206. //if (callback) {
  88207. // $(callback);
  88208. //}
  88209. let elProfile = $('<div>').load(new URL(Potree.scriptPath + '/profile.html').href, () => {
  88210. $(document.body).append(elProfile.children());
  88211. this.profileWindow = new ProfileWindow(this);
  88212. this.profileWindowController = new ProfileWindowController(this);
  88213. $('#profile_window').draggable({
  88214. handle: $('#profile_titlebar'),
  88215. containment: $(document.body)
  88216. });
  88217. $('#profile_window').resizable({
  88218. containment: $(document.body),
  88219. handles: 'n, e, s, w'
  88220. });
  88221. $(() => {
  88222. this.guiLoaded = true;
  88223. for(let task of this.guiLoadTasks){
  88224. task();
  88225. }
  88226. });
  88227. });
  88228. });
  88229. });
  88230. return this.promiseGuiLoaded();
  88231. }
  88232. setLanguage (lang) {
  88233. i18n.setLng(lang);
  88234. $('body').i18n();
  88235. }
  88236. setServer (server) {
  88237. this.server = server;
  88238. }
  88239. initDragAndDrop(){
  88240. function allowDrag(e) {
  88241. e.dataTransfer.dropEffect = 'copy';
  88242. e.preventDefault();
  88243. }
  88244. let dropHandler = async (event) => {
  88245. console.log(event);
  88246. event.preventDefault();
  88247. for(const item of event.dataTransfer.items){
  88248. console.log(item);
  88249. if(item.kind !== "file"){
  88250. continue;
  88251. }
  88252. const file = item.getAsFile();
  88253. const isJson = file.name.toLowerCase().endsWith(".json");
  88254. const isGeoPackage = file.name.toLowerCase().endsWith(".gpkg");
  88255. if(isJson){
  88256. try{
  88257. const text = await file.text();
  88258. const json = JSON.parse(text);
  88259. if(json.type === "Potree"){
  88260. Potree.loadProject(viewer, json);
  88261. }
  88262. }catch(e){
  88263. console.error("failed to parse the dropped file as JSON");
  88264. console.error(e);
  88265. }
  88266. }else if(isGeoPackage){
  88267. const hasPointcloud = viewer.scene.pointclouds.length > 0;
  88268. if(!hasPointcloud){
  88269. let msg = "At least one point cloud is needed that specifies the ";
  88270. msg += "coordinate reference system before loading vector data.";
  88271. console.error(msg);
  88272. }else {
  88273. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  88274. proj4.defs("pointcloud", this.getProjection());
  88275. let transform = proj4("WGS84", "pointcloud");
  88276. const buffer = await file.arrayBuffer();
  88277. const params = {
  88278. transform: transform,
  88279. source: file.name,
  88280. };
  88281. const geo = await Potree.GeoPackageLoader.loadBuffer(buffer, params);
  88282. viewer.scene.addGeopackage(geo);
  88283. }
  88284. }
  88285. }
  88286. };
  88287. $("body")[0].addEventListener("dragenter", allowDrag);
  88288. $("body")[0].addEventListener("dragover", allowDrag);
  88289. $("body")[0].addEventListener("drop", dropHandler);
  88290. }
  88291. updateAnnotations () {
  88292. if(!this.visibleAnnotations){
  88293. this.visibleAnnotations = new Set();
  88294. }
  88295. this.scene.annotations.updateBounds();
  88296. this.scene.cameraP.updateMatrixWorld();
  88297. this.scene.cameraO.updateMatrixWorld();
  88298. let distances = [];
  88299. let renderAreaSize = this.renderer.getSize(new Vector2$1());
  88300. let viewer = this;
  88301. let visibleNow = [];
  88302. this.scene.annotations.traverse(annotation => {
  88303. if (annotation === this.scene.annotations) {
  88304. return true;
  88305. }
  88306. if (!annotation.visible) {
  88307. return false;
  88308. }
  88309. annotation.scene = this.scene;
  88310. let element = annotation.domElement;
  88311. let position = annotation.position.clone();
  88312. position.add(annotation.offset);
  88313. if (!position) {
  88314. position = annotation.boundingBox.getCenter(new Vector3());
  88315. }
  88316. let distance = viewer.scene.cameraP.position.distanceTo(position);
  88317. let radius = annotation.boundingBox.getBoundingSphere(new Sphere()).radius;
  88318. let screenPos = new Vector3();
  88319. let screenSize = 0;
  88320. {
  88321. // SCREEN POS
  88322. screenPos.copy(position).project(this.scene.getActiveCamera());
  88323. screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2;
  88324. screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2);
  88325. // SCREEN SIZE
  88326. if(viewer.scene.cameraMode == CameraMode.PERSPECTIVE) {
  88327. let fov = Math.PI * viewer.scene.cameraP.fov / 180;
  88328. let slope = Math.tan(fov / 2.0);
  88329. let projFactor = 0.5 * renderAreaSize.y / (slope * distance);
  88330. screenSize = radius * projFactor;
  88331. } else {
  88332. screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y);
  88333. }
  88334. }
  88335. element.css("left", screenPos.x + "px");
  88336. element.css("top", screenPos.y + "px");
  88337. //element.css("display", "block");
  88338. let zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far);
  88339. if(annotation.descriptionVisible){
  88340. zIndex += 10000000;
  88341. }
  88342. element.css("z-index", parseInt(zIndex));
  88343. if(annotation.children.length > 0){
  88344. let expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position);
  88345. annotation.expand = expand;
  88346. if (!expand) {
  88347. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  88348. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  88349. if(inFrustum){
  88350. visibleNow.push(annotation);
  88351. }
  88352. }
  88353. return expand;
  88354. } else {
  88355. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  88356. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  88357. if(inFrustum){
  88358. visibleNow.push(annotation);
  88359. }
  88360. }
  88361. });
  88362. let notVisibleAnymore = new Set(this.visibleAnnotations);
  88363. for(let annotation of visibleNow){
  88364. annotation.display = true;
  88365. notVisibleAnymore.delete(annotation);
  88366. }
  88367. this.visibleAnnotations = visibleNow;
  88368. for(let annotation of notVisibleAnymore){
  88369. annotation.display = false;
  88370. }
  88371. }
  88372. updateMaterialDefaults(pointcloud){
  88373. // PROBLEM STATEMENT:
  88374. // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded
  88375. // * the point cloud material won't know the range it should use until some data is loaded
  88376. // * users can modify the range at runtime, but sensible default ranges should be
  88377. // applied even if no GUI is present
  88378. // * display ranges shouldn't suddenly change even if the actual range changes over time.
  88379. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to
  88380. // [0, 2047]. We should not automatically change to the new range because that would result
  88381. // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider.
  88382. const material = pointcloud.material;
  88383. const attIntensity = pointcloud.getAttribute("intensity");
  88384. if(attIntensity != null && material.intensityRange[0] === Infinity){
  88385. material.intensityRange = [...attIntensity.range];
  88386. }
  88387. // const attIntensity = pointcloud.getAttribute("intensity");
  88388. // if(attIntensity && material.intensityRange[0] === Infinity){
  88389. // material.intensityRange = [...attIntensity.range];
  88390. // }
  88391. // let attributes = pointcloud.getAttributes();
  88392. // for(let attribute of attributes.attributes){
  88393. // if(attribute.range){
  88394. // let range = [...attribute.range];
  88395. // material.computedRange.set(attribute.name, range);
  88396. // //material.setRange(attribute.name, range);
  88397. // }
  88398. // }
  88399. }
  88400. update(delta, timestamp){
  88401. if(Potree.measureTimings) performance.mark("update-start");
  88402. this.dispatchEvent({
  88403. type: 'update_start',
  88404. delta: delta,
  88405. timestamp: timestamp});
  88406. this.updateScreenSize(); //判断是否改变canvas大小
  88407. const scene = this.scene;
  88408. const camera = scene.getActiveCamera();
  88409. const visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible);
  88410. Potree.pointLoadLimit = Potree.pointBudget * 2;
  88411. const lTarget = camera.position.clone().add(camera.getWorldDirection(new Vector3()).multiplyScalar(1000));
  88412. this.scene.directionalLight.position.copy(camera.position);
  88413. this.scene.directionalLight.lookAt(lTarget);
  88414. for (let pointcloud of visiblePointClouds) {
  88415. pointcloud.showBoundingBox = this.showBoundingBox;
  88416. pointcloud.generateDEM = this.generateDEM;
  88417. pointcloud.minimumNodePixelSize = this.minNodeSize;
  88418. let material = pointcloud.material;
  88419. material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange;
  88420. material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange;
  88421. material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange;
  88422. material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange;
  88423. material.classification = this.classifications;
  88424. material.recomputeClassification();
  88425. this.updateMaterialDefaults(pointcloud);
  88426. }
  88427. {
  88428. if(this.showBoundingBox){
  88429. let bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root");
  88430. if(!bbRoot){
  88431. let node = new Object3D();
  88432. node.name = "potree_bounding_box_root";
  88433. this.scene.scene.add(node);
  88434. bbRoot = node;
  88435. }
  88436. let visibleBoxes = [];
  88437. for(let pointcloud of this.scene.pointclouds){
  88438. for(let node of pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)){
  88439. let box = node.boundingBoxNode;
  88440. visibleBoxes.push(box);
  88441. }
  88442. }
  88443. bbRoot.children = visibleBoxes;
  88444. }
  88445. }
  88446. if (!this.freeze) {
  88447. /*let cameraGroup = []
  88448. let size = this.renderer.getSize(new THREE.Vector2())
  88449. if(this.viewports){
  88450. this.viewports.forEach(viewport=>{
  88451. if(!viewport.active)return
  88452. cameraGroup.push({camera:viewport.camera, areaSize:new THREE.Vector2(Math.floor(size.x * viewport.width), Math.floor(size.y * viewport.height))})
  88453. })
  88454. }else{
  88455. cameraGroup.push({camera, areaSize:size})
  88456. }
  88457. let result = Potree.updatePointClouds(scene.pointclouds, cameraGroup );
  88458. */
  88459. // DEBUG - ONLY DISPLAY NODES THAT INTERSECT MOUSE
  88460. //if(false){
  88461. // let renderer = viewer.renderer;
  88462. // let mouse = viewer.inputHandler.mouse;
  88463. // let nmouse = {
  88464. // x: (mouse.x / renderer.domElement.clientWidth) * 2 - 1,
  88465. // y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1
  88466. // };
  88467. // let pickParams = {};
  88468. // //if(params.pickClipped){
  88469. // // pickParams.pickClipped = params.pickClipped;
  88470. // //}
  88471. // pickParams.x = mouse.x;
  88472. // pickParams.y = renderer.domElement.clientHeight - mouse.y;
  88473. // let raycaster = new THREE.Raycaster();
  88474. // raycaster.setFromCamera(nmouse, camera);
  88475. // let ray = raycaster.ray;
  88476. // for(let pointcloud of scene.pointclouds){
  88477. // let nodes = pointcloud.nodesOnRay(pointcloud.visibleNodes, ray);
  88478. // pointcloud.visibleNodes = nodes;
  88479. // }
  88480. //}
  88481. // const tStart = performance.now();
  88482. // const worldPos = new THREE.Vector3();
  88483. // const camPos = viewer.scene.getActiveCamera().getWorldPosition(new THREE.Vector3());
  88484. // let lowestDistance = Infinity;
  88485. // let numNodes = 0;
  88486. // viewer.scene.scene.traverse(node => {
  88487. // node.getWorldPosition(worldPos);
  88488. // const distance = worldPos.distanceTo(camPos);
  88489. // lowestDistance = Math.min(lowestDistance, distance);
  88490. // numNodes++;
  88491. // if(Number.isNaN(distance)){
  88492. // console.error(":(");
  88493. // }
  88494. // });
  88495. // const duration = (performance.now() - tStart).toFixed(2);
  88496. // Potree.debug.computeNearDuration = duration;
  88497. // Potree.debug.numNodes = numNodes;
  88498. //console.log(lowestDistance.toString(2), duration);
  88499. //搬走
  88500. /* const tStart = performance.now();
  88501. const campos = camera.position;
  88502. let closestImage = Infinity;
  88503. for(const images of this.scene.orientedImages){
  88504. for(const image of images.images){
  88505. const distance = image.mesh.position.distanceTo(campos);
  88506. closestImage = Math.min(closestImage, distance);
  88507. }
  88508. }
  88509. const tEnd = performance.now();
  88510. if(result.lowestSpacing !== Infinity){
  88511. let near = result.lowestSpacing * 10.0;
  88512. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  88513. far = Math.max(far * 1.5, 10000);
  88514. near = Math.min(100.0, Math.max(0.01, near));
  88515. near = Math.min(near, closestImage);
  88516. far = Math.max(far, near + 10000);
  88517. if(near === Infinity){
  88518. near = 0.1;
  88519. }
  88520. camera.near = near;
  88521. camera.far = far;
  88522. }else{
  88523. // don't change near and far in this case
  88524. }
  88525. if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {
  88526. camera.near = -camera.far;
  88527. }*/
  88528. }
  88529. this.scene.cameraP.fov = this.fov;
  88530. let controls = this.getControls();
  88531. if (controls === this.deviceControls) {
  88532. this.controls.setScene(scene);
  88533. this.controls.update(delta);
  88534. this.scene.cameraP.position.copy(scene.view.position);
  88535. this.scene.cameraO.position.copy(scene.view.position);
  88536. } else if (controls !== null) {
  88537. controls.setScene(scene);
  88538. controls.update(delta);
  88539. //更新camera
  88540. this.viewports.forEach(viewport=>{
  88541. if(!viewport.active)return
  88542. viewport.view.applyToCamera(viewport.camera);
  88543. });
  88544. }
  88545. /* this.viewports.forEach(e=>{//判断camera画面是否改变
  88546. if(e.cameraChanged()){
  88547. this.dispatchEvent({
  88548. type: "camera_changed",
  88549. camera: e.camera,
  88550. viewport : e
  88551. })
  88552. }
  88553. }) */
  88554. this.cameraChanged();//判断camera画面是否改变
  88555. /* {//判断camera画面是否改变
  88556. if(this._previousCamera === undefined){
  88557. this._previousCamera = this.scene.getActiveCamera().clone();
  88558. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  88559. }
  88560. if(!this._previousCamera.matrixWorld.equals(camera.matrixWorld) ||
  88561. !this._previousCamera.projectionMatrix.equals(camera.projectionMatrix)
  88562. ){
  88563. this.dispatchEvent({
  88564. type: "camera_changed",
  88565. previous: this._previousCamera,
  88566. camera: camera
  88567. });
  88568. }
  88569. this._previousCamera = this.scene.getActiveCamera().clone();
  88570. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  88571. } */
  88572. { // update clip boxes
  88573. let boxes = [];
  88574. // volumes with clipping enabled
  88575. //boxes.push(...this.scene.volumes.filter(v => (v.clip)));
  88576. boxes.push(...this.scene.volumes.filter(v => (v.clip && v instanceof BoxVolume)));
  88577. // profile segments
  88578. for(let profile of this.scene.profiles){
  88579. boxes.push(...profile.boxes);
  88580. }
  88581. // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816
  88582. let degenerate = (box) => box.matrixWorld.determinant() !== 0;
  88583. let clipBoxes = boxes.filter(degenerate).map( box => {
  88584. box.updateMatrixWorld();
  88585. let boxInverse = box.matrixWorld.clone().invert();
  88586. let boxPosition = box.getWorldPosition(new Vector3());
  88587. return {box: box, inverse: boxInverse, position: boxPosition};
  88588. });
  88589. let clipPolygons = this.scene.polygonClipVolumes.filter(vol => vol.initialized);
  88590. // set clip volumes in material
  88591. for(let pointcloud of visiblePointClouds){
  88592. pointcloud.material.setClipBoxes(clipBoxes);
  88593. pointcloud.material.setClipPolygons(clipPolygons, this.clippingTool.maxPolygonVertices);
  88594. pointcloud.material.clipTask = this.clipTask;
  88595. pointcloud.material.clipMethod = this.clipMethod;
  88596. }
  88597. }
  88598. {
  88599. for(let pointcloud of visiblePointClouds){
  88600. pointcloud.material.elevationGradientRepeat = this.elevationGradientRepeat;
  88601. }
  88602. }
  88603. { // update navigation cube
  88604. this.navigationCube.update(camera.rotation);
  88605. }
  88606. this.updateAnnotations();
  88607. if(this.mapView){
  88608. this.mapView.update(delta);
  88609. if(this.mapView.sceneProjection){
  88610. $( "#potree_map_toggle" ).css("display", "block");
  88611. }
  88612. }
  88613. TWEEN.update(timestamp);
  88614. transitions.update(delta);
  88615. this.transformationTool.update();
  88616. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  88617. this.modules.ParticleEditor.update(delta);
  88618. this.mapViewer.update(delta);
  88619. }
  88620. this.dispatchEvent({
  88621. type: 'update',
  88622. delta: delta,
  88623. timestamp: timestamp});
  88624. if(Potree.measureTimings) {
  88625. performance.mark("update-end");
  88626. performance.measure("update", "update-start", "update-end");
  88627. }
  88628. //add ------
  88629. this.reticule.updateVisible();
  88630. }
  88631. updateViewPointcloud(camera, areaSize, isViewport){
  88632. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize );
  88633. //if(isViewport)return
  88634. const tStart = performance.now();
  88635. const campos = camera.position;
  88636. let closestImage = Infinity;
  88637. for(const images of this.scene.orientedImages){
  88638. for(const image of images.images){
  88639. const distance = image.mesh.position.distanceTo(campos);
  88640. closestImage = Math.min(closestImage, distance);
  88641. }
  88642. }
  88643. const tEnd = performance.now();
  88644. //改:不根据点云修改视野near far
  88645. var near = camera.near, far = camera.far;
  88646. if(!camera.limitFar && result.lowestSpacing !== Infinity){
  88647. //let near = result.lowestSpacing * 10.0;
  88648. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  88649. far = Math.max(far * 1.5, 10000);
  88650. //near = Math.min(100.0, Math.max(0.01, near));
  88651. //near = Math.min(near, closestImage);
  88652. far = Math.max(far, near + 10000);
  88653. /* if(near === Infinity){
  88654. near = 0.1;
  88655. } */
  88656. //camera.near = near; //为了其他物体的显示,不修改near
  88657. camera.far = far;
  88658. }
  88659. /* if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//???
  88660. camera.near = -camera.far;
  88661. } */
  88662. if(/* near != camera.near || */far != camera.far){
  88663. camera.updateProjectionMatrix();
  88664. }
  88665. //注:pointcloud.visibleNodes会随着near far自动更新
  88666. }
  88667. getPRenderer(){
  88668. if(this.useHQ){
  88669. if (!this.hqRenderer) {
  88670. this.hqRenderer = new HQSplatRenderer(this);
  88671. }
  88672. this.hqRenderer.useEDL = this.useEDL;
  88673. return this.hqRenderer;
  88674. }else {
  88675. /* if (this.useEDL && Features.SHADER_EDL.isSupported()) {
  88676. if (!this.edlRenderer) {
  88677. this.edlRenderer = new EDLRenderer(this);
  88678. }
  88679. return this.edlRenderer;
  88680. } else {
  88681. if (!this.potreeRenderer) {
  88682. this.potreeRenderer = new PotreeRenderer(this);
  88683. }
  88684. return this.potreeRenderer;
  88685. } */
  88686. if (!this.edlRenderer) {
  88687. this.edlRenderer = new EDLRenderer(this);
  88688. }
  88689. return this.edlRenderer;
  88690. }
  88691. }
  88692. renderVR(){
  88693. let renderer = this.renderer;
  88694. renderer.setClearColor(0x550000, 0);
  88695. renderer.clear();
  88696. let xr = renderer.xr;
  88697. let dbg = new PerspectiveCamera();
  88698. let xrCameras = xr.getCamera(dbg);
  88699. if(xrCameras.cameras.length !== 2){
  88700. return;
  88701. }
  88702. let makeCam = this.vrControls.getCamera.bind(this.vrControls);
  88703. { // clear framebuffer
  88704. if(viewer.background === "skybox"){
  88705. renderer.setClearColor(0xff0000, 1);
  88706. }else if(viewer.background === "gradient"){
  88707. renderer.setClearColor(0x112233, 1);
  88708. }else if(viewer.background === "black"){
  88709. renderer.setClearColor(0x000000, 1);
  88710. }else if(viewer.background === "white"){
  88711. renderer.setClearColor(0xFFFFFF, 1);
  88712. }else {
  88713. renderer.setClearColor(0x000000, 0);
  88714. }
  88715. renderer.clear();
  88716. }
  88717. // render background
  88718. if(this.background === "skybox"){
  88719. let {skybox} = this;
  88720. let cam = makeCam();
  88721. skybox.camera.rotation.copy(cam.rotation);
  88722. skybox.camera.fov = cam.fov;
  88723. skybox.camera.aspect = cam.aspect;
  88724. // let dbg = new THREE.Object3D();
  88725. let dbg = skybox.parent;
  88726. // dbg.up.set(0, 0, 1);
  88727. dbg.rotation.x = Math.PI / 2;
  88728. // skybox.camera.parent = dbg;
  88729. // dbg.children.push(skybox.camera);
  88730. dbg.updateMatrix();
  88731. dbg.updateMatrixWorld();
  88732. skybox.camera.updateMatrix();
  88733. skybox.camera.updateMatrixWorld();
  88734. skybox.camera.updateProjectionMatrix();
  88735. renderer.render(skybox.scene, skybox.camera);
  88736. // renderer.render(skybox.scene, cam);
  88737. }else if(this.background === "gradient"){
  88738. // renderer.render(this.scene.sceneBG, this.scene.cameraBG);
  88739. }
  88740. this.renderer.xr.getSession().updateRenderState({
  88741. depthNear: 0.1,
  88742. depthFar: 10000
  88743. });
  88744. let cam = null;
  88745. let view = null;
  88746. { // render world scene
  88747. cam = makeCam();
  88748. cam.position.z -= 0.8 * cam.scale.x;
  88749. cam.parent = null;
  88750. // cam.near = 0.05;
  88751. cam.near = viewer.scene.getActiveCamera().near;
  88752. cam.far = viewer.scene.getActiveCamera().far;
  88753. cam.updateMatrix();
  88754. cam.updateMatrixWorld();
  88755. this.scene.scene.updateMatrix();
  88756. this.scene.scene.updateMatrixWorld();
  88757. this.scene.scene.matrixAutoUpdate = false;
  88758. let camWorld = cam.matrixWorld.clone();
  88759. view = camWorld.clone().invert();
  88760. this.scene.scene.matrix.copy(view);
  88761. this.scene.scene.matrixWorld.copy(view);
  88762. cam.matrix.identity();
  88763. cam.matrixWorld.identity();
  88764. cam.matrixWorldInverse.identity();
  88765. renderer.render(this.scene.scene, cam);
  88766. this.scene.scene.matrixWorld.identity();
  88767. }
  88768. for(let pointcloud of this.scene.pointclouds){
  88769. let viewport = xrCameras.cameras[0].viewport;
  88770. pointcloud.material.useEDL = false;
  88771. pointcloud.screenHeight = viewport.height;
  88772. pointcloud.screenWidth = viewport.width;
  88773. // automatically switch to paraboloids because they cause far less flickering in VR,
  88774. // when point sizes are larger than around 2 pixels
  88775. // if(Features.SHADER_INTERPOLATION.isSupported()){
  88776. // pointcloud.material.shape = Potree.PointShape.PARABOLOID;
  88777. // }
  88778. }
  88779. // render point clouds
  88780. for(let xrCamera of xrCameras.cameras){
  88781. let v = xrCamera.viewport;
  88782. renderer.setViewport(v.x, v.y, v.width, v.height);
  88783. // xrCamera.fov = 90;
  88784. { // estimate VR fov
  88785. let proj = xrCamera.projectionMatrix;
  88786. let inv = proj.clone().invert();
  88787. let p1 = new Vector4(0, 1, -1, 1).applyMatrix4(inv);
  88788. let rad = p1.y;
  88789. let fov = 180 * (rad / Math.PI);
  88790. xrCamera.fov = fov;
  88791. }
  88792. for(let pointcloud of this.scene.pointclouds){
  88793. const {material} = pointcloud;
  88794. material.useEDL = false;
  88795. }
  88796. let vrWorld = view.clone().invert();
  88797. vrWorld.multiply(xrCamera.matrixWorld);
  88798. let vrView = vrWorld.clone().invert();
  88799. this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, {
  88800. viewOverride: vrView,
  88801. });
  88802. }
  88803. { // render VR scene
  88804. let cam = makeCam();
  88805. cam.parent = null;
  88806. renderer.render(this.sceneVR, cam);
  88807. }
  88808. renderer.resetState();
  88809. }
  88810. clear(params={}){
  88811. let background = params.background || this.background;
  88812. let backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  88813. let renderer = this.renderer;
  88814. //let gl = renderer.getContext()
  88815. if(background instanceof Color){ //add
  88816. renderer.setClearColor(background, backgroundOpacity);
  88817. }else if(background === "skybox"){
  88818. renderer.setClearColor(0x000000, 0);
  88819. } else if (background === 'gradient') {
  88820. renderer.setClearColor(0x000000, 0);
  88821. } else if (background === 'black') {
  88822. renderer.setClearColor(0x000000, 1);
  88823. } else if (background === 'white') {
  88824. renderer.setClearColor(0xFFFFFF, 1);
  88825. } else {
  88826. renderer.setClearColor(background, backgroundOpacity);
  88827. }
  88828. params.target || renderer.clear();
  88829. }
  88830. renderDefault(params_={}){
  88831. if(!this.visible || this.paused )return
  88832. /* if(this.outlinePass.selectedObjects.length){
  88833. this.clear()
  88834. this.composer.render(this.scene.scene, this.mainViewport.camera );
  88835. return;
  88836. } */
  88837. let pRenderer = this.getPRenderer();
  88838. let viewports = params_.viewports || this.viewports;
  88839. let renderSize;
  88840. if(params_.target){
  88841. renderSize = new Vector2$1(params_.target.width, params_.target.height); //是画布大小
  88842. //可能需要viewer.setSize
  88843. }else {
  88844. renderSize = this.renderer.getSize(new Vector2$1()); //是client大小
  88845. }
  88846. let needSResize = viewports.filter(e=>e.active).length > 1 || params_.resize;
  88847. viewports.forEach(view=>{
  88848. let params = $.extend({},params_);
  88849. params.viewport = view;
  88850. //if(!params.target){
  88851. params.camera = params.camera || view.camera;
  88852. params.extraEnableLayers = view.extraEnableLayers;
  88853. params.cameraLayers = view.cameraLayers;
  88854. //}
  88855. if(!view.active)return
  88856. var left,bottom,width,height;
  88857. {
  88858. left = Math.ceil(renderSize.x * view.left);
  88859. bottom = Math.ceil(renderSize.y * view.bottom);
  88860. if(params_.target){//有target时最好viewport是专门建出来的
  88861. width = Math.ceil(renderSize.x * view.width); //target的大小可能和viewport不同,比如截图,这时会更改viewport大小
  88862. height = Math.ceil(renderSize.y * view.height);
  88863. }else {
  88864. width = view.resolution.x; // 用的是client的width和height
  88865. height = view.resolution.y;
  88866. }
  88867. if(width == 0 || height == 0)return
  88868. let scissorTest = view.width<1 || view.height<1;
  88869. if(params_.target){
  88870. params_.target.viewport.set(left, bottom, width, height);
  88871. scissorTest && params_.target.scissor.set(left, bottom, width, height);
  88872. params_.target.scissorTest = scissorTest;
  88873. }else {
  88874. this.renderer.setViewport(left, bottom, width, height); //规定视口,影响图形变换(画布的使用范围)
  88875. scissorTest && this.renderer.setScissor( left, bottom, width, height );//规定渲染范围
  88876. this.renderer.setScissorTest( scissorTest );//开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪
  88877. }
  88878. }
  88879. if(needSResize){
  88880. this.emitResizeMsg( { viewport:view} );
  88881. }
  88882. //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
  88883. viewer.dispatchEvent({type: "render.begin", viewer: viewer, viewport:view, params });
  88884. if(view.render){
  88885. view.render($.extend({}, params, {
  88886. renderer:this.renderer, clear:this.clear.bind(this), resize:null,
  88887. renderOverlay: this.renderOverlay.bind(this), force:!view.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好)
  88888. }));
  88889. }
  88890. if(!view.render){
  88891. this.clear(params);
  88892. pRenderer.clearTargets(params);
  88893. //先渲染不透明的model:
  88894. /* if(this.objs.children.length){
  88895. this.renderer.setRenderTarget(params.target||null)
  88896. this.setCameraLayers(params.camera, ['model'] )//先渲染模型后渲染点云,否则半透明的点云的blend没有混合模型的部分(但模型为何可以混合点云的部分?估计还是PotreeRenderer有问题)
  88897. this.renderer.render(this.scene.scene, params.camera);
  88898. } */
  88899. if(Potree.settings.notAdditiveBlending){
  88900. params.renderBeforeCloud = true;
  88901. this.renderOverlay1(params);
  88902. //view.render || this.renderOverlay(params)
  88903. }
  88904. }
  88905. /* view.render || this.clear(params)
  88906. pRenderer.clearTargets(params); */
  88907. if(!view.noPointcloud ){
  88908. //if(!params.target){
  88909. //params.width = width; params.height = height;
  88910. //}
  88911. if(view.render){
  88912. params.noBG = true;
  88913. }
  88914. view.beforeRender && view.beforeRender();
  88915. this.updateViewPointcloud(params.camera, view.resolution2, true);
  88916. params.background = view.background;
  88917. params.backgroundColor = view.backgroundColor;
  88918. params.backgroundOpacity = view.backgroundOpacity;
  88919. pRenderer.render(params);
  88920. }
  88921. if(!view.render){
  88922. //view.render || this.renderOverlay(params)
  88923. if(Potree.settings.notAdditiveBlending){
  88924. params.renderBeforeCloud = false;
  88925. this.renderOverlay1(params);
  88926. this.renderOverlay2(params);
  88927. }else {
  88928. /* view.render || */this.renderOverlay(params);
  88929. }
  88930. }
  88931. view.afterRender && view.afterRender();
  88932. this.dispatchEvent({type: "render.end", viewer: this, viewport:view });
  88933. });
  88934. /* if(params_.screenshot){ //抗锯齿
  88935. params_.target.viewport.set(0, 0, params_.target.width, params_.target.height);
  88936. //scissorTest && params_.target.scissor.set(left, bottom, width, height);
  88937. params_.target.scissorTest = false
  88938. this.renderer.setRenderTarget(params_.target)
  88939. this.composer.render();
  88940. this.renderer.setRenderTarget(params_.target) //本想再画一层标签,但是viewport总是出错
  88941. } */
  88942. this.renderer.setRenderTarget(null);
  88943. }
  88944. /*
  88945. 关于透明度:
  88946. 由于点云和mesh是分开渲染的,且材质很不一样,所以透明和blend有冲突
  88947. 1 如果点云的blend是AdditiveBlending,也就是普通的叠加模式。
  88948. 则半透明点云的depthTest和depthWrite都为false
  88949. 这时候mesh要后渲染,且depthWrite不能为false(除非depthTest也为false),否则将被点云遮住。
  88950. 2 如果点云的blend是普通型
  88951. 则半透明点云的depthTest和depthWrite都为true。(为何depthWrite不能像mesh一样为false, 否则点云自身透明会错乱,可能因为太多points了)
  88952. 这时候若mesh全部先渲染,则 透过depthWrite为false的半透明mesh看不透明点云,mesh会完全被点云遮住。但是透明的物体就是depthWrite要为false,否则也会完全遮住点云
  88953. 即使是后渲染半透明的mesh,若透过点云看mesh,mesh会完全被点云遮住(为什么之前遇到过 透过点云看mesh,点云会显示不出)
  88954. 最终选择是先渲染不透明的mesh,然后点云,然后透明的mesh。虽然点云对mesh透明会失效。
  88955. */
  88956. renderOverlay(params){
  88957. this.renderOverlay1(params);
  88958. this.renderOverlay2(params);
  88959. /* let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  88960. this.reticule.updateAtViewports(params.viewport)
  88961. this.renderer.setRenderTarget(params.target||null)
  88962. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  88963. let cameraLayers
  88964. if(params.cameraLayers) cameraLayers = params.cameraLayers
  88965. else{
  88966. if(params.isMap)cameraLayers = ['bothMapAndScene']
  88967. else cameraLayers = ['sceneObjects', 'model', 'bothMapAndScene' ];
  88968. }
  88969. if(cameraLayers.length){
  88970. this.setCameraLayers(camera, cameraLayers, params.extraEnableLayers) //透明贴图层 skybox 、reticule marker 不能遮住测量线
  88971. this.renderer.render(this.scene.scene, camera);
  88972. }
  88973. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  88974. //清除深度 !!!!
  88975. this.renderer.clearDepth();
  88976. //this.transformationTool.update();
  88977. if(!params.magnifier){
  88978. //测量线
  88979. this.dispatchEvent({type: "render.pass.perspective_overlay", camera, screenshot:params.screenshot});
  88980. if(!params.screenshot && !params.isMap){
  88981. this.setCameraLayers(camera, ['magnifier']) //magnifier 遮住测量线
  88982. this.renderer.render(this.scene.scene, camera);
  88983. }
  88984. }
  88985. if(!params.isMap) {
  88986. this.setCameraLayers(camera, ['volume','transformationTool'])
  88987. this.renderer.render(this.clippingTool.sceneVolume, camera);
  88988. this.renderer.render(this.transformationTool.scene, camera);
  88989. } */
  88990. }
  88991. renderOverlay1(params){
  88992. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  88993. this.reticule.updateAtViewports(params.viewport);
  88994. this.renderer.setRenderTarget(params.target||null);
  88995. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  88996. let cameraLayers;
  88997. if(params.cameraLayers) cameraLayers = params.cameraLayers;
  88998. else {
  88999. if(params.isMap)cameraLayers = ['bothMapAndScene'];
  89000. else cameraLayers = ['sceneObjects', 'model', 'bothMapAndScene' ];
  89001. }
  89002. if(cameraLayers.length){
  89003. this.setCameraLayers(camera, cameraLayers, params.extraEnableLayers); //透明贴图层 skybox 、reticule marker 不能遮住测量线
  89004. if('renderBeforeCloud' in params){
  89005. this.scene.scene.traverse((object)=>{
  89006. if(object.material){
  89007. this.updateVisible(object, 'renderOpa',
  89008. (params.renderBeforeCloud && (object.material.opacity<1 || !object.material.depthTest) || (!params.renderBeforeCloud) && (object.material.opacity==1 && object.material.depthTest))? false:true);
  89009. //点云之前渲染的话隐藏半透明的, 点云之后渲染的话隐藏不透明的。 depthTest==false的也最后渲染
  89010. }
  89011. });//ground的材质中opacity为1,所以被当做不透明了
  89012. }
  89013. this.renderer.render(this.scene.scene, camera);
  89014. if('renderBeforeCloud' in params){
  89015. this.scene.scene.traverse((object)=>{
  89016. if(object.material){
  89017. this.updateVisible(object, 'renderOpa', true); //恢复
  89018. }
  89019. });
  89020. }
  89021. }
  89022. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  89023. }
  89024. renderOverlay2(params){
  89025. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  89026. //清除深度 !!!!
  89027. this.renderer.clearDepth();
  89028. //this.transformationTool.update();
  89029. if(!params.magnifier){
  89030. //测量线
  89031. this.dispatchEvent({type: "render.pass.perspective_overlay", camera, screenshot:params.screenshot});
  89032. if(!params.screenshot && !params.isMap){
  89033. this.setCameraLayers(camera, ['magnifier']); //magnifier 遮住测量线
  89034. this.renderer.render(this.scene.scene, camera);
  89035. }
  89036. }
  89037. if(!params.isMap) {
  89038. this.setCameraLayers(camera, ['volume','transformationTool']);
  89039. this.renderer.render(this.clippingTool.sceneVolume, camera);
  89040. this.renderer.render(this.transformationTool.scene, camera);
  89041. }
  89042. }
  89043. /* renderDefault(){//测试 ios15.4.1
  89044. //let pRenderer = this.getPRenderer();
  89045. //this.clear()
  89046. this.renderer.autoClear = false
  89047. this.renderer.setRenderTarget(null)
  89048. let camera = this.scene.getActiveCamera();
  89049. this.setCameraLayers(camera, [ 'sceneObjects', 'marker' , 'reticule' ,'skybox' ])
  89050. this.renderer.render(this.scene.scene, camera);
  89051. // pRenderer.clearTargets( );
  89052. //pRenderer.render( );
  89053. } */
  89054. setLimitFar(state){//切换是否limitFar
  89055. viewer.mainViewport.camera.limitFar = !!state;
  89056. if(state){
  89057. viewer.mainViewport.camera.near = 0.02;
  89058. viewer.mainViewport.camera.far = Potree.settings.displayMode == 'showPanos' ? viewer.farWhenShowPano : Potree.settings.cameraFar;
  89059. viewer.mainViewport.camera.updateProjectionMatrix();
  89060. }
  89061. }
  89062. setCameraLayers(camera, enableLayers, extraEnableLayers=[]){//add
  89063. camera.layers.disableAll();
  89064. enableLayers.concat(extraEnableLayers).forEach(e=>{
  89065. let layer = Potree.config.renderLayers[e];
  89066. if(layer == void 0){
  89067. console.error('setCameraLayer没找到layer!');
  89068. return
  89069. }
  89070. camera.layers.enable(layer);
  89071. });
  89072. }
  89073. setObjectLayers(object, layerName){//add
  89074. let layer = Potree.config.renderLayers[layerName];
  89075. if(layer == void 0){
  89076. console.error('setCameraLayer没找到layer!');
  89077. return
  89078. }
  89079. object.traverse(e=>{
  89080. e.layers.set(layer);
  89081. });
  89082. }
  89083. /* updateVisible(object, reason, ifShow, force){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  89084. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  89085. if(!object.forceVisibleReasons) object.forceVisibleReasons = []; //只要有一项代表一定可见,优先级比unvisibleReasons高
  89086. if(ifShow){
  89087. if(force){
  89088. object.forceVisibleReasons.includes(reason) || object.forceVisibleReasons.push(reason)
  89089. object.visible = true;
  89090. object.dispatchEvent({
  89091. type: 'isVisible',
  89092. visible:true,
  89093. reason
  89094. })
  89095. }
  89096. var index = object.unvisibleReasons.indexOf(reason)
  89097. if(index > -1){
  89098. object.unvisibleReasons.splice(index, 1);
  89099. if(object.unvisibleReasons.length == 0){
  89100. object.visible = true;
  89101. //mapChange()
  89102. object.dispatchEvent({
  89103. type: 'isVisible',
  89104. visible:true,
  89105. reason
  89106. })
  89107. }
  89108. }
  89109. }else{
  89110. var index = object.forceVisibleReasons.indexOf(reason)
  89111. if(index > -1){//如果是forceVisibleReasons里的,就只是单纯取消之前设置的一定可见
  89112. object.forceVisibleReasons.splice(index, 1);
  89113. }else{
  89114. if(!object.unvisibleReasons.includes(reason)) object.unvisibleReasons.push(reason)
  89115. }
  89116. if(object.forceVisibleReasons.length) return
  89117. var visiBefore = object.visible
  89118. if(object.unvisibleReasons.length && visiBefore){
  89119. object.visible = false
  89120. //mapChange()
  89121. object.dispatchEvent({
  89122. type: 'isVisible',
  89123. visible:false,
  89124. reason,
  89125. })
  89126. }else if(object.unvisibleReasons.length ==0 && !visiBefore){
  89127. object.visible = true;
  89128. //mapChange()
  89129. object.dispatchEvent({
  89130. type: 'isVisible',
  89131. visible:true,
  89132. reason
  89133. })
  89134. }
  89135. }
  89136. } */
  89137. updateVisible(object, reason, ifShow, level=0, type){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  89138. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  89139. if(!object.visibleReasons) object.visibleReasons = []; //在同级时,优先可见
  89140. var update = function(){
  89141. //先按从高到低的level排列
  89142. object.unvisibleReasons = object.unvisibleReasons.sort((a,b)=>b.level-a.level);
  89143. object.visibleReasons = object.visibleReasons.sort((a,b)=>b.level-a.level);
  89144. var maxVisiLevel = object.visibleReasons[0] ? object.visibleReasons[0].level : -1;
  89145. var maxunVisiLevel = object.unvisibleReasons[0] ? object.unvisibleReasons[0].level : -1;
  89146. var shouldVisi = maxVisiLevel >= maxunVisiLevel;
  89147. var visiBefore = object.visible;
  89148. if(visiBefore != shouldVisi){
  89149. object.visible = shouldVisi;
  89150. object.dispatchEvent({
  89151. type: 'isVisible',
  89152. visible: shouldVisi,
  89153. reason,
  89154. });
  89155. }
  89156. };
  89157. if(ifShow){
  89158. var index = object.unvisibleReasons.findIndex(e=>e.reason == reason);
  89159. if(index > -1){
  89160. type = 'cancel';
  89161. object.unvisibleReasons.splice(index, 1);
  89162. }
  89163. if(type == 'add' ){
  89164. if(!object.visibleReasons.some(e=>e.reason == reason)){
  89165. object.visibleReasons.push({reason,level});
  89166. }
  89167. }
  89168. }else {
  89169. var index = object.visibleReasons.findIndex(e=>e.reason == reason);
  89170. if(index > -1){
  89171. type = 'cancel';
  89172. object.visibleReasons.splice(index, 1);
  89173. }
  89174. if(type != 'cancel' ){
  89175. if(!object.unvisibleReasons.some(e=>e.reason == reason)){
  89176. object.unvisibleReasons.push({reason,level});
  89177. }
  89178. }
  89179. }
  89180. update();
  89181. }
  89182. getObjVisiByReason(object,reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  89183. if(object.visible)return true
  89184. else {
  89185. return !object.unvisibleReasons || !object.unvisibleReasons.some(e=>e.reason == reason)
  89186. }
  89187. }
  89188. /* 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  89189. https://blog.csdn.net/weixin_30378311/article/details/94846947 */
  89190. render(params={}){//add params
  89191. if(Potree.measureTimings) performance.mark("render-start");
  89192. if(this.outlinePass.selectedObjects.length && this.outlinePass.edgeStrength > 0 && !params.screenshot){
  89193. this.composer.render(this.inputHandler.interactiveScenes.concat(this.scene.scene).concat(viewer.scene.scenePointCloud), null, this.viewports, this.renderDefault.bind(this));
  89194. }else {
  89195. this.renderDefault(params);
  89196. }
  89197. if(Potree.measureTimings){
  89198. performance.mark("render-end");
  89199. performance.measure("render", "render-start", "render-end");
  89200. }
  89201. }
  89202. startScreenshot(info={}, width=800, height=400, compressRatio){//add
  89203. let deferred = info.deferred || $.Deferred();
  89204. let viewerMaster = info.map ? this.mapViewer : this; //截图主体
  89205. let useMap = info.type == 'measure' || info.map;
  89206. if(this.images360.flying){//如果在飞,飞完再截图
  89207. info.deferred = deferred;
  89208. let f = ()=>{
  89209. this.startScreenshot(info, width, height, compressRatio);
  89210. this.images360.removeEventListener('cameraMoveDone', f);
  89211. };
  89212. this.images360.addEventListener('cameraMoveDone', f); //once
  89213. return deferred.promise()
  89214. }
  89215. var sid = Date.now();
  89216. //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小
  89217. console.log('startScreenshot: '+sid);
  89218. let updateCamera = ()=>{
  89219. this.viewports.forEach(e=>{
  89220. e.view.applyToCamera(e.camera); //因为fly时只更新了view所以要强制更新下camera
  89221. this.dispatchEvent({ //update map and sprite
  89222. type: "camera_changed",
  89223. camera: e.camera,
  89224. viewport : e,
  89225. changeInfo:{positionChanged:true,changed:true}
  89226. });
  89227. });
  89228. };
  89229. let screenshot = ()=>{
  89230. useMap && (viewer.mapViewer.needRender = true);
  89231. let { dataUrl } = viewerMaster.makeScreenshot( new Vector2$1(width,height), null, compressRatio );
  89232. if(!Potree.settings.isOfficial){
  89233. Common.downloadFile(dataUrl, 'screenshot.jpg');
  89234. }
  89235. var finish = ()=>{
  89236. oldStates.viewports.forEach(old=>{//恢复相机
  89237. var viewport = viewports.find(v=>v.name == old.name);
  89238. viewport.left = old.left;
  89239. viewport.width = old.width;
  89240. viewport.view.copy(old.view);
  89241. viewport.view.applyToCamera(viewport.camera);
  89242. });
  89243. viewer.updateScreenSize({forceUpdateSize:true});//更新像素
  89244. /* oldStates.viewports.forEach(old=>{//恢复相机
  89245. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  89246. this.dispatchEvent({ //update map
  89247. type: "camera_changed",
  89248. camera: viewport.camera,
  89249. viewport : viewport
  89250. })
  89251. }) */
  89252. updateCamera();
  89253. deferred.resolve(dataUrl);
  89254. console.log('screenshot done: '+sid);
  89255. };
  89256. {//恢复:
  89257. if(info.type == 'measure'){
  89258. this.scene.measurements.forEach(e=>this.updateVisible(e, 'screenshot',true));
  89259. info.measurement.setSelected(false, 'screenshot');
  89260. }
  89261. this.images360.panos.forEach(pano=>{
  89262. viewer.updateVisible(pano, 'screenshot', true);
  89263. });
  89264. viewer.updateVisible(this.reticule, 'screenshot', true);
  89265. if(useMap){
  89266. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', true);
  89267. if(oldStates.attachedToViewer != this.mapViewer.attachedToViewer){
  89268. if(info.type == 'measure'){
  89269. this.mapViewer.attachToMainViewer(false );
  89270. }
  89271. }
  89272. mapViewport.camera.zoom = oldStates.mapZoom;
  89273. mapViewport.camera.updateProjectionMatrix();
  89274. }
  89275. if(Potree.settings.displayMode == 'showPanos') {
  89276. viewer.images360.flyToPano({pano:oldStates.pano, duration:0, callback:()=>{
  89277. finish();
  89278. }});
  89279. }else {
  89280. finish();
  89281. }
  89282. }
  89283. };// screenshot end
  89284. let mapViewport;
  89285. let mainViewport = this.mainViewport;
  89286. let viewports = [mainViewport];
  89287. let oldStates = {
  89288. viewports : [mainViewport.clone()],
  89289. pano: Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : null,
  89290. };
  89291. if(useMap){
  89292. mapViewport = this.mapViewer.viewports[0];
  89293. viewports.push(mapViewport);
  89294. oldStates.viewports.push(mapViewport.clone());
  89295. oldStates.attachedToViewer = this.mapViewer.attachedToViewer;
  89296. oldStates.mapZoom = mapViewport.camera.zoom;
  89297. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', false);//令mapCursor不可见
  89298. }
  89299. if(info.hideMarkers){
  89300. this.images360.panos.forEach(pano=>{//令漫游点不可见
  89301. viewer.updateVisible(pano, 'screenshot', false);
  89302. });
  89303. }
  89304. viewer.updateVisible(this.reticule, 'screenshot', false);//令reticule不可见
  89305. if(info.type == 'measure'){//要截图双屏
  89306. this.scene.measurements.forEach(e=>this.updateVisible(e,'screenshot',e == info.measurement) );
  89307. info.measurement.setSelected(true, 'screenshot');
  89308. //因为分屏后位置才最终确定,才能确定是否显示出floorplan所以先分屏
  89309. if(Potree.settings.floorplanEnable){
  89310. this.mapViewer.attachToMainViewer(true, 'measure', 0.5 );
  89311. }
  89312. viewer.updateScreenSize({forceUpdateSize:true, width, height}); //更新viewports相机透视 使focusOnObject在此窗口大小下
  89313. let begin = ()=>{
  89314. useMap = this.mapViewer.attachedToViewer;
  89315. updateCamera();
  89316. let waitTime = Potree.settings.displayMode == 'showPointCloud' ? 500 : 0; //等点云加载 网速差的话还是加载稀疏 是否要用最高质量点云
  89317. if(useMap){
  89318. let waitMap = ()=>{
  89319. //console.log('waitMap: '+sid)
  89320. this.mapViewer.waitLoadDone(screenshot.bind(this));//等待地图所有加载完
  89321. };
  89322. setTimeout(waitMap.bind(this), waitTime);
  89323. }else {
  89324. setTimeout(screenshot.bind(this), waitTime);
  89325. }
  89326. };
  89327. let {promise}= this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024} );//注意:不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的
  89328. promise.done(()=>{
  89329. //console.log('promise.done')
  89330. //根据当前位置更新floorplan显示
  89331. //console.log('view Pos ', this.mainViewport.view.position.toArray())
  89332. this.updateDatasetAt(true);
  89333. this.modules.SiteModel.updateEntityAt(true);
  89334. //this.updateFpVisiDatasets()
  89335. //console.log('currentFloor', this.modules.SiteModel.currentFloor, 'currentDataset', this.atDatasets )
  89336. let floorplanShowed = this.mapViewer.mapLayer.maps.some(e => e.name.includes('floorplan') && e.objectGroup.visible);
  89337. if(!floorplanShowed && this.mapViewer.attachedToViewer){
  89338. this.mapViewer.attachToMainViewer(false); //取消分屏
  89339. viewer.updateScreenSize({forceUpdateSize:true, width, height}); //更新viewports相机透视
  89340. let {promise} = this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024} );//因画面比例更改,重新focus
  89341. promise.done(()=>{
  89342. begin();
  89343. });
  89344. }else {
  89345. begin();
  89346. }
  89347. });
  89348. }else {
  89349. screenshot();
  89350. }
  89351. /*
  89352. 测量线的截图因为要调用分屏的,会改变画面
  89353. 但是普通截图的话,不会改变画面
  89354. */
  89355. return deferred.promise()
  89356. }
  89357. focusOnObject(object, type, duration, o={} ) {
  89358. //飞向热点、测量线等 。
  89359. //console.log('focusOnObject: ', object, type)
  89360. let deferred = o.deferred || $.Deferred();
  89361. let target = new Vector3, //相机focus的位置
  89362. position = new Vector3, //相机最终位置
  89363. dis; //相机距离目标
  89364. duration = duration == void 0 ? 1000 : duration;
  89365. let camera = viewer.scene.getActiveCamera();
  89366. let cameraPos = camera.position.clone();
  89367. let getPosWithFullBound = (points, boundingBox, target, cameraPos )=>{//使boundingBox差不多占满屏幕时的相机到target的距离
  89368. // points 和 boundingBox 至少有一个
  89369. let scale;
  89370. if(o.dontChangeCamDir){
  89371. var inv = camera.matrixWorldInverse;
  89372. }else {
  89373. var cameraTemp = camera.clone();
  89374. cameraTemp.position.copy(cameraPos);
  89375. cameraTemp.lookAt(target);
  89376. cameraTemp.updateMatrix();
  89377. cameraTemp.updateMatrixWorld();
  89378. //对镜头的bound
  89379. var inv = cameraTemp.matrixWorldInverse;
  89380. }
  89381. var bound = new Box3();
  89382. if(points){//使用points得到的bound更小 //如果points和boundingbox的差别较大,尤其使target和points中心不一致,那么points不一定会刚好在boundingbox内
  89383. points.forEach(e=>{
  89384. var p = e.clone().applyMatrix4(inv);
  89385. bound.expandByPoint(p);
  89386. });
  89387. scale = 1.3;
  89388. }else {
  89389. bound = boundingBox.applyMatrix4(inv);
  89390. scale = 0.9;
  89391. }
  89392. let boundSize = bound.getSize(new Vector3);
  89393. {
  89394. boundSize.x *= scale; //稍微放大一些,不然会靠到屏幕边缘
  89395. boundSize.y *= scale;
  89396. let min = 0.0001;
  89397. boundSize.x = Math.max(min, boundSize.x);
  89398. boundSize.y = Math.max(min, boundSize.y);
  89399. }
  89400. let aspect = boundSize.x / boundSize.y;
  89401. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  89402. dis = boundSize.y/2/ Math.tan(MathUtils.degToRad(camera.fov / 2)) + boundSize.z/2;
  89403. }else {
  89404. let hfov = cameraLight.getHFOVForCamera(camera, true);
  89405. dis = boundSize.x/2 / Math.tan(hfov / 2) + boundSize.z/2;
  89406. }
  89407. dis = Math.max(0.1,dis);
  89408. //三个顶点以上的由于measure的中心不等于bound的中心,所以点会超出bound外。 且由于视椎近大远小,即使是两个点的,bound居中后线看上去仍旧不居中.
  89409. //获得相机最佳位置
  89410. let dir;
  89411. if(o.dontChangeCamDir){
  89412. dir = viewer.mainViewport.view.direction.negate();
  89413. }else {
  89414. dir = new Vector3().subVectors(cameraPos, target).normalize();
  89415. }
  89416. if(o.dontLookUp && dir.z < 0){
  89417. dir.negate();
  89418. }
  89419. position.copy(target).add(dir.multiplyScalar(dis));
  89420. if(false){//打开以检查box
  89421. if(!this.boundBox){//调试
  89422. this.boundBox = new Mesh(new BoxGeometry(1,1,1,1));
  89423. this.boundBox.material.wireframe = true;
  89424. this.boundBox.up.set(0,0,1);
  89425. //viewer.updateVisible(this.boundBox, 'hidden', true)//打开以检查box
  89426. this.setObjectLayers(this.boundBox,'sceneObjects');
  89427. this.scene.scene.add(this.boundBox);
  89428. }
  89429. this.boundBox.position.copy(target);
  89430. this.boundBox.scale.copy(boundSize);
  89431. this.boundBox.lookAt(position);
  89432. }
  89433. return position
  89434. };
  89435. if(this.images360.flying){
  89436. let f = ()=>{
  89437. this.focusOnObject(object, type, duration, $.extend(o,{deferred}));
  89438. this.images360.removeEventListener('cameraMoveDone',f);
  89439. };
  89440. this.images360.addEventListener('cameraMoveDone',f);
  89441. return {promise: deferred.promise() }
  89442. }
  89443. if (type == 'measure') {
  89444. target.copy(object.getCenter());
  89445. //试试改变位置,直视测量线。能避免倾斜角度造成的非常不居中、以及看不到面的情况
  89446. if(object.facePlane/* && window.focusMeasureFaceToIt */){
  89447. let normal;
  89448. if(object.facePlane){
  89449. normal = object.facePlane.normal.clone();
  89450. }
  89451. let angle = this.scene.view.direction.angleTo(normal);
  89452. let minDiff = MathUtils.degToRad(60);
  89453. //console.log('angle',angle)
  89454. if(angle>minDiff && angle<Math.PI-minDiff){//当几乎正对时就不执行
  89455. if(angle<Math.PI/2){ //在背面
  89456. normal.negate();
  89457. }
  89458. let dir = new Vector3().subVectors(camera.position, target).normalize();
  89459. let newDir = new Vector3().addVectors(dir,normal);//两个角度的中间
  89460. cameraPos.copy(target.clone().add(newDir));
  89461. }
  89462. }else if(object.points.length == 2){ //线段
  89463. let lineDir = new Vector3().subVectors(object.points[0],object.points[1]).normalize();
  89464. let angle = this.scene.view.direction.angleTo(lineDir);
  89465. let maxDiff = Math.PI*0.25;// 45度
  89466. if(angle<maxDiff || angle>Math.PI-maxDiff){//当几乎正对时就不执行
  89467. if(angle>Math.PI/2){ //令dir和lineDir成钝角
  89468. lineDir.negate();
  89469. }
  89470. let dir = new Vector3().subVectors(camera.position, target).normalize();
  89471. let mid = new Vector3().addVectors(lineDir, dir).normalize(); //中间法向量(如果刚好dir和lineDir反向,那得到的为零向量,就不移动了,但一般不会酱紫吧)
  89472. let newDir = new Vector3().addVectors(dir, mid);
  89473. cameraPos.copy(target.clone().add(newDir));
  89474. }
  89475. }else {
  89476. console.error('measure 没有facePlane points点数还不为2?');
  89477. }
  89478. position = getPosWithFullBound(object.points, null, target, cameraPos );
  89479. if(this.mapViewer/* .attachedToViewer */){
  89480. //console.log('mapFocusOn: '+target.toArray())
  89481. const minBound = new Vector2$1(4,4);//针对垂直线,在地图上只有一个点
  89482. //原始的bound
  89483. let boundOri = new Box3();
  89484. object.points.forEach(e=>{
  89485. boundOri.expandByPoint(e);
  89486. });
  89487. let boundSizeOri = boundOri.getSize(new Vector3);
  89488. let boundSizeMap = boundSizeOri.clone().multiplyScalar(2);
  89489. boundSizeMap.x = Math.max(minBound.x, boundSizeMap.x );
  89490. boundSizeMap.y = Math.max(minBound.y, boundSizeMap.y );
  89491. this.mapViewer.moveTo(target.clone(), boundSizeMap, duration);
  89492. }
  89493. if(Potree.settings.displayMode == 'showPointCloud'){ //点云
  89494. let minDis = 0.3;
  89495. //if(o.checkIntersect){
  89496. let checkIntersect = ( )=>{
  89497. let intersect = this.inputHandler.ifBlockedByIntersect(position, null , true, target);// 不一定准确
  89498. if(intersect){
  89499. let blockCount = 0, unblockCount = 0, visi;
  89500. for(let i=0;i<object.points.length;i++){ //如果顶点超过一半不可见,就要更改位置
  89501. let p = object.points[i];
  89502. let blocked = this.inputHandler.ifBlockedByIntersect(p, 0.3 , true, position, 4);
  89503. if(blocked){
  89504. blockCount ++;
  89505. if(blockCount / object.points.length >= 0.5){
  89506. visi = false;
  89507. break
  89508. }
  89509. }else {
  89510. unblockCount ++;
  89511. if(unblockCount / object.points.length > 0.5){
  89512. visi = true;
  89513. break
  89514. }
  89515. }
  89516. }
  89517. if(visi == void 0){
  89518. visi = unblockCount / object.points.length > 0.5;
  89519. }
  89520. let shrink = ()=>{
  89521. let dir = new Vector3().subVectors(position, target).normalize().multiplyScalar(intersect.distance);
  89522. position.copy(target).add(dir);
  89523. console.log('checkIntersect newPos', position.clone() );
  89524. };
  89525. if(!visi){//更改位置距离target如果小于最小距离,需要反向。 否则直接缩短距离。
  89526. if(intersect.distance < minDis ){
  89527. console.log('检测到intersect 反向', intersect.distance );
  89528. let position1 = position.clone();
  89529. let dir = new Vector3().subVectors(position, target);
  89530. position.copy(target).sub(dir);
  89531. let intersect2 = this.inputHandler.ifBlockedByIntersect(position, null , true, target);// 不一定准确
  89532. if(intersect2){
  89533. if(intersect2.distance < intersect.distance ){
  89534. position.copy(position1);//恢复
  89535. }
  89536. shrink();
  89537. }
  89538. }else {
  89539. shrink();
  89540. }
  89541. }
  89542. }
  89543. };
  89544. checkIntersect();
  89545. //}
  89546. }else if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  89547. let pano = viewer.images360.fitPanoTowardPoint({
  89548. /*point : target, //不使用目标点来判断是因为缺少measure角度的信息。比如虽然可以靠近线的中心,但是线朝向屏幕,那几乎就是一个点了。
  89549. //bestDistance : dis * 0.5, //乘以小数是为了尽量靠近
  89550. boundSphere: boundOri.getBoundingSphere(new THREE.Sphere), */
  89551. target,
  89552. point : position,
  89553. bestDistance : 0 ,
  89554. checkIntersect: o.checkIntersect
  89555. });
  89556. if(pano){
  89557. viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  89558. }
  89559. if(viewer.images360.currentPano == pano){
  89560. let dis1 = viewer.images360.currentPano.position.distanceTo(target);
  89561. let dis2 = position.distanceTo(target);
  89562. console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2);
  89563. return {mag: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() }
  89564. }else {
  89565. return {promise : deferred.promise()}
  89566. }
  89567. //出现过到达位置后测量线标签闪烁的情况
  89568. }
  89569. } else if (type == 'tag' || type == 'point') {
  89570. //dimension = 1
  89571. target.copy(object.position);
  89572. let bestDistance = o.distance || 3;
  89573. if(!o.dontMoveMap && this.mapViewer){
  89574. //console.log('mapFocusOn: '+target.toArray())
  89575. this.mapViewer.moveTo(target.clone(), null, duration);
  89576. }
  89577. if(Potree.settings.displayMode == 'showPointCloud'){
  89578. if(o.dontChangePos){
  89579. position.copy(cameraPos);
  89580. }else {
  89581. dis = bestDistance;
  89582. let dir = o.direction ? o.direction.clone().negate() : this.mainViewport.view.direction.negate();// */new THREE.Vector3().subVectors(camera.position, target).normalize()
  89583. if(o.dontLookUp && dir.z<0) dir.z *= -1;
  89584. position.copy(target).add(dir.multiplyScalar(dis));
  89585. }
  89586. /* if(o.checkIntersect){//识别被点云遮住的话
  89587. let ifShelter
  89588. while(1){
  89589. ifShelter = this.inputHandler.ifBlockedByIntersect(target, o.checkMargin, true, position)
  89590. if(ifShelter){
  89591. if(dis > 0.5){
  89592. dis --
  89593. dir.dot(ifShelter.normal)>0 ? dir.copy(ifShelter.normal).negate() : dir.copy(ifShelter.normal);
  89594. position.copy(target).add(dir.multiplyScalar(dis))
  89595. }
  89596. }
  89597. }
  89598. } */
  89599. }else if(Potree.settings.displayMode == 'showPanos'){
  89600. let pano = viewer.images360.fitPanoTowardPoint({
  89601. point : target,
  89602. bestDistance //越近越好,但不要太近,bestDistance左右差不多
  89603. });
  89604. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize });
  89605. return {promise:deferred.promise() }
  89606. }
  89607. }else if(object.boundingBox && type == 'boundingBox'){//使屏幕刚好看全boundingBox
  89608. target = object.boundingBox.getCenter(new Vector3);
  89609. position = getPosWithFullBound(object.points, object.boundingBox, target, cameraPos );
  89610. if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  89611. let pano = viewer.images360.fitPanoTowardPoint({
  89612. point : position,
  89613. bestDistance : 0 ,
  89614. });
  89615. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  89616. if(!pano){
  89617. console.error('no pano');
  89618. }
  89619. return {promise:deferred.promise() }
  89620. //出现过到达位置后测量线标签闪烁的情况
  89621. }else {
  89622. /* if(o.dontChangeCamDir){
  89623. target = null
  89624. } */
  89625. }
  89626. }
  89627. /*} else if(dimension == 2){//线
  89628. }else if(dimension == 3){//面
  89629. }else{//立体
  89630. } */
  89631. viewer.scene.view.setView({position, target, duration, callback:()=>{
  89632. //console.log('focusOnObjectSuccess: '+object.name, type)
  89633. deferred.resolve();
  89634. }
  89635. });
  89636. this.dispatchEvent({type:'focusOnObject', CamTarget:target, position}); //给controls发送信息
  89637. return {promise:deferred.promise()}
  89638. }
  89639. flyToDataset(o={}){
  89640. var pointcloud;
  89641. if(o instanceof Object3D) pointcloud = o;
  89642. else if(o.pointcloud) pointcloud = o.pointcloud;
  89643. else pointcloud = this.scene.pointclouds.find(p => p.dataset_id == o.id);
  89644. let duration = o.duration == void 0 ? 1000 : o.duration;
  89645. var center = pointcloud.bound.getCenter(new Vector3);
  89646. let position;
  89647. let getPano = ()=>{//获取离中心最近的pano
  89648. let request = [];
  89649. let rank = [
  89650. Images360.scoreFunctions.distanceSquared({position: center})
  89651. ];
  89652. let r = Common.sortByScore(pointcloud.panos, request, rank);
  89653. if(r && r.length){
  89654. return r[0].item
  89655. }
  89656. };
  89657. if(Potree.settings.displayMode == 'showPanos'){
  89658. let pano = getPano();
  89659. if(pano){
  89660. if(pano == this.images360.currentPano) return 'posNoChange'
  89661. this.images360.flyToPano({
  89662. pano
  89663. });
  89664. }else return false
  89665. }else {
  89666. let target;
  89667. position = center;
  89668. if(pointcloud.panosBound){
  89669. let panosCenter = pointcloud.panosBound.center; //pano集中的地方,也就是真正有点云的地方
  89670. position = panosCenter.clone();
  89671. /* let ratio = 0.2
  89672. position.z = center.z * ratio + panosCenter.z * (1-ratio) //因为panos一般比较低,为了不让相机朝下时看不到点云,加一丢丢中心高度
  89673. */
  89674. let pano = getPano();
  89675. if(pano){
  89676. target = pano.position; //针对像隧道一样的场景, 中心点还是panosCenter都在没有点云的地方,所以还是看向其中一个漫游点好。
  89677. position.z = target.z; //水平, 避免朝上或朝下
  89678. }
  89679. }
  89680. if(this.modules.Clip.editing){
  89681. position.z = center.z; //剪裁时在中心高度,因为以点云为重点
  89682. this.modules.Clip.bus.dispatchEvent({type:'flyToPos', position });
  89683. }else {
  89684. if(math.closeTo(position, this.images360.position)) return 'posNoChange'
  89685. viewer.scene.view.setView({position, target, duration });
  89686. o.dontMoveMap || viewer.mapViewer.moveTo(position.clone(), null , duration);
  89687. }
  89688. }
  89689. return true
  89690. }
  89691. resolveTimings(timestamp){
  89692. if(Potree.measureTimings){
  89693. if(!this.toggle){
  89694. this.toggle = timestamp;
  89695. }
  89696. let duration = timestamp - this.toggle;
  89697. if(duration > 1000.0){
  89698. let measures = performance.getEntriesByType("measure");
  89699. let names = new Set();
  89700. for(let measure of measures){
  89701. names.add(measure.name);
  89702. }
  89703. let groups = new Map();
  89704. for(let name of names){
  89705. groups.set(name, {
  89706. measures: [],
  89707. sum: 0,
  89708. n: 0,
  89709. min: Infinity,
  89710. max: -Infinity
  89711. });
  89712. }
  89713. for(let measure of measures){
  89714. let group = groups.get(measure.name);
  89715. group.measures.push(measure);
  89716. group.sum += measure.duration;
  89717. group.n++;
  89718. group.min = Math.min(group.min, measure.duration);
  89719. group.max = Math.max(group.max, measure.duration);
  89720. }
  89721. let glQueries = Potree.resolveQueries(this.renderer.getContext());
  89722. for(let [key, value] of glQueries){
  89723. let group = {
  89724. measures: value.map(v => {return {duration: v}}),
  89725. sum: value.reduce( (a, i) => a + i, 0),
  89726. n: value.length,
  89727. min: Math.min(...value),
  89728. max: Math.max(...value)
  89729. };
  89730. let groupname = `[tq] ${key}`;
  89731. groups.set(groupname, group);
  89732. names.add(groupname);
  89733. }
  89734. for(let [name, group] of groups){
  89735. group.mean = group.sum / group.n;
  89736. group.measures.sort( (a, b) => a.duration - b.duration );
  89737. if(group.n === 1){
  89738. group.median = group.measures[0].duration;
  89739. }else if(group.n > 1){
  89740. group.median = group.measures[parseInt(group.n / 2)].duration;
  89741. }
  89742. }
  89743. let cn = Array.from(names).reduce( (a, i) => Math.max(a, i.length), 0) + 5;
  89744. let cmin = 10;
  89745. let cmed = 10;
  89746. let cmax = 10;
  89747. let csam = 6;
  89748. let message = ` ${"NAME".padEnd(cn)} |`
  89749. + ` ${"MIN".padStart(cmin)} |`
  89750. + ` ${"MEDIAN".padStart(cmed)} |`
  89751. + ` ${"MAX".padStart(cmax)} |`
  89752. + ` ${"SAMPLES".padStart(csam)} \n`;
  89753. message += ` ${"-".repeat(message.length) }\n`;
  89754. names = Array.from(names).sort();
  89755. for(let name of names){
  89756. let group = groups.get(name);
  89757. let min = group.min.toFixed(3);
  89758. let median = group.median.toFixed(3);
  89759. let max = group.max.toFixed(3);
  89760. let n = group.n;
  89761. message += ` ${name.padEnd(cn)} |`
  89762. + ` ${min.padStart(cmin)} |`
  89763. + ` ${median.padStart(cmed)} |`
  89764. + ` ${max.padStart(cmax)} |`
  89765. + ` ${n.toString().padStart(csam)}\n`;
  89766. }
  89767. message += `\n`;
  89768. console.log(message);
  89769. performance.clearMarks();
  89770. performance.clearMeasures();
  89771. this.toggle = timestamp;
  89772. }
  89773. }
  89774. }
  89775. loop(timestamp){
  89776. if(this.stats){
  89777. this.stats.begin();
  89778. }
  89779. if(Potree.measureTimings){
  89780. performance.mark("loop-start");
  89781. }
  89782. this.update(this.clock.getDelta(), timestamp);
  89783. this.magnifier.render();
  89784. this.render();
  89785. // let vrActive = viewer.renderer.xr.isPresenting;
  89786. // if(vrActive){
  89787. // this.update(this.clock.getDelta(), timestamp);
  89788. // this.render();
  89789. // }else{
  89790. // this.update(this.clock.getDelta(), timestamp);
  89791. // this.render();
  89792. // }
  89793. if(Potree.measureTimings){
  89794. performance.mark("loop-end");
  89795. performance.measure("loop", "loop-start", "loop-end");
  89796. }
  89797. this.resolveTimings(timestamp);
  89798. Potree.framenumber++;
  89799. if(this.stats){
  89800. this.stats.end();
  89801. }
  89802. }
  89803. postError(content, params = {}){
  89804. let message = this.postMessage(content, params);
  89805. message.element.addClass("potree_message_error");
  89806. return message;
  89807. }
  89808. postMessage(content, params = {}){
  89809. let message = new Message(content);
  89810. let animationDuration = 100;
  89811. message.element.css("display", "none");
  89812. message.elClose.click( () => {
  89813. message.element.slideToggle(animationDuration);
  89814. let index = this.messages.indexOf(message);
  89815. if(index >= 0){
  89816. this.messages.splice(index, 1);
  89817. }
  89818. });
  89819. this.elMessages.prepend(message.element);
  89820. message.element.slideToggle(animationDuration);
  89821. this.messages.push(message);
  89822. if(params.duration !== undefined){
  89823. let fadeDuration = 500;
  89824. let slideOutDuration = 200;
  89825. setTimeout(() => {
  89826. message.element.animate({
  89827. opacity: 0
  89828. }, fadeDuration);
  89829. message.element.slideToggle(slideOutDuration);
  89830. }, params.duration);
  89831. }
  89832. return message;
  89833. }
  89834. getBoundingBox (pointclouds) {
  89835. //可以直接返回viewer.bound
  89836. if(!this.bound){
  89837. this.updateModelBound();
  89838. }
  89839. return this.bound.boundingBox.clone()//this.scene.getBoundingBox(pointclouds);
  89840. };
  89841. updateModelBound(){
  89842. this.bound = Utils.computePointcloudsBound(this.scene.pointclouds);
  89843. if(Potree.settings.boundAddObjs){//加上obj的bound
  89844. this.objs.children.forEach(e=>{
  89845. this.bound.boundingBox.union(e.boundingBox.clone().applyMatrix4(e.matrixWorld));
  89846. });
  89847. this.bound.boundingBox.getSize(this.bound.boundSize);
  89848. this.bound.boundingBox.getCenter(this.bound.center);
  89849. }
  89850. viewer.farWhenShowPano = this.bound.boundSize.length() * 10;//全景漫游时要能看到整个skybox 原本*2的但对于距离特远的数据集需要乘大一些否则会黑面
  89851. let boundPlane = new Box3();
  89852. boundPlane.expandByPoint(this.bound.boundingBox.min.clone());//最低高度为bound的最低
  89853. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z));//最高高度为bound的中心高度
  89854. FirstPersonControls.boundPlane = boundPlane;
  89855. FirstPersonControls.standardSpeed = MathUtils.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  89856. viewer.scene.pointclouds.forEach(e=>{//海拔范围
  89857. e.material.heightMin = this.bound.boundingBox.min.z;
  89858. e.material.heightMax = this.bound.boundingBox.max.z;
  89859. });
  89860. this.dispatchEvent({type:'updateModelBound'});
  89861. }
  89862. waitForLoad(object, isLoadedCallback){//等待加载时显示loading。主要是贴图
  89863. this.waitQueue.push({
  89864. object,
  89865. isLoadedCallback,
  89866. });
  89867. 1 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:true});
  89868. }
  89869. ifAllLoaded(object){
  89870. if(this.waitQueue.length>0){
  89871. this.waitQueue = this.waitQueue.filter(function(e) {
  89872. return !e.isLoadedCallback()
  89873. });
  89874. }
  89875. 0 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:false});
  89876. }
  89877. setView(o={}){
  89878. let callback = ()=>{
  89879. if(o.displayMode){
  89880. Potree.settings.displayMode = o.displayMode;
  89881. }
  89882. o.callback && o.callback();
  89883. };
  89884. if(o.pano != void 0){//pano 权重高于 position
  89885. this.images360.flyToPano(o);
  89886. }else {
  89887. this.scene.view.setView($.extend({},o, {callback}));
  89888. }
  89889. }
  89890. //设置点云为标准模式
  89891. setPointStandardMat(state, pointDensity, fitPointsize){
  89892. console.log('setPointStandardMat',state);
  89893. if(state){
  89894. if(this.pointStatesBefore){
  89895. return console.error('已设置过pointStatesBefore!')
  89896. }
  89897. this.pointStatesBefore = {
  89898. opacity : new Map(),
  89899. size: new Map(),
  89900. density:Potree.settings.pointDensity,
  89901. useEDL:this.getEDLEnabled(),
  89902. shape: viewer.scene.pointclouds[0].material.shape
  89903. };
  89904. viewer.scene.pointclouds.forEach(e=>{
  89905. this.pointStatesBefore.opacity.set(e, e.temp.pointOpacity); //因为更改pointDensity时会自动变opacity,所以这项最先获取
  89906. this.pointStatesBefore.colorType = e.material.activeAttributeName;
  89907. fitPointsize && this.pointStatesBefore.size.set(e,e.temp.pointSize); //这项不一定有用,因为会被后期覆盖
  89908. });
  89909. if(pointDensity)Potree.settings.pointDensity = pointDensity; //万一之后切换到全景模式怎么办
  89910. if(fitPointsize)Potree.settings.sizeFitToLevel = true;
  89911. viewer.scene.pointclouds.forEach(e=>{
  89912. e.material.activeAttributeName = 'rgba';
  89913. e.material.shape = Potree.PointShape['SQUARE'];
  89914. fitPointsize && e.changePointSize(Potree.config.material.realPointSize, true);
  89915. e.changePointOpacity(1);
  89916. });
  89917. viewer.setEDLEnabled(false);
  89918. }else {
  89919. if(!this.pointStatesBefore){
  89920. return console.error('未设置过pointStatesBefore!')
  89921. }
  89922. Potree.settings.sizeFitToLevel = false;
  89923. if(pointDensity)Potree.settings.pointDensity = this.pointStatesBefore.pointDensity;
  89924. viewer.scene.pointclouds.forEach(e=>{
  89925. e.material.activeAttributeName = this.pointStatesBefore.colorType;
  89926. e.changePointOpacity(this.pointStatesBefore.opacity.get(e));
  89927. e.material.shape = this.pointStatesBefore.shape;
  89928. let size = this.pointStatesBefore.size.get(e);
  89929. if(size) e.changePointSize(size);
  89930. });
  89931. viewer.setEDLEnabled(this.pointStatesBefore.useEDL);
  89932. this.pointStatesBefore = null;
  89933. }
  89934. }
  89935. //调试时显示transformControl来调节object
  89936. transformObject(object){
  89937. let seleted = viewer.inputHandler.selection[0];
  89938. if(!object){//取消
  89939. seleted && viewer.inputHandler.toggleSelection(seleted);
  89940. return
  89941. }
  89942. if(seleted && seleted != object){//要更换,先取消
  89943. return this.transformObject(null)
  89944. }
  89945. if(!object.boundingBox){
  89946. object.boundingBox = new Box3(); //任意大小 只是为了显示黄色外框
  89947. //??? computeBoundingBox
  89948. }
  89949. if(!viewer.inputHandler.selection.includes(object)){
  89950. viewer.inputHandler.toggleSelection(object);
  89951. }
  89952. }
  89953. pointInWhichPointcloud(pos){//选择最接近中心的那个 使用boundSphere
  89954. let result = Common.sortByScore(this.scene.pointclouds,[],[
  89955. (pointcloud)=>{
  89956. var size = pointcloud.pcoGeometry.tightBoundingBox.getSize(new Vector3);
  89957. var center = pointcloud.bound.getCenter(new Vector3);
  89958. var length = size.length() / 2;
  89959. var dis = pos.distanceTo(center);
  89960. return length / dis //到数据集中心的距离占数据集大小越小越好
  89961. }
  89962. ]);
  89963. //若要求更准确的话,可以使用ifContainsPoint判断一下是否在bound中
  89964. let r = result && result[0];
  89965. return r.score > 1 ? result[0].item : null
  89966. }
  89967. /* addObjectTest1(){//加水管
  89968. if(Potree.settings.number == 't-8KbK1JjubE'){
  89969. let boundingBox = new THREE.Box3()
  89970. boundingBox.min.set(-1,-1,-1); boundingBox.max.set(1,1,1)
  89971. let radius = 0.08;
  89972. let radialSegments = 5
  89973. let radSegments = Math.PI*2 / radialSegments
  89974. var circlePts = [];//横截面
  89975. for(let i=0;i<radialSegments;i++){
  89976. let angle = radSegments * i;
  89977. circlePts.push(new THREE.Vector2(radius * Math.cos(angle), radius * Math.sin(angle) ))
  89978. }
  89979. var count = 0
  89980. var addMesh = (color, path, height)=>{//height:在path之上的高度,负数代表在path之下
  89981. var name = 'cylinder'+count
  89982. var mat = new THREE.MeshStandardMaterial({color, depthTest:false, roughness:0.4,metalness:0.5}) 
  89983. let linePath = path.map(e=>new THREE.Vector3().copy(e).setZ(e.z+height))
  89984. let geo = MeshDraw.getExtrudeGeo( circlePts, null,{ extrudePath:linePath, tension:0.2} )
  89985. var mesh = new THREE.Mesh(geo,mat);
  89986. mesh.name = name
  89987. window[name] = mesh
  89988. mesh.boundingBox = boundingBox
  89989. mesh.matrixAutoUpdate = false
  89990. mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix)
  89991. mesh.matrixWorldNeedsUpdate = true
  89992. this.scene.scene.add(mesh);
  89993. count ++
  89994. }
  89995. let linePath, height
  89996. //地上管子 黄色
  89997. 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}
  89998. ,{"x":43.58,"y":27.7,"z":-0.97},{"x":40.22,"y":35.37,"z":-0.67}// 拐弯向右
  89999. , {"x":39.18,"y":36.71,"z":0.35},{"x":38.69,"y":36.04,"z":18.04} // 拐弯向上
  90000. ]
  90001. height = radius + 0.05;
  90002. addMesh('#b86', linePath, height)
  90003. //地下管子 藍色
  90004. 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}
  90005. ]
  90006. height = -0.5;
  90007. addMesh('#48a', linePath, height)
  90008. }
  90009. }
  90010. */
  90011. /* createRoomEv(){
  90012. const environment = new RoomEnvironment();
  90013. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  90014. }
  90015. */
  90016. loadModel(fileInfo, done, onProgress_, onError){
  90017. let boundingBox = new Box3();
  90018. if(!Potree.settings.boundAddObjs){
  90019. boundingBox.min.set(-0.5,-0.5,-0.5); boundingBox.max.set(0.5,0.5,0.5);
  90020. }
  90021. let fileType = fileInfo.objurl ? 'obj' : 'glb';
  90022. let loadDone = (object, total, url)=>{
  90023. //object.scale.set(1,1,1);//先获取原始的大小时的boundingBox
  90024. object.opacity = 1; //初始化 记录
  90025. object.updateMatrixWorld();
  90026. let weight = Math.round((total / 1024 / 1024) * 100) / 100;
  90027. if(fileInfo.id != void 0)object.dataset_id = fileInfo.id;
  90028. console.log(url.split('/').pop() ,/* fileInfo.id, */ '加载完毕, 模型数据量:' + weight + 'M');
  90029. this.setObjectLayers(object,'model');
  90030. object.traverse( ( child )=>{
  90031. if ( child instanceof Mesh ) {
  90032. child.renderOrder = Potree.config.renderOrders.model;
  90033. if(Potree.settings.boundAddObjs){
  90034. child.geometry.computeBoundingBox();
  90035. //console.log(child.matrixWorld.clone())
  90036. boundingBox.union(child.geometry.boundingBox.clone().applyMatrix4(child.matrixWorld)); //但感觉如果最外层object大小不为1,要还原下scale再乘
  90037. }//获取在scale为1时,表现出的大小
  90038. Common.makeTexDontResize(child.material.map);
  90039. //console.log(child.name, 'roughness',child.material.roughness,'metalness',child.material.metalness)
  90040. /* child.depthMat = child.material.clone()
  90041. child.standardMat = child.material
  90042. child.depthMat.onBeforeCompile = function ( shader ) {
  90043. console.log('vertexShader',shader.vertexShader)
  90044. console.log('fragmentShader',shader.fragmentShader)
  90045. shader.fragmentShader = `
  90046. ${shader.fragmentShader.replace(
  90047. 'gl_FragColor = vec4( outgoingLight, diffuseColor.a );',
  90048. 'diffuseColor.a = log(vViewPosition.z); gl_FragColor = vec4( outgoingLight, diffuseColor.a );'
  90049. )}
  90050. `;
  90051. console.log('fragmentShader1',shader.fragmentShader)
  90052. }; */
  90053. //暂时用这种材质:
  90054. if(fileInfo.unlit && (!(child.material instanceof MeshBasicMaterial) || fileType == 'glb')){
  90055. //let material = new THREE.MeshBasicMaterial({map:child.material.map})
  90056. let material = new BasicMaterial({map : child.material.map}); //很奇怪glb的图会使原本的MeshBasicMaterial 会偏暗,所以自己重新写
  90057. //child.material.dispose()
  90058. child.material = material;
  90059. }
  90060. if(child.material instanceof MeshStandardMaterial){
  90061. child.material.roughness = 0.6;
  90062. child.material.metalness = 0.3;
  90063. }
  90064. }
  90065. } );
  90066. object.name = fileInfo.name != void 0 ? fileInfo.name : 'obj';
  90067. this.objs.add(object);
  90068. object.boundingBox = boundingBox; //未乘上matrixWorld的本地boundingBox
  90069. if(fileInfo.transform){
  90070. let setTransfrom = (name)=>{
  90071. let value = fileInfo.transform[name];
  90072. if(!value)return
  90073. if(value instanceof Array){
  90074. object[name].fromArray(value);
  90075. }else {
  90076. object[name].copy(value);
  90077. }
  90078. };
  90079. setTransfrom('position');
  90080. setTransfrom('rotation');
  90081. setTransfrom('scale');
  90082. }
  90083. if(fileInfo.moveWithPointcloud){
  90084. object.updateMatrix();
  90085. object.matrixAutoUpdate = false;
  90086. object.matrix.premultiply(viewer.scene.pointclouds[0].transformMatrix); //默认跟随第一个数据集
  90087. object.matrixWorldNeedsUpdate = true;
  90088. }
  90089. done && done(object);
  90090. };
  90091. let onProgress = function ( xhr ) {
  90092. if ( xhr.lengthComputable ) {
  90093. let percentComplete = xhr.loaded / xhr.total * 100;
  90094. //console.log( Math.round(percentComplete, 2) + '% downloaded' );
  90095. onProgress_ && onProgress_(percentComplete);
  90096. }
  90097. };
  90098. if(fileType == 'obj'){
  90099. /* manager.onProgress = function ( item, loaded, total ) {
  90100. console.log( item, loaded, total );
  90101. }; */
  90102. /* let onError = function ( xhr ) {
  90103. }; */
  90104. loaders.mtlLoader.load( fileInfo.mtlurl , (materials)=>{
  90105. materials.preload();
  90106. loaders.objLoader.setMaterials( materials ).load(fileInfo.objurl, (object, total)=>{
  90107. loadDone(object, total, fileInfo.objurl);
  90108. });
  90109. } , onProgress, onError );
  90110. }else if(fileType == 'glb'){
  90111. loaders.glbLoader.unlitMat = true;//!!fileInfo.unlit
  90112. loaders.glbLoader.load(fileInfo.glburl, ( gltf, total )=>{ //.setPath( Potree.resourcePath + '/models/glb/' );
  90113. //console.log('loadGLTF', gltf)
  90114. loadDone(gltf.scene, total, fileInfo.glburl);
  90115. }, onProgress, onError);
  90116. }
  90117. /* viewer.onGUILoaded(() => {
  90118. // Add entries to object list in sidebar
  90119. let tree = $(`#jstree_scene`);
  90120. let parentNode = "other";
  90121. let bunnyID = tree.jstree('create_node', parentNode, {
  90122. text: "Bunny Textured",
  90123. icon: `${Potree.resourcePath}/icons/triangle.svg`,
  90124. data: object
  90125. },
  90126. "last", false, false);
  90127. tree.jstree(object.visible ? "check_node" : "uncheck_node", bunnyID);
  90128. //tree.jstree("open_node", parentNode);
  90129. }); */
  90130. }
  90131. removeObj(object){
  90132. this.objs.remove(object);
  90133. if(Potree.settings.boundAddObjs){
  90134. this.updateModelBound();
  90135. }
  90136. }
  90137. loadGLTF(name='87b3a367bc3e4273832cb4fa398782e5.glb'){
  90138. const loader = new GLTFLoader(undefined, this.renderer).setPath( Potree.resourcePath + '/models/glb/' );
  90139. /*
  90140. coffeemat.glb
  90141. ModernJPHouseSofa44216499.glb
  90142. ModernJPHouseSofa44105209.glb
  90143. 87ecd10fb0374ea6b3e0bf24c6459e3c.glb
  90144. 87b3a367bc3e4273832cb4fa398782e5.glb
  90145. */
  90146. loader.load(name, ( gltf )=>{
  90147. console.log('loadGLTF', gltf);
  90148. this.objs.add(gltf.scene);
  90149. });
  90150. }
  90151. addFire(){
  90152. if(Potree.settings.number == 't-CwfhfqJ'){
  90153. let position = Potree.Utils.datasetPosTransform({
  90154. pointcloud:viewer.scene.pointclouds[0],
  90155. position: new Vector3(4.4318,-0.580291847759, -0.78),
  90156. fromDataset:true
  90157. });
  90158. viewer.modules.ParticleEditor.addParticle( {
  90159. type:'fire',
  90160. positions:[position],
  90161. radius:0.42,
  90162. height:10,
  90163. });
  90164. viewer.modules.ParticleEditor.addParticle( {
  90165. type:'smoke',
  90166. positions: [ new Vector3().addVectors(position,new Vector3(0,0,0.3))],
  90167. positionStyle : 'sphere' ,
  90168. positionRadius : 0.3,
  90169. sizeTween: [[0, 0.3, 0.9, 1], [0.05, 0.1, 1, 0.8]],
  90170. opacityBase : 0.2,
  90171. opacityTween :[ [0, 0.3, 0.7, 0.95, 1], [0, 0.2, 1 , 0.1, 0] ],
  90172. velocityBase : new Vector3( 0, 0, 1),
  90173. velocitySpread : new Vector3( 0.2, 0.2, -0.3),
  90174. accelerationBase : 0.2,
  90175. accelerationSpread : 0.7,
  90176. radius:0,
  90177. //particlesPerSecond : 30,
  90178. particleDeathAge : 3.0,
  90179. });
  90180. viewer.modules.ParticleEditor.addParticle( {
  90181. type:'explode',
  90182. name:'fire splash',
  90183. position: new Vector3().addVectors(position,new Vector3(0,0,0.3)),
  90184. size: 0.1,
  90185. sizeRange: 0.3,
  90186. sizeTween:[[0, 0.05, 0.3, 0.45], [0, 0.02, 0.1, 0.05] ],
  90187. opacityTween: [[0, 0.05, 0.3, 0.45], [1, 1, 0.5, 0]] ,
  90188. speed : 1, //sphere
  90189. speedRange : 4,
  90190. radius: 0.1,
  90191. acceleration : 0.3,
  90192. accelerationRange : 1,
  90193. particleSpaceTime:0,
  90194. strength:4,
  90195. });
  90196. }
  90197. }
  90198. addVideo11(){
  90199. if(Potree.settings.number != 'SS-fckI7CClKC')return
  90200. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  90201. video.setAttribute("crossOrigin", 'Anonymous');
  90202. //video.src = Potree.resourcePath+'/video/SS-fckI7CClKC/19.mp4'
  90203. var map = new VideoTexture(video);
  90204. var plane = this.videoPlane = new Mesh(new PlaneGeometry(1, 1, 1, 1), new MeshBasicMaterial({
  90205. color:"#ffffff",
  90206. transparent: !0,
  90207. depthTest:false,
  90208. opacity:0.7,
  90209. side:2,
  90210. map
  90211. }));
  90212. plane.visible = false;
  90213. plane.geometry.computeBoundingBox();
  90214. plane.boundingBox = plane.geometry.boundingBox.clone();//.applyMatrix4()
  90215. plane.boundingBox.max.z = 1;
  90216. plane.boundingBox.max.y = -0.4;
  90217. plane.boundingBox.max.x = 1;
  90218. /* plane.position.copy(this.images360.panos[19].position);
  90219. plane.lookAt(plane.position.clone().setX(0))
  90220. 9:
  90221. viewer.videoPlane.rotation.set(-1.432978005954197, 1.2296264545169697, 3.0098547630197667)
  90222. viewer.videoPlane.position.set( 6.532456676287381, -9.806373049095631, -0.024205281024294284)
  90223. //viewer.transformObject(viewer.videoPlane)
  90224. //19:
  90225. viewer.videoPlane.rotation.set( 1.627167773445286, -1.172425902600188, 0.04682299709711613)
  90226. viewer.videoPlane.position.set( -9.558613948539932,-1.042301166581578, 0.08159683876743667) */
  90227. video.addEventListener('loadeddata', function(e) {
  90228. video.play();
  90229. //plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1) // 1080 * 1920
  90230. console.log('video loadeddata');
  90231. });
  90232. plane.scale.set(1080/1000,1920/1000,1); // 1080 * 1920
  90233. var startPlay = ()=>{
  90234. video.play();
  90235. //video.pause()
  90236. //video.currentTime = 0.1;
  90237. this.removeEventListener('global_mousedown', startPlay);
  90238. };
  90239. this.addEventListener('global_mousedown', startPlay);
  90240. var videoInfo = {
  90241. 9:{
  90242. rotation:[-1.432978005954197, 1.2296264545169697, 3.0098547630197667],
  90243. position:[6.532456676287381, -9.806373049095631, -0.024205281024294284]
  90244. },
  90245. 19:{
  90246. rotation:[1.627167773445286, -1.172425902600188, 0.04682299709711613],
  90247. position:[-9.558613948539932,-1.042301166581578, 0.08159683876743667]
  90248. },
  90249. };
  90250. /* this.images360.addEventListener('cameraMoveDone',(e)=>{
  90251. let info = videoInfo[this.images360.currentPano.id]
  90252. if(info ){
  90253. plane.visible = true;
  90254. plane.material.opacity = 1;
  90255. plane.position.fromArray(info.position)
  90256. plane.rotation.fromArray(info.rotation)
  90257. }
  90258. }) */
  90259. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  90260. if(Potree.settings.displayMode != 'showPanos') return
  90261. let info = videoInfo[e.toPano.pano.id];
  90262. if(info ){ //出现
  90263. setTimeout(()=>{
  90264. plane.visible = true;
  90265. plane.position.fromArray(info.position);
  90266. plane.rotation.fromArray(info.rotation);
  90267. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`;
  90268. video.play();
  90269. video.currentTime = 0;
  90270. Potree.settings.zoom.enabled = false;
  90271. transitions.start(lerp.property(plane.material, "opacity", 1/* , (e)=>{console.log('fadeIn',e)} */) , e.toPano.duration*0.4 , ()=>{
  90272. }, 0, easing['easeInOutQuad']);
  90273. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  90274. }
  90275. //消失
  90276. transitions.start(lerp.property(plane.material, "opacity", 0, /* (e)=>{console.log('fadeOut',e)} */) , e.toPano.duration*0.4, ()=>{
  90277. if(!info){
  90278. plane.visible = false;
  90279. video.pause();
  90280. Potree.settings.zoom.enabled = true;
  90281. }
  90282. }, 0, easing['easeInOutQuad']);
  90283. });
  90284. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  90285. if(e.mode == 'showPanos'){
  90286. let info = videoInfo[this.images360.currentPano.id];
  90287. if(info ){ //出现
  90288. plane.visible = true;
  90289. plane.position.fromArray(info.position);
  90290. plane.rotation.fromArray(info.rotation);
  90291. plane.material.opacity = 0;
  90292. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`;
  90293. video.play();
  90294. video.currentTime = 0;
  90295. Potree.settings.zoom.enabled = false;
  90296. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e);}) , 300 , ()=>{
  90297. }, 0, easing['easeInOutQuad']);
  90298. }
  90299. }else {
  90300. plane.visible = false;
  90301. Potree.settings.zoom.enabled = true;
  90302. }
  90303. });
  90304. this.scene.scene.add(plane);
  90305. }
  90306. ////////////////////////
  90307. addVideo(){
  90308. if(Potree.settings.number != 'SS-t-P6zBR73Gke')return
  90309. var geo = new PlaneGeometry(1, 1, 1, 1);
  90310. var videoInfo = this.videoInfo = [
  90311. /* {
  90312. id: 45,
  90313. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/c02a2c1e-8420-4f34-b951-5f7a07abe932.mp4',
  90314. rotation:[-1.629007730553656, 0.042029565584517974, -3.1345506775116627],
  90315. position:[ 9.467649296794061, -0.7596961214872837, -0.12477576310191862],
  90316. scale:[4.52209111454416,3.3888400031207984,1],
  90317. }, */
  90318. {
  90319. id: '40-2',
  90320. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/10/0aabafee-36b8-455d-9c11-0780bf694786.mp4',
  90321. rotation:[-1.494468618954883, -1.4987317433158989, -3.061254983446741],
  90322. position:[ 19.801820617361624, 2.884673619844108, -0.03362305858221648],
  90323. scale:[3.5741423153151763, 2.8738725275578703, 1],
  90324. },
  90325. {
  90326. id: 40,
  90327. /* rotation:[-1.534692822378723, 0.01083403560862361, 3.141535283661569],
  90328. position:[17.2934294239949861, 2.413510747928117, -0.008057029580231356], */
  90329. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/7896d6ef-a2d6-4fd7-949c-768782a5b484.mp4',
  90330. rotation:[-1.5487684197910518, 0.021848470169552752, -3.1387534893955236],
  90331. position:[17.277316608096, 2.0840432922115846, -0.0931149415437065],
  90332. scale:[2.0821757723834047, 0.6129478480765236, 1],
  90333. visibles: [40]
  90334. },
  90335. ];
  90336. let add = (info)=>{
  90337. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  90338. video.setAttribute("crossOrigin", 'Anonymous');
  90339. video.src = info.url || Potree.resourcePath+`/video/${Potree.settings.number}/${info.id}.mp4`;
  90340. var map = new VideoTexture(video);
  90341. var plane = this.videoPlane = new Mesh(geo, new MeshBasicMaterial({
  90342. color:"#ffffff",
  90343. transparent: !0,
  90344. depthTest:false,
  90345. opacity:0 ,
  90346. //side:2,
  90347. map
  90348. }));
  90349. plane.position.fromArray(info.position);
  90350. plane.rotation.fromArray(info.rotation);
  90351. info.scale && plane.scale.fromArray(info.scale);
  90352. this.scene.scene.add(plane);
  90353. info.plane = plane;
  90354. plane.boundingBox = new Box3(new Vector3(0,-0.5,0),new Vector3(1,-0.4,0.2));
  90355. video.addEventListener('loadeddata', function(e) {
  90356. video.play();
  90357. if(!info.visibles/* ||!viewer.images360.currentPano || info.visibles.includes(viewer.images360.currentPano.id) */){
  90358. plane.material.opacity = 1;
  90359. }
  90360. info.scale || plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1); // 1080 * 1920
  90361. console.log('video loadeddata', info.id);
  90362. });
  90363. if(info.visibles){
  90364. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  90365. if(info.visibles.includes(e.toPano.pano.id)){ //出现
  90366. setTimeout(()=>{
  90367. plane.visible = true;
  90368. video.currentTime = 0;
  90369. video.play();
  90370. if(video.paused){
  90371. var startPlay = ()=>{
  90372. plane.visible && video.play();
  90373. this.removeEventListener('global_mousedown', startPlay);
  90374. };
  90375. this.addEventListener('global_mousedown', startPlay);
  90376. }
  90377. Potree.settings.zoom.enabled = false;
  90378. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  90379. }, 0, easing['easeInOutQuad']);
  90380. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  90381. }else {
  90382. //消失
  90383. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  90384. if(!info){
  90385. plane.visible = false;
  90386. video.pause();
  90387. Potree.settings.zoom.enabled = true;
  90388. }
  90389. }, 0, easing['easeInOutQuad']);
  90390. }
  90391. });
  90392. }
  90393. var startPlay = ()=>{
  90394. video.play();
  90395. //video.pause()
  90396. //video.currentTime = 0.1;
  90397. this.removeEventListener('global_mousedown', startPlay);
  90398. };
  90399. this.addEventListener('global_mousedown', startPlay);
  90400. Potree.settings.isTest && plane.addEventListener('select',(e)=>{console.log(e);});
  90401. };
  90402. videoInfo.forEach(info=>{
  90403. add(info);
  90404. });
  90405. /* var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0]
  90406. video.setAttribute("crossOrigin", 'Anonymous')
  90407. video.src = Potree.resourcePath+'/video/SS-t-P6zBR73Gke/40.mp4'
  90408. var map = new THREE.VideoTexture(video);
  90409. var plane = this.videoPlane = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
  90410. color:"#ffffff",
  90411. transparent: !0,
  90412. depthTest:false,
  90413. opacity:0.7,
  90414. side:2,
  90415. map
  90416. }))
  90417. //plane.visible = false
  90418. this.scene.scene.add(plane)
  90419. plane.geometry.computeBoundingBox();
  90420. plane.boundingBox = plane.geometry.boundingBox.clone()//.applyMatrix4()
  90421. plane.boundingBox.max.z = 0.3
  90422. plane.boundingBox.max.y = -0.4
  90423. plane.boundingBox.max.x = 1
  90424. plane.position.copy(this.images360.panos[40].position);
  90425. plane.lookAt(plane.position.clone().setX(0))
  90426. plane.rotation.set(-1.534692822378723, 0.01083403560862361, 3.141535283661569)
  90427. plane.position.set( 17.2934294239949861, 2.413510747928117, -0.008057029580231356)
  90428. //viewer.transformObject(viewer.videoPlane)
  90429. //19:
  90430. video.addEventListener('loadeddata', function(e) {
  90431. video.play()
  90432. plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1) // 1080 * 1920
  90433. console.log('video loadeddata')
  90434. })
  90435. //plane.scale.set(1080/1000,1920/1000,1) // 1080 * 1920
  90436. var startPlay = ()=>{
  90437. video.play()
  90438. //video.pause()
  90439. //video.currentTime = 0.1;
  90440. this.removeEventListener('global_mousedown', startPlay)
  90441. }
  90442. this.addEventListener('global_mousedown', startPlay)
  90443. */
  90444. /* this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  90445. if(Potree.settings.displayMode != 'showPanos') return
  90446. let info = videoInfo[e.toPano.pano.id]
  90447. if(info ){ //出现
  90448. setTimeout(()=>{
  90449. plane.visible = true;
  90450. plane.position.fromArray(info.position)
  90451. plane.rotation.fromArray(info.rotation)
  90452. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`
  90453. video.play();
  90454. video.currentTime = 0
  90455. Potree.settings.zoom.enabled = false
  90456. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  90457. }, 0, easing['easeInOutQuad'])
  90458. }, e.toPano.duration*0.6) //时间上不能和消失的重叠 延迟
  90459. }
  90460. //消失
  90461. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  90462. if(!info){
  90463. plane.visible = false
  90464. video.pause()
  90465. Potree.settings.zoom.enabled = true
  90466. }
  90467. }, 0, easing['easeInOutQuad'])
  90468. })
  90469. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  90470. if(e.mode == 'showPanos'){
  90471. let info = videoInfo[this.images360.currentPano.id]
  90472. if(info ){ //出现
  90473. plane.visible = true;
  90474. plane.position.fromArray(info.position)
  90475. plane.rotation.fromArray(info.rotation)
  90476. plane.material.opacity = 0
  90477. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`
  90478. video.play();
  90479. video.currentTime = 0
  90480. Potree.settings.zoom.enabled = false
  90481. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e)}) , 300 , ()=>{
  90482. }, 0, easing['easeInOutQuad'])
  90483. }
  90484. }else{
  90485. plane.visible = false;
  90486. Potree.settings.zoom.enabled = true
  90487. }
  90488. })
  90489. */
  90490. }
  90491. };
  90492. //------ CLIP 默认clipTask都是clipInside ----------------------
  90493. /*
  90494. 并集相当于加法,交集相当于加法。 所有结果都能展开成多个乘积相加。
  90495. 假设有4个clipBoxes,ABCD, 如果是 A*B + C*D ,那么这是最终结果。 如果是 (A+B)*(C+D) = A*C+A*D+B*C+B*D
  90496. */
  90497. let Clips = {
  90498. boxes : [],
  90499. unionGroups : [], //二维数组。最外层要求并集,里层要求交集(如果只有一个元素就是本身)。总结起来就是要求一堆交集的并集
  90500. shaderParams:{},
  90501. needsUpdate : true,
  90502. addClip(box, clipMethod){
  90503. //不允许重复
  90504. if(this.boxes.includes(box)){
  90505. return console.warn('addClip重复添加了box',box)
  90506. }
  90507. boxes.push(box);
  90508. if(clipMethod == 'any'){//并
  90509. this.unionGroups.push([box]);
  90510. }else if(clipMethod == 'all'){//交
  90511. this.unionGroups.forEach(mixGroup=>mixGroup.push(box));
  90512. }
  90513. this.needsUpdate = true;
  90514. },
  90515. removeClip(box){
  90516. if(!this.boxes.includes(box)){
  90517. return console.warn('removeClip没有找到该box',box)
  90518. }
  90519. var newGroups = [];
  90520. this.unionGroups.forEach(mixGroup=>{
  90521. if(mixGroup.length == 1 && mixGroup[0] == box)return;//直接删除
  90522. newGroups.push(mixGroup.filter(e=>e!=box));
  90523. });
  90524. this.unionGroups = newGroups;
  90525. this.needsUpdate = true;
  90526. }
  90527. ,
  90528. clearClip(){
  90529. this.boxes = [];
  90530. this.unionGroups = [];
  90531. this.needsUpdate = true;
  90532. }
  90533. ,
  90534. updateShaderParams(){//没写完 - - 见 pointcloud clip.vs
  90535. /*
  90536. uniform mat4 clipBoxes[num_clipboxes];
  90537. uniform int clipBoxGroupCount;
  90538. uniform int mixClipIndices[clipboxGroupItemCount]; //把所有的要求都直接放到数组内
  90539. */
  90540. //这里需要转为Float32Array..? 参考material.setClipBoxes
  90541. let everyClipGroupCount = this.unionGroups.map(e=>e.length);
  90542. let mixClipIndices = [];
  90543. this.unionGroups.forEach(e=>{
  90544. mixClipIndices.push(...e);
  90545. });
  90546. this.shaderParams = {
  90547. num_clipboxes : this.boxes.length,
  90548. clipBoxGroupCount : this.unionGroups.length,
  90549. everyClipGroupCount,
  90550. clipBoxIndexCount: mixClipIndices.length,
  90551. mixClipIndices
  90552. };
  90553. }
  90554. ,
  90555. getShaderParams(){//每次要传递参数到shader中,执行这个就好
  90556. if(this.needsUpdate){
  90557. this.updateShaderParams();
  90558. }
  90559. return this.shaderParams
  90560. }
  90561. };
  90562. /* setTimeout(()=>{
  90563. if( Potree.settings.number == 't-YLZ5XAALl7' || 't-e2Kb2iU' ){
  90564. let transform = {
  90565. 't-YLZ5XAALl7' : {
  90566. rotation : [0, 0, 0.002326740152215126],
  90567. position : [0.421017820930033, -0.22730084679456727, 0.0068952417582]
  90568. },
  90569. 't-e2Kb2iU' : {
  90570. rotation : [0.06595546058095993, -0.026986798620029413, 0.8429662590573239],
  90571. position : [ -502.6216232179794, 1051.5690392495885, 15.48490744053752]
  90572. },
  90573. }
  90574. var path = `${Potree.resourcePath}/models/${Potree.settings.number}/`
  90575. viewer.loadObj({
  90576. objurl: path+'pipe.obj',
  90577. mtlurl: path+'pipe.mtl',
  90578. transform : transform[Potree.settings.number]
  90579. })
  90580. }
  90581. },1000)
  90582. //if(!Potree.settings.isOfficial){
  90583. if(number == 't-e2Kb2iU') {
  90584. setTimeout(//暂时延迟,等focus第一个点之后
  90585. ()=>{
  90586. viewer.loadProject(Potree.scriptPath + "/data/"+ number +"/potree.json5", ()=>{
  90587. viewer.scene.cameraAnimations[0].play()
  90588. })
  90589. },
  90590. 3000)
  90591. }
  90592. */
  90593. OrthographicCamera.prototype.zoomTo = function( node, factor = 1){
  90594. if ( !node.geometry && !node.boundingBox) {
  90595. return;
  90596. }
  90597. // TODO
  90598. //let minWS = new THREE.Vector4(node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z, 1);
  90599. //let minVS = minWS.applyMatrix4(this.matrixWorldInverse);
  90600. //let right = node.boundingBox.max.x;
  90601. //let bottom = node.boundingBox.min.y;
  90602. //let top = node.boundingBox.max.y;
  90603. this.updateProjectionMatrix();
  90604. };
  90605. PerspectiveCamera.prototype.zoomTo = function (node, factor) {
  90606. if (!node.geometry && !node.boundingSphere && !node.boundingBox) {
  90607. return;
  90608. }
  90609. if (node.geometry && node.geometry.boundingSphere === null) {
  90610. node.geometry.computeBoundingSphere();
  90611. }
  90612. node.updateMatrixWorld();
  90613. let bs;
  90614. if (node.boundingSphere) {
  90615. bs = node.boundingSphere;
  90616. } else if (node.geometry && node.geometry.boundingSphere) {
  90617. bs = node.geometry.boundingSphere;
  90618. } else {
  90619. bs = node.boundingBox.getBoundingSphere(new Sphere());
  90620. }
  90621. let _factor = factor || 1;
  90622. bs = bs.clone().applyMatrix4(node.matrixWorld);
  90623. let radius = bs.radius;
  90624. let fovr = this.fov * Math.PI / 180;
  90625. if (this.aspect < 1) {
  90626. fovr = fovr * this.aspect;
  90627. }
  90628. let distanceFactor = Math.abs(radius / Math.sin(fovr / 2)) * _factor;
  90629. let offset = this.getWorldDirection(new Vector3()).multiplyScalar(-distanceFactor);
  90630. this.position.copy(bs.center.clone().add(offset));
  90631. };
  90632. Ray.prototype.distanceToPlaneWithNegative = function (plane) {
  90633. let denominator = plane.normal.dot(this.direction);
  90634. if (denominator === 0) {
  90635. // line is coplanar, return origin
  90636. if (plane.distanceToPoint(this.origin) === 0) {
  90637. return 0;
  90638. }
  90639. // Null is preferable to undefined since undefined means.... it is undefined
  90640. return null;
  90641. }
  90642. let t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  90643. return t;
  90644. };
  90645. const workerPool = new WorkerPool();
  90646. const version = {
  90647. major: 1,
  90648. minor: 8,
  90649. suffix: '.0'
  90650. };
  90651. let lru = new LRU();
  90652. //console.log('Potree ' + version.major + '.' + version.minor + version.suffix);
  90653. let pointBudget = 1 * 1000 * 1000;
  90654. let framenumber = 0;
  90655. let numNodesLoading = 0;
  90656. let maxNodesLoading = 4;
  90657. const debug = {};
  90658. exports.scriptPath = "";
  90659. if (document.currentScript && document.currentScript.src) {
  90660. exports.scriptPath = new URL(document.currentScript.src + '/..').href;
  90661. if (exports.scriptPath.slice(-1) === '/') {
  90662. exports.scriptPath = exports.scriptPath.slice(0, -1);
  90663. }
  90664. } 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)) })){
  90665. 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;
  90666. if (exports.scriptPath.slice(-1) === '/') {
  90667. exports.scriptPath = exports.scriptPath.slice(0, -1);
  90668. }
  90669. }else {
  90670. 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?');
  90671. }
  90672. let resourcePath = exports.scriptPath + '/resources';
  90673. //add:
  90674. async function loadFile(path, callback, onError){
  90675. if(Potree.fileServer){
  90676. Potree.fileServer.get(path).then(data=>{
  90677. if(data.data)data = data.data;
  90678. if(data.data)data = data.data; //融合页面getdataset需要查找两次data
  90679. callback && callback(data);
  90680. }).catch(onError);
  90681. }else {
  90682. try{
  90683. let response = await fetch(path);
  90684. let text = await response.text();
  90685. var data = JSON.parse(text);
  90686. if(data.data) data = data.data;
  90687. callback && callback(data);
  90688. return data
  90689. }catch(e){
  90690. onError && onError(e);
  90691. }
  90692. }
  90693. //查询: http://192.168.0.26:8080/doc.html#/default/filter-%E6%BC%AB%E6%B8%B8%E7%82%B9/filterUsingGET
  90694. }
  90695. async function loadDatasets(callback,sceneCode,onError){//之后直接把path写进来
  90696. let path;
  90697. sceneCode = sceneCode || Potree.settings.number;
  90698. if(Potree.fileServer){
  90699. path = `/laser/dataset/${sceneCode}/getDataSet`;
  90700. }else {
  90701. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/datasets`
  90702. //现在只能加载得了本地的了
  90703. path = `${Potree.settings.urls.prefix}/laser/dataset/${sceneCode}/getDataSet`;
  90704. //path = `${Potree.scriptPath}/data/${sceneCode}/getDataSet.json`
  90705. }
  90706. return loadFile(path, callback,onError)
  90707. }
  90708. //目前上传平面图后如果不点击保存按钮,数据还是旧的不生效
  90709. async function loadMapEntity(datasetId, force){
  90710. if(!Potree.settings.floorplanEnable && !force && Potree.fileServer )return /* 等待平面图类型定义好会加载 */
  90711. let loaded = 0;
  90712. let needLoads = datasetId == 'all' ? viewer.scene.pointclouds.map(e=>e.dataset_id) : [datasetId];
  90713. let callback = (dataset_id, floorplanType, data )=>{
  90714. //要防止旧的比新的先获取到导致覆盖新的,因为两种type随时可能切换
  90715. if(floorplanType != Potree.settings.floorplanType[dataset_id]) return //如果请求的floorplanType不是当前最新的floorplanType就返回
  90716. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'floorplan_'+ dataset_id);
  90717. if(map){
  90718. viewer.mapViewer.mapLayer.removeMap(map);
  90719. }
  90720. var mapNew = viewer.mapViewer.mapLayer.addMapEntity(data.data || data, dataset_id);
  90721. if(map){
  90722. mapNew.visibleReasons = map.visibleReasons;
  90723. mapNew.unvisibleReasons = map.unvisibleReasons;
  90724. }
  90725. loaded ++;
  90726. };
  90727. needLoads.forEach(dataset_id=>{
  90728. let floorplanType = Potree.settings.floorplanType[dataset_id], prefix = '';
  90729. if(!Potree.fileServer){
  90730. prefix = Potree.settings.urls.prefix;
  90731. }
  90732. if(!floorplanType)return
  90733. var path;
  90734. /* if(Potree.fileServer){
  90735. path = `/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`
  90736. }else{
  90737. path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/tiled_maps`
  90738. } */
  90739. path = `${prefix}/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`;
  90740. Potree.settings.floorplanRequests[dataset_id] = true; //开始加载了
  90741. return loadFile(path, callback.bind(this, dataset_id, floorplanType) )
  90742. });
  90743. }
  90744. async function loadPanos(datasetId, callback){
  90745. var path;
  90746. let query = `?datasetId=${datasetId}`; //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  90747. if(Potree.fileServer){
  90748. path = `/laser/filter/${Potree.settings.number}/query` + query;
  90749. }else {
  90750. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/images/filter` + query
  90751. //path = `${Potree.scriptPath}/data/${Potree.settings.number}/panos-${datasetId}.json`
  90752. path = `${Potree.settings.urls.prefix}/laser/filter/${Potree.settings.number}/query` + query;
  90753. }
  90754. return loadFile(path, callback)
  90755. }
  90756. async function loadPanosInfo(callback){
  90757. var path;
  90758. if(Potree.fileServer){
  90759. }else {
  90760. path = `${Potree.scriptPath}/data/panoEdit/vision_edit.txt`;
  90761. }
  90762. return loadFile(path, callback)
  90763. }
  90764. //site_model
  90765. /* {
  90766. "area": 2503.30551910935,
  90767. "attributes": {},
  90768. "center": [
  90769. 113.59568277455075,
  90770. 22.366566635195288,
  90771. 12.78751625
  90772. ],
  90773. "children": [],
  90774. "geometry_hash": 1891071345,
  90775. "id": 10,
  90776. "name": "港湾一号",
  90777. "parentId": null,
  90778. "polygon": {
  90779. "coordinates": [
  90780. [
  90781. [
  90782. 113.59590810534583,
  90783. 22.36679132753878
  90784. ],
  90785. [
  90786. 113.59590810534583,
  90787. 22.366807172528629
  90788. ],
  90789. [
  90790. 113.59545610274934,
  90791. 22.366807172528629
  90792. ],
  90793. [
  90794. 113.59545610274934,
  90795. 22.36679132753878
  90796. ]
  90797. ]
  90798. ],
  90799. "type": "Polygon"
  90800. },
  90801. "type": "BUILDING",
  90802. "volume": null,
  90803. "z_max": null,
  90804. "z_min": null
  90805. }
  90806. */
  90807. function Log(value, color, fontSize){
  90808. color = color || '#13f';
  90809. fontSize = fontSize || 14;
  90810. console.warn(`%c${value}`, `color:${color};font-size:${fontSize}px`);
  90811. }
  90812. function loadPointCloud$1(path, name, sceneCode, timeStamp, callback, onError){
  90813. let loaded = function(e){
  90814. e.pointcloud.name = name;
  90815. e.pointcloud.sceneCode = sceneCode; //对应4dkk的场景码
  90816. callback(e);
  90817. };
  90818. let promise = new Promise( resolve => {
  90819. // load pointcloud
  90820. if (!path){
  90821. // TODO: callback? comment? Hello? Bueller? Anyone?
  90822. } else if (path.indexOf('ept.json') > 0) {
  90823. EptLoader.load(path, function(geometry) {
  90824. if (!geometry) {
  90825. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90826. }
  90827. else {
  90828. let pointcloud = new PointCloudOctree(geometry);
  90829. //loaded(pointcloud);
  90830. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90831. }
  90832. });
  90833. } else if (path.indexOf('cloud.js') > 0) {
  90834. POCLoader.load(path, timeStamp, function (geometry) {
  90835. if (!geometry) {
  90836. //callback({type: 'loading_failed'});
  90837. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90838. onError && onError();
  90839. } else {
  90840. let pointcloud = new PointCloudOctree(geometry);
  90841. // loaded(pointcloud);
  90842. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90843. }
  90844. });
  90845. }/* else if (path.indexOf('metadata.json') > 0) { //部分浏览器(如uc)不支持NodeLoader中的1n的大数据写法
  90846. Potree.OctreeLoader.load(path).then(e => {
  90847. let geometry = e.geometry;
  90848. if(!geometry){
  90849. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90850. }else{
  90851. let pointcloud = new PointCloudOctree(geometry);
  90852. let aPosition = pointcloud.getAttribute("position");
  90853. let material = pointcloud.material;
  90854. material.elevationRange = [
  90855. aPosition.range[0][2],
  90856. aPosition.range[1][2],
  90857. ];
  90858. // loaded(pointcloud);
  90859. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90860. }
  90861. });
  90862. OctreeLoader.load(path, function (geometry) {
  90863. if (!geometry) {
  90864. //callback({type: 'loading_failed'});
  90865. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90866. } else {
  90867. let pointcloud = new PointCloudOctree(geometry);
  90868. // loaded(pointcloud);
  90869. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90870. }
  90871. });
  90872. } */else if (path.indexOf('.vpc') > 0) {
  90873. PointCloudArena4DGeometry.load(path, function (geometry) {
  90874. if (!geometry) {
  90875. //callback({type: 'loading_failed'});
  90876. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90877. } else {
  90878. let pointcloud = new PointCloudArena4D(geometry);
  90879. // loaded(pointcloud);
  90880. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90881. }
  90882. });
  90883. } else {
  90884. //callback({'type': 'loading_failed'});
  90885. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90886. }
  90887. });
  90888. if(callback){
  90889. promise.then(pointcloud => {
  90890. loaded(pointcloud);
  90891. });
  90892. }else {
  90893. return promise;
  90894. }
  90895. };
  90896. // add selectgroup
  90897. (function($){
  90898. $.fn.extend({
  90899. selectgroup: function(args = {}){
  90900. let elGroup = $(this);
  90901. let rootID = elGroup.prop("id");
  90902. let groupID = `${rootID}`;
  90903. let groupTitle = (args.title !== undefined) ? args.title : "";
  90904. let elButtons = [];
  90905. elGroup.find("option").each((index, value) => {
  90906. let buttonID = $(value).prop("id");
  90907. let label = $(value).html();
  90908. let optionValue = $(value).prop("value");
  90909. let elButton = $(`
  90910. <span style="flex-grow: 1; display: inherit">
  90911. <label for="${buttonID}" class="ui-button" style="width: 100%; padding: .4em .1em">${label}</label>
  90912. <input type="radio" name="${groupID}" id="${buttonID}" value="${optionValue}" style="display: none"/>
  90913. </span>
  90914. `);
  90915. let elLabel = elButton.find("label");
  90916. let elInput = elButton.find("input");
  90917. elInput.change( () => {
  90918. elGroup.find("label").removeClass("ui-state-active");
  90919. elGroup.find("label").addClass("ui-state-default");
  90920. if(elInput.is(":checked")){
  90921. elLabel.addClass("ui-state-active");
  90922. }else {
  90923. //elLabel.addClass("ui-state-default");
  90924. }
  90925. });
  90926. elButtons.push(elButton);
  90927. });
  90928. let elFieldset = $(`
  90929. <fieldset style="border: none; margin: 0px; padding: 0px">
  90930. <legend>${groupTitle}</legend>
  90931. <span style="display: flex">
  90932. </span>
  90933. </fieldset>
  90934. `);
  90935. let elButtonContainer = elFieldset.find("span");
  90936. for(let elButton of elButtons){
  90937. elButtonContainer.append(elButton);
  90938. }
  90939. elButtonContainer.find("label").each( (index, value) => {
  90940. $(value).css("margin", "0px");
  90941. $(value).css("border-radius", "0px");
  90942. $(value).css("border", "1px solid black");
  90943. $(value).css("border-left", "none");
  90944. });
  90945. elButtonContainer.find("label:first").each( (index, value) => {
  90946. $(value).css("border-radius", "4px 0px 0px 4px");
  90947. });
  90948. elButtonContainer.find("label:last").each( (index, value) => {
  90949. $(value).css("border-radius", "0px 4px 4px 0px");
  90950. $(value).css("border-left", "none");
  90951. });
  90952. elGroup.empty();
  90953. elGroup.append(elFieldset);
  90954. }
  90955. });
  90956. })(jQuery);
  90957. exports.Action = Action;
  90958. exports.Alignment = Alignment;
  90959. exports.AnimationPath = AnimationPath;
  90960. exports.Annotation = Annotation;
  90961. exports.Box3Helper = Box3Helper$1;
  90962. exports.BoxVolume = BoxVolume;
  90963. exports.Buttons = Buttons;
  90964. exports.CameraAnimation = CameraAnimation;
  90965. exports.CameraMode = CameraMode;
  90966. exports.ClassificationScheme = ClassificationScheme;
  90967. exports.ClipMethod = ClipMethod;
  90968. exports.ClipTask = ClipTask;
  90969. exports.ClipVolume = ClipVolume;
  90970. exports.ClippingTool = ClippingTool;
  90971. exports.DeviceOrientationControls = DeviceOrientationControls;
  90972. exports.DownloadStatus = DownloadStatus;
  90973. exports.EarthControls = EarthControls;
  90974. exports.ElevationGradientRepeat = ElevationGradientRepeat;
  90975. exports.Enum = Enum;
  90976. exports.EnumItem = EnumItem;
  90977. exports.EptBinaryLoader = EptBinaryLoader;
  90978. exports.EptKey = EptKey;
  90979. exports.EptLaszipLoader = EptLaszipLoader;
  90980. exports.EptLazBatcher = EptLazBatcher;
  90981. exports.EptLoader = EptLoader;
  90982. exports.EptZstandardLoader = EptZstandardLoader;
  90983. exports.EventDispatcher = EventDispatcher$1;
  90984. exports.EyeDomeLightingMaterial = EyeDomeLightingMaterial;
  90985. exports.Features = Features;
  90986. exports.FirstPersonControls = FirstPersonControls;
  90987. exports.GLCubeFaces = GLCubeFaces$1;
  90988. exports.GeoPackageLoader = GeoPackageLoader;
  90989. exports.Geopackage = Geopackage$1;
  90990. exports.Gradients = Gradients;
  90991. exports.HierarchicalSlider = HierarchicalSlider;
  90992. exports.Images360 = Images360;
  90993. exports.KeyCodes = KeyCodes;
  90994. exports.LRU = LRU;
  90995. exports.LRUItem = LRUItem;
  90996. exports.LengthUnits = LengthUnits;
  90997. exports.Log = Log;
  90998. exports.Measure = Measure;
  90999. exports.MeasuringTool = MeasuringTool;
  91000. exports.Message = Message;
  91001. exports.ModelManagerEvents = ModelManagerEvents;
  91002. exports.NormalizationEDLMaterial = NormalizationEDLMaterial;
  91003. exports.NormalizationMaterial = NormalizationMaterial;
  91004. exports.OrbitControls = OrbitControls;
  91005. exports.OrientedImage = OrientedImage;
  91006. exports.OrientedImageLoader = OrientedImageLoader;
  91007. exports.OrientedImages = OrientedImages;
  91008. exports.POCLoader = POCLoader;
  91009. exports.PanoRendererEvents = PanoRendererEvents;
  91010. exports.PanoSizeClass = PanoSizeClass;
  91011. exports.PanoramaEvents = PanoramaEvents;
  91012. exports.PathAnimation = PathAnimation;
  91013. exports.PointAttribute = PointAttribute;
  91014. exports.PointAttributeTypes = PointAttributeTypes;
  91015. exports.PointAttributes = PointAttributes;
  91016. exports.PointCloudEptGeometry = PointCloudEptGeometry;
  91017. exports.PointCloudEptGeometryNode = PointCloudEptGeometryNode;
  91018. exports.PointCloudMaterial = PointCloudMaterial$1;
  91019. exports.PointCloudOctree = PointCloudOctree;
  91020. exports.PointCloudOctreeGeometry = PointCloudOctreeGeometry;
  91021. exports.PointCloudOctreeGeometryNode = PointCloudOctreeGeometryNode;
  91022. exports.PointCloudOctreeNode = PointCloudOctreeNode;
  91023. exports.PointCloudSM = PointCloudSM;
  91024. exports.PointCloudTree = PointCloudTree;
  91025. exports.PointCloudTreeNode = PointCloudTreeNode;
  91026. exports.PointShape = PointShape;
  91027. exports.PointSizeType = PointSizeType;
  91028. exports.Points = Points$1;
  91029. exports.PolygonClipVolume = PolygonClipVolume;
  91030. exports.Profile = Profile;
  91031. exports.ProfileData = ProfileData;
  91032. exports.ProfileRequest = ProfileRequest;
  91033. exports.ProfileTool = ProfileTool;
  91034. exports.Renderer = Renderer;
  91035. exports.Scene = Scene$1;
  91036. exports.SceneRendererEvents = SceneRendererEvents;
  91037. exports.ScreenBoxSelectTool = ScreenBoxSelectTool;
  91038. exports.ShapefileLoader = ShapefileLoader;
  91039. exports.SphereVolume = SphereVolume;
  91040. exports.SpotLightHelper = SpotLightHelper$1;
  91041. exports.TileDownloaderEvents = TileDownloaderEvents;
  91042. exports.TransformationTool = TransformationTool;
  91043. exports.TreeType = TreeType;
  91044. exports.Utils = Utils;
  91045. exports.VRControls = VRControls;
  91046. exports.Vectors = Vectors;
  91047. exports.Vectors2 = Vectors2;
  91048. exports.Version = Version;
  91049. exports.Viewer = Viewer;
  91050. exports.Volume = Volume;
  91051. exports.VolumeTool = VolumeTool;
  91052. exports.WorkerPool = WorkerPool;
  91053. exports.XHRFactory = XHRFactory;
  91054. exports.config = config$1;
  91055. exports.debug = debug;
  91056. exports.framenumber = framenumber;
  91057. exports.loadDatasets = loadDatasets;
  91058. exports.loadFile = loadFile;
  91059. exports.loadMapEntity = loadMapEntity;
  91060. exports.loadPanos = loadPanos;
  91061. exports.loadPanosInfo = loadPanosInfo;
  91062. exports.loadPointCloud = loadPointCloud$1;
  91063. exports.loadProject = loadProject;
  91064. exports.lru = lru;
  91065. exports.maxNodesLoading = maxNodesLoading;
  91066. exports.mergeEditStart = mergeEditStart;
  91067. exports.numNodesLoading = numNodesLoading;
  91068. exports.panoEditStart = panoEditStart;
  91069. exports.pointBudget = pointBudget;
  91070. exports.resourcePath = resourcePath;
  91071. exports.saveProject = saveProject;
  91072. exports.settings = settings;
  91073. exports.start = start;
  91074. exports.updatePointClouds = updatePointClouds;
  91075. exports.updateVisibility = updateVisibility;
  91076. exports.updateVisibilityStructures = updateVisibilityStructures;
  91077. exports.version = version;
  91078. exports.workerPool = workerPool;
  91079. Object.defineProperty(exports, '__esModule', { value: true });
  91080. })));
  91081. //# sourceMappingURL=potree.js.map